Repository navigation
Expand file tree
/
Copy pathcudagraph_topology.cpp
More file actions
2894 lines (2584 loc) · 129 KB
/
Copy pathcudagraph_topology.cpp
File metadata and controls
2894 lines (2584 loc) · 129 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: Apache-2.0
*/
/*
Reproducer for the CUDA graph topology / lifecycle investigation tracked in
NVIDIA/cudnn-frontend#186.
Run it with:
bin/samples "[cudagraph_186]" -s
bin/samples "[cudagraph_186_multidevice]" -s # needs 2 visible devices
This file deliberately does not assert a fixed number of backend root or kernel
nodes. It dumps what the driver reports for each encapsulation layer and only
compares layers relatively (for example: "the caller parent adds exactly one
more child graph level than the frontend graph it embeds").
Paths covered (see the execution plan for #186):
P0 plain execution of the same plan (numerical baseline)
P1 current frontend populate_cuda_graph -> instantiate -> launch
P2 P1's frontend graph embedded as the child of a caller-owned parent graph
P3 direct population of an empty caller graph (populate_cuda_graph_direct)
P4 frontend auxiliary memcpy node plus the backend graph (SDPA bwd + alibi)
Correctness / lifecycle matrix covered: G01..G10.
Set CUDNN186_LOG=<path> to also append every printed line to a raw log file.
*/
#include "../utils/helpers.h"
#include <catch2/catch_test_macros.hpp>
#include <cuda_runtime_api.h>
#include <cudnn_frontend.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <unistd.h>
#endif
namespace fe = cudnn_frontend;
std::shared_ptr<fe::graph::Graph>
create_sdpa_backward_graph(int64_t const b,
int64_t const h_q,
int64_t const h_k,
int64_t const h_v,
int64_t const s_q,
int64_t const s_kv,
int64_t const d_qk,
int64_t const d_v,
float const attn_scale,
bool const generate_stats,
bool const causal_mask,
bool const alibi_mask,
bool const padding_mask,
bool has_attn_bias,
bool is_deterministic);
// Graph builders already defined by other translation units of the same
// `samples` binary. Reused here so this reproducer exercises the same frontend
// graphs as the shipped samples instead of a private look-alike.
std::shared_ptr<fe::graph::Graph>
create_sdpa_forward_graph(int64_t const b,
int64_t const h_q,
int64_t const h_k,
int64_t const h_v,
int64_t const s_q,
int64_t const s_kv,
int64_t const d_qk,
int64_t const d_v,
float const attn_scale,
bool const generate_stats,
bool const causal_mask,
bool const padding_mask);
namespace {
// ===========================================================================
// Evidence logging
// ===========================================================================
std::ofstream &
evidence_file() {
static std::ofstream file = []() -> std::ofstream {
char const *path = fe::get_environment("CUDNN186_LOG");
if (path == nullptr || path[0] == '\0') {
return std::ofstream();
}
return std::ofstream(path, std::ios::app);
}();
return file;
}
void
ev(std::string const &line) {
std::cout << line << '\n';
auto &file = evidence_file();
if (file.is_open()) {
file << line << '\n';
file.flush();
}
}
void
ev_header(std::string const &title) {
ev("");
ev("[186] ==================== " + title + " ====================");
}
std::string
fmt(double value, int precision = 3) {
char buffer[64];
std::snprintf(buffer, sizeof(buffer), "%.*f", precision, value);
return std::string(buffer);
}
std::string
note_name(fe::BehaviorNote_t note) {
switch (note) {
case fe::BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API:
return "SUPPORTS_CUDA_GRAPH_NATIVE_API";
default:
return "OTHER";
}
}
size_t
host_rss_bytes() {
#if defined(__linux__)
std::ifstream statm("/proc/self/statm");
long total_pages = 0;
long rss_pages = 0;
if (!(statm >> total_pages >> rss_pages)) {
return 0;
}
(void)total_pages;
return static_cast<size_t>(rss_pages) * static_cast<size_t>(sysconf(_SC_PAGESIZE));
#else
return 0;
#endif
}
// Returns {free_bytes, total_bytes}.
std::pair<size_t, size_t>
device_memory() {
size_t free_bytes = 0;
size_t total_bytes = 0;
if (cudaMemGetInfo(&free_bytes, &total_bytes) != cudaSuccess) {
return {0, 0};
}
return {free_bytes, total_bytes};
}
// ===========================================================================
// CUDA graph topology dump
// ===========================================================================
char const *
node_type_name(cudaGraphNodeType type) {
switch (type) {
case cudaGraphNodeTypeKernel:
return "kernel";
case cudaGraphNodeTypeMemcpy:
return "memcpy";
case cudaGraphNodeTypeMemset:
return "memset";
case cudaGraphNodeTypeHost:
return "host";
case cudaGraphNodeTypeGraph:
return "child_graph";
case cudaGraphNodeTypeEmpty:
return "empty";
case cudaGraphNodeTypeWaitEvent:
return "wait_event";
case cudaGraphNodeTypeEventRecord:
return "event_record";
#if defined(CUDART_VERSION) && CUDART_VERSION >= 11040
case cudaGraphNodeTypeExtSemaphoreSignal:
return "ext_semaphore_signal";
case cudaGraphNodeTypeExtSemaphoreWait:
return "ext_semaphore_wait";
#endif
#if defined(CUDART_VERSION) && CUDART_VERSION >= 11020
case cudaGraphNodeTypeMemAlloc:
return "mem_alloc";
case cudaGraphNodeTypeMemFree:
return "mem_free";
#endif
#if defined(CUDART_VERSION) && CUDART_VERSION >= 12030
case cudaGraphNodeTypeConditional:
return "conditional";
#endif
default:
return "unknown";
}
}
struct TopoSummary {
std::string label;
size_t root_nodes = 0; // roots at the top level only
size_t top_level_nodes = 0; // nodes at the top level only
size_t total_nodes = 0; // recursive
size_t kernels = 0; // recursive
size_t memcpys = 0;
size_t memsets = 0;
size_t child_graphs = 0;
size_t empty_nodes = 0;
size_t other_nodes = 0;
int max_child_depth = 0; // 0 == no child graph node
std::vector<std::string> lines;
};
void
walk_graph(cudaGraph_t graph, std::string const &path, int depth, TopoSummary &summary) {
size_t node_count = 0;
if (cudaGraphGetNodes(graph, nullptr, &node_count) != cudaSuccess) {
summary.lines.push_back(path + ": <cudaGraphGetNodes failed>");
return;
}
std::vector<cudaGraphNode_t> nodes(node_count);
if (node_count > 0) {
if (cudaGraphGetNodes(graph, nodes.data(), &node_count) != cudaSuccess) {
summary.lines.push_back(path + ": <cudaGraphGetNodes(2) failed>");
return;
}
}
size_t root_count = 0;
if (cudaGraphGetRootNodes(graph, nullptr, &root_count) != cudaSuccess) {
summary.lines.push_back(path + ": <cudaGraphGetRootNodes failed>");
return;
}
if (depth == 0) {
summary.root_nodes = root_count;
summary.top_level_nodes = node_count;
}
summary.total_nodes += node_count;
summary.lines.push_back(path + ": nodes=" + std::to_string(node_count) + " roots=" + std::to_string(root_count));
std::unordered_map<cudaGraphNode_t, size_t> index_of;
for (size_t i = 0; i < node_count; ++i) {
index_of.emplace(nodes[i], i);
}
for (size_t i = 0; i < node_count; ++i) {
cudaGraphNodeType type = cudaGraphNodeTypeCount;
if (cudaGraphNodeGetType(nodes[i], &type) != cudaSuccess) {
continue;
}
switch (type) {
case cudaGraphNodeTypeKernel:
summary.kernels++;
break;
case cudaGraphNodeTypeMemcpy:
summary.memcpys++;
break;
case cudaGraphNodeTypeMemset:
summary.memsets++;
break;
case cudaGraphNodeTypeGraph:
summary.child_graphs++;
break;
case cudaGraphNodeTypeEmpty:
summary.empty_nodes++;
break;
default:
summary.other_nodes++;
break;
}
std::string dependents = "[";
size_t dependent_count = 0;
if (cudnn_frontend::detail::cuda_graph_node_get_dependent_nodes(nodes[i], nullptr, &dependent_count) ==
cudaSuccess) {
std::vector<cudaGraphNode_t> dependent_nodes(dependent_count);
if (dependent_count > 0 && cudnn_frontend::detail::cuda_graph_node_get_dependent_nodes(
nodes[i], dependent_nodes.data(), &dependent_count) == cudaSuccess) {
for (size_t d = 0; d < dependent_count; ++d) {
auto it = index_of.find(dependent_nodes[d]);
dependents +=
(it == index_of.end()) ? std::string("?") : (path + ".n" + std::to_string(it->second));
dependents += " ";
}
}
}
dependents += "]";
std::string dependencies = "[";
size_t dependency_count = 0;
if (cudnn_frontend::detail::cuda_graph_node_get_dependencies(nodes[i], nullptr, &dependency_count) ==
cudaSuccess) {
std::vector<cudaGraphNode_t> dependency_nodes(dependency_count);
if (dependency_count > 0 && cudnn_frontend::detail::cuda_graph_node_get_dependencies(
nodes[i], dependency_nodes.data(), &dependency_count) == cudaSuccess) {
for (size_t d = 0; d < dependency_count; ++d) {
auto it = index_of.find(dependency_nodes[d]);
dependencies +=
(it == index_of.end()) ? std::string("?") : (path + ".n" + std::to_string(it->second));
dependencies += " ";
}
}
}
dependencies += "]";
std::string const node_path = path + ".n" + std::to_string(i);
summary.lines.push_back(node_path + " type=" + node_type_name(type) + " dependencies=" + dependencies +
" dependents=" + dependents);
if (type == cudaGraphNodeTypeGraph) {
cudaGraph_t child = nullptr;
if (cudaGraphChildGraphNodeGetGraph(nodes[i], &child) == cudaSuccess) {
if (depth + 1 > summary.max_child_depth) {
summary.max_child_depth = depth + 1;
}
walk_graph(child, node_path + "/child", depth + 1, summary);
}
}
}
}
TopoSummary
analyze_graph(cudaGraph_t graph, std::string const &label) {
TopoSummary summary;
summary.label = label;
walk_graph(graph, "L0", 0, summary);
return summary;
}
void
print_topology(TopoSummary const &summary, bool print_nodes) {
ev("[186][TOPO] " + summary.label);
if (print_nodes) {
for (auto const &line : summary.lines) {
ev("[186][TOPO] " + line);
}
}
ev("[186][TOPO] " + summary.label + " SUMMARY root_nodes=" + std::to_string(summary.root_nodes) +
" top_level_nodes=" + std::to_string(summary.top_level_nodes) +
" recursive_nodes=" + std::to_string(summary.total_nodes) + " kernel_nodes=" + std::to_string(summary.kernels) +
" memcpy_nodes=" + std::to_string(summary.memcpys) + " memset_nodes=" + std::to_string(summary.memsets) +
" child_graph_nodes=" + std::to_string(summary.child_graphs) +
" empty_nodes=" + std::to_string(summary.empty_nodes) + " other_nodes=" + std::to_string(summary.other_nodes) +
" max_child_depth=" + std::to_string(summary.max_child_depth));
}
std::vector<cudaGraphNode_t>
top_level_nodes_of_type(cudaGraph_t graph, cudaGraphNodeType wanted) {
std::vector<cudaGraphNode_t> result;
size_t node_count = 0;
if (cudaGraphGetNodes(graph, nullptr, &node_count) != cudaSuccess || node_count == 0) {
return result;
}
std::vector<cudaGraphNode_t> nodes(node_count);
if (cudaGraphGetNodes(graph, nodes.data(), &node_count) != cudaSuccess) {
return result;
}
for (size_t i = 0; i < node_count; ++i) {
cudaGraphNodeType type = cudaGraphNodeTypeCount;
if (cudaGraphNodeGetType(nodes[i], &type) != cudaSuccess) {
continue;
}
if (type == wanted) {
result.push_back(nodes[i]);
}
}
return result;
}
// Returns the graph held by the first child graph node found at the top level,
// or nullptr. Inspection-only: the library never dispatches on this.
cudaGraph_t
first_child_graph(cudaGraph_t graph) {
auto nodes = top_level_nodes_of_type(graph, cudaGraphNodeTypeGraph);
if (nodes.empty()) {
return nullptr;
}
cudaGraph_t child = nullptr;
if (cudaGraphChildGraphNodeGetGraph(nodes[0], &child) != cudaSuccess) {
return nullptr;
}
return child;
}
size_t
count_nodes(cudaGraph_t graph) {
size_t node_count = 0;
if (cudaGraphGetNodes(graph, nullptr, &node_count) != cudaSuccess) {
return 0;
}
return node_count;
}
// ===========================================================================
// Plan preparation
// ===========================================================================
struct PlanStatus {
bool built = false;
bool native_api = false;
std::string reason;
};
PlanStatus
prepare_native_plan(std::shared_ptr<fe::graph::Graph> const &graph, cudnnHandle_t handle) {
PlanStatus status;
auto result = graph->validate();
if (result.is_bad()) {
status.reason = "validate(): " + result.get_message();
return status;
}
result = graph->build_operation_graph(handle);
if (result.is_bad()) {
status.reason = "build_operation_graph(): " + result.get_message();
return status;
}
result = graph->create_execution_plans({fe::HeurMode_t::A});
if (result.is_bad()) {
status.reason = "create_execution_plans(): " + result.get_message();
return status;
}
graph->select_behavior_notes({fe::BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API});
result = graph->check_support();
if (result.is_bad()) {
status.reason = "check_support(SUPPORTS_CUDA_GRAPH_NATIVE_API): " + result.get_message();
return status;
}
result = graph->build_plans();
if (result.is_bad()) {
status.reason = "build_plans(): " + result.get_message();
return status;
}
std::vector<fe::BehaviorNote_t> notes;
if (graph->get_behavior_notes(notes).is_good()) {
for (auto note : notes) {
if (note == fe::BehaviorNote_t::SUPPORTS_CUDA_GRAPH_NATIVE_API) {
status.native_api = true;
}
}
}
status.built = true;
status.reason = status.native_api ? "native CUDA graph API supported" : "plan built but native note absent";
return status;
}
void
print_plan_identity(std::shared_ptr<fe::graph::Graph> const &graph, std::string const &label) {
std::string candidate_name;
auto name_status = graph->get_plan_name(candidate_name);
std::string plan0_name;
auto plan0_status = graph->get_plan_name_at_index(0, plan0_name);
int64_t workspace_size = 0;
auto ws_status = graph->get_workspace_size(workspace_size);
std::vector<fe::BehaviorNote_t> notes;
auto notes_status = graph->get_behavior_notes_for_plan_at_index(0, notes);
std::string note_names;
for (auto note : notes) {
if (!note_names.empty()) {
note_names += ",";
}
note_names += note_name(note);
}
ev("[186][PLAN] " + label + " cudnn_version=" + std::to_string(cudnnGetVersion()) + " cudart_version=" +
std::to_string(cudnnGetCudartVersion()) + " plan_count=" + std::to_string(graph->get_execution_plan_count()) +
" candidate_plan_name=" + (name_status.is_good() ? candidate_name : std::string("<error>")) +
" plan0_name=" + (plan0_status.is_good() ? plan0_name : std::string("<error>")) +
" total_workspace_bytes=" + (ws_status.is_good() ? std::to_string(workspace_size) : std::string("<error>")) +
" plan0_behavior_notes=" + (notes_status.is_good() ? note_names : std::string("<error>")));
}
int64_t
workspace_size_of(std::shared_ptr<fe::graph::Graph> const &graph) {
int64_t size = 0;
auto status = graph->get_workspace_size(size);
REQUIRE(status.is_good());
return size;
}
// ---------------------------------------------------------------------------
// Direct-population facade.
//
// The opt-in direct entry points are added by the same change that adds this
// reproducer. Defining CUDNN186_BASELINE_ONLY builds the very same file against
// a tree that only has the shipping populate/update API, so a paired baseline
// can be produced from one source instead of a forked copy: the facade then
// routes to the wrapped path and reports direct population as unsupported.
// ---------------------------------------------------------------------------
#if defined(CUDNN186_BASELINE_ONLY)
constexpr bool kDirectPopulationSupported = false;
#else
constexpr bool kDirectPopulationSupported = true;
#endif
bool
direct_population_supported() {
return kDirectPopulationSupported;
}
std::string
direct_path_label() {
return kDirectPopulationSupported ? std::string("P3") : std::string("P3_absent_from_this_tree");
}
bool
direct_population_eligible(std::shared_ptr<fe::graph::Graph> const &graph) {
#if defined(CUDNN186_BASELINE_ONLY)
(void)graph;
return false;
#else
return graph->cuda_graph_direct_population_eligible();
#endif
}
fe::error_t
populate_graph(std::shared_ptr<fe::graph::Graph> const &graph,
cudnnHandle_t handle,
std::unordered_map<int64_t, void *> &variant_pack,
void *workspace,
cudaGraph_t target) {
#if defined(CUDNN186_BASELINE_ONLY)
return graph->populate_cuda_graph(handle, variant_pack, workspace, target);
#else
return graph->populate_cuda_graph_direct(handle, variant_pack, workspace, target);
#endif
}
fe::error_t
update_graph(std::shared_ptr<fe::graph::Graph> const &graph,
cudnnHandle_t handle,
std::unordered_map<int64_t, void *> &variant_pack,
void *workspace,
cudaGraph_t target) {
#if defined(CUDNN186_BASELINE_ONLY)
return graph->update_cuda_graph(handle, variant_pack, workspace, target);
#else
return graph->update_cuda_graph_direct(handle, variant_pack, workspace, target);
#endif
}
void
log_environment(std::string const &title) {
int device = 0;
cudaDeviceProp properties{};
int visible = 0;
CUDA_CHECK(cudaGetDevice(&device));
CUDA_CHECK(cudaGetDeviceProperties(&properties, device));
(void)cudaGetDeviceCount(&visible);
cudaUUID_t uuid = properties.uuid;
char uuid_string[64];
std::snprintf(uuid_string,
sizeof(uuid_string),
"GPU-%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
static_cast<unsigned>(uuid.bytes[0]),
static_cast<unsigned>(uuid.bytes[1]),
static_cast<unsigned>(uuid.bytes[2]),
static_cast<unsigned>(uuid.bytes[3]),
static_cast<unsigned>(uuid.bytes[4]),
static_cast<unsigned>(uuid.bytes[5]),
static_cast<unsigned>(uuid.bytes[6]),
static_cast<unsigned>(uuid.bytes[7]),
static_cast<unsigned>(uuid.bytes[8]),
static_cast<unsigned>(uuid.bytes[9]),
static_cast<unsigned>(uuid.bytes[10]),
static_cast<unsigned>(uuid.bytes[11]),
static_cast<unsigned>(uuid.bytes[12]),
static_cast<unsigned>(uuid.bytes[13]),
static_cast<unsigned>(uuid.bytes[14]),
static_cast<unsigned>(uuid.bytes[15]));
auto memory = device_memory();
ev_header(title);
ev("[186][ENV] cudnn_version=" + std::to_string(cudnnGetVersion()) +
" cudart_version=" + std::to_string(cudnnGetCudartVersion()) +
" compiled_cudart=" + std::to_string(CUDART_VERSION) + " device_index=" + std::to_string(device) +
" device_name=" + std::string(properties.name) + " device_uuid=" + std::string(uuid_string) +
" cc=" + std::to_string(properties.major) + "." + std::to_string(properties.minor) +
" visible_device_count=" + std::to_string(visible) + " mem_free_bytes=" + std::to_string(memory.first) +
" mem_total_bytes=" + std::to_string(memory.second) + " host_rss_bytes=" + std::to_string(host_rss_bytes()));
}
// ===========================================================================
// matmul + add fixture (same shape as the existing misc/cudagraphs.cpp)
// ===========================================================================
constexpr int64_t kUidA = 0;
constexpr int64_t kUidB = 1;
constexpr int64_t kUidC = 2;
constexpr int64_t kUidD = 3;
std::shared_ptr<fe::graph::Graph>
make_matmul_add_graph(int64_t b, int64_t m, int64_t n, int64_t k, float scale_value) {
auto graph = std::make_shared<fe::graph::Graph>();
graph->set_io_data_type(fe::DataType_t::HALF)
.set_intermediate_data_type(fe::DataType_t::FLOAT)
.set_compute_data_type(fe::DataType_t::FLOAT);
auto A = graph->tensor(
fe::graph::Tensor_attributes().set_name("A").set_dim({b, m, k}).set_stride({m * k, k, 1}).set_uid(kUidA));
auto scale_options = fe::graph::Pointwise_attributes().set_mode(fe::PointwiseMode_t::MUL);
auto S = graph->pointwise(A, graph->tensor(scale_value), scale_options);
S->set_data_type(fe::DataType_t::HALF);
auto B = graph->tensor(
fe::graph::Tensor_attributes().set_name("B").set_dim({b, k, n}).set_stride({n * k, n, 1}).set_uid(kUidB));
auto T = graph->matmul(S, B, fe::graph::Matmul_attributes());
auto C = graph->tensor(fe::graph::Tensor_attributes()
.set_name("C")
.set_dim({1, 1, 1})
.set_stride({1, 1, 1})
.set_is_pass_by_value(true)
.set_uid(kUidC));
auto add_options = fe::graph::Pointwise_attributes().set_mode(fe::PointwiseMode_t::ADD);
auto D = graph->pointwise(T, C, add_options);
D->set_output(true).set_uid(kUidD);
return graph;
}
// ===========================================================================
// Legacy Slice aliasing (a frontend/backend pair below cuDNN 9.22)
// ===========================================================================
constexpr int64_t kUidSliceX = 21;
constexpr int64_t kUidSliceY = 22;
constexpr int64_t kUidSliceZ = 23;
constexpr int64_t kUidSliceW = 24;
// Y = Slice(X)[:, 1:2, :], Z = Y @ W, all rank-3. When Slice cannot be
// expressed as a backend operation the frontend records a variant-pack
// replacement instead: Y has to be bound to X plus a byte offset, and the
// caller supplies the source pointer. Rank-3 on purpose: this is the shape the
// legacy lane builds on machines where a rank-2 slice feeding a pointwise has
// no engine at all (measured on cuDNN 9.21.1 / SM100), so the replacement is
// exercised rather than skipped.
std::shared_ptr<fe::graph::Graph>
make_slice_matmul_graph(int64_t b, int64_t s, int64_t d, int64_t n) {
auto graph = std::make_shared<fe::graph::Graph>();
graph->set_io_data_type(fe::DataType_t::HALF)
.set_intermediate_data_type(fe::DataType_t::FLOAT)
.set_compute_data_type(fe::DataType_t::FLOAT);
auto X = graph->tensor(
fe::graph::Tensor_attributes().set_name("X").set_dim({b, s, d}).set_stride({s * d, d, 1}).set_uid(kUidSliceX));
auto Y = graph->slice(X, fe::graph::Slice_attributes().set_slices({{0, b}, {1, 2}, {0, d}}));
Y->set_data_type(fe::DataType_t::HALF).set_uid(kUidSliceY);
auto W = graph->tensor(
fe::graph::Tensor_attributes().set_name("W").set_dim({b, d, n}).set_stride({d * n, n, 1}).set_uid(kUidSliceW));
auto Z = graph->matmul(Y, W, fe::graph::Matmul_attributes());
Z->set_data_type(fe::DataType_t::HALF).set_output(true).set_uid(kUidSliceZ);
return graph;
}
// Fill values are powers of two / small integers so that the expected result is
// exactly representable and can be compared without a tolerance.
class MatmulAddFixture {
public:
MatmulAddFixture(int64_t b,
int64_t m,
int64_t n,
int64_t k,
float scale,
half a_fill,
half b_fill,
half bias,
int64_t workspace_bytes,
half output_fill)
: k_(k),
scale_(scale),
a_fill_(a_fill),
b_fill_(b_fill),
bias_(bias),
a_(static_cast<size_t>(b * m * k), a_fill),
bmat_(static_cast<size_t>(b * k * n), b_fill),
d_(static_cast<size_t>(b * m * n), output_fill),
workspace_(static_cast<size_t>(std::max<int64_t>(workspace_bytes, 1))) {
variant_pack_ = {{kUidA, a_.devPtr}, {kUidB, bmat_.devPtr}, {kUidC, &bias_}, {kUidD, d_.devPtr}};
}
std::unordered_map<int64_t, void *> &
variant_pack() {
return variant_pack_;
}
half
expected() const {
return __float2half(scale_ * __half2float(a_fill_) * static_cast<float>(k_) * __half2float(b_fill_) +
__half2float(bias_));
}
std::vector<half>
read_output() const {
std::vector<half> host(d_.size);
CUDA_CHECK(cudaMemcpy(host.data(), d_.devPtr, sizeof(half) * d_.size, cudaMemcpyDeviceToHost));
return host;
}
bool
output_all_equal(half value) const {
for (auto element : read_output()) {
if (element != value) {
return false;
}
}
return true;
}
void *
output_ptr() const {
return d_.devPtr;
}
void *
workspace_ptr() const {
return workspace_.devPtr;
}
void
fill_output(half value) {
fillImage(d_.devPtr, d_.size, value);
}
int64_t
output_size() const {
return d_.size;
}
private:
int64_t k_ = 0;
float scale_ = 1.0f;
half a_fill_ = __float2half(0.f);
half b_fill_ = __float2half(0.f);
half bias_ = __float2half(0.f);
Surface<half> a_;
Surface<half> bmat_;
Surface<half> d_;
Surface<int8_t> workspace_;
std::unordered_map<int64_t, void *> variant_pack_;
};
// ===========================================================================
// SDPA forward + alibi fixture (the frontend auxiliary node case)
// ===========================================================================
// helpers.h' initImage() advances a file-static PRNG, so two fixtures built in
// the same process would otherwise hold different data. This fill depends only
// on (seed, index) and makes the two fixtures bitwise comparable.
void
fill_deterministic_half(half *device_ptr, size_t count, unsigned seed) {
std::vector<half> host(count);
unsigned state = seed;
for (size_t i = 0; i < count; ++i) {
state = (1103515245u * state + 12345u) & 0xffffffffu;
float v = (static_cast<float>(state) * 2.3283064e-10f) - 0.5f;
host[i] = cpu_float2half_rn(v);
}
CUDA_CHECK(cudaMemcpy(device_ptr, host.data(), sizeof(half) * count, cudaMemcpyHostToDevice));
CUDA_CHECK(cudaDeviceSynchronize());
}
constexpr int64_t kSdpaQ = 1;
constexpr int64_t kSdpaK = 2;
constexpr int64_t kSdpaV = 3;
constexpr int64_t kSdpaO = 4;
constexpr int64_t kSdpaStats = 5;
constexpr int64_t kSdpaDo = 101;
constexpr int64_t kSdpaDq = 102;
constexpr int64_t kSdpaDk = 103;
constexpr int64_t kSdpaDv = 104;
// A flash-attention forward graph with an alibi mask. The alibi slopes are not
// a caller-provided tensor: the frontend caches them and emits its own
// workspace memcpy node, which is exactly the auxiliary-node case P4/G06 needs.
std::shared_ptr<fe::graph::Graph>
make_sdpa_fwd_alibi_graph(int64_t b, int64_t h, int64_t s_q, int64_t s_kv, int64_t d, float attn_scale) {
auto graph = std::make_shared<fe::graph::Graph>();
graph->set_io_data_type(fe::DataType_t::HALF)
.set_intermediate_data_type(fe::DataType_t::FLOAT)
.set_compute_data_type(fe::DataType_t::FLOAT);
auto Q = graph->tensor(fe::graph::Tensor_attributes()
.set_name("Q")
.set_uid(kSdpaQ)
.set_dim({b, h, s_q, d})
.set_stride({h * s_q * d, s_q * d, d, 1}));
auto K = graph->tensor(fe::graph::Tensor_attributes()
.set_name("K")
.set_uid(kSdpaK)
.set_dim({b, h, s_kv, d})
.set_stride({h * s_kv * d, s_kv * d, d, 1}));
auto V = graph->tensor(fe::graph::Tensor_attributes()
.set_name("V")
.set_uid(kSdpaV)
.set_dim({b, h, s_kv, d})
.set_stride({h * s_kv * d, s_kv * d, d, 1}));
auto sdpa_options = fe::graph::SDPA_attributes()
.set_name("flash_attention_alibi")
.set_generate_stats(false)
.set_alibi_mask(true)
.set_diagonal_band_right_bound(0)
.set_attn_scale(attn_scale);
auto [O, Stats] = graph->sdpa(Q, K, V, sdpa_options);
(void)Stats;
O->set_output(true).set_dim({b, h, s_q, d}).set_stride({h * s_q * d, s_q * d, d, 1}).set_uid(kSdpaO);
return graph;
}
class SdpaFwdFixture {
public:
SdpaFwdFixture(int64_t b, int64_t h, int64_t s_q, int64_t s_kv, int64_t d, int64_t workspace_bytes)
: q_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
k_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
v_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
o_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
workspace_(static_cast<size_t>(std::max<int64_t>(workspace_bytes, 1))) {
fill_deterministic_half(q_.devPtr, q_.size, 11u);
fill_deterministic_half(k_.devPtr, k_.size, 22u);
fill_deterministic_half(v_.devPtr, v_.size, 33u);
variant_pack_ = {{kSdpaQ, q_.devPtr}, {kSdpaK, k_.devPtr}, {kSdpaV, v_.devPtr}, {kSdpaO, o_.devPtr}};
}
std::unordered_map<int64_t, void *> &
variant_pack() {
return variant_pack_;
}
void *
workspace_ptr() const {
return workspace_.devPtr;
}
std::vector<half>
read_output() const {
std::vector<half> host(o_.size);
CUDA_CHECK(cudaMemcpy(host.data(), o_.devPtr, sizeof(half) * o_.size, cudaMemcpyDeviceToHost));
return host;
}
void
reset_output() {
fillImage(o_.devPtr, o_.size, __float2half(0.f));
}
bool
output_is_all_zero() const {
for (auto element : read_output()) {
if (__half2float(element) != 0.0f) {
return false;
}
}
return true;
}
private:
Surface<half> q_;
Surface<half> k_;
Surface<half> v_;
Surface<half> o_;
Surface<int8_t> workspace_;
std::unordered_map<int64_t, void *> variant_pack_;
};
// Minimal SDPA backward variant pack plus a wrapped population, used only to
// count the frontend's own CUDA graph nodes for the eligibility discussion.
struct SdpaBwdProbe {
Surface<half> q_;
Surface<half> k_;
Surface<half> v_;
Surface<half> o_;
Surface<half> d_o_;
Surface<float> stats_;
Surface<half> d_q_;
Surface<half> d_k_;
Surface<half> d_v_;
Surface<int8_t> workspace_;
std::unordered_map<int64_t, void *> variant_pack_;
bool populated = false;
std::string populate_message = "<not attempted>";
size_t top_level_nodes = 0;
size_t memcpy_nodes = 0;
size_t memset_nodes = 0;
size_t child_graph_nodes = 0;
SdpaBwdProbe(int64_t b,
int64_t h,
int64_t s_q,
int64_t s_kv,
int64_t d,
int64_t workspace_bytes,
cudnnHandle_t handle,
std::shared_ptr<fe::graph::Graph> const &graph)
: q_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
k_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
v_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
o_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
d_o_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
stats_(static_cast<size_t>(b * h * s_q)),
d_q_(static_cast<size_t>(b * h * s_q * d), __float2half(0.f)),
d_k_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
d_v_(static_cast<size_t>(b * h * s_kv * d), __float2half(0.f)),
workspace_(static_cast<size_t>(std::max<int64_t>(workspace_bytes, 1))) {
fill_deterministic_half(q_.devPtr, q_.size, 11u);
fill_deterministic_half(k_.devPtr, k_.size, 22u);
fill_deterministic_half(v_.devPtr, v_.size, 33u);
fill_deterministic_half(o_.devPtr, o_.size, 44u);
fill_deterministic_half(d_o_.devPtr, d_o_.size, 55u);
variant_pack_ = {{kSdpaQ, q_.devPtr},
{kSdpaK, k_.devPtr},
{kSdpaV, v_.devPtr},
{kSdpaO, o_.devPtr},
{kSdpaDo, d_o_.devPtr},
{kSdpaStats, stats_.devPtr},
{kSdpaDq, d_q_.devPtr},
{kSdpaDk, d_k_.devPtr},
{kSdpaDv, d_v_.devPtr}};
cudaGraph_t populated_graph = nullptr;
if (cudaGraphCreate(&populated_graph, 0) != cudaSuccess) {
populate_message = "<cudaGraphCreate failed>";
return;
}
auto status = graph->populate_cuda_graph(handle, variant_pack_, workspace_.devPtr, populated_graph);
populated = status.is_good();
populate_message = status.get_message();
if (populated) {
top_level_nodes = count_nodes(populated_graph);
memcpy_nodes = top_level_nodes_of_type(populated_graph, cudaGraphNodeTypeMemcpy).size();
memset_nodes = top_level_nodes_of_type(populated_graph, cudaGraphNodeTypeMemset).size();
child_graph_nodes = top_level_nodes_of_type(populated_graph, cudaGraphNodeTypeGraph).size();
}
cudaGraphDestroy(populated_graph);
}
};
// ===========================================================================
// Timing helpers
// ===========================================================================
struct Distribution {
std::vector<double> samples_us;
void
add(double value) {
samples_us.push_back(value);
}
double
quantile(double q) const {
if (samples_us.empty()) {
return 0.0;
}
std::vector<double> sorted = samples_us;
std::sort(sorted.begin(), sorted.end());
size_t index = static_cast<size_t>(q * static_cast<double>(sorted.size() - 1));
return sorted[index];
}
double
median() const {
return quantile(0.5);
}
double
p90() const {
return quantile(0.9);
}
double
best() const {
return quantile(0.0);
}
size_t
size() const {
return samples_us.size();
}
};
void
report(char const *phase, std::string const &path, Distribution const &distribution, std::string const &mechanism) {