forked from hw-native-sys/simpler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice_runner_base.cpp
More file actions
1800 lines (1639 loc) · 75.3 KB
/
Copy pathdevice_runner_base.cpp
File metadata and controls
1800 lines (1639 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) PyPTO Contributors.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
* -----------------------------------------------------------------------------------------------------------
*/
/**
* `DeviceRunnerBase` — onboard host lifecycle shared by a2a3 and a5.
*
* Constructor wires the three arenas to call back into `mem_alloc_` via
* the static trampolines declared in the header. Per-region commit is
* still driven by the subclass's `setup_static_arena`.
*
* Shared lifecycle methods own runner-level resources; architecture-specific
* launch, completion, and reset behavior remains in each DeviceRunner.
*/
#include "device_runner_base.h"
#include <runtime/rt.h>
#include <acl/acl.h>
#include <dlfcn.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "callable.h"
#include "callable_protocol.h"
#include "call_config.h"
#include "chip_callable_layout.h"
#include "common/core_type.h"
#include "common/host_api.h"
#include "common/platform_config.h"
#include "common/unified_log.h"
#include "host/acl_error_log.h"
#include "host/host_phase_records_artifact.h"
#include "host/raii_scope_guard.h"
#include "host_log.h"
#include "platform_comm/comm.h"
#include "pto_runtime_c_api.h"
#include "task_args.h"
#include "utils/elf_build_id.h"
// `runtime.h` (pulled in via `device_runner_helpers.h` in the base header)
// supplies the per-arch `Handshake` + `Runtime` types used by
// `print_handshake_results` / `bind_callable_to_runtime` /
// `prepare_orch_so`.
// Implemented by each runtime's host part (runtime_maker.cpp). Reports the
// AICPU entry symbols this runtime exports beyond the base {exec, init} set, so
// the common AICPU loader carries no runtime-specific symbol knowledge. TMARB
// returns simpler_aicpu_register_callable; host_build_graph returns none.
extern "C" const char *const *runtime_extra_aicpu_symbols(size_t *count);
namespace {
HostRuntimeTimeoutConfig resolve_onboard_timeout_config() {
RuntimeTimeoutConfig order_defaults{
PLATFORM_OP_EXECUTE_TIMEOUT_US, PLATFORM_STREAM_SYNC_TIMEOUT_MS, PLATFORM_ONBOARD_SCHEDULER_TIMEOUT_MS
};
RuntimeTimeoutParseStatus parse_status;
RuntimeTimeoutConfig cfg = resolve_runtime_timeout_config(order_defaults, &parse_status);
if (parse_status.op_execute_env_set && !parse_status.op_execute_valid) {
const char *op_env = std::getenv(SIMPLER_OP_EXECUTE_TIMEOUT_US_ENV);
LOG_WARN(
"%s=%s invalid, using default %llu", SIMPLER_OP_EXECUTE_TIMEOUT_US_ENV, op_env,
(unsigned long long)order_defaults.op_execute_timeout_us
);
}
if (parse_status.stream_sync_env_set && !parse_status.stream_sync_valid) {
const char *sync_env = std::getenv(SIMPLER_STREAM_SYNC_TIMEOUT_MS_ENV);
LOG_WARN(
"%s=%s invalid, using default %d", SIMPLER_STREAM_SYNC_TIMEOUT_MS_ENV, sync_env,
order_defaults.stream_sync_timeout_ms
);
}
if (parse_status.scheduler_env_set && !parse_status.scheduler_valid) {
const char *sched_env = std::getenv(SIMPLER_SCHEDULER_TIMEOUT_MS_ENV);
LOG_WARN(
"%s=%s invalid, using default %d", SIMPLER_SCHEDULER_TIMEOUT_MS_ENV, sched_env,
order_defaults.scheduler_timeout_ms
);
}
bool host_timeout_env_set =
parse_status.op_execute_env_set || parse_status.stream_sync_env_set || parse_status.scheduler_env_set;
RuntimeTimeoutOrderStatus order_status = validate_runtime_timeout_order(cfg);
// The scheduler override is forwarded to the device (via InitArgs at init)
// only when explicitly set, valid, and consistent with the op/stream
// ordering. 0 means "no override" — the AICPU scheduler then keeps its
// compile-time default. op/stream remain host-side acl knobs.
int32_t scheduler_override = (parse_status.scheduler_env_set && parse_status.scheduler_valid &&
order_status == RuntimeTimeoutOrderStatus::OK) ?
cfg.scheduler_timeout_ms :
0;
if (host_timeout_env_set && order_status != RuntimeTimeoutOrderStatus::OK) {
LOG_WARN(
"Ignoring PTO2 timeout env overrides: %s (scheduler=%d ms, op_execute=%llu us, stream_sync=%d ms)",
runtime_timeout_order_status_name(order_status), cfg.scheduler_timeout_ms,
(unsigned long long)cfg.op_execute_timeout_us, cfg.stream_sync_timeout_ms
);
return HostRuntimeTimeoutConfig{
order_defaults.op_execute_timeout_us, order_defaults.stream_sync_timeout_ms, scheduler_override
};
}
return HostRuntimeTimeoutConfig{cfg.op_execute_timeout_us, cfg.stream_sync_timeout_ms, scheduler_override};
}
} // namespace
DeviceRunnerBase::DeviceRunnerBase() {
for (auto &bank : arena_banks_) {
bank = std::make_unique<ArenaBank>(&arena_alloc_trampoline, &arena_free_trampoline, &mem_alloc_);
}
}
uint64_t DeviceRunnerBase::arena_bank_gm_heap_base(uint32_t bank_id) const {
if (bank_id >= arena_banks_.size()) return 0;
const ArenaBank &bank = *arena_banks_[bank_id];
return bank.gm_heap.is_committed() ? reinterpret_cast<uint64_t>(bank.gm_heap.base()) : 0;
}
uint64_t DeviceRunnerBase::retained_temp_addr(uint32_t slot_id) const {
if (slot_id >= retained_temp_addrs_.size()) return 0;
return reinterpret_cast<uint64_t>(retained_temp_addrs_[slot_id]);
}
void *DeviceRunnerBase::allocate_tensor(std::size_t bytes) { return mem_alloc_.alloc(bytes); }
void DeviceRunnerBase::free_tensor(void *dev_ptr) {
if (dev_ptr != nullptr) {
mem_alloc_.free(dev_ptr);
}
}
int DeviceRunnerBase::copy_to_device(void *dev_ptr, const void *host_ptr, std::size_t bytes) {
return rtMemcpy(dev_ptr, bytes, host_ptr, bytes, RT_MEMCPY_HOST_TO_DEVICE);
}
int DeviceRunnerBase::copy_from_device(void *host_ptr, const void *dev_ptr, std::size_t bytes) {
return rtMemcpy(host_ptr, bytes, dev_ptr, bytes, RT_MEMCPY_DEVICE_TO_HOST);
}
int DeviceRunnerBase::device_memset(void *dev_ptr, int value, std::size_t bytes) {
return aclrtMemset(dev_ptr, bytes, value, bytes);
}
void DeviceRunnerBase::get_retained_temp_buffer(uint32_t pipeline_slot, void **addr, size_t *size) {
if (pipeline_slot >= retained_temp_addrs_.size()) {
if (addr != nullptr) *addr = nullptr;
if (size != nullptr) *size = 0;
return;
}
if (addr != nullptr) *addr = retained_temp_addrs_[pipeline_slot];
if (size != nullptr) *size = retained_temp_sizes_[pipeline_slot];
}
void DeviceRunnerBase::set_retained_temp_buffer(uint32_t pipeline_slot, void *addr, size_t size) {
if (pipeline_slot >= retained_temp_addrs_.size()) return;
retained_temp_addrs_[pipeline_slot] = addr;
retained_temp_sizes_[pipeline_slot] = size;
}
void *DeviceRunnerBase::acquire_graph_definition_buffer(
uint32_t pipeline_slot, uint64_t key, size_t bytes, size_t alignment
) {
if (pipeline_slot >= graph_definition_buffers_.size() || bytes == 0 || alignment == 0 ||
(alignment & (alignment - 1)) != 0 || bytes > SIZE_MAX - (alignment - 1)) {
return nullptr;
}
RetainedGraphBuffer &buffer = graph_definition_buffers_[pipeline_slot][key];
if (buffer.aligned_addr != nullptr && buffer.capacity >= bytes &&
reinterpret_cast<uintptr_t>(buffer.aligned_addr) % alignment == 0) {
return buffer.aligned_addr;
}
const size_t allocation_bytes = bytes + alignment - 1;
void *allocation = mem_alloc_.alloc(allocation_bytes);
if (allocation == nullptr) return nullptr;
const uintptr_t raw = reinterpret_cast<uintptr_t>(allocation);
if (raw > UINTPTR_MAX - (alignment - 1)) {
mem_alloc_.free(allocation);
return nullptr;
}
void *aligned_addr = reinterpret_cast<void *>((raw + alignment - 1) & ~(alignment - 1));
if (device_memset(aligned_addr, 0, bytes) != 0) {
mem_alloc_.free(allocation);
return nullptr;
}
if (buffer.allocation != nullptr && mem_alloc_.free(buffer.allocation) != 0) {
mem_alloc_.free(allocation);
return nullptr;
}
buffer = RetainedGraphBuffer{allocation, aligned_addr, bytes};
return aligned_addr;
}
void DeviceRunnerBase::release_graph_definition_buffers() {
for (GraphDefinitionBufferMap &by_key : graph_definition_buffers_) {
for (auto &entry : by_key) {
if (entry.second.allocation != nullptr) mem_alloc_.free(entry.second.allocation);
}
by_key.clear();
}
}
void DeviceRunnerBase::abandon_graph_definition_buffers() {
for (GraphDefinitionBufferMap &by_key : graph_definition_buffers_) {
by_key.clear();
}
}
void DeviceRunnerBase::clear_temporary_buffer() {
for (size_t slot = 0; slot < retained_temp_addrs_.size(); ++slot) {
if (retained_temp_addrs_[slot] == nullptr) continue;
mem_alloc_.free(retained_temp_addrs_[slot]);
retained_temp_addrs_[slot] = nullptr;
retained_temp_sizes_[slot] = 0;
}
}
void *DeviceRunnerBase::acquire_pooled_gm_heap(uint32_t arena_bank) {
if (arena_bank >= arena_banks_.size()) return nullptr;
DeviceArena &arena = this->arena_bank(arena_bank).gm_heap;
if (!arena.is_committed()) return nullptr;
return arena.base();
}
void *DeviceRunnerBase::acquire_pooled_gm_sm(uint32_t arena_bank) {
if (arena_bank >= arena_banks_.size()) return nullptr;
DeviceArena &arena = this->arena_bank(arena_bank).gm_sm;
if (!arena.is_committed()) return nullptr;
return arena.base();
}
void *DeviceRunnerBase::acquire_pooled_runtime_arena(uint32_t arena_bank) {
if (arena_bank >= arena_banks_.size()) return nullptr;
// hbg calls setup_static_arena(...,0) and leaves the runtime pool
// uncommitted — fail loudly if a caller asks for it anyway.
DeviceArena &arena = this->arena_bank(arena_bank).runtime_pool;
if (!arena.is_committed()) return nullptr;
return arena.base();
}
bool DeviceRunnerBase::lookup_prebuilt_runtime_arena_cache(
uint32_t arena_bank, uint64_t hash, const void *key_data, size_t key_size, void **gm_heap_base, void **sm_base,
void **runtime_arena_base, size_t *runtime_off, const void **image_data, size_t *image_size
) const {
// The cache holds one entry and its bases point into bank 0, so any other
// bank must rebuild rather than be handed a region it does not own.
if (arena_bank != 0) return false;
if (!prebuilt_runtime_arena_cache_valid_ || prebuilt_runtime_arena_cache_hash_ != hash ||
prebuilt_runtime_arena_cache_key_.size() != key_size || key_data == nullptr || gm_heap_base == nullptr ||
sm_base == nullptr || runtime_arena_base == nullptr || runtime_off == nullptr || image_data == nullptr ||
image_size == nullptr) {
return false;
}
if (std::memcmp(prebuilt_runtime_arena_cache_key_.data(), key_data, key_size) != 0) {
return false;
}
*gm_heap_base = prebuilt_runtime_arena_cache_gm_heap_base_;
*sm_base = prebuilt_runtime_arena_cache_sm_base_;
*runtime_arena_base = prebuilt_runtime_arena_cache_runtime_arena_base_;
*runtime_off = prebuilt_runtime_arena_cache_runtime_off_;
*image_data = prebuilt_runtime_arena_cache_image_.data();
*image_size = prebuilt_runtime_arena_cache_image_.size();
return true;
}
void DeviceRunnerBase::mark_prebuilt_runtime_arena_cached(
uint32_t arena_bank, uint64_t hash, const void *key_data, size_t key_size, void *gm_heap_base, void *sm_base,
void *runtime_arena_base, size_t runtime_off, const void *image_data, size_t image_size
) {
// Single-entry cache owned by bank 0; see lookup_prebuilt_runtime_arena_cache.
if (arena_bank != 0) return;
prebuilt_runtime_arena_cache_valid_ = false;
prebuilt_runtime_arena_cache_hash_ = hash;
prebuilt_runtime_arena_cache_key_.assign(
static_cast<const uint8_t *>(key_data), static_cast<const uint8_t *>(key_data) + key_size
);
prebuilt_runtime_arena_cache_gm_heap_base_ = gm_heap_base;
prebuilt_runtime_arena_cache_sm_base_ = sm_base;
prebuilt_runtime_arena_cache_runtime_arena_base_ = runtime_arena_base;
prebuilt_runtime_arena_cache_runtime_off_ = runtime_off;
prebuilt_runtime_arena_cache_image_.assign(
static_cast<const uint8_t *>(image_data), static_cast<const uint8_t *>(image_data) + image_size
);
prebuilt_runtime_arena_cache_valid_ = true;
}
int DeviceRunnerBase::setup_static_arena(
uint32_t arena_bank, size_t gm_heap_size, size_t gm_sm_size, size_t runtime_arena_size
) {
if (arena_bank >= arena_banks_.size()) {
LOG_ERROR("arena bank %u is outside [0, %zu)", arena_bank, arena_banks_.size());
return -1;
}
// Three independent device_malloc'd buffers: GM heap, PTO2 SM, prebuilt
// runtime arena. Split out from a single large allocation because the
// combined size can exceed the device allocator's largest contiguous
// block. Each arena commits exactly one region, so its base() is the
// pooled pointer the caller wants.
//
// Idempotent for the production case (sizes do not change across a
// worker's lifetime). If a caller asks for a larger layout on any
// region, redo just that region — already-committed peers stay alive
// so their callers don't have to re-acquire.
ArenaBank &bank = this->arena_bank(arena_bank);
bool arena_changed = false;
auto commit_region = [&arena_changed](DeviceArena &arena, size_t &cached_size, size_t requested_size) -> int {
if (requested_size == 0) {
// hbg's runtime_arena path: caller passed 0 and never reserved
// a region. Leave the arena uncommitted; acquire_pooled_* will
// return nullptr.
if (arena.is_committed() && cached_size != 0) {
arena.release();
cached_size = 0;
arena_changed = true;
}
return 0;
}
if (arena.is_committed() && requested_size <= cached_size) {
return 0;
}
arena.release();
cached_size = 0;
arena_changed = true;
arena.reserve(requested_size, DeviceArena::kDefaultBaseAlign);
if (arena.commit(DeviceArena::kDefaultBaseAlign) == nullptr) {
// commit() failure leaves committed_=false, so the next entry's
// is_committed() guard skips the release branch. release() is
// idempotent on a never-committed arena (zeroes cursor_).
arena.release();
return -1;
}
cached_size = requested_size;
return 0;
};
// Try to commit all three regions; on any failure, fully roll back —
// including any earlier-committed peers from a PRIOR successful call.
// The simpler "only roll back peers from this call" pattern would
// leave stale committed regions when a re-init (e.g., later worker
// asking for a larger layout) fails midway, defeating the
// "failure means failure" guarantee. Reset everything to the
// post-construction state so the caller can retry with a new layout.
bool ok = commit_region(bank.gm_heap, bank.cached_gm_heap_size, gm_heap_size) == 0;
ok = ok && commit_region(bank.gm_sm, bank.cached_gm_sm_size, gm_sm_size) == 0;
ok = ok && commit_region(bank.runtime_pool, bank.cached_runtime_arena_size, runtime_arena_size) == 0;
if (!ok) {
bank.gm_heap.release();
bank.gm_sm.release();
bank.runtime_pool.release();
bank.cached_gm_heap_size = 0;
bank.cached_gm_sm_size = 0;
bank.cached_runtime_arena_size = 0;
if (arena_bank == 0) {
prebuilt_runtime_arena_cache_valid_ = false;
prebuilt_runtime_arena_cache_key_.clear();
prebuilt_runtime_arena_cache_gm_heap_base_ = nullptr;
prebuilt_runtime_arena_cache_sm_base_ = nullptr;
prebuilt_runtime_arena_cache_runtime_arena_base_ = nullptr;
prebuilt_runtime_arena_cache_image_.clear();
}
return -1;
}
if (arena_changed && arena_bank == 0) {
prebuilt_runtime_arena_cache_valid_ = false;
prebuilt_runtime_arena_cache_key_.clear();
prebuilt_runtime_arena_cache_gm_heap_base_ = nullptr;
prebuilt_runtime_arena_cache_sm_base_ = nullptr;
prebuilt_runtime_arena_cache_runtime_arena_base_ = nullptr;
prebuilt_runtime_arena_cache_image_.clear();
}
return 0;
}
std::thread DeviceRunnerBase::create_thread(std::function<void()> fn) {
int dev_id = device_id_;
return std::thread([dev_id, fn = std::move(fn)]() {
rtSetDevice(dev_id);
fn();
});
}
int DeviceRunnerBase::attach_current_thread(int device_id) {
if (device_id < 0) {
LOG_ERROR("Invalid device_id: %d", device_id);
return -1;
}
if (device_id_ != -1 && device_id_ != device_id) {
LOG_ERROR(
"DeviceRunner already initialized on device %d; reset/finalize before switching to device %d", device_id_,
device_id
);
return -1;
}
// CANN device context is per-thread, so every caller must attach explicitly.
int rc = rtSetDevice(device_id);
if (rc != 0) {
LOG_ERROR("rtSetDevice(%d) failed: %d", device_id, rc);
ACL_LOG_ERROR_DETAIL(rc);
return rc;
}
// simpler_init performs the only lifetime write. Prepared-run admission
// and execution subsequently attach different host threads, so repeated
// same-value writes here would still be a C++ data race.
if (device_id_ == -1) {
timeout_config_ = resolve_onboard_timeout_config();
configure_aicore_op_timeout();
device_id_ = device_id;
}
return 0;
}
void DeviceRunnerBase::configure_aicore_op_timeout() {
uint64_t actual_timeout = 0;
int rc = aclrtSetOpExecuteTimeOutV2(timeout_config_.op_execute_timeout_us, &actual_timeout);
if (rc != 0) {
LOG_ERROR(
"aclrtSetOpExecuteTimeOutV2(%llu us) failed: %d", (unsigned long long)timeout_config_.op_execute_timeout_us,
rc
);
} else {
LOG_INFO(
"aclrtSetOpExecuteTimeOutV2: requested=%llu us, actual=%llu us",
(unsigned long long)timeout_config_.op_execute_timeout_us, (unsigned long long)actual_timeout
);
}
}
int DeviceRunnerBase::ensure_device_initialized() {
// Attach the current thread to the device (device_id_ was set in
// attach_current_thread() during simpler_init) and create the persistent
// AICPU/AICore streams. Streams live for the DeviceRunner's lifetime and
// are destroyed in finalize().
int rc = attach_current_thread(device_id_);
if (rc != 0) {
return rc;
}
bool aicpu_created_here = false;
bool aicore_created_here = false;
if (stream_aicpu_ == nullptr) {
rc = rtStreamCreate(&stream_aicpu_, 0);
if (rc != 0) {
LOG_ERROR("rtStreamCreate (AICPU) failed: %d", rc);
ACL_LOG_ERROR_DETAIL(rc);
return rc;
}
aicpu_created_here = true;
}
if (stream_aicore_ == nullptr) {
rc = rtStreamCreate(&stream_aicore_, 0);
if (rc != 0) {
LOG_ERROR("rtStreamCreate (AICore) failed: %d", rc);
ACL_LOG_ERROR_DETAIL(rc);
// Roll back only the AICPU stream we just created, not a
// pre-existing persistent one.
if (aicpu_created_here) {
rtStreamDestroy(stream_aicpu_);
stream_aicpu_ = nullptr;
}
return rc;
}
aicore_created_here = true;
}
if (aicpu_created_here || aicore_created_here) {
LOG_INFO("DeviceRunner: device=%d set, streams created", device_id_);
}
// Latch the AICore stream's block_dim ceiling. resolve_block_dim() is then
// pure arithmetic and can run before any per-run stream work.
if (max_block_dim_ == 0) {
max_block_dim_ = query_max_block_dim(stream_aicore_, &max_cube_cores_, &max_vector_cores_);
LOG_INFO(
"DeviceRunner: device=%d max_block_dim=%d (cube=%u, vector=%u)", device_id_, max_block_dim_,
max_cube_cores_, max_vector_cores_
);
}
rc = ensure_binaries_loaded();
if (rc != 0) return rc;
return ensure_aicpu_init_launched();
}
int DeviceRunnerBase::ensure_aicpu_init_launched() {
if (aicpu_init_launched_) {
return 0;
}
InitArgs init_args{};
init_args.device_id = static_cast<uint32_t>(device_id_);
init_args.log_level = static_cast<uint32_t>(HostLogger::get_instance().level());
// Per-device scheduler watchdog override, resolved once at attach into
// timeout_config_. 0 -> the AICPU scheduler keeps its compile-time default.
init_args.scheduler_timeout_ms = timeout_config_.scheduler_timeout_ms;
// Publish the provisioned async-DMA workspace addresses (all-zero until a
// Worker opts into SDMA). provision_dma_workspace() re-launches this entry to
// re-latch them; the AICPU SO stays resident, so the latest values survive
// every subsequent per-task launch.
for (int kind = 0; kind < DMA_WORKSPACE_KIND_COUNT; ++kind) {
init_args.dma_workspace_addr[kind] = dma_workspace_addr_[kind];
}
LOG_INFO("=== launch_aicpu_payload %s ===", host::KernelNames::InitName);
int rc = launch_aicpu_payload(
stream_aicpu_, &init_args, sizeof(init_args), host::KernelNames::InitName, /*aicpu_num=*/1
);
if (rc != 0) {
LOG_ERROR("ensure_aicpu_init_launched: launch_aicpu_payload failed: %d", rc);
return rc;
}
rc = aclrtSynchronizeStreamWithTimeout(stream_aicpu_, PLATFORM_STREAM_SYNC_TIMEOUT_MS);
if (rc != 0) {
LOG_ERROR("ensure_aicpu_init_launched: stream sync failed: %d (device_id=%d)", rc, device_id_);
return rc;
}
aicpu_init_launched_ = true;
return 0;
}
int DeviceRunnerBase::ensure_binaries_loaded() {
// Check if already loaded (binaries are owned by the runner via
// set_executors and live for the runner's lifetime).
if (binaries_loaded_) {
return 0;
}
// Device must be set first
if (stream_aicpu_ == nullptr) {
LOG_ERROR("Device not set before loading binaries");
return -1;
}
if (dispatcher_so_binary_.empty()) {
LOG_ERROR(
"DeviceRunner: dispatcher SO bytes not provided; pass dispatcher_path through ChipWorker.init "
"(RuntimeBinaries.dispatcher_path)"
);
return -1;
}
// One-shot bootstrap: libaicpu_extend_kernels invokes our dispatcher,
// which writes the runtime AICPU SO bytes to
// simpler_inner_<fp>_<device_id>.so in the device-side preinstall path.
// The dispatcher SO itself is never persisted to disk — only the
// transient libaicpu_extend_kernels dlopen. Subsequent per-task AICPU
// launches resolve symbols via rtsBinaryLoadFromFile + rtsFuncGetByName +
// rtsLaunchCpuKernel directly against the preinstall file.
int rc = load_aicpu_op_.BootstrapDispatcher(
dispatcher_so_binary_.data(), dispatcher_so_binary_.size(), aicpu_so_binary_.data(), aicpu_so_binary_.size(),
stream_aicpu_, device_id_
);
if (rc != 0) {
LOG_ERROR("LoadAicpuOp::BootstrapDispatcher failed: %d", rc);
return rc;
}
LOG_INFO("DeviceRunner: inner SO uploaded to preinstall via dispatcher bootstrap");
// JSON-register the inner SO and resolve its runtime entry handles. The
// runtime reports any AICPU entries it exports beyond the base set so the
// loader stays runtime-agnostic.
std::vector<std::string> extra_symbols;
size_t extra_count = 0;
const char *const *extra = runtime_extra_aicpu_symbols(&extra_count);
for (size_t i = 0; i < extra_count && extra != nullptr; ++i) {
if (extra[i] != nullptr) extra_symbols.emplace_back(extra[i]);
}
rc = load_aicpu_op_.Init(extra_symbols);
if (rc != 0) {
LOG_ERROR("LoadAicpuOp::Init failed: %d", rc);
return rc;
}
LOG_INFO("DeviceRunner: inner SO registered (runtime entry handles ready)");
// Release host bytes — bootstrap is done. Per-task launches go through
// the cached rtFuncHandle owned by LoadAicpuOp; dispatcher SO bytes are
// never referenced again; the aicpu kernel SO's host buffer is no longer
// needed either (we used to H2D it through AicpuSoInfo as a CANN-internal
// bookkeeping workaround; that's gone).
dispatcher_so_binary_.clear();
dispatcher_so_binary_.shrink_to_fit();
aicpu_so_binary_.clear();
aicpu_so_binary_.shrink_to_fit();
binaries_loaded_ = true;
LOG_INFO("DeviceRunner: binaries loaded");
return 0;
}
int DeviceRunnerBase::query_max_block_dim(rtStream_t stream, uint32_t *out_cube, uint32_t *out_vector) {
uint32_t cube_limit = 0, vector_limit = 0;
bool got_limits = (aclrtGetStreamResLimit(stream, ACL_RT_DEV_RES_CUBE_CORE, &cube_limit) == ACL_ERROR_NONE) &&
(aclrtGetStreamResLimit(stream, ACL_RT_DEV_RES_VECTOR_CORE, &vector_limit) == ACL_ERROR_NONE) &&
cube_limit > 0 && vector_limit > 0;
if (out_cube != nullptr) *out_cube = got_limits ? cube_limit : 0;
if (out_vector != nullptr) *out_vector = got_limits ? vector_limit : 0;
if (got_limits) {
// Cap by PLATFORM_MAX_BLOCKDIM as well: runtime handshake/scheduler
// arrays are statically sized to RUNTIME_MAX_WORKER (= PLATFORM_MAX_BLOCKDIM
// * PLATFORM_CORES_PER_BLOCKDIM), so even if ACL reports more cores
// than the platform cap we must not exceed it.
int from_stream = static_cast<int>(
std::min(cube_limit / PLATFORM_AIC_CORES_PER_BLOCKDIM, vector_limit / PLATFORM_AIV_CORES_PER_BLOCKDIM)
);
return std::min(from_stream, PLATFORM_MAX_BLOCKDIM);
}
return PLATFORM_MAX_BLOCKDIM;
}
void DeviceRunnerBase::print_handshake_results(const KernelArgsHelper &kernel_args) {
if (stream_aicpu_ == nullptr || worker_count_ == 0 || kernel_args.args.runtime_args == nullptr) {
return;
}
// Allocate temporary buffer to read handshake data from device
std::vector<Handshake> workers(worker_count_);
size_t total_size = sizeof(Handshake) * worker_count_;
rtMemcpy(
workers.data(), total_size, kernel_args.args.runtime_args->get_workers(), total_size, RT_MEMCPY_DEVICE_TO_HOST
);
LOG_DEBUG("Handshake results for %d cores:", worker_count_);
for (int i = 0; i < worker_count_; i++) {
LOG_DEBUG(
" Core %d: aicore_done=%d aicpu_ready=%d task=%d", i, workers[i].aicore_done, workers[i].aicpu_ready,
workers[i].task
);
}
}
// =============================================================================
// Group D — chip-callable upload + per-callable_id registration
// =============================================================================
uint64_t DeviceRunnerBase::upload_chip_callable_buffer(const ChipCallable *callable) {
if (callable == nullptr) {
return 0;
}
if (stream_aicpu_ == nullptr) {
LOG_ERROR("Run context not prepared before upload_chip_callable_buffer()");
return 0;
}
const ChipCallableLayout layout = compute_chip_callable_layout(callable);
// Content-hash dedup: identical bytes → return cached chip_dev.
auto it = chip_callable_buffers_.find(layout.content_hash);
if (it != chip_callable_buffers_.end()) {
it->second.refcount++;
LOG_DEBUG(
"Chip callable dedup hit: chip_dev=0x%lx, size=%zu, hash=0x%lx, refcount=%d", it->second.chip_dev,
it->second.total_size, layout.content_hash, it->second.refcount
);
return it->second.chip_dev;
}
void *gm_addr = mem_alloc_.alloc(layout.total_size);
if (gm_addr == nullptr) {
LOG_ERROR("Failed to allocate device GM for ChipCallable buffer (size=%zu)", layout.total_size);
return 0;
}
const uint64_t chip_dev = reinterpret_cast<uint64_t>(gm_addr);
assert((chip_dev & (CALLABLE_ALIGN - 1)) == 0 && "device alloc must be CALLABLE_ALIGN-byte aligned");
// Build a host scratch with each child's resolved_addr_ fixed up to the
// device-side address of that child's binary code (so the AICPU dispatch
// path's `reinterpret_cast<CoreCallable*>(addr)->resolved_addr()` lands
// on the right device offset).
std::vector<uint8_t> scratch(layout.total_size);
std::memcpy(scratch.data(), callable, layout.total_size);
patch_chip_callable_scratch_for_device(callable, layout, chip_dev, scratch.data());
int rc = rtMemcpy(gm_addr, layout.total_size, scratch.data(), layout.total_size, RT_MEMCPY_HOST_TO_DEVICE);
if (rc != 0) {
LOG_ERROR("rtMemcpy chip callable H2D failed: %d", rc);
ACL_LOG_ERROR_DETAIL(rc);
mem_alloc_.free(gm_addr);
return 0;
}
mark_run_streams_stale();
chip_callable_buffers_.emplace(layout.content_hash, ChipCallableBuffer{chip_dev, layout.total_size, 1});
LOG_DEBUG(
"Uploaded chip callable: chip_dev=0x%lx, size=%zu, child_count=%d, hash=0x%lx", chip_dev, layout.total_size,
callable->child_count(), layout.content_hash
);
return chip_dev;
}
int DeviceRunnerBase::release_chip_callable_buffer(uint64_t hash) {
if (hash == 0) {
return 0;
}
auto it = chip_callable_buffers_.find(hash);
if (it == chip_callable_buffers_.end()) {
LOG_WARN("release_chip_callable_buffer: hash=0x%lx not found", hash);
return 0;
}
if (--it->second.refcount <= 0) {
mem_alloc_.free(reinterpret_cast<void *>(it->second.chip_dev));
LOG_DEBUG(
"Freed chip callable buffer: chip_dev=0x%lx, size=%zu, hash=0x%lx", it->second.chip_dev,
it->second.total_size, hash
);
chip_callable_buffers_.erase(it);
}
return 0;
}
int DeviceRunnerBase::stamp_orch_so(Runtime &runtime, int32_t cid) {
// Registered-callable flow only: the orch SO was already H2D'd and
// dlopen'd device-side at record_device_orch_callable / launch_device_register
// time. All that remains for a run is to tell the AICPU which orch_so_table_
// slot to dispatch — the active callable_id.
if (cid < 0) {
LOG_ERROR("stamp_orch_so: invalid callable_id=%d", cid);
return -1;
}
auto it = callables_.find(cid);
if (it == callables_.end()) {
LOG_ERROR("stamp_orch_so: callable_id=%d not registered", cid);
return -1;
}
runtime.set_active_callable_id(cid);
return 0;
}
int DeviceRunnerBase::prepare_orch_so(Runtime &runtime) {
const int32_t cid = runtime.get_active_callable_id();
if (cid < 0) {
LOG_ERROR("prepare_orch_so: no active callable_id; registered-callable flow required");
return -1;
}
return stamp_orch_so(runtime, cid);
}
int DeviceRunnerBase::commit_device_register(int32_t cid) {
auto it = callables_.find(cid);
if (it == callables_.end()) {
LOG_ERROR("commit_device_register: callable_id=%d not registered", cid);
return -1;
}
const auto &state = it->second;
if (state.host_dlopen_handle != nullptr) {
return 0;
}
const bool inserted = aicpu_seen_callable_ids_.insert(cid).second;
if (inserted) {
++aicpu_dlopen_total_;
LOG_INFO("AICPU callable load committed cid=%d (count=%zu)", cid, aicpu_dlopen_total_);
}
return 0;
}
int DeviceRunnerBase::launch_device_register(int32_t callable_id) {
auto it = callables_.find(callable_id);
if (it == callables_.end()) {
LOG_ERROR("launch_device_register: callable_id=%d not registered", callable_id);
return -1;
}
if (it->second.host_dlopen_handle != nullptr) {
return 0;
}
int rc = ensure_device_initialized();
if (rc != 0) {
LOG_ERROR("launch_device_register: ensure_device_initialized failed: %d", rc);
return rc;
}
// Build the orch-SO descriptor straight from CallableState — no full
// Runtime H2D as the old prewarm path did. Registration always (re)dlopens
// the SO device-side, so there is no per-callable "new?" bit to carry.
const CallableState &state = it->second;
RegisterCallableArgs reg_args{};
reg_args.active_callable_id = callable_id;
reg_args.dev_orch_so_addr = state.dev_orch_so_addr;
reg_args.dev_orch_so_size = state.dev_orch_so_size;
snprintf(reg_args.device_orch_func_name, sizeof(reg_args.device_orch_func_name), "%s", state.func_name.c_str());
snprintf(
reg_args.device_orch_config_name, sizeof(reg_args.device_orch_config_name), "%s", state.config_name.c_str()
);
LOG_INFO("=== launch_aicpu_payload %s ===", host::KernelNames::RegisterCallableName);
rc = launch_aicpu_payload(
stream_aicpu_, ®_args, sizeof(reg_args), host::KernelNames::RegisterCallableName, /*aicpu_num=*/1
);
if (rc != 0) {
LOG_ERROR("launch_device_register: launch_aicpu_payload failed: %d", rc);
return rc;
}
rc = aclrtSynchronizeStreamWithTimeout(stream_aicpu_, PLATFORM_STREAM_SYNC_TIMEOUT_MS);
if (rc == ACL_ERROR_RT_STREAM_SYNC_TIMEOUT) {
LOG_ERROR(
"launch_device_register: stream sync timeout timeout_ms=%d device_id=%d", PLATFORM_STREAM_SYNC_TIMEOUT_MS,
device_id_
);
return rc;
}
if (rc != 0) {
LOG_ERROR("launch_device_register: aclrtSynchronizeStreamWithTimeout failed: %d", rc);
ACL_LOG_ERROR_DETAIL(rc);
return rc;
}
return commit_device_register(callable_id);
}
int DeviceRunnerBase::record_device_orch_callable(
int32_t callable_id, uint64_t chip_buffer_hash, uint64_t aicore_image_hash, uint64_t chip_dev,
const void *orch_so_data, size_t orch_so_size, const char *func_name, const char *config_name,
std::vector<std::pair<int, uint64_t>> kernel_addrs, std::vector<ArgDirection> signature
) {
// The AICPU executor reserves `orch_so_table_[MAX_REGISTERED_CALLABLE_IDS]`
// (declared in src/common/task_interface/callable_protocol.h) and indexes
// it by callable_id; rejecting an out-of-range id here keeps the host and
// AICPU sides in sync and avoids an OOB access at run time.
if (callable_id < 0 || callable_id >= MAX_REGISTERED_CALLABLE_IDS) {
LOG_ERROR(
"record_device_orch_callable: callable_id=%d out of range [0, %d)", callable_id, MAX_REGISTERED_CALLABLE_IDS
);
return -1;
}
if (orch_so_data == nullptr || orch_so_size == 0) {
LOG_ERROR("record_device_orch_callable: empty orch SO for callable_id=%d", callable_id);
return -1;
}
if (chip_buffer_hash == 0 || chip_dev == 0) {
LOG_ERROR("record_device_orch_callable: missing chip buffer for callable_id=%d", callable_id);
return -1;
}
if (callables_.count(callable_id) != 0) {
LOG_ERROR("record_device_orch_callable: callable_id=%d already registered", callable_id);
return -1;
}
const uint64_t hash = simpler::common::utils::elf_build_id_64(orch_so_data, orch_so_size);
CallableState state;
state.hash = hash;
state.chip_buffer_hash = chip_buffer_hash;
state.aicore_image_hash = aicore_image_hash;
state.dev_orch_so_addr = chip_dev + offsetof(ChipCallable, storage_);
state.dev_orch_so_size = orch_so_size;
state.func_name = (func_name != nullptr) ? func_name : "";
state.config_name = (config_name != nullptr) ? config_name : "";
state.kernel_addrs = std::move(kernel_addrs);
state.signature = std::move(signature);
callables_.emplace(callable_id, std::move(state));
LOG_INFO(
"record_device_orch_callable: cid=%d orch_hash=0x%lx chip_hash=0x%lx %zu bytes", callable_id, hash,
chip_buffer_hash, orch_so_size
);
return 0;
}
int DeviceRunnerBase::record_host_orch_callable(
int32_t callable_id, uint64_t chip_buffer_hash, uint64_t aicore_image_hash, void *host_dlopen_handle,
void *host_orch_func_ptr, std::vector<std::pair<int, uint64_t>> kernel_addrs, std::vector<ArgDirection> signature
) {
if (callable_id < 0 || callable_id >= MAX_REGISTERED_CALLABLE_IDS) {
LOG_ERROR(
"record_host_orch_callable: callable_id=%d out of range [0, %d)", callable_id, MAX_REGISTERED_CALLABLE_IDS
);
return -1;
}
if (host_dlopen_handle == nullptr || host_orch_func_ptr == nullptr) {
LOG_ERROR("record_host_orch_callable: null handle/fn for callable_id=%d", callable_id);
return -1;
}
if (chip_buffer_hash == 0) {
LOG_ERROR("record_host_orch_callable: missing chip buffer for callable_id=%d", callable_id);
return -1;
}
if (callables_.count(callable_id) != 0) {
LOG_ERROR("record_host_orch_callable: callable_id=%d already registered", callable_id);
return -1;
}
CallableState state;
state.chip_buffer_hash = chip_buffer_hash;
state.aicore_image_hash = aicore_image_hash;
state.host_dlopen_handle = host_dlopen_handle;
state.host_orch_func_ptr = host_orch_func_ptr;
state.kernel_addrs = std::move(kernel_addrs);
state.signature = std::move(signature);
callables_.emplace(callable_id, std::move(state));
++host_dlopen_total_;
LOG_INFO("record_host_orch_callable: cid=%d (host dlopen #%zu)", callable_id, host_dlopen_total_);
return 0;
}
int DeviceRunnerBase::unregister_callable(int32_t callable_id) {
auto it = callables_.find(callable_id);
if (it == callables_.end()) {
return 0;
}
CallableState state = std::move(it->second);
callables_.erase(it);
aicpu_seen_callable_ids_.erase(callable_id);
release_chip_callable_buffer(state.chip_buffer_hash);
if (state.host_dlopen_handle != nullptr) {
// hbg path: no device-side orch SO handle, just dlclose the host handle.
dlclose(state.host_dlopen_handle);
return 0;
}
return 0;
}
bool DeviceRunnerBase::has_callable(int32_t callable_id) const { return callables_.count(callable_id) != 0; }
int DeviceRunnerBase::provision_dma_workspace(uint32_t required_mask) {
const uint32_t supported = dma_workspace_supported_mask();
if ((required_mask & ~supported) != 0) {
LOG_ERROR("provision_dma_workspace: unsupported mask=0x%x (supported=0x%x)", required_mask, supported);
return -1;
}
if (dma_workspace_handle_ != nullptr) {
LOG_ERROR("provision_dma_workspace: workspace already provisioned");
return -1;
}
for (int kind = 0; kind < DMA_WORKSPACE_KIND_COUNT; ++kind)
dma_workspace_addr_[kind] = 0;
// The provisioned addresses are stable for the Worker's life.
int rc =
dma_workspace_provision(required_mask, dma_workspace_addr_, DMA_WORKSPACE_KIND_COUNT, &dma_workspace_handle_);
if (rc != 0) {
LOG_ERROR("provision_dma_workspace: mask=0x%x failed: %d", required_mask, rc);
for (int kind = 0; kind < DMA_WORKSPACE_KIND_COUNT; ++kind)
dma_workspace_addr_[kind] = 0;
dma_workspace_handle_ = nullptr;
return rc;
}
// Re-latch the resident AICPU globals: simpler_aicpu_init publishes the
// provisioned addresses into g_dma_workspace_addr, which the scheduler
// prefills into every core's GlobalContext (get_dma_workspace). The AICPU SO
// stays dlopen'd, so the values survive every subsequent per-task launch.
aicpu_init_launched_ = false;
rc = ensure_aicpu_init_launched();
if (rc != 0) {
LOG_ERROR("provision_dma_workspace: re-latch of simpler_aicpu_init failed: %d", rc);
dma_workspace_release(dma_workspace_handle_);
dma_workspace_handle_ = nullptr;
for (int kind = 0; kind < DMA_WORKSPACE_KIND_COUNT; ++kind)
dma_workspace_addr_[kind] = 0;
return rc;
}
return 0;
}
uint64_t DeviceRunnerBase::callable_hash(int32_t callable_id) const {
auto it = callables_.find(callable_id);
return it == callables_.end() ? 0 : it->second.hash;
}
// Per-run binding half, defined in each runtime's runtime_maker.cpp and linked
// into this same host_runtime.so. Declared here (rather than only in
// c_api_shared.cpp) so bind_callable_to_runtime can call it directly, keeping
// the CallableState-derived host_orch_func_ptr / signature internal to the
// runner instead of returning them across the c_api boundary.
extern "C" int bind_callable_to_runtime_impl(
Runtime *runtime, const HostApi *api, const ChipStorageTaskArgs *orch_args, void *host_orch_func_ptr,
const ArgDirection *signature, int sig_count, const uint64_t *ring_task_window, const uint64_t *ring_heap,
const uint64_t *ring_dep_pool
);
int DeviceRunnerBase::bind_callable_to_runtime(
Runtime &runtime, int32_t callable_id, const HostApi *api, const void *orch_args, const uint64_t *ring_task_window,
const uint64_t *ring_heap, const uint64_t *ring_dep_pool
) {
auto it = callables_.find(callable_id);
if (it == callables_.end()) {
LOG_ERROR("bind_callable_to_runtime: callable_id=%d not registered", callable_id);
return -1;
}
const auto &state = it->second;
// runtime.func_id_to_addr_ holds exactly the active callable's mappings.
//