-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathtest_cufile.py
More file actions
1928 lines (1554 loc) · 69.3 KB
/
test_cufile.py
File metadata and controls
1928 lines (1554 loc) · 69.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NVIDIA-SOFTWARE-LICENSE
import ctypes
import errno
import logging
import os
import pathlib
import platform
import subprocess
import tempfile
from contextlib import suppress
from functools import cache
import pytest
import cuda.bindings.driver as cuda
cufile = pytest.importorskip("cuda.bindings.cufile")
# Configure logging to show INFO level and above
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s: %(message)s",
force=True, # Override any existing logging configuration
)
cufile = pytest.importorskip("cuda.bindings.cufile", reason="skipping tests on Windows")
@pytest.fixture
def cufile_env_json(monkeypatch):
"""Set CUFILE_ENV_PATH_JSON environment variable for async tests."""
# Get absolute path to cufile.json in the same directory as this test file
test_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(test_dir, "cufile.json")
assert os.path.isfile(config_path)
monkeypatch.setenv("CUFILE_ENV_PATH_JSON", config_path)
logging.info(f"Using cuFile config: {config_path}")
@cache
def cufileLibraryAvailable():
"""Check if cuFile library is available on the system."""
try:
# Try to get cuFile library version - this will fail if library is not available
version = cufile.get_version()
logging.info(f"cuFile library available, version: {version}")
return True
except Exception as e:
logging.warning(f"cuFile library not available: {e}")
return False
@cache
def cufileVersionLessThan(target):
"""Check if cuFile library version is less than target version."""
try:
# Get cuFile library version
version = cufile.get_version()
logging.info(f"cuFile library version: {version}")
# Check if version is less than target
if version < target:
logging.warning(f"cuFile library version {version} is less than required {target}")
return True
return False
except Exception as e:
logging.error(f"Error checking cuFile version: {e}")
return True # Assume old version if any error occurs
@cache
def isSupportedFilesystem():
"""Check if the current filesystem is supported (ext4 or xfs).
This uses `findmnt` so the kernel's mount table logic owns the decoding of the filesystem type.
"""
fs_type = subprocess.check_output(["findmnt", "-no", "FSTYPE", "-T", os.getcwd()], text=True).strip() # noqa: S603, S607
logging.info(f"Current filesystem type (findmnt): {fs_type}")
return fs_type in ("ext4", "xfs")
@cache
def get_tegra_kind():
"""Detect Tegra device kind (Orin/Thor) via nvidia-smi, or None if not Tegra."""
if not pathlib.Path("/etc/nv_tegra_release").exists():
return None
out = subprocess.check_output(["nvidia-smi"], text=True, stderr=subprocess.STDOUT) # noqa: S607
tegra_kinds_found = []
for kind in ("Orin", "Thor"):
if f" {kind} " in out:
tegra_kinds_found.append(kind)
assert len(tegra_kinds_found) == 1, f"UNEXPECTED nvidia-smi output:\n{out}"
return tegra_kinds_found[0]
# Global skip condition for all tests if cuFile library is not available
pytestmark = [
pytest.mark.skipif(not cufileLibraryAvailable(), reason="cuFile library not available on this system"),
pytest.mark.skipif(
platform.system() == "Linux" and "microsoft" in pathlib.Path("/proc/version").read_text().lower(),
reason="skipping cuFile tests on WSL",
),
pytest.mark.skipif(get_tegra_kind() == "Orin", reason="skipping cuFile tests on Orin (Tegra Linux)"),
pytest.mark.skipif(
get_tegra_kind() == "Thor" and cufileVersionLessThan(1160),
reason="skipping cuFile tests on Thor (Tegra Linux) with CTK < 13.1",
),
]
xfail_handle_register = pytest.mark.xfail(
condition=isSupportedFilesystem() and os.environ.get("CI") is not None,
raises=cufile.cuFileError,
reason="handle_register call fails in CI for unknown reasons",
)
def test_cufile_success_defined():
"""Check if CUFILE_SUCCESS is defined in OpError enum."""
assert hasattr(cufile.OpError, "SUCCESS")
@pytest.fixture
def ctx():
# Initialize CUDA
(err,) = cuda.cuInit(0)
assert err == cuda.CUresult.CUDA_SUCCESS
err, device = cuda.cuDeviceGet(0)
assert err == cuda.CUresult.CUDA_SUCCESS
err, ctx = cuda.cuDevicePrimaryCtxRetain(device)
assert err == cuda.CUresult.CUDA_SUCCESS
(err,) = cuda.cuCtxSetCurrent(ctx)
assert err == cuda.CUresult.CUDA_SUCCESS
yield
cuda.cuDevicePrimaryCtxRelease(device)
@pytest.fixture
def driver(ctx):
cufile.driver_open()
yield
cufile.driver_close()
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("driver")
@xfail_handle_register
def test_handle_register():
"""Test file handle registration with cuFile."""
# Create test file
file_path = "test_handle_register.bin"
# Create file with POSIX operations
fd = os.open(file_path, os.O_CREAT | os.O_RDWR, 0o600)
# Write test data using POSIX write
test_data = b"Test data for cuFile - POSIX write"
bytes_written = os.write(fd, test_data)
# Sync to ensure data is on disk
os.fsync(fd)
# Close and reopen with O_DIRECT for cuFile operations
os.close(fd)
# Reopen with O_DIRECT
flags = os.O_RDWR | os.O_DIRECT
fd = os.open(file_path, flags)
try:
# Create and initialize the descriptor
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
# Register the handle
handle = cufile.handle_register(descr.ptr)
# Deregister the handle
cufile.handle_deregister(handle)
finally:
os.close(fd)
with suppress(OSError):
os.unlink(file_path)
@pytest.mark.usefixtures("driver")
def test_buf_register_simple():
"""Simple test for buffer registration with cuFile."""
# Allocate CUDA memory
buffer_size = 4096 # 4KB, aligned to 4096 bytes
err, buf_ptr = cuda.cuMemAlloc(buffer_size)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Register the buffer with cuFile
flags = 0
buf_ptr_int = int(buf_ptr)
cufile.buf_register(buf_ptr_int, buffer_size, flags)
# Deregister the buffer
cufile.buf_deregister(buf_ptr_int)
finally:
# Free CUDA memory
cuda.cuMemFree(buf_ptr)
@pytest.mark.usefixtures("driver")
def test_buf_register_host_memory():
"""Test buffer registration with host memory."""
# Allocate host memory
buffer_size = 4096 # 4KB, aligned to 4096 bytes
err, buf_ptr = cuda.cuMemHostAlloc(buffer_size, 0)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Register the host buffer with cuFile
flags = 0
buf_ptr_int = int(buf_ptr)
cufile.buf_register(buf_ptr_int, buffer_size, flags)
# Deregister the buffer
cufile.buf_deregister(buf_ptr_int)
finally:
# Free host memory
cuda.cuMemFreeHost(buf_ptr)
@pytest.mark.usefixtures("driver")
def test_buf_register_multiple_buffers():
"""Test registering multiple buffers."""
# Allocate multiple CUDA buffers
buffer_sizes = [4096, 16384, 65536] # All aligned to 4096 bytes
buffers = []
for size in buffer_sizes:
err, buf_ptr = cuda.cuMemAlloc(size)
assert err == cuda.CUresult.CUDA_SUCCESS
buffers.append(buf_ptr)
try:
# Register all buffers
flags = 0
for buf_ptr, size in zip(buffers, buffer_sizes):
buf_ptr_int = int(buf_ptr)
cufile.buf_register(buf_ptr_int, size, flags)
# Deregister all buffers
for buf_ptr in buffers:
buf_ptr_int = int(buf_ptr)
cufile.buf_deregister(buf_ptr_int)
finally:
# Free all buffers
for buf_ptr in buffers:
cuda.cuMemFree(buf_ptr)
@pytest.mark.usefixtures("driver")
def test_buf_register_invalid_flags():
"""Test buffer registration with invalid flags."""
# Allocate CUDA memory
buffer_size = 65536
err, buf_ptr = cuda.cuMemAlloc(buffer_size)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Try to register with invalid flags
invalid_flags = 999
buf_ptr_int = int(buf_ptr)
with suppress(Exception):
cufile.buf_register(buf_ptr_int, buffer_size, invalid_flags)
# If we get here, deregister to clean up
cufile.buf_deregister(buf_ptr_int)
finally:
# Free CUDA memory
cuda.cuMemFree(buf_ptr)
@pytest.mark.usefixtures("driver")
def test_buf_register_large_buffer():
"""Test buffer registration with a large buffer."""
# Allocate large CUDA memory (1MB, aligned to 4096 bytes)
buffer_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0)
err, buf_ptr = cuda.cuMemAlloc(buffer_size)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Register the large buffer with cuFile
flags = 0
buf_ptr_int = int(buf_ptr)
cufile.buf_register(buf_ptr_int, buffer_size, flags)
# Deregister the buffer
cufile.buf_deregister(buf_ptr_int)
finally:
# Free CUDA memory
cuda.cuMemFree(buf_ptr)
@pytest.mark.usefixtures("driver")
def test_buf_register_already_registered():
"""Test that registering an already registered buffer fails."""
# Allocate CUDA memory
buffer_size = 4096 # 4KB, aligned to 4096 bytes
err, buf_ptr = cuda.cuMemAlloc(buffer_size)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Register the buffer first time
flags = 0
buf_ptr_int = int(buf_ptr)
cufile.buf_register(buf_ptr_int, buffer_size, flags)
# Try to register the same buffer again
try:
cufile.buf_register(buf_ptr_int, buffer_size, flags)
# If we get here, deregister both times
cufile.buf_deregister(buf_ptr_int)
cufile.buf_deregister(buf_ptr_int)
except Exception:
# Expected error when registering buffer twice
# Deregister the first registration
cufile.buf_deregister(buf_ptr_int)
finally:
# Free CUDA memory
cuda.cuMemFree(buf_ptr)
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("driver")
@xfail_handle_register
def test_cufile_read_write():
"""Test cuFile read and write operations."""
# Create test file
file_path = "test_cufile_rw.bin"
# Allocate CUDA memory for write and read
write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0)
err, write_buf = cuda.cuMemAlloc(write_size)
assert err == cuda.CUresult.CUDA_SUCCESS
err, read_buf = cuda.cuMemAlloc(write_size)
assert err == cuda.CUresult.CUDA_SUCCESS
# Allocate host memory for data verification
host_buf = ctypes.create_string_buffer(write_size)
try:
# Create file with O_DIRECT
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
# Register buffers with cuFile
write_buf_int = int(write_buf)
read_buf_int = int(read_buf)
cufile.buf_register(write_buf_int, write_size, 0)
cufile.buf_register(read_buf_int, write_size, 0)
# Create file descriptor
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
# Register file handle
handle = cufile.handle_register(descr.ptr)
# Prepare test data
test_string = b"Hello cuFile! This is test data for read/write operations. "
test_string_len = len(test_string)
repetitions = write_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:write_size] # Ensure it fits exactly in buffer
host_buf = ctypes.create_string_buffer(test_data, write_size)
# Copy test data to CUDA write buffer
cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0)
cuda.cuStreamSynchronize(0)
# Write data using cuFile
bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0)
# Read data back using cuFile
bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0)
# Verify bytes written equals bytes read
assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}"
assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}"
assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})"
# Copy read data back to host
cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0)
cuda.cuStreamSynchronize(0)
# Verify the data
read_data = host_buf.value
assert read_data == test_data, "Read data doesn't match written data"
# Deregister file handle
cufile.handle_deregister(handle)
# Deregister buffers
cufile.buf_deregister(write_buf_int)
cufile.buf_deregister(read_buf_int)
finally:
# Close file
os.close(fd)
# Free CUDA memory
cuda.cuMemFree(write_buf)
cuda.cuMemFree(read_buf)
# Clean up test file
try:
os.unlink(file_path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("driver")
@xfail_handle_register
def test_cufile_read_write_host_memory():
"""Test cuFile read and write operations using host memory."""
# Create test file
file_path = "test_cufile_rw_host.bin"
# Allocate host memory for write and read
write_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0)
err, write_buf = cuda.cuMemHostAlloc(write_size, 0)
assert err == cuda.CUresult.CUDA_SUCCESS
err, read_buf = cuda.cuMemHostAlloc(write_size, 0)
assert err == cuda.CUresult.CUDA_SUCCESS
try:
# Create file with O_DIRECT
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
# Register host buffers with cuFile
write_buf_int = int(write_buf)
read_buf_int = int(read_buf)
cufile.buf_register(write_buf_int, write_size, 0)
cufile.buf_register(read_buf_int, write_size, 0)
# Create file descriptor
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
# Register file handle
handle = cufile.handle_register(descr.ptr)
# Prepare test data
test_string = b"Host memory test data for cuFile operations! "
test_string_len = len(test_string)
repetitions = write_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:write_size] # Ensure it fits exactly in buffer
# Copy test data to host write buffer
host_buf = ctypes.create_string_buffer(test_data, write_size)
write_buf_content = ctypes.string_at(write_buf, write_size)
# Write data using cuFile
bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0)
# Sync to ensure data is on disk
os.fsync(fd)
# Read data back using cuFile
bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0)
# Verify bytes written equals bytes read
assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}"
assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}"
assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})"
# Verify the data
read_data = ctypes.string_at(read_buf, write_size)
expected_data = write_buf_content
assert read_data == expected_data, "Read data doesn't match written data"
# Deregister file handle
cufile.handle_deregister(handle)
# Deregister buffers
cufile.buf_deregister(write_buf_int)
cufile.buf_deregister(read_buf_int)
finally:
# Close file
os.close(fd)
# Free host memory
cuda.cuMemFreeHost(write_buf)
cuda.cuMemFreeHost(read_buf)
# Clean up test file
try:
os.unlink(file_path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("driver")
@xfail_handle_register
def test_cufile_read_write_large():
"""Test cuFile read and write operations with large data."""
# Create test file
file_path = "test_cufile_rw_large.bin"
# Allocate large CUDA memory (1MB, aligned to 4096 bytes)
write_size = 1024 * 1024 # 1MB, aligned to 4096 bytes (1048576 % 4096 == 0)
err, write_buf = cuda.cuMemAlloc(write_size)
assert err == cuda.CUresult.CUDA_SUCCESS
err, read_buf = cuda.cuMemAlloc(write_size)
assert err == cuda.CUresult.CUDA_SUCCESS
# Allocate host memory for data verification
host_buf = ctypes.create_string_buffer(write_size)
try:
# Create file with O_DIRECT
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
# Register buffers with cuFile
write_buf_int = int(write_buf)
read_buf_int = int(read_buf)
cufile.buf_register(write_buf_int, write_size, 0)
cufile.buf_register(read_buf_int, write_size, 0)
# Create file descriptor
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
# Register file handle
handle = cufile.handle_register(descr.ptr)
# Generate large test data
import random
test_data = bytes(random.getrandbits(8) for _ in range(write_size))
host_buf = ctypes.create_string_buffer(test_data, write_size)
# Copy test data to CUDA write buffer
cuda.cuMemcpyHtoDAsync(write_buf, host_buf, write_size, 0)
cuda.cuStreamSynchronize(0)
# Get the actual data that was written to CUDA buffer
cuda.cuMemcpyDtoHAsync(host_buf, write_buf, write_size, 0)
cuda.cuStreamSynchronize(0)
expected_data = host_buf.value
# Write data using cuFile
bytes_written = cufile.write(handle, write_buf_int, write_size, 0, 0)
# Read data back using cuFile
bytes_read = cufile.read(handle, read_buf_int, write_size, 0, 0)
# Verify bytes written equals bytes read
assert bytes_written == write_size, f"Expected to write {write_size} bytes, but wrote {bytes_written}"
assert bytes_read == write_size, f"Expected to read {write_size} bytes, but read {bytes_read}"
assert bytes_written == bytes_read, f"Bytes written ({bytes_written}) doesn't match bytes read ({bytes_read})"
# Copy read data back to host
cuda.cuMemcpyDtoHAsync(host_buf, read_buf, write_size, 0)
cuda.cuStreamSynchronize(0)
# Verify the data
read_data = host_buf.value
assert read_data == expected_data, "Large read data doesn't match written data"
# Deregister file handle
cufile.handle_deregister(handle)
# Deregister buffers
cufile.buf_deregister(write_buf_int)
cufile.buf_deregister(read_buf_int)
finally:
# Close file
os.close(fd)
# Free CUDA memory
cuda.cuMemFree(write_buf)
cuda.cuMemFree(read_buf)
# Clean up test file
try:
os.unlink(file_path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver")
@xfail_handle_register
def test_cufile_write_async():
"""Test cuFile asynchronous write operations."""
# Create test file
file_path = "test_cufile_write_async.bin"
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
try:
# Register file handle
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
handle = cufile.handle_register(descr.ptr)
# Allocate and register device buffer
buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0)
err, buf_ptr = cuda.cuMemAlloc(buf_size)
assert err == cuda.CUresult.CUDA_SUCCESS
cufile.buf_register(int(buf_ptr), buf_size, 0)
# Create CUDA stream
err, stream = cuda.cuStreamCreate(0)
assert err == cuda.CUresult.CUDA_SUCCESS
# Register stream with cuFile
cufile.stream_register(int(stream), 0)
# Prepare test data in device buffer
test_string = b"Async write test data for cuFile!"
test_string_len = len(test_string)
repetitions = buf_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:buf_size] # Ensure it fits exactly in buffer
host_buf = ctypes.create_string_buffer(test_data, buf_size)
cuda.cuMemcpyHtoDAsync(buf_ptr, host_buf, buf_size, 0)
cuda.cuStreamSynchronize(0)
# Create parameter arrays for async write
size_p = ctypes.c_size_t(buf_size)
file_offset_p = ctypes.c_int64(0)
buf_ptr_offset_p = ctypes.c_int64(0)
bytes_written_p = ctypes.c_ssize_t(0)
# Perform async write
cufile.write_async(
int(handle),
int(buf_ptr),
ctypes.addressof(size_p),
ctypes.addressof(file_offset_p),
ctypes.addressof(buf_ptr_offset_p),
ctypes.addressof(bytes_written_p),
int(stream),
)
# Synchronize stream to wait for completion
cuda.cuStreamSynchronize(stream)
# Verify bytes written
assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}"
# Deregister stream
cufile.stream_deregister(int(stream))
# Deregister and cleanup
cufile.buf_deregister(int(buf_ptr))
cufile.handle_deregister(handle)
cuda.cuStreamDestroy(stream)
cuda.cuMemFree(buf_ptr)
finally:
os.close(fd)
with suppress(OSError):
os.unlink(file_path)
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver")
@xfail_handle_register
def test_cufile_read_async():
"""Test cuFile asynchronous read operations."""
# Create test file
file_path = "test_cufile_read_async.bin"
# First create and write test data without O_DIRECT
fd_temp = os.open(file_path, os.O_CREAT | os.O_RDWR, 0o600)
# Create test data that's aligned to 4096 bytes
test_string = b"Async read test data for cuFile!"
test_string_len = len(test_string)
buf_size = 65536 # 64KB, aligned to 4096 bytes
repetitions = buf_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:buf_size] # Ensure exact 64KB
os.write(fd_temp, test_data)
os.fsync(fd_temp)
os.close(fd_temp)
# Now open with O_DIRECT for cuFile operations
fd = os.open(file_path, os.O_RDWR | os.O_DIRECT)
try:
# Register file handle
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
handle = cufile.handle_register(descr.ptr)
# Allocate and register device buffer
buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0)
err, buf_ptr = cuda.cuMemAlloc(buf_size)
assert err == cuda.CUresult.CUDA_SUCCESS
cufile.buf_register(int(buf_ptr), buf_size, 0)
# Create CUDA stream
err, stream = cuda.cuStreamCreate(0)
assert err == cuda.CUresult.CUDA_SUCCESS
# Register stream with cuFile
cufile.stream_register(int(stream), 0)
# Create parameter arrays for async read
size_p = ctypes.c_size_t(buf_size)
file_offset_p = ctypes.c_int64(0)
buf_ptr_offset_p = ctypes.c_int64(0)
bytes_read_p = ctypes.c_ssize_t(0)
# Perform async read
cufile.read_async(
int(handle),
int(buf_ptr),
ctypes.addressof(size_p),
ctypes.addressof(file_offset_p),
ctypes.addressof(buf_ptr_offset_p),
ctypes.addressof(bytes_read_p),
int(stream),
)
# Synchronize stream to wait for completion
cuda.cuStreamSynchronize(stream)
# Verify bytes read
assert bytes_read_p.value > 0, f"Expected bytes read, got {bytes_read_p.value}"
# Copy read data back to host and verify
host_buf = ctypes.create_string_buffer(buf_size)
cuda.cuMemcpyDtoHAsync(host_buf, buf_ptr, buf_size, 0)
cuda.cuStreamSynchronize(0)
read_data = host_buf.value[: bytes_read_p.value]
expected_data = test_data[: bytes_read_p.value]
assert read_data == expected_data, "Read data doesn't match written data"
# Deregister stream
cufile.stream_deregister(int(stream))
# Deregister and cleanup
cufile.buf_deregister(int(buf_ptr))
cufile.handle_deregister(handle)
cuda.cuStreamDestroy(stream)
cuda.cuMemFree(buf_ptr)
finally:
os.close(fd)
with suppress(OSError):
os.unlink(file_path)
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@xfail_handle_register
@pytest.mark.usefixtures("ctx", "cufile_env_json", "driver")
def test_cufile_async_read_write():
"""Test cuFile asynchronous read and write operations in sequence."""
# Create test file
file_path = "test_cufile_async_rw.bin"
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
try:
# Register file handle
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
handle = cufile.handle_register(descr.ptr)
# Allocate and register device buffers
buf_size = 65536 # 64KB, aligned to 4096 bytes (65536 % 4096 == 0)
err, write_buf = cuda.cuMemAlloc(buf_size)
assert err == cuda.CUresult.CUDA_SUCCESS
cufile.buf_register(int(write_buf), buf_size, 0)
err, read_buf = cuda.cuMemAlloc(buf_size)
assert err == cuda.CUresult.CUDA_SUCCESS
cufile.buf_register(int(read_buf), buf_size, 0)
# Create CUDA stream
err, stream = cuda.cuStreamCreate(0)
assert err == cuda.CUresult.CUDA_SUCCESS
# Register stream with cuFile
cufile.stream_register(int(stream), 0)
# Prepare test data in write buffer
test_string = b"Async RW test data for cuFile!"
test_string_len = len(test_string)
repetitions = buf_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:buf_size] # Ensure it fits exactly in buffer
host_buf = ctypes.create_string_buffer(test_data, buf_size)
cuda.cuMemcpyHtoDAsync(write_buf, host_buf, buf_size, 0)
cuda.cuStreamSynchronize(0)
# Create parameter arrays for async write
write_size_p = ctypes.c_size_t(buf_size)
write_file_offset_p = ctypes.c_int64(0)
write_buf_ptr_offset_p = ctypes.c_int64(0)
bytes_written_p = ctypes.c_ssize_t(0)
# Perform async write
cufile.write_async(
int(handle),
int(write_buf),
ctypes.addressof(write_size_p),
ctypes.addressof(write_file_offset_p),
ctypes.addressof(write_buf_ptr_offset_p),
ctypes.addressof(bytes_written_p),
int(stream),
)
# Synchronize stream to wait for write completion
cuda.cuStreamSynchronize(stream)
# Verify bytes written
assert bytes_written_p.value == buf_size, f"Expected {buf_size} bytes written, got {bytes_written_p.value}"
# Create parameter arrays for async read
read_size_p = ctypes.c_size_t(buf_size)
read_file_offset_p = ctypes.c_int64(0)
read_buf_ptr_offset_p = ctypes.c_int64(0)
bytes_read_p = ctypes.c_ssize_t(0)
# Perform async read
cufile.read_async(
int(handle),
int(read_buf),
ctypes.addressof(read_size_p),
ctypes.addressof(read_file_offset_p),
ctypes.addressof(read_buf_ptr_offset_p),
ctypes.addressof(bytes_read_p),
int(stream),
)
# Synchronize stream to wait for read completion
cuda.cuStreamSynchronize(stream)
# Verify bytes read
assert bytes_read_p.value == buf_size, f"Expected {buf_size} bytes read, got {bytes_read_p.value}"
# Copy read data back to host and verify
host_buf = ctypes.create_string_buffer(buf_size)
cuda.cuMemcpyDtoHAsync(host_buf, read_buf, buf_size, 0)
cuda.cuStreamSynchronize(0)
read_data = host_buf.value
assert read_data == test_data, "Read data doesn't match written data"
# Deregister stream
cufile.stream_deregister(int(stream))
# Deregister and cleanup
cufile.buf_deregister(int(write_buf))
cufile.buf_deregister(int(read_buf))
cufile.handle_deregister(handle)
cuda.cuStreamDestroy(stream)
cuda.cuMemFree(write_buf)
cuda.cuMemFree(read_buf)
finally:
os.close(fd)
with suppress(OSError):
os.unlink(file_path)
@pytest.mark.skipif(not isSupportedFilesystem(), reason="cuFile handle_register requires ext4 or xfs filesystem")
@pytest.mark.usefixtures("driver")
@xfail_handle_register
def test_batch_io_basic():
"""Test basic batch IO operations with multiple read/write operations."""
# Create test file
file_path = "test_batch_io.bin"
# Allocate CUDA memory for multiple operations
buf_size = 65536 # 64KB
num_operations = 4
buffers = []
read_buffers = [] # Initialize read_buffers to avoid UnboundLocalError
for i in range(num_operations):
err, buf = cuda.cuMemAlloc(buf_size)
assert err == cuda.CUresult.CUDA_SUCCESS
buffers.append(buf)
# Allocate host memory for data verification
host_buf = ctypes.create_string_buffer(buf_size)
try:
# Create file with O_DIRECT
fd = os.open(file_path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
# Register buffers with cuFile
for buf in buffers:
buf_int = int(buf)
cufile.buf_register(buf_int, buf_size, 0)
# Create file descriptor
descr = cufile.Descr()
descr.type = cufile.FileHandleType.OPAQUE_FD
descr.handle.fd = fd
descr.fs_ops = 0
# Register file handle
handle = cufile.handle_register(descr.ptr)
# Set up batch IO
batch_handle = cufile.batch_io_set_up(num_operations)
# Create IOParams array for batch operations
io_params = cufile.IOParams(num_operations)
io_events = cufile.IOEvents(num_operations)
# Prepare test data for each operation
test_strings = [
b"Batch operation 1 data for testing cuFile! ",
b"Batch operation 2 data for testing cuFile! ",
b"Batch operation 3 data for testing cuFile! ",
b"Batch operation 4 data for testing cuFile! ",
]
# Set up write operations
for i in range(num_operations):
# Prepare test data
test_string = test_strings[i]
test_string_len = len(test_string)
repetitions = buf_size // test_string_len
test_data = test_string * repetitions
test_data = test_data[:buf_size] # Ensure it fits exactly in buffer
host_buf = ctypes.create_string_buffer(test_data, buf_size)
# Copy test data to CUDA buffer
cuda.cuMemcpyHtoDAsync(buffers[i], host_buf, buf_size, 0)
cuda.cuStreamSynchronize(0)
# Set up IOParams for this operation
io_params[i].mode = cufile.BatchMode.BATCH # Batch mode
io_params[i].fh = handle
io_params[i].opcode = cufile.Opcode.WRITE # Write opcode
io_params[i].cookie = i # Use index as cookie for identification
io_params[i].u.batch.dev_ptr_base = int(buffers[i])
io_params[i].u.batch.file_offset = i * buf_size # Sequential file offsets
io_params[i].u.batch.dev_ptr_offset = 0
io_params[i].u.batch.size_ = buf_size
# Submit batch write operations
cufile.batch_io_submit(batch_handle, num_operations, io_params.ptr, 0)
# Get batch status
min_nr = num_operations # Wait for all operations to complete
nr_completed = ctypes.c_uint(num_operations) # Initialize to max operations posted
timeout = ctypes.c_int(5000) # 5 second timeout
cufile.batch_io_get_status(
batch_handle, min_nr, ctypes.addressof(nr_completed), io_events.ptr, ctypes.addressof(timeout)
)
# Verify all operations completed successfully
assert nr_completed.value == num_operations, f"Expected {num_operations} operations, got {nr_completed.value}"
# Collect all returned cookies
returned_cookies = set()
for i in range(num_operations):
assert io_events[i].status == cufile.Status.COMPLETE, (
f"Operation {i} failed with status {io_events[i].status}"
)
assert io_events[i].ret == buf_size, f"Expected {buf_size} bytes, got {io_events[i].ret} for operation {i}"
returned_cookies.add(io_events[i].cookie)