-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnpusim_runtime.cpp
More file actions
3087 lines (2945 loc) · 133 KB
/
Copy pathnpusim_runtime.cpp
File metadata and controls
3087 lines (2945 loc) · 133 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
#include "npusim_runtime.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <deque>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <nlohmann/json.hpp>
namespace NPUSim {
#if defined(__GNUC__) && !defined(NPUSIM_REQUIRE_OFFICIAL_ONNX)
// Direct-MatMul artifact binaries may link only the runtime object. Keep that
// legacy direct path independent of ONNX, while every ONNX entry point built
// by NPUSim CMake links the strong official parser from
// onnx_official_parser.cpp.
extern Model parseOnnxModel(const std::vector<char>& bytes) __attribute__((weak));
#endif
namespace {
constexpr std::uint64_t kSpmAccessBytes = 64;
std::uint64_t ceilDiv(std::uint64_t a, std::uint64_t b) {
b = std::max<std::uint64_t>(1, b);
return (a + b - 1) / b;
}
std::uint64_t productU64(const std::vector<std::int64_t>& shape) {
std::uint64_t total = 1;
for (std::int64_t dim : shape) {
total *= static_cast<std::uint64_t>(std::max<std::int64_t>(1, dim));
}
return total;
}
std::string readFileToString(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in.is_open()) {
return {};
}
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
std::string dirnameOf(const std::string& path) {
const std::size_t pos = path.find_last_of("/\\");
if (pos == std::string::npos) {
return {};
}
return path.substr(0, pos);
}
bool isAbsolutePath(const std::string& path) {
if (path.empty()) {
return false;
}
#ifdef _WIN32
return path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':';
#else
return path[0] == '/';
#endif
}
std::string joinPath(const std::string& base, const std::string& path) {
if (path.empty() || isAbsolutePath(path) || base.empty()) {
return path;
}
const char last = base.back();
if (last == '/' || last == '\\') {
return base + path;
}
return base + "/" + path;
}
struct TopologyEdge {
int src = 0;
int dst = 0;
std::uint64_t weight = 1;
};
struct MacProfile {
int mac_id = 0;
int node_id = 0;
int degree = 0;
std::uint64_t distance_to_controller = 0;
std::uint64_t sram_bytes = 0;
std::uint64_t ops_per_cycle = 0;
};
struct RuntimeTopology {
int node_count = 0;
int controller_node = 0;
std::string gv_path;
std::vector<TopologyEdge> edges;
std::vector<std::vector<std::pair<int, std::uint64_t>>> adj;
std::vector<std::uint64_t> distance_from_controller;
std::vector<MacProfile> macs;
};
struct WorkShard {
int mac_id = 0;
int node_id = 0;
std::int64_t begin = 0;
std::int64_t end = 0;
};
struct ShardActivity {
std::uint64_t ops = 0;
std::uint64_t bytes = 0;
std::uint64_t spm_read_bytes = 0;
std::uint64_t spm_write_bytes = 0;
std::uint64_t spm_miss_bytes = 0;
std::uint64_t input_read_bytes = 0;
std::uint64_t weight_read_bytes = 0;
std::uint64_t psum_read_bytes = 0;
std::uint64_t psum_write_bytes = 0;
std::uint64_t output_write_bytes = 0;
std::uint64_t ddr_read_bytes = 0;
std::uint64_t ddr_write_bytes = 0;
std::uint64_t dram_read_transactions = 0;
std::uint64_t dram_write_transactions = 0;
std::uint64_t dram_cycles = 0;
std::uint64_t tile_count = 0;
double array_utilization = 1.0;
};
struct OpActivity {
std::uint64_t work_items = 0;
std::uint64_t ops = 0;
std::uint64_t bytes = 0;
std::vector<WorkShard> shards;
std::vector<ShardActivity> shard_activity;
};
struct ExternalAccessStats {
std::uint64_t cycles = 0;
std::uint64_t read_transactions = 0;
std::uint64_t write_transactions = 0;
};
bool isIntegerToken(const std::string& token) {
if (token.empty()) {
return false;
}
std::size_t i = token[0] == '-' ? 1 : 0;
if (i >= token.size()) {
return false;
}
for (; i < token.size(); ++i) {
if (!std::isdigit(static_cast<unsigned char>(token[i]))) {
return false;
}
}
return true;
}
// Instead of fully parsing Graphviz, split topology file into tokens for subsequent code to extract integer nodes, undirected edges and integer weights
std::vector<std::string> tokenizeDot(const std::string& text) {
std::vector<std::string> tokens;
for (std::size_t i = 0; i < text.size();) {
const char c = text[i];
if (std::isspace(static_cast<unsigned char>(c))) {
++i;
continue;
}
if (c == '/' && i + 1 < text.size() && text[i + 1] == '/') {
i += 2;
while (i < text.size() && text[i] != '\n') {
++i;
}
continue;
}
if (c == '/' && i + 1 < text.size() && text[i + 1] == '*') {
i += 2;
while (i + 1 < text.size() && !(text[i] == '*' && text[i + 1] == '/')) {
++i;
}
i = std::min(text.size(), i + 2);
continue;
}
if (c == '#') {
while (i < text.size() && text[i] != '\n') {
++i;
}
continue;
}
if (c == '-' && i + 1 < text.size() && text[i + 1] == '-') {
tokens.push_back("--");
i += 2;
continue;
}
if (std::string("{}[]=;,").find(c) != std::string::npos) {
tokens.emplace_back(1, c);
++i;
continue;
}
if (c == '"') {
++i;
std::string token;
while (i < text.size() && text[i] != '"') {
if (text[i] == '\\' && i + 1 < text.size()) {
++i;
}
token.push_back(text[i++]);
}
if (i < text.size() && text[i] == '"') {
++i;
}
tokens.push_back(token);
continue;
}
std::string token;
while (i < text.size()) {
const char ch = text[i];
if (std::isspace(static_cast<unsigned char>(ch)) ||
std::string("{}[]=;,").find(ch) != std::string::npos ||
(ch == '-' && i + 1 < text.size() && text[i + 1] == '-')) {
break;
}
token.push_back(ch);
++i;
}
if (!token.empty()) {
tokens.push_back(token);
} else {
++i;
}
}
return tokens;
}
std::uint64_t readAttrWeight(const std::vector<std::string>& tokens,
std::size_t& i,
std::uint64_t fallback) {
if (i >= tokens.size() || tokens[i] != "[") {
return fallback;
}
std::uint64_t weight = fallback;
int depth = 0;
for (; i < tokens.size(); ++i) {
if (tokens[i] == "[") {
++depth;
} else if (tokens[i] == "]") {
--depth;
if (depth == 0) {
++i;
break;
}
} else if (tokens[i] == "weight" && i + 2 < tokens.size() && tokens[i + 1] == "=" &&
isIntegerToken(tokens[i + 2])) {
weight = static_cast<std::uint64_t>(std::max(1, std::stoi(tokens[i + 2])));
}
}
return weight;
}
std::vector<TopologyEdge> parseGvEdges(const std::string& path,
std::set<int>& nodes,
std::uint64_t& default_weight) {
const std::string text = readFileToString(path);
if (text.empty()) {
throw std::runtime_error("cannot read NPU topology gv file: " + path);
}
const std::vector<std::string> tokens = tokenizeDot(text);
std::vector<TopologyEdge> edges;
default_weight = 1;
for (std::size_t i = 0; i < tokens.size();) {
if (tokens[i] == "edge") {
++i;
default_weight = readAttrWeight(tokens, i, default_weight);
continue;
}
if (!isIntegerToken(tokens[i])) {
++i;
continue;
}
const int first = std::stoi(tokens[i++]);
nodes.insert(first);
if (i < tokens.size() && tokens[i] == "--") {
std::vector<int> chain{first};
while (i < tokens.size() && tokens[i] == "--") {
++i;
if (i >= tokens.size() || !isIntegerToken(tokens[i])) {
throw std::runtime_error("malformed edge chain in gv topology: " + path);
}
const int node = std::stoi(tokens[i++]);
nodes.insert(node);
chain.push_back(node);
}
std::uint64_t weight = default_weight;
if (i < tokens.size() && tokens[i] == "[") {
weight = readAttrWeight(tokens, i, default_weight);
}
for (std::size_t e = 0; e + 1 < chain.size(); ++e) {
edges.push_back({chain[e], chain[e + 1], weight});
}
} else if (i < tokens.size() && tokens[i] == "[") {
(void)readAttrWeight(tokens, i, default_weight);
}
}
return edges;
}
std::vector<std::uint64_t> dijkstraFrom(
int source,
const std::vector<std::vector<std::pair<int, std::uint64_t>>>& adj) {
constexpr std::uint64_t kInf = std::numeric_limits<std::uint64_t>::max() / 4;
std::vector<std::uint64_t> dist(adj.size(), kInf);
using Item = std::pair<std::uint64_t, int>;
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
dist[static_cast<std::size_t>(source)] = 0;
pq.push({0, source});
while (!pq.empty()) {
const auto [d, u] = pq.top();
pq.pop();
if (d != dist[static_cast<std::size_t>(u)]) {
continue;
}
for (const auto& [v, w] : adj[static_cast<std::size_t>(u)]) {
const std::uint64_t nd = d + std::max<std::uint64_t>(1, w);
if (nd < dist[static_cast<std::size_t>(v)]) {
dist[static_cast<std::size_t>(v)] = nd;
pq.push({nd, v});
}
}
}
return dist;
}
RuntimeTopology buildRuntimeTopology(const NPUConfig& cfg) {
RuntimeTopology topo;
topo.controller_node = cfg.controller_local_id;
topo.gv_path = cfg.topology_gv_path;
if (cfg.topology_mode != "custom_gv" || topo.gv_path.empty()) {
throw std::runtime_error(
"NPUSim requires an explicit custom_gv topology. Pass --topology-gv from the benchmark yml "
"or NPUSIM_TOPOLOGY_GV from the local debug environment.");
}
std::set<int> nodes;
std::uint64_t default_weight = 1;
topo.edges = parseGvEdges(topo.gv_path, nodes, default_weight);
(void)default_weight;
if (cfg.mac_nodes.empty()) {
throw std::runtime_error(
"NPUSim requires npu.topology.mac_nodes in the JSON config. The simulator does not "
"derive MAC nodes from mac_unit_count or assume a default topology.");
}
std::vector<int> mac_nodes = cfg.mac_nodes;
if (mac_nodes.size() != static_cast<std::size_t>(cfg.mac_unit_count)) {
std::ostringstream oss;
oss << "invalid NPU topology: mac_nodes has " << mac_nodes.size()
<< " entries, mac_unit_count is " << cfg.mac_unit_count;
throw std::runtime_error(oss.str());
}
int max_node = topo.controller_node;
for (int node : nodes) {
max_node = std::max(max_node, node);
}
for (int node : mac_nodes) {
max_node = std::max(max_node, node);
nodes.insert(node);
}
nodes.insert(topo.controller_node);
topo.node_count = std::max(cfg.topology_node_count, max_node + 1);
if (topo.node_count <= 0) {
throw std::runtime_error("invalid NPU topology: node_count must be positive");
}
topo.adj.assign(static_cast<std::size_t>(topo.node_count), {});
for (const auto& edge : topo.edges) {
if (edge.src < 0 || edge.dst < 0 || edge.src >= topo.node_count || edge.dst >= topo.node_count) {
throw std::runtime_error("gv topology edge endpoint exceeds configured node_count");
}
topo.adj[static_cast<std::size_t>(edge.src)].push_back({edge.dst, edge.weight});
topo.adj[static_cast<std::size_t>(edge.dst)].push_back({edge.src, edge.weight});
}
if (topo.controller_node < 0 || topo.controller_node >= topo.node_count) {
throw std::runtime_error("NPU controller_node is outside topology node range");
}
topo.distance_from_controller = dijkstraFrom(topo.controller_node, topo.adj);
std::set<int> seen_macs;
topo.macs.reserve(mac_nodes.size());
constexpr std::uint64_t kInf = std::numeric_limits<std::uint64_t>::max() / 4;
for (std::size_t mac_id = 0; mac_id < mac_nodes.size(); ++mac_id) {
const int node = mac_nodes[mac_id];
if (node < 0 || node >= topo.node_count) {
throw std::runtime_error("NPU mac_nodes entry is outside topology node range");
}
if (node == topo.controller_node) {
throw std::runtime_error("NPU MAC node cannot reuse controller_node");
}
if (!seen_macs.insert(node).second) {
throw std::runtime_error("NPU mac_nodes contains duplicate node id");
}
const std::uint64_t dist = topo.distance_from_controller[static_cast<std::size_t>(node)];
if (dist >= kInf) {
std::ostringstream oss;
oss << "NPU MAC node " << node << " is not reachable from controller node " << topo.controller_node;
throw std::runtime_error(oss.str());
}
MacProfile mac;
mac.mac_id = static_cast<int>(mac_id);
mac.node_id = node;
mac.degree = static_cast<int>(topo.adj[static_cast<std::size_t>(node)].size());
mac.distance_to_controller = dist;
mac.sram_bytes = cfg.sram_per_mac_bytes;
mac.ops_per_cycle = cfg.mac_ops_per_cycle;
topo.macs.push_back(mac);
}
return topo;
}
std::vector<WorkShard> buildLinearSchedule(std::int64_t work_items,
std::uint64_t bytes,
const RuntimeTopology& topo) {
if (work_items <= 0 || topo.macs.empty()) {
return {};
}
std::vector<double> weights;
weights.reserve(topo.macs.size());
const std::uint64_t expected_bytes_per_mac =
ceilDiv(std::max<std::uint64_t>(1, bytes), static_cast<std::uint64_t>(topo.macs.size()));
double total_weight = 0.0;
for (const auto& mac : topo.macs) {
const double spm_factor =
expected_bytes_per_mac <= mac.sram_bytes
? 1.0
: std::max(0.10, static_cast<double>(mac.sram_bytes) /
static_cast<double>(std::max<std::uint64_t>(1, expected_bytes_per_mac)));
const double distance_factor = 1.0 / (1.0 + static_cast<double>(mac.distance_to_controller));
const double degree_factor = 1.0 + 0.05 * static_cast<double>(std::max(0, mac.degree - 1));
const double w = std::max(1.0, static_cast<double>(mac.ops_per_cycle)) * spm_factor *
distance_factor * degree_factor;
weights.push_back(w);
total_weight += w;
}
if (total_weight <= 0.0) {
total_weight = static_cast<double>(weights.size());
std::fill(weights.begin(), weights.end(), 1.0);
}
std::vector<WorkShard> shards;
std::int64_t begin = 0;
double cumulative = 0.0;
for (std::size_t idx = 0; idx < topo.macs.size(); ++idx) {
cumulative += static_cast<double>(work_items) * weights[idx] / total_weight;
std::int64_t end = (idx + 1 == topo.macs.size())
? work_items
: static_cast<std::int64_t>(std::llround(cumulative));
end = std::max(begin, std::min<std::int64_t>(work_items, end));
if (end > begin) {
shards.push_back({topo.macs[idx].mac_id, topo.macs[idx].node_id, begin, end});
}
begin = end;
}
return shards;
}
std::uint64_t scaleCycles(std::uint64_t cycles, double scale) {
if (cycles == 0) {
return 0;
}
return std::max<std::uint64_t>(
1,
static_cast<std::uint64_t>(std::llround(static_cast<double>(cycles) *
std::max(0.0, scale))));
}
enum class ExternalMemoryTimingMode {
kDisabled,
kStandaloneAnalytic,
kJointChiplet,
};
ExternalMemoryTimingMode selectExternalMemoryTimingMode(const NPUConfig& cfg) {
if (!cfg.external_memory_enable || cfg.external_memory_model == "none") {
return ExternalMemoryTimingMode::kDisabled;
}
if (cfg.external_memory_model == "analytic") {
return ExternalMemoryTimingMode::kStandaloneAnalytic;
}
if (cfg.external_memory_model == "chiplet") {
return ExternalMemoryTimingMode::kJointChiplet;
}
throw std::runtime_error("unsupported NPUSim external_memory.model: " + cfg.external_memory_model);
}
class ExternalMemoryAccounting {
public:
explicit ExternalMemoryAccounting(const NPUConfig& cfg)
: cfg_(cfg), mode_(selectExternalMemoryTimingMode(cfg)) {}
ExternalAccessStats access(bool is_write, std::uint64_t bytes) {
ExternalAccessStats stats;
if (mode_ == ExternalMemoryTimingMode::kDisabled || bytes == 0) {
return stats;
}
const std::uint64_t tx_bytes =
std::max<std::uint64_t>(1, cfg_.dram_transaction_bytes);
const std::uint64_t txns = ceilDiv(bytes, tx_bytes);
if (is_write) {
stats.write_transactions = txns;
} else {
stats.read_transactions = txns;
}
// Joint LEGOSim mode keeps the traffic counters here, but the service
// latency belongs to the separate LPDDR5 chiplet and its PopNet
// completion path. NPUSim should not add a local DRAM delay.
if (mode_ == ExternalMemoryTimingMode::kJointChiplet) {
return stats;
}
if (mode_ == ExternalMemoryTimingMode::kStandaloneAnalytic) {
const std::uint64_t fixed =
is_write ? cfg_.dram_write_fixed_latency_cycles
: cfg_.dram_read_fixed_latency_cycles;
const std::uint64_t transfer =
ceilDiv(bytes, std::max<std::uint64_t>(1, cfg_.ddr_bandwidth_bytes_per_cycle));
stats.cycles = scaleCycles(fixed + transfer + ceilDiv(txns, 4),
cfg_.dram_cycle_scale);
return stats;
}
return stats;
}
private:
const NPUConfig& cfg_;
ExternalMemoryTimingMode mode_ = ExternalMemoryTimingMode::kDisabled;
};
std::vector<std::int64_t> shapeForExternalInput(const Model& model, const std::string& name, std::size_t count) {
auto it = model.value_shapes.find(name);
if (it != model.value_shapes.end() && productU64(it->second) == count) {
return it->second;
}
return {static_cast<std::int64_t>(count)};
}
Tensor tensorFromI64(const std::vector<std::int64_t>& src, const std::vector<std::int64_t>& shape) {
Tensor t;
t.integer_semantics = true;
t.shape = shape.empty() ? std::vector<std::int64_t>{static_cast<std::int64_t>(src.size())} : shape;
t.data.reserve(src.size());
for (std::int64_t value : src) {
t.data.push_back(static_cast<float>(value));
}
const std::size_t elems = static_cast<std::size_t>(productU64(t.shape));
if (t.data.size() < elems) {
t.data.resize(elems, 0.0f);
} else if (t.data.size() > elems && elems > 0) {
t.data.resize(elems);
}
return t;
}
Tensor normalizeExternalFunctionalInput(const Tensor& source,
const std::vector<std::int64_t>& target_shape,
const std::string& input_name) {
if (target_shape.empty()) {
throw std::runtime_error("functional ONNX input '" + input_name +
"' lacks a static shape");
}
const std::size_t target_elements = static_cast<std::size_t>(productU64(target_shape));
if (target_elements == 0) {
throw std::runtime_error("functional ONNX input '" + input_name +
"' has an empty static shape");
}
if (source.data.empty()) {
throw std::runtime_error("functional ONNX input '" + input_name + "' has no data");
}
Tensor normalized;
normalized.shape = target_shape;
normalized.integer_semantics = source.integer_semantics;
if (source.data.size() == target_elements) {
normalized.data = source.data;
return normalized;
}
// A scalar descriptor/value sent by a CPU may represent a constant input
// activation in a smoke test. Do not silently pad or truncate arbitrary
// tensors: only this explicit scalar broadcast is permitted.
if (source.data.size() == 1) {
normalized.data.assign(target_elements, source.data.front());
return normalized;
}
throw std::runtime_error("functional ONNX input '" + input_name + "' has " +
std::to_string(source.data.size()) + " elements, expected " +
std::to_string(target_elements) + " (or one scalar to broadcast)");
}
std::vector<std::int64_t> normalizeAxisShape(std::vector<std::int64_t> shape) {
if (shape.empty()) {
shape.push_back(1);
}
for (auto& dim : shape) {
dim = std::max<std::int64_t>(1, dim);
}
return shape;
}
std::int64_t offsetOf(const std::vector<std::int64_t>& shape, const std::vector<std::int64_t>& idx) {
std::int64_t off = 0;
for (std::size_t i = 0; i < shape.size(); ++i) {
off = off * std::max<std::int64_t>(1, shape[i]) + idx[i];
}
return off;
}
std::vector<std::int64_t> unravel(std::int64_t linear, const std::vector<std::int64_t>& shape) {
std::vector<std::int64_t> idx(shape.size(), 0);
for (std::size_t rev = 0; rev < shape.size(); ++rev) {
const std::size_t i = shape.size() - 1 - rev;
const std::int64_t dim = std::max<std::int64_t>(1, shape[i]);
idx[i] = linear % dim;
linear /= dim;
}
return idx;
}
Tensor elementwiseBinary(const Tensor& a, const Tensor& b, const std::string& op) {
const std::size_t rank = std::max(a.shape.size(), b.shape.size());
std::vector<std::int64_t> out_shape(rank, 1);
std::vector<std::int64_t> a_shape(rank, 1);
std::vector<std::int64_t> b_shape(rank, 1);
std::copy_backward(a.shape.begin(), a.shape.end(), a_shape.end());
std::copy_backward(b.shape.begin(), b.shape.end(), b_shape.end());
for (std::size_t i = 0; i < rank; ++i) {
out_shape[i] = std::max(a_shape[i], b_shape[i]);
}
Tensor out;
out.integer_semantics = a.integer_semantics && b.integer_semantics;
out.shape = out_shape;
out.data.assign(static_cast<std::size_t>(productU64(out_shape)), 0.0f);
for (std::size_t linear = 0; linear < out.data.size(); ++linear) {
const auto idx = unravel(static_cast<std::int64_t>(linear), out_shape);
std::vector<std::int64_t> ai(rank, 0);
std::vector<std::int64_t> bi(rank, 0);
for (std::size_t d = 0; d < rank; ++d) {
ai[d] = (a_shape[d] == 1) ? 0 : idx[d];
bi[d] = (b_shape[d] == 1) ? 0 : idx[d];
}
const float av = a.data[static_cast<std::size_t>(offsetOf(a_shape, ai))];
const float bv = b.data[static_cast<std::size_t>(offsetOf(b_shape, bi))];
if (op == "Add") {
out.data[linear] = av + bv;
} else if (op == "Sub") {
out.data[linear] = av - bv;
} else if (op == "Mul") {
out.data[linear] = av * bv;
} else if (op == "Div") {
out.data[linear] = bv == 0.0f ? 0.0f : av / bv;
} else if (op == "Pow") {
out.data[linear] = std::pow(av, bv);
}
}
return out;
}
Tensor unary(const Tensor& x, const std::string& op) {
Tensor out = x;
for (float& value : out.data) {
if (op == "Relu") {
value = std::max(0.0f, value);
} else if (op == "Sigmoid") {
value = 1.0f / (1.0f + std::exp(-value));
} else if (op == "Tanh") {
value = std::tanh(value);
} else if (op == "Neg") {
value = -value;
} else if (op == "Abs") {
value = std::fabs(value);
} else if (op == "Exp") {
value = std::exp(value);
} else if (op == "Log") {
value = std::log(value);
} else if (op == "Sqrt") {
value = std::sqrt(std::max(0.0f, value));
} else if (op == "Reciprocal") {
value = value == 0.0f ? 0.0f : 1.0f / value;
} else if (op == "Rsqrt") {
value = value <= 0.0f ? 0.0f : 1.0f / std::sqrt(value);
} else if (op == "Erf") {
value = std::erf(value);
} else if (op == "SiLU") {
value = value / (1.0f + std::exp(-value));
} else if (op == "Gelu") {
value = 0.5f * value *
(1.0f + std::erf(value / std::sqrt(2.0f)));
}
}
return out;
}
Tensor matmul2D(const Tensor& a,
const Tensor& b,
const RuntimeTopology& topology,
std::uint64_t& ops,
TensorDType accumulator_dtype = TensorDType::kFp32) {
if (a.shape.size() < 2 || b.shape.size() < 2) {
throw std::runtime_error("MatMul expects tensors with rank >= 2");
}
const std::int64_t m = a.shape[a.shape.size() - 2];
const std::int64_t k = a.shape[a.shape.size() - 1];
const std::int64_t kb = b.shape[b.shape.size() - 2];
const std::int64_t n = b.shape[b.shape.size() - 1];
if (k != kb) {
throw std::runtime_error("MatMul shape mismatch");
}
const bool simple_rank2 = a.shape.size() == 2 && b.shape.size() == 2;
const std::size_t output_batch_rank =
std::max(a.shape.size(), b.shape.size()) - 2;
std::vector<std::int64_t> output_batch_shape(output_batch_rank, 1);
for (std::size_t reverse = 0; reverse < output_batch_rank; ++reverse) {
const std::int64_t a_dim = reverse < a.shape.size() - 2
? a.shape[a.shape.size() - 3 - reverse] : 1;
const std::int64_t b_dim = reverse < b.shape.size() - 2
? b.shape[b.shape.size() - 3 - reverse] : 1;
if (a_dim <= 0 || b_dim <= 0 || (a_dim != b_dim && a_dim != 1 && b_dim != 1)) {
throw std::runtime_error("MatMul batch dimensions are not broadcast-compatible");
}
output_batch_shape[output_batch_rank - 1 - reverse] = std::max(a_dim, b_dim);
}
Tensor out;
out.shape = output_batch_shape;
out.shape.push_back(m);
out.shape.push_back(n);
out.data.assign(static_cast<std::size_t>(productU64(out.shape)), 0.0f);
const auto batchOffset = [&](const Tensor& tensor,
const std::vector<std::int64_t>& output_batch_index) {
const std::size_t tensor_batch_rank = tensor.shape.size() - 2;
std::uint64_t offset = 0;
for (std::size_t dim = 0; dim < tensor_batch_rank; ++dim) {
const std::int64_t tensor_dim = tensor.shape[dim];
const std::size_t output_dim = output_batch_rank - tensor_batch_rank + dim;
const std::int64_t coordinate = tensor_dim == 1 ? 0 : output_batch_index[output_dim];
offset = offset * static_cast<std::uint64_t>(tensor_dim) +
static_cast<std::uint64_t>(coordinate);
}
return offset * static_cast<std::uint64_t>(tensor.shape[tensor.shape.size() - 2]) *
static_cast<std::uint64_t>(tensor.shape.back());
};
const std::uint64_t batch_count = productU64(output_batch_shape);
for (std::uint64_t batch = 0; batch < batch_count; ++batch) {
const std::vector<std::int64_t> batch_index =
unravel(static_cast<std::int64_t>(batch), output_batch_shape);
const std::uint64_t a_base = batchOffset(a, batch_index);
const std::uint64_t b_base = batchOffset(b, batch_index);
const std::uint64_t out_base = batch * static_cast<std::uint64_t>(m) * static_cast<std::uint64_t>(n);
for (std::int64_t i = 0; i < m; ++i) {
for (std::int64_t j = 0; j < n; ++j) {
float sum = 0.0f;
for (std::int64_t kk = 0; kk < k; ++kk) {
sum += a.data[static_cast<std::size_t>(a_base +
static_cast<std::uint64_t>(i * k + kk))] *
b.data[static_cast<std::size_t>(b_base +
static_cast<std::uint64_t>(kk * n + j))];
sum = convertFloatForTensorDType(sum, accumulator_dtype);
}
out.data[static_cast<std::size_t>(out_base +
static_cast<std::uint64_t>(i * n + j))] = sum;
}
}
}
// Keep the legacy topology-aware sharding for the standard rank-2
// functional path. Batched functional MatMul below is deliberately
// serial/reference-only; timing comes from the separate ONNX lowerer.
if (simple_rank2) {
const std::uint64_t work_bytes =
static_cast<std::uint64_t>(std::max<std::int64_t>(1, m * n)) * sizeof(float) +
static_cast<std::uint64_t>(std::max<std::int64_t>(1, m * k + k * n)) * sizeof(float);
(void)buildLinearSchedule(m, work_bytes, topology);
}
ops = 2ULL * batch_count * static_cast<std::uint64_t>(m) *
static_cast<std::uint64_t>(n) * static_cast<std::uint64_t>(k);
return out;
}
Tensor reduceTensor(const Tensor& x,
const std::vector<std::int64_t>& axes_argument,
bool keep_dims,
const std::string& op) {
if (x.shape.empty()) {
return x;
}
std::vector<bool> reduce_axis(x.shape.size(), false);
std::vector<std::int64_t> axes = axes_argument;
bool reduce_all = false;
if (axes.empty()) {
// ONNX opset 13+ distinguishes an omitted axes input (reduce all)
// from an explicitly supplied empty axes tensor (reduce nothing).
reduce_all = true;
}
if (reduce_all) {
std::fill(reduce_axis.begin(), reduce_axis.end(), true);
} else {
for (std::int64_t axis : axes) {
if (axis < 0) {
axis += static_cast<std::int64_t>(x.shape.size());
}
if (axis < 0 || axis >= static_cast<std::int64_t>(x.shape.size())) {
throw std::runtime_error("Reduce operator received an invalid axis");
}
reduce_axis[static_cast<std::size_t>(axis)] = true;
}
}
Tensor out;
std::vector<int> output_dimension_for_input(x.shape.size(), -1);
for (std::size_t dim = 0; dim < x.shape.size(); ++dim) {
if (reduce_axis[dim]) {
if (keep_dims) {
output_dimension_for_input[dim] = static_cast<int>(out.shape.size());
out.shape.push_back(1);
}
} else {
output_dimension_for_input[dim] = static_cast<int>(out.shape.size());
out.shape.push_back(x.shape[dim]);
}
}
const std::size_t output_elements = static_cast<std::size_t>(productU64(out.shape));
const bool is_max = op == "ReduceMax";
const bool is_min = op == "ReduceMin";
out.data.assign(output_elements,
is_max ? -std::numeric_limits<float>::infinity()
: (is_min ? std::numeric_limits<float>::infinity() : 0.0f));
std::vector<std::uint64_t> counts(output_elements, 0);
for (std::size_t linear = 0; linear < x.data.size(); ++linear) {
const std::vector<std::int64_t> input_index =
unravel(static_cast<std::int64_t>(linear), x.shape);
std::vector<std::int64_t> output_index(out.shape.size(), 0);
for (std::size_t dim = 0; dim < x.shape.size(); ++dim) {
const int output_dim = output_dimension_for_input[dim];
if (output_dim >= 0 && !reduce_axis[dim]) {
output_index[static_cast<std::size_t>(output_dim)] = input_index[dim];
}
}
const std::size_t output_linear =
static_cast<std::size_t>(offsetOf(out.shape, output_index));
const float value = x.data[linear];
if (is_max) {
out.data[output_linear] = std::max(out.data[output_linear], value);
} else if (is_min) {
out.data[output_linear] = std::min(out.data[output_linear], value);
} else if (op == "ReduceL1") {
out.data[output_linear] += std::fabs(value);
} else if (op == "ReduceL2") {
out.data[output_linear] += value * value;
} else {
out.data[output_linear] += value;
}
++counts[output_linear];
}
for (std::size_t index = 0; index < out.data.size(); ++index) {
if (op == "ReduceMean") {
out.data[index] /= static_cast<float>(std::max<std::uint64_t>(1, counts[index]));
} else if (op == "ReduceL2") {
out.data[index] = std::sqrt(out.data[index]);
}
}
return out;
}
Tensor transpose2DIfNeeded(const Tensor& t, bool trans) {
if (!trans) {
return t;
}
if (t.shape.size() != 2) {
throw std::runtime_error("Gemm transpose only supports 2D tensors");
}
Tensor out;
out.integer_semantics = t.integer_semantics;
out.shape = {t.shape[1], t.shape[0]};
out.data.assign(t.data.size(), 0.0f);
for (std::int64_t i = 0; i < t.shape[0]; ++i) {
for (std::int64_t j = 0; j < t.shape[1]; ++j) {
out.data[static_cast<std::size_t>(j * t.shape[0] + i)] =
t.data[static_cast<std::size_t>(i * t.shape[1] + j)];
}
}
return out;
}
Tensor softmax(const Tensor& x, std::int64_t axis) {
Tensor out = x;
const auto shape = normalizeAxisShape(x.shape);
const std::int64_t rank = static_cast<std::int64_t>(shape.size());
if (axis < 0) {
axis += rank;
}
axis = std::max<std::int64_t>(0, std::min<std::int64_t>(rank - 1, axis));
std::int64_t outer = 1;
for (std::int64_t i = 0; i < axis; ++i) {
outer *= shape[static_cast<std::size_t>(i)];
}
const std::int64_t dim = shape[static_cast<std::size_t>(axis)];
std::int64_t inner = 1;
for (std::int64_t i = axis + 1; i < rank; ++i) {
inner *= shape[static_cast<std::size_t>(i)];
}
for (std::int64_t o = 0; o < outer; ++o) {
for (std::int64_t in = 0; in < inner; ++in) {
float max_v = -std::numeric_limits<float>::infinity();
for (std::int64_t d = 0; d < dim; ++d) {
const std::size_t idx = static_cast<std::size_t>((o * dim + d) * inner + in);
max_v = std::max(max_v, x.data[idx]);
}
float denom = 0.0f;
for (std::int64_t d = 0; d < dim; ++d) {
const std::size_t idx = static_cast<std::size_t>((o * dim + d) * inner + in);
out.data[idx] = std::exp(x.data[idx] - max_v);
denom += out.data[idx];
}
for (std::int64_t d = 0; d < dim; ++d) {
const std::size_t idx = static_cast<std::size_t>((o * dim + d) * inner + in);
out.data[idx] = denom == 0.0f ? 0.0f : out.data[idx] / denom;
}
}
}
return out;
}
Tensor rmsNormalization(const Tensor& x,
const Tensor& scale,
float epsilon,
std::int64_t axis) {
const std::vector<std::int64_t> shape = normalizeAxisShape(x.shape);
const std::int64_t rank = static_cast<std::int64_t>(shape.size());
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
throw std::runtime_error("RMSNormalization received an invalid axis");
}
std::size_t outer = 1;
std::size_t normalized = 1;
for (std::int64_t dimension = 0; dimension < rank; ++dimension) {
const std::size_t extent = static_cast<std::size_t>(shape[static_cast<std::size_t>(dimension)]);
if (dimension < axis) {
outer *= extent;
} else {
normalized *= extent;
}
}
if (scale.data.empty() || (scale.data.size() != 1 && scale.data.size() != normalized)) {
throw std::runtime_error("RMSNormalization scale must be scalar or match normalized dimensions");
}
Tensor out = x;
for (std::size_t group = 0; group < outer; ++group) {
const std::size_t base = group * normalized;
float square_sum = 0.0f;
for (std::size_t index = 0; index < normalized; ++index) {
const float value = x.data[base + index];
square_sum += value * value;
}
const float inverse_rms = 1.0f /
std::sqrt(square_sum / static_cast<float>(normalized) + std::max(0.0f, epsilon));
for (std::size_t index = 0; index < normalized; ++index) {
const float scale_value = scale.data.size() == 1 ? scale.data.front() : scale.data[index];
out.data[base + index] = x.data[base + index] * inverse_rms * scale_value;
}
}
return out;
}
Tensor layerNormalization(const Tensor& x,
const Tensor& scale,
const Tensor* bias,
float epsilon,
std::int64_t axis) {
const std::vector<std::int64_t> shape = normalizeAxisShape(x.shape);
const std::int64_t rank = static_cast<std::int64_t>(shape.size());
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
throw std::runtime_error("LayerNormalization received an invalid axis");
}
std::size_t outer = 1;
std::size_t normalized = 1;
for (std::int64_t dimension = 0; dimension < rank; ++dimension) {
const std::size_t extent = static_cast<std::size_t>(shape[static_cast<std::size_t>(dimension)]);
if (dimension < axis) {
outer *= extent;
} else {
normalized *= extent;