forked from NVIDIA/cuda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_graph_definition.py
More file actions
1296 lines (1014 loc) · 40 KB
/
Copy pathtest_graph_definition.py
File metadata and controls
1296 lines (1014 loc) · 40 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-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Tests for GraphDefinition topology, node types, instantiation, and execution."""
from collections.abc import Callable
from dataclasses import dataclass, field
import pytest
from helpers.graph_kernels import compile_common_kernels
from helpers.misc import try_create_condition
from cuda.core import Device, LaunchConfig
from cuda.core.graph import (
AllocNode,
ChildGraphNode,
ConditionalNode,
EmptyNode,
EventRecordNode,
EventWaitNode,
FreeNode,
GraphCompleteOptions,
GraphDebugPrintOptions,
GraphDefinition,
GraphNode,
HostCallbackNode,
IfElseNode,
IfNode,
KernelNode,
MemcpyNode,
MemsetNode,
SwitchNode,
WhileNode,
)
from cuda.core.typing import GraphConditionalType, GraphMemoryType
ALLOC_SIZE = 1024
def _skip_if_no_mempool():
if not Device(0).properties.memory_pools_supported:
pytest.skip("Device does not support mempool operations")
def _skip_if_no_managed_mempool():
_skip_if_no_mempool()
if not Device(0).properties.concurrent_managed_access:
pytest.skip("Device does not support managed memory pool operations")
def _has_node_get_params():
from cuda.core._utils.version import binding_version, driver_version
return driver_version() >= (13, 2, 0) and binding_version() >= (13, 2, 0)
_HAS_NODE_GET_PARAMS = _has_node_get_params()
def _bindings_major_version():
from cuda.core._utils.version import binding_version
return binding_version()[0]
_BINDINGS_MAJOR = _bindings_major_version()
# =============================================================================
# GraphSpec — representative graph topologies
# =============================================================================
@dataclass
class GraphSpec:
"""Describes a graph topology with expected structural properties."""
name: str
graph_definition: GraphDefinition
named_nodes: dict = field(default_factory=dict)
expected_edges: set = field(default_factory=set)
expected_pred: dict = field(default_factory=dict)
expected_succ: dict = field(default_factory=dict)
def _build_empty():
"""No nodes, no edges."""
return GraphSpec("empty", GraphDefinition())
def _build_single():
"""One alloc node, no edges."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
return GraphSpec(
"single",
g,
named_nodes={"a": a},
expected_edges=set(),
expected_pred={"a": set()},
expected_succ={"a": set()},
)
def _build_chain():
"""Linear chain: a -> b -> c."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
b = a.allocate(ALLOC_SIZE)
c = b.allocate(ALLOC_SIZE)
return GraphSpec(
"chain",
g,
named_nodes={"a": a, "b": b, "c": c},
expected_edges={("a", "b"), ("b", "c")},
expected_pred={"a": set(), "b": {"a"}, "c": {"b"}},
expected_succ={"a": {"b"}, "b": {"c"}, "c": set()},
)
def _build_fan_out():
"""One node feeds three: a -> {b, c, d}."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
b = a.allocate(ALLOC_SIZE)
c = a.allocate(ALLOC_SIZE)
d = a.allocate(ALLOC_SIZE)
return GraphSpec(
"fan_out",
g,
named_nodes={"a": a, "b": b, "c": c, "d": d},
expected_edges={("a", "b"), ("a", "c"), ("a", "d")},
expected_pred={"a": set(), "b": {"a"}, "c": {"a"}, "d": {"a"}},
expected_succ={"a": {"b", "c", "d"}, "b": set(), "c": set(), "d": set()},
)
def _build_fan_in():
"""Three entry nodes merge: {a, b, c} -> d (join)."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
b = g.allocate(ALLOC_SIZE)
c = g.allocate(ALLOC_SIZE)
d = g.join(a, b, c)
return GraphSpec(
"fan_in",
g,
named_nodes={"a": a, "b": b, "c": c, "d": d},
expected_edges={("a", "d"), ("b", "d"), ("c", "d")},
expected_pred={"a": set(), "b": set(), "c": set(), "d": {"a", "b", "c"}},
expected_succ={"a": {"d"}, "b": {"d"}, "c": {"d"}, "d": set()},
)
def _build_diamond():
"""Diamond: a -> {b, c} -> d (join)."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
b = a.allocate(ALLOC_SIZE)
c = a.allocate(ALLOC_SIZE)
d = b.join(c)
return GraphSpec(
"diamond",
g,
named_nodes={"a": a, "b": b, "c": c, "d": d},
expected_edges={("a", "b"), ("a", "c"), ("b", "d"), ("c", "d")},
expected_pred={"a": set(), "b": {"a"}, "c": {"a"}, "d": {"b", "c"}},
expected_succ={"a": {"b", "c"}, "b": {"d"}, "c": {"d"}, "d": set()},
)
def _build_disconnected():
"""Two independent entry nodes: a, b."""
g = GraphDefinition()
a = g.allocate(ALLOC_SIZE)
b = g.allocate(ALLOC_SIZE)
return GraphSpec(
"disconnected",
g,
named_nodes={"a": a, "b": b},
expected_edges=set(),
expected_pred={"a": set(), "b": set()},
expected_succ={"a": set(), "b": set()},
)
_ALL_BUILDERS = [
pytest.param(_build_empty, id="empty"),
pytest.param(_build_single, id="single"),
pytest.param(_build_chain, id="chain"),
pytest.param(_build_fan_out, id="fan_out"),
pytest.param(_build_fan_in, id="fan_in"),
pytest.param(_build_diamond, id="diamond"),
pytest.param(_build_disconnected, id="disconnected"),
]
_NONEMPTY_BUILDERS = [p for p in _ALL_BUILDERS if p.values[0] is not _build_empty]
@pytest.fixture(params=_ALL_BUILDERS)
def graph_spec(request, init_cuda):
if request.param is not _build_empty:
_skip_if_no_mempool()
return request.param()
@pytest.fixture(params=_NONEMPTY_BUILDERS)
def nonempty_graph_spec(request, init_cuda):
_skip_if_no_mempool()
return request.param()
# =============================================================================
# NodeSpec — representative node types
# =============================================================================
@dataclass
class NodeSpec:
"""Describes a node type with expected properties.
The builder returns (node, expected_attrs) where expected_attrs maps
property names to expected values. Callable values are treated as
predicates (e.g., ``lambda v: v != 0``).
"""
name: str
expected_class: type
expected_type_name: str
builder: Callable[[GraphDefinition], tuple[GraphNode, dict]]
reconstructed_class: type | None = None
needs_mempool: bool = True
@property
def roundtrip_class(self):
"""Class expected after reconstruction from the driver."""
return self.reconstructed_class or self.expected_class
def _build_empty_node(g):
a = g.allocate(ALLOC_SIZE)
b = g.allocate(ALLOC_SIZE)
return g.join(a, b), {}
def _build_kernel_node(g):
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=(2, 3, 1), block=(32, 4, 1), shmem_size=128)
entry = g.allocate(ALLOC_SIZE)
node = entry.launch(config, kernel)
return node, {
"grid": (2, 3, 1),
"block": (32, 4, 1),
"shmem_size": 128,
"kernel": kernel,
"config": config,
}
def _build_alloc_node(g):
device_id = Device().device_id
entry = g.allocate(ALLOC_SIZE)
node = entry.allocate(ALLOC_SIZE)
return node, {
"dptr": lambda v: v != 0,
"bytesize": ALLOC_SIZE,
"device_id": device_id,
"memory_type": "device",
"peer_access": (),
}
def _build_alloc_managed_node(g):
_skip_if_no_managed_mempool()
device_id = Device().device_id
entry = g.allocate(ALLOC_SIZE)
node = entry.allocate(ALLOC_SIZE, memory_type=GraphMemoryType.MANAGED)
return node, {
"dptr": lambda v: v != 0,
"bytesize": ALLOC_SIZE,
"device_id": device_id,
"memory_type": "managed",
"peer_access": (),
}
def _build_free_node(g):
alloc = g.allocate(ALLOC_SIZE)
node = alloc.deallocate(alloc.dptr)
return node, {
"dptr": alloc.dptr,
}
def _build_memset_node(g):
alloc = g.allocate(ALLOC_SIZE)
node = alloc.memset(alloc.dptr, 42, ALLOC_SIZE)
return node, {
"dptr": alloc.dptr,
"value": 42,
"element_size": 1,
"width": ALLOC_SIZE,
"height": 1,
"pitch": 0,
}
def _build_memset_node_u16(g):
alloc = g.allocate(ALLOC_SIZE)
node = alloc.memset(alloc.dptr, b"\xab\xcd", ALLOC_SIZE // 2)
return node, {
"dptr": alloc.dptr,
"value": int.from_bytes(b"\xab\xcd", byteorder="little"),
"element_size": 2,
"width": ALLOC_SIZE // 2,
"height": 1,
"pitch": 0,
}
def _build_memset_node_u32(g):
alloc = g.allocate(ALLOC_SIZE)
node = alloc.memset(alloc.dptr, b"\x01\x02\x03\x04", ALLOC_SIZE // 4)
return node, {
"dptr": alloc.dptr,
"value": int.from_bytes(b"\x01\x02\x03\x04", byteorder="little"),
"element_size": 4,
"width": ALLOC_SIZE // 4,
"height": 1,
"pitch": 0,
}
def _build_memset_node_2d(g):
rows = 4
cols = ALLOC_SIZE // rows
alloc = g.allocate(ALLOC_SIZE)
node = alloc.memset(alloc.dptr, 0xFF, cols, height=rows, pitch=cols)
return node, {
"dptr": alloc.dptr,
"value": 0xFF,
"element_size": 1,
"width": cols,
"height": rows,
"pitch": cols,
}
def _build_event_record_node(g):
event = Device().create_event()
entry = g.allocate(ALLOC_SIZE)
node = entry.record(event)
return node, {
"event": event,
}
def _build_event_wait_node(g):
event = Device().create_event()
entry = g.allocate(ALLOC_SIZE)
node = entry.wait(event)
return node, {
"event": event,
}
def _build_memcpy_node(g):
src_alloc = g.allocate(ALLOC_SIZE)
dst_alloc = g.allocate(ALLOC_SIZE)
dep = g.join(src_alloc, dst_alloc)
node = dep.memcpy(dst_alloc.dptr, src_alloc.dptr, ALLOC_SIZE)
return node, {
"dst": dst_alloc.dptr,
"src": src_alloc.dptr,
"size": ALLOC_SIZE,
}
def _build_host_callback_node(g):
def my_callback():
pass
node = g.callback(my_callback)
return node, {
"callback": lambda v: v is my_callback,
}
def _build_host_callback_cfunc_node(g):
import ctypes
CALLBACK = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
@CALLBACK
def noop(data):
pass
node = g.callback(noop)
return node, {}
def _build_child_graph_node(g):
child = GraphDefinition()
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=1, block=1)
child.launch(config, kernel)
child.launch(config, kernel)
node = g.embed(child)
return node, {
"child_graph": lambda v: isinstance(v, GraphDefinition) and len(v.nodes()) == 2,
}
def _build_if_then_node(g):
condition = try_create_condition(g)
node = g.if_then(condition)
return node, {
"condition": condition,
"cond_type": lambda v: isinstance(v, GraphConditionalType) and v == "if",
"branches": lambda v: isinstance(v, tuple) and len(v) == 1,
"then": lambda v: isinstance(v, GraphDefinition),
}
def _build_if_else_node(g):
condition = try_create_condition(g)
node = g.if_else(condition)
return node, {
"condition": condition,
"cond_type": lambda v: isinstance(v, GraphConditionalType) and v == "if",
"branches": lambda v: isinstance(v, tuple) and len(v) == 2,
"then": lambda v: isinstance(v, GraphDefinition),
"else_": lambda v: isinstance(v, GraphDefinition),
}
def _build_while_loop_node(g):
condition = try_create_condition(g)
node = g.while_loop(condition)
return node, {
"condition": condition,
"cond_type": lambda v: isinstance(v, GraphConditionalType) and v == "while",
"branches": lambda v: isinstance(v, tuple) and len(v) == 1,
"body": lambda v: isinstance(v, GraphDefinition),
}
def _build_switch_node(g):
condition = try_create_condition(g)
node = g.switch(condition, 3)
return node, {
"condition": condition,
"cond_type": lambda v: isinstance(v, GraphConditionalType) and v == "switch",
"branches": lambda v: isinstance(v, tuple) and len(v) == 3,
}
_NODE_SPECS = [
pytest.param(NodeSpec("empty", EmptyNode, "CU_GRAPH_NODE_TYPE_EMPTY", _build_empty_node), id="empty"),
pytest.param(NodeSpec("kernel", KernelNode, "CU_GRAPH_NODE_TYPE_KERNEL", _build_kernel_node), id="kernel"),
pytest.param(NodeSpec("alloc", AllocNode, "CU_GRAPH_NODE_TYPE_MEM_ALLOC", _build_alloc_node), id="alloc"),
pytest.param(
NodeSpec("alloc_managed", AllocNode, "CU_GRAPH_NODE_TYPE_MEM_ALLOC", _build_alloc_managed_node),
id="alloc_managed",
marks=pytest.mark.skipif(_BINDINGS_MAJOR < 13, reason="managed alloc requires CUDA 13.0+ bindings"),
),
pytest.param(NodeSpec("free", FreeNode, "CU_GRAPH_NODE_TYPE_MEM_FREE", _build_free_node), id="free"),
pytest.param(NodeSpec("memset", MemsetNode, "CU_GRAPH_NODE_TYPE_MEMSET", _build_memset_node), id="memset"),
pytest.param(
NodeSpec("memset_u16", MemsetNode, "CU_GRAPH_NODE_TYPE_MEMSET", _build_memset_node_u16), id="memset_u16"
),
pytest.param(
NodeSpec("memset_u32", MemsetNode, "CU_GRAPH_NODE_TYPE_MEMSET", _build_memset_node_u32), id="memset_u32"
),
pytest.param(NodeSpec("memset_2d", MemsetNode, "CU_GRAPH_NODE_TYPE_MEMSET", _build_memset_node_2d), id="memset_2d"),
pytest.param(
NodeSpec("memcpy", MemcpyNode, "CU_GRAPH_NODE_TYPE_MEMCPY", _build_memcpy_node),
id="memcpy",
),
pytest.param(
NodeSpec(
"child_graph", ChildGraphNode, "CU_GRAPH_NODE_TYPE_GRAPH", _build_child_graph_node, needs_mempool=False
),
id="child_graph",
),
pytest.param(
NodeSpec(
"host_callback", HostCallbackNode, "CU_GRAPH_NODE_TYPE_HOST", _build_host_callback_node, needs_mempool=False
),
id="host_callback",
),
pytest.param(
NodeSpec(
"host_callback_cfunc",
HostCallbackNode,
"CU_GRAPH_NODE_TYPE_HOST",
_build_host_callback_cfunc_node,
needs_mempool=False,
),
id="host_callback_cfunc",
),
pytest.param(
NodeSpec("event_record", EventRecordNode, "CU_GRAPH_NODE_TYPE_EVENT_RECORD", _build_event_record_node),
id="event_record",
),
pytest.param(
NodeSpec("event_wait", EventWaitNode, "CU_GRAPH_NODE_TYPE_WAIT_EVENT", _build_event_wait_node),
id="event_wait",
),
pytest.param(
NodeSpec(
"if_then",
IfNode,
"CU_GRAPH_NODE_TYPE_CONDITIONAL",
_build_if_then_node,
reconstructed_class=IfNode if _HAS_NODE_GET_PARAMS else ConditionalNode,
needs_mempool=False,
),
id="if_then",
),
pytest.param(
NodeSpec(
"if_else",
IfElseNode,
"CU_GRAPH_NODE_TYPE_CONDITIONAL",
_build_if_else_node,
reconstructed_class=IfElseNode if _HAS_NODE_GET_PARAMS else ConditionalNode,
needs_mempool=False,
),
id="if_else",
),
pytest.param(
NodeSpec(
"while_loop",
WhileNode,
"CU_GRAPH_NODE_TYPE_CONDITIONAL",
_build_while_loop_node,
reconstructed_class=WhileNode if _HAS_NODE_GET_PARAMS else ConditionalNode,
needs_mempool=False,
),
id="while_loop",
),
pytest.param(
NodeSpec(
"switch",
SwitchNode,
"CU_GRAPH_NODE_TYPE_CONDITIONAL",
_build_switch_node,
reconstructed_class=SwitchNode if _HAS_NODE_GET_PARAMS else ConditionalNode,
needs_mempool=False,
),
id="switch",
),
]
@pytest.fixture(params=_NODE_SPECS)
def node_spec(request, init_cuda):
spec = request.param
if spec.needs_mempool:
_skip_if_no_mempool()
g = GraphDefinition()
node, expected_attrs = spec.builder(g)
return spec, g, node, expected_attrs
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def sample_graphdef(init_cuda):
"""A sample GraphDefinition for standalone tests."""
return GraphDefinition()
@pytest.fixture
def dot_file(tmp_path):
"""Temporary DOT file path, cleaned up after test."""
path = tmp_path / "graph.dot"
yield path
path.unlink(missing_ok=True)
# =============================================================================
# Topology tests (parameterized over graph specs)
# =============================================================================
def test_node_count(graph_spec):
"""Graph contains the expected number of nodes."""
assert len(graph_spec.graph_definition.nodes()) == len(graph_spec.named_nodes)
def test_nodes_match(nonempty_graph_spec):
"""nodes() returns exactly the expected nodes."""
spec = nonempty_graph_spec
assert set(spec.graph_definition.nodes()) == set(spec.named_nodes.values())
def test_edges(graph_spec):
"""edges() returns exactly the expected edges."""
spec = graph_spec
node_to_name = {v: k for k, v in spec.named_nodes.items()}
actual = {(node_to_name[a], node_to_name[b]) for a, b in spec.graph_definition.edges()}
assert actual == spec.expected_edges
def test_pred(nonempty_graph_spec):
"""Each node has the expected predecessors."""
spec = nonempty_graph_spec
node_to_name = {v: k for k, v in spec.named_nodes.items()}
for name, node in spec.named_nodes.items():
actual = {node_to_name[p] for p in node.pred}
assert actual == spec.expected_pred[name], f"pred mismatch for node {name}"
def test_succ(nonempty_graph_spec):
"""Each node has the expected successors."""
spec = nonempty_graph_spec
node_to_name = {v: k for k, v in spec.named_nodes.items()}
for name, node in spec.named_nodes.items():
actual = {node_to_name[s] for s in node.succ}
assert actual == spec.expected_succ[name], f"succ mismatch for node {name}"
def test_node_graph_property(nonempty_graph_spec):
"""Every node's .graph property returns the parent GraphDefinition."""
spec = nonempty_graph_spec
for name, node in spec.named_nodes.items():
assert node.graph == spec.graph_definition, f"graph mismatch for node {name}"
# =============================================================================
# Node type tests (parameterized over node specs)
# =============================================================================
def test_node_isinstance(node_spec):
"""GraphNode is an instance of the expected subclass."""
spec, g, node, _ = node_spec
assert isinstance(node, spec.expected_class)
assert isinstance(node, GraphNode)
def test_node_type_property(node_spec):
"""Node.type returns the expected CUgraphNodeType."""
spec, g, node, _ = node_spec
assert node.type.name == spec.expected_type_name
def test_node_type_preserved_by_nodes(node_spec):
"""Node type is preserved when retrieved via graph_definition.nodes()."""
spec, g, node, _ = node_spec
all_nodes = g.nodes()
matched = [n for n in all_nodes if n == node]
assert len(matched) == 1
assert isinstance(matched[0], spec.roundtrip_class)
assert matched[0] is node
def test_node_type_preserved_by_pred_succ(node_spec):
"""Node type is preserved when retrieved via pred/succ traversal."""
spec, g, node, _ = node_spec
for predecessor in node.pred:
matched = [s for s in predecessor.succ if s == node]
assert len(matched) == 1
assert isinstance(matched[0], spec.roundtrip_class)
assert matched[0] is node
def test_node_attrs(node_spec):
"""Type-specific attributes have expected values after construction."""
spec, g, node, expected_attrs = node_spec
if not expected_attrs:
pytest.skip("no type-specific attributes")
for attr, expected in expected_attrs.items():
actual = getattr(node, attr)
if callable(expected):
assert expected(actual), f"{spec.name}.{attr}: check failed (got {actual})"
else:
assert actual == expected, f"{spec.name}.{attr}: expected {expected}, got {actual}"
def test_node_attrs_preserved_by_nodes(node_spec):
"""Type-specific attributes survive round-trip through graph_definition.nodes()."""
spec, g, node, expected_attrs = node_spec
if not expected_attrs:
pytest.skip("no type-specific attributes")
if spec.roundtrip_class != spec.expected_class:
pytest.skip("reconstructed type differs — attrs not preserved")
retrieved = next(n for n in g.nodes() if n == node)
for attr in expected_attrs:
assert getattr(retrieved, attr) == getattr(node, attr), f"{spec.name}.{attr} not preserved by nodes()"
def test_identity_preservation(init_cuda):
"""Round-trips through nodes(), edges(), and pred/succ return extant
objects rather than duplicates."""
g = GraphDefinition()
a = g.empty()
b = g.empty()
# nodes()
assert any(x is a for x in g.nodes())
assert any(x is b for x in g.nodes())
# succ/pred
a.succ = {b}
(b2,) = a.succ
assert b2 is b
(a2,) = b.pred
assert a2 is a
# edges()
((a2, b2),) = g.edges()
assert a2 is a
assert b2 is b
def test_registry_cleanup(init_cuda):
"""Node registry entries are removed on destroy() and graph teardown."""
import gc
from cuda.core.graph._graph_node import _node_registry
def registered(node):
return any(v is node for v in _node_registry.values())
gc.collect()
assert len(_node_registry) == 0
g = GraphDefinition()
a = g.empty()
b = g.empty()
c = g.empty()
assert len(_node_registry) == 3
assert registered(a)
assert registered(b)
assert registered(c)
a.destroy()
assert len(_node_registry) == 2
assert not registered(a)
assert registered(b)
assert registered(c)
del g
gc.collect()
assert len(_node_registry) == 2
assert registered(b)
assert registered(c)
b.destroy()
assert len(_node_registry) == 1
assert not registered(b)
assert registered(c)
del c
gc.collect()
assert len(_node_registry) == 0
# =============================================================================
# GraphDefinition basics
# =============================================================================
def test_graphdef_handle_valid(sample_graphdef):
"""GraphDefinition has a valid non-null handle."""
assert sample_graphdef.handle is not None
assert int(sample_graphdef.handle) != 0
def test_graphdef_entry_is_virtual(sample_graphdef):
"""Internal entry node is virtual (no pred/succ, type is None)."""
entry = sample_graphdef._entry
assert isinstance(entry, GraphNode)
assert entry.pred == set()
assert entry.succ == set()
assert entry.type is None
# =============================================================================
# Alloc/free API
# =============================================================================
def test_alloc_zero_size_fails(sample_graphdef):
"""Alloc with zero size raises error (CUDA limitation)."""
_skip_if_no_mempool()
from cuda.core._utils.cuda_utils import CUDAError
with pytest.raises(CUDAError):
sample_graphdef.allocate(0)
def test_free_creates_dependency(sample_graphdef):
"""Free node depends on its predecessor."""
_skip_if_no_mempool()
alloc = sample_graphdef.allocate(ALLOC_SIZE)
free = alloc.deallocate(alloc.dptr)
assert alloc in free.pred
def test_alloc_free_chain(sample_graphdef):
"""Alloc and free can be chained."""
_skip_if_no_mempool()
a1 = sample_graphdef.allocate(ALLOC_SIZE)
a2 = a1.allocate(ALLOC_SIZE)
f2 = a2.deallocate(a2.dptr)
f1 = f2.deallocate(a1.dptr)
assert a1 in a2.pred
assert a2 in f2.pred
assert f2 in f1.pred
# =============================================================================
# Allocation options (error cases, input variants, multi-GPU)
# =============================================================================
def test_alloc_memory_type_invalid(sample_graphdef):
"""Invalid memory type raises ValueError."""
with pytest.raises(ValueError, match="Invalid memory_type"):
sample_graphdef.allocate(ALLOC_SIZE, memory_type="invalid")
@pytest.mark.parametrize(
"device_spec",
[
pytest.param(lambda d: d.device_id, id="device_id"),
pytest.param(lambda d: d, id="Device_object"),
],
)
def test_alloc_device_option(sample_graphdef, device_spec):
"""Device can be specified as int or Device object."""
_skip_if_no_mempool()
device = Device()
node = sample_graphdef.allocate(ALLOC_SIZE, device=device_spec(device))
assert node.dptr != 0
def test_alloc_peer_access(mempool_device_x2):
"""AllocNode.peer_access reflects requested peers."""
d0, d1 = mempool_device_x2
g = GraphDefinition()
node = g.allocate(ALLOC_SIZE, device=d0.device_id, peer_access=[d1.device_id])
assert d1.device_id in node.peer_access
# =============================================================================
# Join API
# =============================================================================
@pytest.mark.parametrize("num_branches", [2, 3, 5])
def test_join_merges_branches(sample_graphdef, num_branches):
"""join() with multiple branches creates correct dependencies."""
_skip_if_no_mempool()
branches = [sample_graphdef.allocate(ALLOC_SIZE) for _ in range(num_branches)]
joined = sample_graphdef.join(*branches)
assert isinstance(joined, EmptyNode)
assert set(joined.pred) == set(branches)
# =============================================================================
# Kernel launch
# =============================================================================
def test_launch_creates_node(sample_graphdef):
"""launch() creates a KernelNode."""
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=1, block=1)
node = sample_graphdef.launch(config, kernel)
assert isinstance(node, KernelNode)
def test_launch_chain_dependencies(sample_graphdef):
"""Chained launches create correct dependencies."""
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=1, block=1)
n1 = sample_graphdef.launch(config, kernel)
n2 = n1.launch(config, kernel)
n3 = n2.launch(config, kernel)
assert n1 in n2.pred
assert n2 in n3.pred
assert n1 not in n3.pred
# =============================================================================
# Instantiation and execution
# =============================================================================
_SENTINEL_UPLOAD_STREAM = "USE_TEST_STREAM"
_INSTANTIATE_ONLY_OPTIONS = [
pytest.param({"no_arg": True}, id="no-options"),
pytest.param({"options": None}, id="none-options"),
pytest.param(
{"options": GraphCompleteOptions(auto_free_on_launch=True, use_node_priority=True)},
id="all-bool-flags",
),
]
_EXECUTE_OPTIONS = [
pytest.param({}, id="no-options"),
pytest.param({"options": GraphCompleteOptions(auto_free_on_launch=True)}, id="auto-free"),
pytest.param({"options": GraphCompleteOptions(use_node_priority=True)}, id="node-priority"),
pytest.param(
{"options": GraphCompleteOptions(upload_stream=_SENTINEL_UPLOAD_STREAM)},
id="upload-stream",
),
]
def _instantiate(graph_definition, kwargs, stream=None):
"""Call graph_definition.instantiate() with the given kwargs, resolving sentinels."""
if "no_arg" in kwargs:
return graph_definition.instantiate()
opts = kwargs.get("options")
if opts is not None and opts.upload_stream == _SENTINEL_UPLOAD_STREAM:
opts = GraphCompleteOptions(
auto_free_on_launch=opts.auto_free_on_launch,
upload_stream=stream,
device_launch=opts.device_launch,
use_node_priority=opts.use_node_priority,
)
return graph_definition.instantiate(options=opts)
def _instantiate_and_upload(graph_definition, kwargs, stream):
"""Instantiate and upload, handling upload_stream option."""
graph = _instantiate(graph_definition, kwargs, stream)
if not (kwargs.get("options") and kwargs["options"].upload_stream):
graph.upload(stream)
return graph
@pytest.mark.parametrize("inst_kwargs", _INSTANTIATE_ONLY_OPTIONS)
def test_instantiate_empty_graph(sample_graphdef, inst_kwargs):
"""Empty graph can be instantiated."""
graph = _instantiate(sample_graphdef, inst_kwargs)
assert graph is not None
@pytest.mark.parametrize("inst_kwargs", _INSTANTIATE_ONLY_OPTIONS)
def test_instantiate_with_nodes(sample_graphdef, inst_kwargs):
"""Graph with nodes can be instantiated."""
_skip_if_no_mempool()
sample_graphdef.allocate(ALLOC_SIZE)
sample_graphdef.allocate(ALLOC_SIZE)
graph = _instantiate(sample_graphdef, inst_kwargs)
assert graph is not None
@pytest.mark.skipif(not Device(0).properties.unified_addressing, reason="requires unified addressing")
def test_instantiate_and_execute_kernel_device_launch(sample_graphdef):
"""Kernel-only graph can be instantiated with device_launch flag."""
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=1, block=1)
sample_graphdef.launch(config, kernel)
opts = GraphCompleteOptions(device_launch=True)
graph = sample_graphdef.instantiate(options=opts)
stream = Device().create_stream()
graph.upload(stream)
graph.launch(stream)
stream.sync()
@pytest.mark.parametrize("inst_kwargs", _EXECUTE_OPTIONS)
def test_instantiate_and_execute_kernel(sample_graphdef, inst_kwargs):
"""Graph with kernel can be instantiated and executed."""
mod = compile_common_kernels()
kernel = mod.get_kernel("empty_kernel")
config = LaunchConfig(grid=1, block=1)
sample_graphdef.launch(config, kernel)
stream = Device().create_stream()
graph = _instantiate_and_upload(sample_graphdef, inst_kwargs, stream)
graph.launch(stream)
stream.sync()
@pytest.mark.parametrize("inst_kwargs", _EXECUTE_OPTIONS)
def test_instantiate_and_execute_alloc_free(sample_graphdef, inst_kwargs):
"""Graph with alloc/free can be executed."""
_skip_if_no_mempool()
alloc = sample_graphdef.allocate(ALLOC_SIZE)