Repository navigation
Expand file tree
/
Copy pathcuda_backend.cpp
More file actions
1561 lines (1419 loc) · 62.4 KB
/
Copy pathcuda_backend.cpp
File metadata and controls
1561 lines (1419 loc) · 62.4 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <c10/util/safe_numerics.h>
#include <executorch/extension/cuda/runtime_api.h>
#include <executorch/runtime/backend/interface.h>
#include <executorch/runtime/backend/options.h>
#include <executorch/runtime/core/error.h>
#include <executorch/runtime/core/evalue.h>
#include <executorch/runtime/core/exec_aten/util/scalar_type_util.h>
#include <executorch/runtime/core/exec_aten/util/tensor_util.h>
#include <cctype>
#include <cstdio>
#include <array>
#include <atomic>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// Include SlimTensor headers for CUDA backend
#include <executorch/backends/aoti/slim/c10/core/Device.h>
#include <executorch/backends/aoti/slim/c10/cuda/Exception.h>
#include <executorch/backends/aoti/slim/core/slim_tensor.h>
#include <executorch/backends/aoti/slim/core/storage.h>
#include <executorch/backends/aoti/slim/cuda/guard.h>
#include <executorch/backends/aoti/slim/factory/empty.h>
#include <executorch/backends/aoti/slim/factory/from_blob.h>
#include <executorch/backends/aoti/slim/util/array_ref_util.h>
#include <executorch/extension/cuda/caller_stream.h>
// Include our shim layer headers
#include <executorch/backends/aoti/aoti_delegate_handle.h>
#include <executorch/backends/aoti/utils.h>
#include <executorch/backends/cuda/runtime/cuda_allocator.h>
#include <executorch/backends/cuda/runtime/cuda_delegate_handle.h>
#include <executorch/backends/cuda/runtime/cuda_kv_cache.h>
#include <executorch/backends/cuda/runtime/cuda_mutable_state.h>
#include <executorch/backends/cuda/runtime/cuda_weight_cache.h>
#include <executorch/backends/cuda/runtime/platform/platform.h>
#include <executorch/backends/cuda/runtime/shims/memory.h>
#include <executorch/backends/cuda/runtime/utils.h>
#include <executorch/extension/llm/cache/cache_registry.h>
namespace executorch::backends::cuda {
using namespace std;
using namespace aoti;
using executorch::runtime::ArrayRef;
using executorch::runtime::BackendExecutionContext;
using executorch::runtime::BackendInitContext;
using executorch::runtime::BackendOption;
using executorch::runtime::BackendOptionContext;
using executorch::runtime::CompileSpec;
using executorch::runtime::DelegateHandle;
using executorch::runtime::Error;
using executorch::runtime::EValue;
using executorch::runtime::FreeableBuffer;
using executorch::runtime::kMaxOptionValueLength;
using executorch::runtime::NamedDataMap;
using executorch::runtime::Result;
using executorch::runtime::Span;
using executorch::runtime::etensor::Tensor;
// SlimTensor type aliases
using cuda::CudaGraphPhase;
using slim::SlimTensor;
using slim::c10::Device;
namespace {
constexpr char kSkipCopyOutputToCpuForMethod[] =
"skip_copy_output_to_cpu_for_method";
constexpr char kUseSharedCudaStream[] = "use_shared_cuda_stream";
constexpr char kEnableCudaGraphForMethod[] = "enable_cuda_graph_for_method";
constexpr int kCudaGraphWarmupSteps = 3;
constexpr char kWeightSharingAcrossMethods[] = "weight_sharing_across_methods";
} // anonymous namespace
// Advances the off-graph KV cache past a step's tokens. Every successful exit
// of execute() ends here, and only those: a run that failed never wrote its
// tokens, and committing them would desynchronise the cache's length from the
// history the kernels actually hold.
Error commit_offgraph_kv_step(CudaDelegateHandle* handle, int64_t width) {
if (handle->kv_cache == nullptr) {
return Error::Ok;
}
return handle->kv_cache->commit_step(width);
}
class ET_EXPERIMENTAL CudaBackend final
: public ::executorch::runtime::BackendInterface {
private:
// Trim leading/trailing whitespace from a view of the string.
static std::string_view trim(std::string_view s) {
size_t start = 0;
while (start < s.size() &&
std::isspace(static_cast<unsigned char>(s[start]))) {
++start;
}
size_t end = s.size();
while (end > start &&
std::isspace(static_cast<unsigned char>(s[end - 1]))) {
--end;
}
return s.substr(start, end - start);
}
// Check if method_name appears in a comma-separated list.
static bool method_in_csv(
const std::string& method_name,
const std::string& csv) {
size_t pos = 0;
while (pos <= csv.size()) {
const size_t comma = csv.find(',', pos);
const std::string_view token =
trim(std::string_view(csv).substr(pos, comma - pos));
if (!token.empty() && token == method_name) {
return true;
}
if (comma == std::string::npos) {
break;
}
pos = comma + 1;
}
return false;
}
void set_cuda_graph_method(
const std::array<char, kMaxOptionValueLength>& raw) {
std::lock_guard<std::mutex> guard(cuda_graph_method_mutex_);
cuda_graph_method_ = std::string(raw.data());
}
bool should_use_cuda_graph_for_method(const std::string& method_name) const {
if (method_name.empty()) {
return false;
}
std::lock_guard<std::mutex> guard(cuda_graph_method_mutex_);
return method_in_csv(method_name, cuda_graph_method_);
}
// Enable the legacy dense-blob per-FQN cache. New FQN artifacts use
// their FQN-addressed data keys automatically.
void set_weight_sharing_across_methods(bool enabled) {
weight_sharing_across_methods_.store(enabled, std::memory_order_relaxed);
}
bool is_weight_sharing_across_methods_enabled() const {
return weight_sharing_across_methods_.load(std::memory_order_relaxed);
}
Error load_function_pointers_into_handle(
void* so_handle,
cuda::CudaDelegateHandle* handle) const {
#define LOAD_SYMBOL(member, name) \
do { \
auto symbol_res = get_function(so_handle, #name); \
if (!symbol_res.ok()) { \
return symbol_res.error(); \
} \
handle->member = reinterpret_cast<name##Func>(symbol_res.get()); \
} while (0)
LOAD_SYMBOL(create_with_device, AOTInductorModelContainerCreateWithDevice);
LOAD_SYMBOL(delete_container, AOTInductorModelContainerDelete);
LOAD_SYMBOL(get_num_inputs, AOTInductorModelContainerGetNumInputs);
LOAD_SYMBOL(get_num_outputs, AOTInductorModelContainerGetNumOutputs);
LOAD_SYMBOL(run, AOTInductorModelContainerRun);
#undef LOAD_SYMBOL
auto symbol_res =
get_function(so_handle, "AOTInductorModelUpdateConstantsFromBlob");
if (symbol_res.ok()) {
handle->update_constants_from_blob =
reinterpret_cast<AOTInductorModelUpdateConstantsFromBlobFunc>(
symbol_res.get());
} else {
ET_LOG(
Info,
"Failed to load AOTInductorModelUpdateConstantsFromBlob. This .so is probably compiled on an old version of torch (<2.9.0)");
}
// Load constant management symbols (optional — needed for cross-method
// buffer sharing). These are available in torch >= 2.6.
#define LOAD_OPTIONAL_SYMBOL(member, name) \
do { \
auto res = get_function(so_handle, #name); \
handle->member = \
res.ok() ? reinterpret_cast<name##Func>(res.get()) : nullptr; \
} while (0)
LOAD_OPTIONAL_SYMBOL(
get_num_constants, AOTInductorModelContainerGetNumConstants);
LOAD_OPTIONAL_SYMBOL(
get_constant_name, AOTInductorModelContainerGetConstantName);
LOAD_OPTIONAL_SYMBOL(
get_constant_original_fqn,
AOTInductorModelContainerGetConstantOriginalFQN);
LOAD_OPTIONAL_SYMBOL(
get_constant_dtype, AOTInductorModelContainerGetConstantDtype);
LOAD_OPTIONAL_SYMBOL(
get_constant_data_size, AOTInductorModelContainerGetConstantDataSize);
LOAD_OPTIONAL_SYMBOL(
extract_constants_map, AOTInductorModelContainerExtractConstantsMap);
LOAD_OPTIONAL_SYMBOL(
update_user_managed_constant_buffer_pairs,
AOTInductorModelContainerUpdateUserManagedConstantBufferPairs);
#undef LOAD_OPTIONAL_SYMBOL
return Error::Ok;
}
public:
bool is_available() const override {
return 1;
}
Error set_option(
ET_UNUSED BackendOptionContext& context,
const executorch::runtime::Span<BackendOption>& backend_options)
override {
for (const auto& option : backend_options) {
if (std::strcmp(option.key, kSkipCopyOutputToCpuForMethod) == 0) {
// Deprecated, no-op option. CUDA delegate IO is now GPU-resident under
// device memory planning, and host<->device transfers are handled by
// graph-level et_copy ops. To skip those copies, export the .pte with
// ExecutorchBackendConfig.propagate_device_config =
// PropagateDeviceConfig( skip_d2h_for_method_outputs=...,
// skip_h2d_for_method_inputs=...).
ET_LOG(
Info,
"Runtime backend option '%s' is DEPRECATED and no longer has any "
"effect; ignoring it.",
kSkipCopyOutputToCpuForMethod);
} else if (std::strcmp(option.key, kUseSharedCudaStream) == 0) {
// Refused rather than ignored: this option was the only thing ordering
// methods driven from different threads, so silently dropping it would
// give such a caller unordered device work and wrong results. Methods
// now run on the calling thread's stream, which orders methods called
// from one thread but not across threads; a caller that needs that must
// order the calls itself.
if (auto* val = std::get_if<bool>(&option.value)) {
if (*val) {
ET_LOG(
Error,
"Option %s is deprecated and no longer orders methods across "
"threads. See the comment at this check for what to do instead.",
kUseSharedCudaStream);
return Error::NotSupported;
}
} else {
ET_LOG(Error, "Option %s must be a boolean.", kUseSharedCudaStream);
return Error::InvalidArgument;
}
} else if (std::strcmp(option.key, kWeightSharingAcrossMethods) == 0) {
if (auto* val = std::get_if<bool>(&option.value)) {
set_weight_sharing_across_methods(*val);
} else {
ET_LOG(
Error,
"Option %s must be a boolean.",
kWeightSharingAcrossMethods);
return Error::InvalidArgument;
}
} else if (std::strcmp(option.key, kEnableCudaGraphForMethod) == 0) {
#if defined(EXECUTORCH_USE_HIP)
// HIP ignores the graph-instantiation flag required by this path.
ET_LOG(
Error,
"Option %s is not supported on ROCm: HIP ignores graph "
"instantiation flags.",
kEnableCudaGraphForMethod);
return Error::NotSupported;
#else
if (auto* val = std::get_if<std::array<char, kMaxOptionValueLength>>(
&option.value)) {
set_cuda_graph_method(*val);
} else {
ET_LOG(
Error,
"Option %s must be a method name string.",
kEnableCudaGraphForMethod);
return Error::InvalidArgument;
}
#endif
}
}
return Error::Ok;
}
Error get_option(
ET_UNUSED BackendOptionContext& context,
ET_UNUSED executorch::runtime::Span<BackendOption>& backend_options)
override {
return Error::Ok;
}
// Once per loaded binary blob
Result<DelegateHandle*> init(
BackendInitContext& context,
FreeableBuffer* processed, // This will be a empty buffer
ArrayRef<CompileSpec> compile_specs // This will be my empty list
) const override {
std::string method_name;
std::optional<OffGraphKVStepWidth> kv_step_width;
for (const CompileSpec& spec : compile_specs) {
if (std::strcmp(spec.key, kOffGraphKVStepWidthSpec) == 0) {
auto parsed = parse_offgraph_kv_step_width(std::string_view(
static_cast<const char*>(spec.value.buffer), spec.value.nbytes));
ET_CHECK_OK_OR_RETURN_ERROR(parsed.error());
kv_step_width = parsed.get();
}
if (std::strcmp(spec.key, "method_name") == 0) {
method_name.assign(
static_cast<const char*>(spec.value.buffer),
spec.value.nbytes); // no nullptr guarantee, so pass size
}
}
std::string so_blob_key;
std::string weights_blob_key;
CudaWeightCache::Metadata fqn_weights;
const bool has_fqn_weights =
CudaWeightCache::is_serialized(processed->data(), processed->size());
if (has_fqn_weights) {
ET_CHECK_OK_OR_RETURN_ERROR(
CudaWeightCache::parse(
processed->data(), processed->size(), fqn_weights),
"Malformed CUDA FQN weight metadata");
size_t variant_index = 0;
bool uses_ptx_fallback = false;
uint32_t current_sm = 0;
if (!(fqn_weights.variants.size() == 1 &&
fqn_weights.variants[0].target_sm == 0)) {
#if defined(EXECUTORCH_USE_HIP)
ET_LOG(
Error,
"Multi-SM CUDA AOTI metadata is not supported by the ROCm runtime");
return Error::NotSupported;
#else
int device_index = 0;
cudaDeviceProp device_properties{};
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaGetDevice(&device_index));
ET_CUDA_CHECK_OR_RETURN_ERROR(
cudaGetDeviceProperties(&device_properties, device_index));
current_sm = static_cast<uint32_t>(
device_properties.major * 10 + device_properties.minor);
ET_CHECK_OK_OR_RETURN_ERROR(
CudaWeightCache::select_variant(
fqn_weights, current_sm, variant_index, uses_ptx_fallback),
"Failed to select a CUDA AOTI variant for sm%u",
current_sm);
#endif
}
const auto& variant = fqn_weights.variants[variant_index];
so_blob_key = variant.so_blob_key;
if (variant.target_sm == 0) {
ET_LOG(Info, "Selected untargeted CUDA AOTI variant");
} else if (uses_ptx_fallback) {
ET_LOG(
Info,
"Selected sm%u CUDA AOTI PTX fallback (compute_%u) for sm%u",
variant.target_sm,
variant.ptx_compute,
current_sm);
} else {
ET_LOG(
Info, "Selected native sm%u CUDA AOTI variant", variant.target_sm);
}
} else {
ET_CHECK_OK_OR_RETURN_ERROR(
executorch::backends::aoti::resolve_blob_keys(
processed, method_name, so_blob_key, weights_blob_key),
"Malformed named-data key payload");
}
const NamedDataMap* named_data_map = context.get_named_data_map();
auto aoti_dso_buffer = named_data_map->get_data(so_blob_key.c_str());
ET_CHECK_OR_RETURN_ERROR(
aoti_dso_buffer.ok(),
Internal,
"Failed to get data for key %s: 0x%x",
so_blob_key.c_str(),
static_cast<uint32_t>(aoti_dso_buffer.error()));
// Generate a unique temporary file path. so_blob_key already selected the
// blob above and is deliberately kept out of the filename: it can be an
// untrusted, variable-length payload key, so embedding it risks path
// traversal and cross-key collisions. Uniqueness comes from the pid
// (across processes) and an atomic counter (within a process, since two
// identical CUDA partitions would otherwise clobber each other's .so).
static std::atomic<uint64_t> so_file_counter{0};
filesystem::path temp_dir = filesystem::temp_directory_path();
filesystem::path so_path = temp_dir /
("executorch_cuda_" + to_string(get_process_id()) + "_" +
to_string(so_file_counter.fetch_add(1, std::memory_order_relaxed)) +
".so");
// Create a temporary file
ofstream outfile(so_path, ios::binary);
// Write the ELF buffer to the temporary file
ET_LOG(
Info,
"Writing %zu bytes to %s",
aoti_dso_buffer->size(),
so_path.c_str());
outfile.write(
static_cast<const char*>(aoti_dso_buffer->data()),
aoti_dso_buffer->size());
ET_CHECK_OR_RETURN_ERROR(
outfile, AccessFailed, "Failed to write to file %s", so_path.c_str());
// Finish writing the file to disk
outfile.close();
// Free the buffer immediately after writing to disk
aoti_dso_buffer->Free();
// Load the lib
Result<void*> lib_handle_res = load_library(so_path);
if (!lib_handle_res.ok()) {
return lib_handle_res.error();
}
void* lib_handle = lib_handle_res.get();
processed->Free();
// Create handle and load function pointers into it
cuda::CudaDelegateHandle* handle = new cuda::CudaDelegateHandle();
handle->so_handle = lib_handle;
handle->so_path = so_path.string();
handle->method_name = method_name;
// Load function pointers specific to this handle's shared library
ET_CHECK_OK_OR_RETURN_ERROR(
load_function_pointers_into_handle(lib_handle, handle));
AOTInductorModelContainerHandle container_handle = nullptr;
ET_CHECK_OK_OR_RETURN_ERROR(
handle->create_with_device(&container_handle, 1, "cuda", nullptr));
ET_LOG(Info, "container_handle = %p", container_handle);
handle->container_handle = container_handle;
// Runtime-owned off-graph buffers must capture their AOTI names before
// the serialized constants update installs the ordinary weight set.
//
// The cache is found by the key the runner published as a runtime spec.
// No key means an in-graph model, whose KV state is ordinary mutable
// buffers -- that is the whole of the off-graph/in-graph detection, and it
// needs nothing from the user.
//
// The key alone does not decide it, though: a program whose storage was
// lowered off-graph carries no bytes for it, so running one without a cache
// would hand its kernels unbound memory. That requirement is read from the
// program's own constants and checked whether or not a key was passed.
const char* cache_key = nullptr;
if (auto spec = context.get_runtime_spec<const char*>(
::executorch::extension::llm::cache::kCacheKeyOption);
spec.ok() && spec.get() != nullptr && *spec.get() != '\0') {
cache_key = spec.get();
}
const auto needs_offgraph_kv = requires_offgraph_kv_storage(*handle);
ET_CHECK_OK_OR_RETURN_ERROR(needs_offgraph_kv.error());
if (cache_key != nullptr) {
#if defined(EXECUTORCH_BUILD_EXTENSION_LLM)
ET_CHECK_OK_OR_RETURN_ERROR(
attach_offgraph_kv_cache(*handle, cache_key, kv_step_width));
#else
ET_LOG(
Error,
"init: an off-graph KV cache was supplied, but this CUDA backend was "
"built without EXECUTORCH_BUILD_EXTENSION_LLM");
return Error::NotSupported;
#endif
}
ET_CHECK_OR_RETURN_ERROR(
!needs_offgraph_kv.get() || handle->kv_cache != nullptr,
InvalidArgument,
"init: method '%s' keeps its KV cache off-graph but no cache was "
"installed under the '%s' backend option (a CUDA backend built without "
"EXECUTORCH_BUILD_EXTENSION_LLM cannot run it)",
method_name.c_str(),
::executorch::extension::llm::cache::kCacheKeyOption);
// Versioned artifacts load each (device, FQN) through the same process-wide
// cross-method cache model used by the legacy path. The payload only adds
// the tensor metadata needed to reconstruct independently named PTD blobs.
if (has_fqn_weights) {
ET_CHECK_OK_OR_RETURN_ERROR(
fqn_weight_cache_.load(handle, named_data_map, fqn_weights));
} else if (is_weight_sharing_across_methods_enabled()) {
ET_CHECK_OK_OR_RETURN_ERROR(load_constants_with_cache(
handle, named_data_map, method_name, weights_blob_key));
} else {
ET_CHECK_OK_OR_RETURN_ERROR(
load_constants_legacy(handle, named_data_map, weights_blob_key));
}
// Handles on one thread share that thread's stream, so one delegate's
// output is ordered against the next one's read, which a stream per handle
// left unordered. cudaStreamPerThread is a different stream on each host
// thread, so this orders delegates called from the same thread and not
// delegates called from different ones. The TensorRT delegate falls back to
// the same stream, in its executorch backend, so a split program on one
// thread is ordered too.
handle->cuda_stream = cudaStreamPerThread;
ET_LOG(
Info,
"Using the per-thread CUDA stream %p for method %s",
handle->get_cuda_stream(),
method_name.c_str());
// Initialize CUDA graph state if enabled for this method.
if (should_use_cuda_graph_for_method(method_name)) {
handle->cuda_graph_state.phase = CudaGraphPhase::Warmup;
handle->cuda_graph_state.warmup_remaining = kCudaGraphWarmupSteps;
ET_LOG(
Info,
"CUDA graph enabled for method '%s' (warmup=%d)",
method_name.c_str(),
kCudaGraphWarmupSteps);
}
mutable_state_note_handle(handle);
live_handles_.fetch_add(1, std::memory_order_acq_rel);
return (DelegateHandle*)handle; // Return the handle post-processing
}
// Once per execution
Error execute(
BackendExecutionContext& context,
DelegateHandle* handle_,
Span<EValue*> args) const override {
cuda::CudaDelegateHandle* handle = (cuda::CudaDelegateHandle*)handle_;
size_t n_inputs;
handle->get_num_inputs(handle->container_handle, &n_inputs);
size_t n_outputs;
handle->get_num_outputs(handle->container_handle, &n_outputs);
// Run on the caller-selected stream when one is active on this thread (e.g.
// a CUDA green-context stream), otherwise the per-thread stream. Every
// kernel and boundary copy reads getCurrentCUDAStream, so installing the
// choice here routes the whole execution; restore the prior selection on
// return so a caller stream does not linger for later work on this thread.
const std::optional<cudaStream_t> caller_stream =
executorch::extension::cuda::getCallerStream();
// Replaying a captured graph on a caller-provided stream is not itself a
// CUDA error, but the static buffers this path pins are shared by every
// replay, so two callers on two streams would race over them. Refused
// rather than synchronized, which predates this change.
ET_CHECK_OR_RETURN_ERROR(
!(caller_stream &&
handle->cuda_graph_state.phase != CudaGraphPhase::Disabled),
NotSupported,
"CUDA graph is not supported together with a caller-provided CUDA stream.");
// Snapshot the prior selection without creating one (peek, not get), so the
// restore is exact and we don't leak a stream just to snapshot.
std::optional<cudaStream_t> prev_stream;
if (caller_stream) {
prev_stream = peekCurrentCUDAStream(0);
}
setCurrentCUDAStream(caller_stream.value_or(handle->get_cuda_stream()), 0);
executorch::backends::aoti::ScopeGuard restore_stream([&]() noexcept {
if (!caller_stream) {
return;
}
if (prev_stream) {
setCurrentCUDAStream(*prev_stream, 0);
} else {
clearCurrentCUDAStream(0);
}
});
size_t n_io_sum = 0;
ET_CHECK_OR_RETURN_ERROR(
!c10::add_overflows(n_inputs, n_outputs, &n_io_sum) &&
n_io_sum == args.size(),
InvalidArgument,
"number of user input %zd and output %zd generated from AOT Inductor does not match ET runner's %zd. Exit.",
n_inputs,
n_outputs,
args.size())
// Verify device info on all memory-planned, ET-driven IO tensors.
// All input and output tensors should have device_type = CUDA, which
// is set during serialization by PropagateDevicePass based on the
// target_device compile spec from CudaPartitioner.
//
// Under device memory planning, these tensors are GPU-resident: their
// storage lives in a planned CUDA arena. The backend wraps them in place
// and performs no host<->device copies — graph-level et_copy ops handle
// any host<->device transfers outside the delegate.
for (size_t i = 0; i < n_inputs + n_outputs; i++) {
auto* tensor = &(args[i]->toTensor());
auto device_type = tensor->unsafeGetTensorImpl()->device_type();
ET_CHECK_OR_RETURN_ERROR(
device_type == executorch::runtime::etensor::DeviceType::CUDA,
InvalidArgument,
"Tensor %zu expected device_type=CUDA (1), got %d. "
"Device info may not be properly propagated from CudaPartitioner.",
i,
static_cast<int>(device_type));
// device_type above is only metadata. Also verify the storage actually
// lives in CUDA device memory, so a CUDA-typed tensor that is secretly
// backed by host memory is caught here instead of corrupting the run.
const void* data_ptr = tensor->const_data_ptr();
if (data_ptr != nullptr) {
cudaPointerAttributes attributes{};
const cudaError_t attr_err =
cudaPointerGetAttributes(&attributes, data_ptr);
ET_CHECK_OR_RETURN_ERROR(
attr_err == cudaSuccess &&
(attributes.type == cudaMemoryTypeDevice ||
attributes.type == cudaMemoryTypeManaged),
InvalidArgument,
"Tensor %zu has device_type=CUDA but its data pointer %p is not "
"backed by CUDA device memory (cudaPointerGetAttributes err=%d, "
"cudaMemoryType=%d).",
i,
data_ptr,
static_cast<int>(attr_err),
static_cast<int>(attributes.type));
}
}
// The cache has to grow, and its storage be rebound, before the compiled
// program reads it -- and nothing inside that program can call back out, so
// the step is driven from here rather than by the runner.
int64_t kv_step_width = 0;
if (handle->kv_cache != nullptr) {
const auto step_width = read_offgraph_kv_step_width(
handle->kv_step_width, Span<EValue*>(args.data(), n_inputs));
ET_CHECK_OK_OR_RETURN_ERROR(step_width.error());
kv_step_width = step_width.get();
// Growth is ordered on the stream this step runs on, which was just
// installed as current above.
const Result<cudaStream_t> step_stream = getCurrentCUDAStream(0);
ET_CHECK_OK_OR_RETURN_ERROR(step_stream.error());
ET_CHECK_OK_OR_RETURN_ERROR(
handle->kv_cache->prepare_step(kv_step_width, step_stream.get()));
ET_CHECK_OK_OR_RETURN_ERROR(handle->kv_cache->rebind_for_execute(handle));
}
ET_CHECK_OK_OR_RETURN_ERROR(mutable_state_rebind_for_execute(handle));
// ---------------------------------------------------------------
// CUDA graph REPLAY path — skip all tensor setup and just replay
// ---------------------------------------------------------------
if (handle->cuda_graph_state.phase == CudaGraphPhase::Replay) {
Result<cudaStream_t> csr = getCurrentCUDAStream(0);
ET_CHECK_OK_OR_RETURN_ERROR(csr.error());
cudaStream_t cs = csr.get();
// Copy new input data (GPU-resident) into static input buffers (D2D)
for (size_t i = 0; i < n_inputs; i++) {
auto* et_input = &(args[i]->toTensor());
ET_CHECK_OR_RETURN_ERROR(
et_input->nbytes() ==
handle->cuda_graph_state.static_input_nbytes[i],
InvalidArgument,
"CUDA graph replay: input %zu size mismatch (expected %zu, got %zu)",
i,
handle->cuda_graph_state.static_input_nbytes[i],
et_input->nbytes());
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaMemcpyAsync(
handle->cuda_graph_state.static_input_ptrs[i],
et_input->const_data_ptr(),
handle->cuda_graph_state.static_input_nbytes[i],
cudaMemcpyDeviceToDevice,
cs));
}
// Replay the captured graph
cudaError_t gerr =
cudaGraphLaunch(handle->cuda_graph_state.graph_exec, cs);
ET_CHECK_OR_RETURN_ERROR(
gerr == cudaSuccess,
Internal,
"cudaGraphLaunch failed: %s",
cudaGetErrorString(gerr));
// Copy outputs from static buffers into the planned GPU ET buffers (D2D)
for (size_t i = 0; i < n_outputs; i++) {
auto* et_output = &(args[i + n_inputs]->toTensor());
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaMemcpyAsync(
et_output->mutable_data_ptr(),
handle->cuda_graph_state.static_output_ptrs[i],
handle->cuda_graph_state.static_output_nbytes[i],
cudaMemcpyDeviceToDevice,
cs));
}
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaStreamSynchronize(cs));
return commit_offgraph_kv_step(handle, kv_step_width);
}
// ---------------------------------------------------------------
// Normal path (also used for WARMUP and CAPTURE phases)
// ---------------------------------------------------------------
bool is_capture_step =
(handle->cuda_graph_state.phase == CudaGraphPhase::Warmup &&
handle->cuda_graph_state.warmup_remaining == 0);
// Wrrap them as SlimTensors for AOTI execution without any host<->device
// copies.
std::vector<SlimTensor*> slim_inputs(n_inputs);
std::vector<SlimTensor*> slim_outputs(n_outputs);
// Undoes a capture attempt that an early return would otherwise abandon.
//
// The buffers this attempt pinned would otherwise stay in their vectors
// with the phase still at warmup and no steps left, so the next call
// captures again and appends a second set. Replay then reads the second set
// while the input copies target the first, and every execute returns
// whatever those buffers held at capture time, with nothing reporting an
// error.
//
// Ending the capture itself is a separate guard, declared after the tensor
// cleanup below so that it runs before it: freeing a device buffer on a
// still-capturing stream fails with invalid argument and leaks the block.
//
// Disarmed once the capture step has fully succeeded.
class CaptureGuard {
public:
~CaptureGuard() {
if (state_ == nullptr) {
return;
}
// Free what this attempt pinned and disable graphs for this method, so
// a capture that cannot succeed costs one error rather than one on
// every fourth call for the life of the process. Eager execution is
// correct, just slower.
for (void* ptr : state_->static_input_ptrs) {
(void)cudaFree(ptr);
}
state_->static_input_ptrs.clear();
state_->static_output_ptrs.clear();
state_->static_input_nbytes.clear();
state_->static_output_nbytes.clear();
// Same order as ~CudaGraphState: the exec depends on the graph.
if (state_->graph_exec != nullptr) {
(void)cudaGraphExecDestroy(state_->graph_exec);
state_->graph_exec = nullptr;
}
if (state_->graph != nullptr) {
(void)cudaGraphDestroy(state_->graph);
state_->graph = nullptr;
}
state_->phase = CudaGraphPhase::Disabled;
state_->warmup_remaining = 0;
(void)cudaGetLastError();
}
// Before capture begins. From here a failure still unwinds the pinned
// buffers.
void arm(cuda::CudaGraphState* state) {
state_ = state;
}
void disarm() {
state_ = nullptr;
}
private:
cuda::CudaGraphState* state_ = nullptr;
} capture_guard;
if (is_capture_step) {
capture_guard.arm(&handle->cuda_graph_state);
}
// Process input tensors: wrap the GPU-resident ETensor buffers directly.
for (size_t i = 0; i < n_inputs; i++) {
auto* et_input = &(args[i]->toTensor());
// CAPTURE step: allocate persistent static GPU buffers and seed them
// from the GPU-resident ET inputs (D2D).
if (is_capture_step) {
size_t nbytes = et_input->nbytes();
void* static_ptr = nullptr;
cudaError_t merr = cudaMalloc(&static_ptr, nbytes);
ET_CHECK_OR_RETURN_ERROR(
merr == cudaSuccess,
Internal,
"cudaMalloc for static input %zu failed: %s",
i,
cudaGetErrorString(merr));
// Tracked before the seeding copy, so a failed copy still unwinds
// through the guard instead of leaking this allocation.
handle->cuda_graph_state.static_input_ptrs.push_back(static_ptr);
handle->cuda_graph_state.static_input_nbytes.push_back(nbytes);
ET_CUDA_CHECK_OR_RETURN_ERROR(cudaMemcpy(
static_ptr,
et_input->const_data_ptr(),
nbytes,
cudaMemcpyDeviceToDevice));
slim_inputs[i] = make_slimtensor_from_blob_with_etensor_metadata(
static_ptr, et_input);
continue;
}
// Normal path: wrap the GPU buffer in place (zero-copy, non-owning).
slim_inputs[i] = make_slimtensor_from_blob_with_etensor_metadata(
const_cast<void*>(et_input->const_data_ptr()), et_input);
}
// Process output tensors: wrap the GPU-resident ET output buffers as
// non-owning SlimTensors so AOTI can write into the planned slot directly
// when it does not allocate its own output. Save pre-run handles to detect
// when AOTI replaces them with its own allocation.
std::vector<SlimTensor*> pre_run_outputs(n_outputs, nullptr);
for (size_t i = 0; i < n_outputs; i++) {
auto* et_output = &(args[i + n_inputs]->toTensor());
slim_outputs[i] = make_slimtensor_from_blob_with_etensor_metadata(
const_cast<void*>(et_output->const_data_ptr()), et_output);
pre_run_outputs[i] = slim_outputs[i];
}
bool run_called = false;
// Scope guard: deletes any non-null slim_outputs on exit. Normal paths
// null entries as they take ownership, so the guard only fires on
// early-return error paths. Also cleans up inputs if run() was never
// called (run() steals them via internal RAII).
executorch::backends::aoti::ScopeGuard cleanup([&]() noexcept {
if (!run_called) {
delete_slimtensor_vector(slim_inputs);
}
for (size_t i = 0; i < slim_outputs.size(); i++) {
if (slim_outputs[i]) {
delete slim_outputs[i];
}
}
});
// Ends a capture that an early return would otherwise leave running.
// Declared after `cleanup` so it is destroyed before it: a device buffer
// freed on a still-capturing stream fails with invalid argument and leaks
// the block.
//
// Leaving the stream capturing matters because handles share the per-thread
// stream: the next delegate on this thread would have its kernels captured
// instead of run, and later synchronizes would fail.
class EndCaptureGuard {
public:
~EndCaptureGuard() {
if (stream_ == nullptr) {
return;
}
cudaGraph_t abandoned = nullptr;
if (cudaStreamEndCapture(stream_, &abandoned) == cudaSuccess) {
if (abandoned != nullptr) {
(void)cudaGraphDestroy(abandoned);
}
} else {
// Clears the sticky error so the next unrelated CUDA call on this
// thread does not inherit it. This clears whatever error is pending,
// not only the one from above.
(void)cudaGetLastError();
}
}
void arm(cudaStream_t stream) {
stream_ = stream;
}
void disarm() {
stream_ = nullptr;
}
private:
cudaStream_t stream_ = nullptr;
} end_capture_guard;
// Run the AOTI container.
// NOTE: run() steals input handles (RAII wraps them at the start of
// run_impl) and may replace output handles with its own.
Result<cudaStream_t> cuda_stream_ret = getCurrentCUDAStream(0);
ET_CHECK_OK_OR_RETURN_ERROR(cuda_stream_ret.error());
cudaStream_t cuda_stream = cuda_stream_ret.get();
if (is_capture_step) {
// ----- CUDA graph CAPTURE -----
ET_LOG(
Info,
"CUDA graph: beginning stream capture for '%s'",
handle->method_name.c_str());
cudaError_t cerr =
cudaStreamBeginCapture(cuda_stream, cudaStreamCaptureModeRelaxed);
ET_CHECK_OR_RETURN_ERROR(
cerr == cudaSuccess,
Internal,
"cudaStreamBeginCapture failed: %s",
cudaGetErrorString(cerr));
end_capture_guard.arm(cuda_stream);
}
AOTIRuntimeError error = handle->run(
handle->container_handle,
reinterpret_cast<Tensor**>(slim_inputs.data()),
n_inputs,
reinterpret_cast<Tensor**>(slim_outputs.data()),
n_outputs,
static_cast<void*>(cuda_stream),
nullptr);
run_called = true;
// Delete orphaned pre-created outputs that run() replaced.
// Must happen before the error check — if run() fails after
// replacing some outputs, the originals would otherwise leak.
for (size_t i = 0; i < n_outputs; i++) {
if (pre_run_outputs[i] != slim_outputs[i]) {
delete pre_run_outputs[i];
}
}
ET_CHECK_OR_RETURN_ERROR(
error == Error::Ok,
Internal,
"AOTInductorModelContainerRun failed with error code %d",
error);
if (is_capture_step) {
// End capture → instantiate graph
cudaError_t gerr =
cudaStreamEndCapture(cuda_stream, &handle->cuda_graph_state.graph);
// The stream has left capture either way, so the guard must not end it
// again; the state guard below still unwinds what the attempt pinned.
end_capture_guard.disarm();
ET_CHECK_OR_RETURN_ERROR(
gerr == cudaSuccess,
Internal,
"cudaStreamEndCapture failed: %s",
cudaGetErrorString(gerr));
gerr = cudaGraphInstantiate(
&handle->cuda_graph_state.graph_exec,
handle->cuda_graph_state.graph,
cudaGraphInstantiateFlagAutoFreeOnLaunch);
ET_CHECK_OR_RETURN_ERROR(
gerr == cudaSuccess,
Internal,
"cudaGraphInstantiate failed: %s",
cudaGetErrorString(gerr));
// Record static output pointers (stable under graph replay). Releasing
// them from slim_outputs here, before the copies below, keeps the cleanup
// guard from deleting buffers the AOTI runtime owns if one of those
// copies fails.
for (size_t i = 0; i < n_outputs; i++) {
SlimTensor* out = slim_outputs[i];
handle->cuda_graph_state.static_output_ptrs.push_back(out->data_ptr());
handle->cuda_graph_state.static_output_nbytes.push_back(out->nbytes());
slim_outputs[i] = nullptr;
}
handle->cuda_graph_state.phase = CudaGraphPhase::Replay;
ET_LOG(
Info,
"CUDA graph: captured and instantiated for '%s'",
handle->method_name.c_str());
// Replay once to actually produce output (capture doesn't execute)
gerr = cudaGraphLaunch(handle->cuda_graph_state.graph_exec, cuda_stream);
ET_CHECK_OR_RETURN_ERROR(
gerr == cudaSuccess,
Internal,
"cudaGraphLaunch (first replay) failed: %s",
cudaGetErrorString(gerr));
// Copy capture-step outputs into the planned GPU ET buffers (D2D).