载入中...
搜索中...
未找到
OnnxQuant.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <bit>
3#include <cmath>
4#include <functional>
5#include <numeric>
6#include <queue>
7#include <random>
8#include <set>
12#include "tensor/OnnxInternal.h"
13
14// OnnxQuant.cpp
16namespace {
17affine::ByteView bytes(const RuntimeTensor& t) {
18 if (t.element != OnnxElement::Int8 && t.element != OnnxElement::UInt8)
19 throw Failure("Expected packed int8/uint8 tensor");
20 return {t.bytes, t.element == OnnxElement::Int8};
21}
22template <class T>
23T checked(Result<T> result) {
24 if (!result.ok()) throw Failure(result.error()->message(), result.error()->code());
25 return std::move(result.value());
26}
27int zero(const std::vector<const RuntimeTensor*>& in, size_t i, const RuntimeTensor& owner) {
28 if (i >= in.size() || !in[i]) return 0;
29 if (in[i]->element != owner.element || count(in[i]->shape) != 1)
30 throw Failure("Expected matching scalar zero point");
31 return static_cast<int>(integer(*in[i]));
32}
33} // namespace
34std::vector<RuntimeTensor> executeQuant(const Node& n, const std::vector<const RuntimeTensor*>& in,
36 const auto& x = required(in, 0);
37 if (n.op == "DynamicQuantizeLinear") {
38 if (compute && count(x.shape)) {
39 if (x.element != OnnxElement::Float32) throw Failure("Expected FP32 quantization input");
40 const size_t total = count(x.shape);
41 auto stats = dispatchFloat(
42 *compute, {&x}, {3},
43 "float lo=0.0,hi=0.0,invalid=0.0;for(uint j=0;j<" + std::to_string(total) +
44 "u;++j){float v=x0[j];if(isinf(v))invalid=1.0;if(!isnan(v)){lo=min(lo,v);hi=max(hi,v);}}float "
45 "s=(hi==lo)?1.0:(hi-lo)/255.0;y[0]=s;y[1]=clamp(roundEven(-lo/s),0.0,255.0);y[2]=invalid;",
46 1);
47 auto values = floats(stats);
48 if (values[2] != 0 || !std::isfinite(values[0]) || !(values[0] > 0))
49 throw Failure("Nonfinite quantization input/range");
50 auto scale = make(OnnxElement::Float32, {}, std::vector<float>{values[0]});
51 auto zeroPoint = make(OnnxElement::UInt8, {}, std::vector<uint8_t>{static_cast<uint8_t>(values[1])});
52 auto params = make(OnnxElement::Float32, {2}, std::vector<float>{values[0], values[1]});
53 std::string source =
54 "#version 450\nlayout(local_size_x=64)in;layout(std430,binding=0)readonly buffer X{float "
55 "x[];};layout(std430,binding=1)readonly buffer P{float p[];};layout(std430,binding=2)writeonly buffer "
56 "Y{uint y[];};void main(){uint word=gl_GlobalInvocationID.x;if(word>=" +
57 std::to_string((total + 3) / 4) +
58 "u)return;uint packed=0u;for(uint c=0u;c<4u;++c){uint j=word*4u+c;if(j<" + std::to_string(total) +
59 "u){float v=x[j];uint "
60 "q=isnan(v)?0u:uint(clamp(roundEven(v/p[0])+p[1],0.0,255.0));packed|=q<<(c*8u);}}y[word]=packed;}";
61 const std::vector<OnnxBuffer> inputs{x.bytes.buffer(), params.bytes.buffer()};
62 auto q = checked(compute->enqueue(source, inputs, total, static_cast<uint32_t>((total + 3) / 4)));
63 std::vector<RuntimeTensor> result;
64 result.reserve(3);
65 result.emplace_back(RuntimeTensor{OnnxElement::UInt8, x.shape, std::move(q)});
66 result.emplace_back(std::move(scale));
67 result.emplace_back(std::move(zeroPoint));
68 return result;
69 }
70 auto input = floats(x);
71 // ORT CPU DynamicQuantizeLinear ignores NaN for range estimation and stores code 0.
72 // Exported Kokoro phase graphs produce 0/0 at zero-amplitude STFT bins.
73 std::vector<size_t> nanPositions;
74 for (size_t i = 0; i < input.size(); ++i)
75 if (std::isnan(input[i])) {
76 nanPositions.push_back(i);
77 input[i] = 0;
78 }
79 auto q = checked(affine::dynamicQuantize(input));
80 for (auto i : nanPositions) q.values[i] = 0;
81 std::vector<RuntimeTensor> result;
82 result.reserve(3);
83 result.emplace_back(RuntimeTensor{OnnxElement::UInt8, x.shape, std::move(q.values)});
84 result.emplace_back(make(OnnxElement::Float32, {}, std::vector<float>{q.scale}));
85 result.emplace_back(make(OnnxElement::UInt8, {}, std::vector<uint8_t>{q.zeroPoint}));
86 return result;
87 }
88 if (n.op == "QuantizeLinear" || n.op == "DequantizeLinear") {
89 const auto scales = floats(required(in, 1));
90 if (required(in, 1).shape.size() > 1) throw Failure("Quantization scale must be scalar or vector");
91 if (scales.empty()) throw Failure("Empty quantization scales");
92 const RuntimeTensor* zp = in.size() > 2 ? in[2] : nullptr;
93 const auto type = n.op == "DequantizeLinear" ? x.element : (zp ? zp->element : OnnxElement::UInt8);
95 throw Failure("Unsupported quantization dtype", DiagnosticCode::Unsupported);
96 if (zp && (zp->element != type || zp->shape != required(in, 1).shape))
97 throw Failure("Scale/zero point mismatch");
98 std::vector<int32_t> zeros(scales.size(), 0);
99 if (zp)
100 for (size_t i = 0; i < zeros.size(); ++i) zeros[i] = static_cast<int32_t>(integer(*zp, i));
101 size_t inner = 1;
102 if (scales.size() > 1) {
103 const int a = axis(attr(n, "axis", 1), x.shape.size());
104 if (static_cast<size_t>(x.shape[a]) != scales.size()) throw Failure("Scale channel count mismatch");
105 for (size_t i = a + 1; i < x.shape.size(); ++i) inner *= x.shape[i];
106 }
107 if (n.op == "DequantizeLinear")
108 return single(
109 make(OnnxElement::Float32, x.shape, checked(affine::dequantize(bytes(x), scales, zeros, inner))));
110 const auto values = floats(x);
111 std::vector<uint8_t> out(values.size());
112 for (size_t i = 0; i < values.size(); i += inner) {
113 const size_t channel = (i / inner) % scales.size();
114 auto q = checked(affine::quantize(std::span(values).subspan(i, inner), scales[channel], zeros[channel],
116 std::copy(q.begin(), q.end(), out.begin() + i);
117 }
118 return single(RuntimeTensor{type, x.shape, std::move(out)});
119 }
120 if (n.op == "MatMulInteger") {
121 const auto& b = required(in, 1);
122 if (x.shape.size() < 2 || b.shape.size() != 2)
123 throw Failure("MatMulInteger requires rank >=2 A and rank 2 B", DiagnosticCode::Unsupported);
124 const size_t k = x.shape.back(), columns = b.shape[1];
125 if (k != static_cast<size_t>(b.shape[0]) || k == 0) throw Failure("Invalid MatMulInteger inner dimension");
126 const size_t rows = count(x.shape) / k;
127 auto shape = x.shape;
128 shape.back() = columns;
129 if (compute) {
130 if ((x.element != OnnxElement::Int8 && x.element != OnnxElement::UInt8) ||
131 (b.element != OnnxElement::Int8 && b.element != OnnxElement::UInt8))
132 throw Failure("Expected packed integer matrices");
133 std::vector<int32_t> bz{zero(in, 3, b)};
134 return single(RuntimeTensor{
136 gpuMatmulResident(*compute, x.bytes.buffer(), b.bytes.buffer(), x.element == OnnxElement::Int8,
137 b.element == OnnxElement::Int8, rows, k, columns, zero(in, 2, x), bz)});
138 }
139 return single(make(
141 checked(affine::matmul(bytes(x), bytes(b), rows, k, columns, zero(in, 2, x), zero(in, 3, b), compute))));
142 }
143 if (n.op == "ConvInteger") {
144 const auto& w = required(in, 1);
145 if ((x.shape.size() != 3 && x.shape.size() != 4) || w.shape.size() != x.shape.size())
146 throw Failure("ConvInteger supports 1D/2D NCHW", DiagnosticCode::Unsupported);
147 const size_t spatial = x.shape.size() - 2;
148 if (n.attrs.contains("kernel_shape") &&
149 n.attrs.at("kernel_shape").integers != std::vector<int64_t>(w.shape.begin() + 2, w.shape.end()))
150 throw Failure("Convolution kernel_shape mismatch");
151 auto strides = attrs(n, "strides", std::vector<int64_t>(spatial, 1));
152 auto pads = attrs(n, "pads", std::vector<int64_t>(2 * spatial, 0));
153 auto dilations = attrs(n, "dilations", std::vector<int64_t>(spatial, 1));
154 if (strides.size() != spatial || pads.size() != 2 * spatial || dilations.size() != spatial)
155 throw Failure("Invalid convolution attributes");
156 auto narrow = [](int64_t v) {
157 if (v < 0 || v > 65536) throw Failure("Convolution attribute out of range");
158 return static_cast<int>(v);
159 };
161 s.batch = narrow(x.shape[0]);
162 s.channels = narrow(x.shape[1]);
163 s.outputs = narrow(w.shape[0]);
164 s.width = narrow(x.shape.back());
165 s.kernelW = narrow(w.shape.back());
166 s.strideW = narrow(strides.back());
167 s.dilationW = narrow(dilations.back());
168 s.padLeft = narrow(pads[spatial - 1]);
169 s.padRight = narrow(pads.back());
170 s.groups = narrow(attr(n, "group", 1));
171 if (spatial == 2) {
172 s.height = narrow(x.shape[2]);
173 s.kernelH = narrow(w.shape[2]);
174 s.strideH = narrow(strides[0]);
175 s.dilationH = narrow(dilations[0]);
176 s.padTop = narrow(pads[0]);
177 s.padBottom = narrow(pads[2]);
178 }
179 if (!s.groups || s.channels % s.groups || w.shape[1] != s.channels / s.groups)
180 throw Failure("Convolution channel mismatch");
181 std::vector<int32_t> wz{0};
182 if (in.size() > 3 && in[3]) {
183 if (in[3]->element != w.element) throw Failure("Weight zero-point type mismatch");
184 wz.clear();
185 for (auto z : ints(*in[3])) wz.push_back(static_cast<int32_t>(z));
186 }
187 if (compute) {
188 if ((x.element != OnnxElement::Int8 && x.element != OnnxElement::UInt8) ||
189 (w.element != OnnxElement::Int8 && w.element != OnnxElement::UInt8))
190 throw Failure("Expected packed convolution inputs");
191 const auto extent =
192 checked(affine::detail::validateConv(x.bytes.size(), w.bytes.size(), x.element == OnnxElement::Int8,
193 w.element == OnnxElement::Int8, s, zero(in, 2, x), wz));
194 std::vector<int64_t> outputShape{s.batch, s.outputs};
195 if (spatial == 2) outputShape.push_back(extent.height);
196 outputShape.push_back(extent.width);
197 return single(RuntimeTensor{
198 OnnxElement::Int32, outputShape,
199 gpuConvResident(*compute, x.bytes.buffer(), w.bytes.buffer(), x.element == OnnxElement::Int8,
200 w.element == OnnxElement::Int8, s, zero(in, 2, x), wz)});
201 }
202 auto values = checked(affine::conv(bytes(x), bytes(w), s, zero(in, 2, x), wz, compute));
203 std::vector<int64_t> shape{s.batch, s.outputs};
204 if (spatial == 2)
205 shape.push_back(
206 (s.height + s.padTop + s.padBottom - int64_t(s.dilationH) * (s.kernelH - 1) - 1) / s.strideH + 1);
207 shape.push_back((s.width + s.padLeft + s.padRight - int64_t(s.dilationW) * (s.kernelW - 1) - 1) / s.strideW +
208 1);
210 }
211 throw Failure("Unsupported quantized operation", DiagnosticCode::Unsupported);
212}
213} // namespace eve::tensor::onnx_detail
214
215// OnnxReader.cpp
216namespace eve::tensor::onnx_detail {
217namespace {
218struct Field {
219 int id = 0, wire = 0;
220 uint64_t number = 0;
221 std::span<const uint8_t> bytes;
222 std::string text() const { return {reinterpret_cast<const char*>(bytes.data()), bytes.size()}; }
223};
224class Reader {
225public:
226 explicit Reader(std::span<const uint8_t> data) : data_(data) {}
227 bool empty() const { return offset_ == data_.size(); }
228 uint64_t varint() {
229 uint64_t n = 0;
230 for (int shift = 0; shift < 70; shift += 7) {
231 if (offset_ == data_.size()) throw Failure("Truncated protobuf varint", DiagnosticCode::ParseError);
232 const uint8_t b = data_[offset_++];
233 if (shift == 63 && b > 1) throw Failure("Overflowing protobuf varint", DiagnosticCode::ParseError);
234 n |= static_cast<uint64_t>(b & 127) << shift;
235 if (!(b & 128)) return n;
236 }
237 throw Failure("Invalid protobuf varint", DiagnosticCode::ParseError);
238 }
239 std::span<const uint8_t> take(uint64_t n) {
240 if (n > data_.size() - offset_) throw Failure("Truncated protobuf field", DiagnosticCode::ParseError);
241 auto result = data_.subspan(offset_, static_cast<size_t>(n));
242 offset_ += static_cast<size_t>(n);
243 return result;
244 }
245 Field next() {
246 const uint64_t tag = varint();
247 if ((tag >> 3) == 0 || (tag >> 3) > 0x1fffffff)
248 throw Failure("Invalid protobuf tag", DiagnosticCode::ParseError);
249 Field f;
250 f.id = static_cast<int>(tag >> 3);
251 f.wire = tag & 7;
252 switch (f.wire) {
253 case 0: f.number = varint(); break;
254 case 1: f.bytes = take(8); break;
255 case 2: f.bytes = take(varint()); break;
256 case 5: f.bytes = take(4); break;
257 default: throw Failure("Unsupported protobuf wire type", DiagnosticCode::ParseError);
258 }
259 return f;
260 }
261
262private:
263 std::span<const uint8_t> data_;
264 size_t offset_ = 0;
265};
266void wire(const Field& f, int expected) {
267 if (f.wire != expected) throw Failure("Unexpected protobuf field type", DiagnosticCode::ParseError);
268}
269void integers(const Field& f, std::vector<int64_t>& out) {
270 if (f.wire == 0)
271 out.push_back(std::bit_cast<int64_t>(f.number));
272 else {
273 wire(f, 2);
274 Reader r(f.bytes);
275 while (!r.empty()) out.push_back(std::bit_cast<int64_t>(r.varint()));
276 }
277}
278void reals(const Field& f, std::vector<float>& out) {
279 if (f.wire != 2 && f.wire != 5) throw Failure("Invalid float wire type", DiagnosticCode::ParseError);
280 if (f.bytes.size() % 4) throw Failure("Truncated float payload", DiagnosticCode::ParseError);
281 for (size_t i = 0; i < f.bytes.size(); i += 4) {
282 float x;
283 std::memcpy(&x, f.bytes.data() + i, 4);
284 out.push_back(x);
285 }
286}
287std::pair<std::string, RuntimeTensor> tensor(std::span<const uint8_t> data) {
288 Reader r(data);
289 RuntimeTensor v;
290 std::string name;
291 std::vector<int64_t> iv;
292 std::vector<float> fv;
293 bool raw = false, type = false;
294 while (!r.empty()) {
295 auto f = r.next();
296 switch (f.id) {
297 case 1: integers(f, v.shape); break;
298 case 2:
299 wire(f, 0);
300 if (f.number > 9) throw Failure("Unsupported tensor element type", DiagnosticCode::Unsupported);
301 v.element = static_cast<OnnxElement>(f.number);
302 type = true;
303 break;
304 case 4: reals(f, fv); break;
305 case 5:
306 case 7: integers(f, iv); break;
307 case 8:
308 wire(f, 2);
309 name = f.text();
310 break;
311 case 9:
312 wire(f, 2);
313 if (raw) throw Failure("Duplicate raw tensor data", DiagnosticCode::ParseError);
314 v.bytes.assign(f.bytes.begin(), f.bytes.end());
315 raw = true;
316 break;
317 case 14:
318 wire(f, 0);
319 if (f.number != 0) throw Failure("External tensor data unsupported", DiagnosticCode::Unsupported);
320 break;
321 case 3:
322 case 6:
323 case 10:
324 case 11:
325 case 13: throw Failure("External, segmented or unsupported tensor data", DiagnosticCode::Unsupported);
326 default: break;
327 }
328 }
329 if (!type) throw Failure("Tensor has no dtype", DiagnosticCode::ParseError);
330 const size_t n = count(v.shape), size = elementSize(v.element);
331 if (raw && (!iv.empty() || !fv.empty())) throw Failure("Ambiguous tensor payload", DiagnosticCode::ParseError);
332 if (!raw) {
333 if (v.element == OnnxElement::Float32) {
334 if (fv.size() != n || !iv.empty())
335 throw Failure("Invalid float tensor payload", DiagnosticCode::ParseError);
336 v.bytes.resize(n * size);
337 if (n) std::memcpy(v.bytes.data(), fv.data(), v.bytes.size());
338 } else {
339 if (iv.size() != n || !fv.empty())
340 throw Failure("Invalid integer tensor payload", DiagnosticCode::ParseError);
341 v.bytes.resize(n * size);
342 for (size_t i = 0; i < n; ++i) {
343 const auto x = iv[i];
344 if ((v.element == OnnxElement::UInt8 && (x < 0 || x > 255)) ||
345 (v.element == OnnxElement::Int8 && (x < -128 || x > 127)) ||
346 (v.element == OnnxElement::Bool && x != 0 && x != 1) ||
347 (v.element == OnnxElement::Int32 && (x < INT32_MIN || x > INT32_MAX)))
348 throw Failure("Integer initializer out of range", DiagnosticCode::ParseError);
349 std::memcpy(v.bytes.data() + i * size, &x, size);
350 }
351 }
352 }
353 validate(v);
354 return {std::move(name), std::move(v)};
355}
356ModelData parseGraph(std::span<const uint8_t> bytes, size_t depth);
357std::pair<std::string, Attribute> attribute(std::span<const uint8_t> bytes, size_t depth) {
358 Reader r(bytes);
359 Attribute a;
360 std::string name;
361 while (!r.empty()) {
362 auto f = r.next();
363 switch (f.id) {
364 case 1:
365 wire(f, 2);
366 name = f.text();
367 break;
368 case 20:
369 wire(f, 0);
370 a.type = static_cast<int>(f.number);
371 break;
372 case 2: {
373 wire(f, 5);
374 std::memcpy(&a.real, f.bytes.data(), 4);
375 break;
376 }
377 case 3:
378 wire(f, 0);
379 a.integer = std::bit_cast<int64_t>(f.number);
380 break;
381 case 4:
382 wire(f, 2);
383 a.text = f.text();
384 break;
385 case 5:
386 wire(f, 2);
387 a.tensor = tensor(f.bytes).second;
388 break;
389 case 7: reals(f, a.reals); break;
390 case 8: integers(f, a.integers); break;
391 case 9:
392 wire(f, 2);
393 a.strings.push_back(f.text());
394 break;
395 case 6:
396 wire(f, 2);
397 a.graph = std::make_shared<ModelData>(parseGraph(f.bytes, depth + 1));
398 break;
399 case 11: throw Failure("Multiple graph attributes unsupported", DiagnosticCode::Unsupported);
400 case 21: throw Failure("Function attribute references unsupported", DiagnosticCode::Unsupported);
401 default: break;
402 }
403 }
404 if (name.empty() || !a.type) throw Failure("Incomplete attribute", DiagnosticCode::ParseError);
405 return {std::move(name), std::move(a)};
406}
407Node node(std::span<const uint8_t> bytes, size_t depth) {
408 Reader r(bytes);
409 Node n;
410 while (!r.empty()) {
411 auto f = r.next();
412 if (f.id >= 1 && f.id <= 5) wire(f, 2);
413 switch (f.id) {
414 case 1: n.inputs.push_back(f.text()); break;
415 case 2: n.outputs.push_back(f.text()); break;
416 case 3: n.name = f.text(); break;
417 case 4: n.op = f.text(); break;
418 case 5:
419 if (!n.attrs.insert(attribute(f.bytes, depth)).second)
420 throw Failure("Duplicate attribute", DiagnosticCode::ParseError);
421 break;
422 case 7:
423 wire(f, 2);
424 n.domain = f.text();
425 break;
426 case 8: throw Failure("Function overloads unsupported", DiagnosticCode::Unsupported);
427 default: break;
428 }
429 }
430 if (n.op.empty() || n.outputs.empty()) throw Failure("Incomplete node", DiagnosticCode::ParseError);
431 return n;
432}
433std::pair<std::string, Input> input(std::span<const uint8_t> bytes) {
434 Reader r(bytes);
435 std::string name;
436 Input value;
437 while (!r.empty()) {
438 auto f = r.next();
439 if (f.id == 1) {
440 wire(f, 2);
441 name = f.text();
442 }
443 if (f.id == 2) {
444 wire(f, 2);
445 Reader type(f.bytes);
446 while (!type.empty()) {
447 auto t = type.next();
448 if (t.id == 4) {
449 value.type = 0;
450 continue;
451 }
452 if (t.id != 1) throw Failure("Non-tensor graph input", DiagnosticCode::Unsupported);
453 wire(t, 2);
454 Reader tt(t.bytes);
455 while (!tt.empty()) {
456 auto p = tt.next();
457 if (p.id == 1) {
458 wire(p, 0);
459 value.type = static_cast<int>(p.number);
460 }
461 if (p.id == 2) {
462 wire(p, 2);
463 Reader shape(p.bytes);
464 while (!shape.empty()) {
465 auto d = shape.next();
466 if (d.id != 1) continue;
467 wire(d, 2);
468 Reader dim(d.bytes);
469 int64_t v = -1;
470 while (!dim.empty()) {
471 auto x = dim.next();
472 if (x.id == 1) {
473 wire(x, 0);
474 v = std::bit_cast<int64_t>(x.number);
475 }
476 }
477 value.shape.push_back(v);
478 }
479 }
480 }
481 }
482 }
483 }
484 if (name.empty()) throw Failure("Empty value name", DiagnosticCode::ParseError);
485 if (value.shape.size() > 6) throw Failure("Input rank exceeds six", DiagnosticCode::Unsupported);
486 for (auto d : value.shape)
487 if (d < -1 || d > INT32_MAX) throw Failure("Invalid interface dimension", DiagnosticCode::ParseError);
488 return {name, value};
489}
490ModelData parseGraph(std::span<const uint8_t> bytes, size_t depth) {
491 ModelData model;
492 if (depth > 16) throw Failure("ONNX graph nesting limit exceeded", DiagnosticCode::ParseError);
493 Reader g(bytes);
494 while (!g.empty()) {
495 auto f = g.next();
496 if (f.id == 1) {
497 wire(f, 2);
498 if (model.nodes.size() >= 100000) throw Failure("Node limit exceeded", DiagnosticCode::ParseError);
499 model.nodes.push_back(node(f.bytes, depth));
500 }
501 if (f.id == 5) {
502 wire(f, 2);
503 auto t = tensor(f.bytes);
504 t.second.bytes.retainAcrossRuns();
505 if (t.first.empty() || !model.constants.emplace(std::move(t)).second)
506 throw Failure("Duplicate/empty initializer", DiagnosticCode::ParseError);
507 }
508 if (f.id == 11) {
509 wire(f, 2);
510 auto v = input(f.bytes);
511 model.info.inputs.push_back(v.first);
512 if (!model.inputs.emplace(std::move(v)).second)
513 throw Failure("Duplicate graph input", DiagnosticCode::ParseError);
514 }
515 if (f.id == 12) {
516 wire(f, 2);
517 model.info.outputs.push_back(input(f.bytes).first);
518 }
519 if (f.id == 15) throw Failure("Sparse initializers unsupported", DiagnosticCode::Unsupported);
520 }
521 return model;
522}
523} // namespace
524
525ModelData parse(std::span<const uint8_t> bytes) {
526 if constexpr (std::endian::native != std::endian::little)
527 throw Failure("ONNX requires little-endian host", DiagnosticCode::Unsupported);
528 if (bytes.empty() || bytes.size() > 512u * 1024u * 1024u)
529 throw Failure("Model size exceeds import limit", DiagnosticCode::ParseError);
531 Reader r(bytes);
532 std::span<const uint8_t> graph;
533 while (!r.empty()) {
534 auto f = r.next();
535 if (f.id == 1) {
536 wire(f, 0);
537 model.info.irVersion = static_cast<int64_t>(f.number);
538 }
539 if (f.id == 7) {
540 wire(f, 2);
541 if (!graph.empty()) throw Failure("Duplicate graph", DiagnosticCode::ParseError);
542 graph = f.bytes;
543 }
544 if (f.id == 8) {
545 wire(f, 2);
546 Reader ops(f.bytes);
547 std::string domain;
548 int64_t version = 0;
549 while (!ops.empty()) {
550 auto x = ops.next();
551 if (x.id == 1) {
552 wire(x, 2);
553 domain = x.text();
554 }
555 if (x.id == 2) {
556 wire(x, 0);
557 version = x.number;
558 }
559 }
560 if (!model.opsets.emplace(domain, version).second)
561 throw Failure("Duplicate opset", DiagnosticCode::ParseError);
562 }
563 if (f.id == 20 || f.id == 25 || f.id == 26)
564 throw Failure("Training/functions/device configuration unsupported", DiagnosticCode::Unsupported);
565 }
566 if (model.info.irVersion < 3 || model.info.irVersion > 10 || !model.opsets.contains("") ||
567 model.opsets.at("") < 13 || model.opsets.at("") > 17)
568 throw Failure("Unsupported ONNX IR/opset version", DiagnosticCode::UnknownVersion);
569 if (model.opsets.contains("com.microsoft") && model.opsets.at("com.microsoft") != 1)
570 throw Failure("Unsupported Microsoft opset", DiagnosticCode::UnknownVersion);
571 if (graph.empty()) throw Failure("Missing ONNX graph", DiagnosticCode::ParseError);
572 auto parsed = parseGraph(graph, 0);
573 model.nodes = std::move(parsed.nodes);
574 model.constants = std::move(parsed.constants);
575 model.inputs = std::move(parsed.inputs);
576 model.info.inputs = std::move(parsed.info.inputs);
577 model.info.outputs = std::move(parsed.info.outputs);
578 std::set<std::string> names;
579 for (const auto& [name, v] : model.constants) {
580 names.insert(name);
581 model.info.initializerBytes += v.bytes.size();
582 }
583 for (const auto& [name, v] : model.inputs) names.insert(name);
584 for (const auto& n : model.nodes) {
585 if (!model.opsets.contains(n.domain)) throw Failure("Node domain has no opset", DiagnosticCode::ParseError);
586 for (const auto& name : n.inputs)
587 if (!name.empty() && !names.contains(name))
588 throw Failure("Input not in topological order: " + name, DiagnosticCode::ParseError);
589 for (const auto& name : n.outputs)
590 if (!name.empty() && !names.insert(name).second)
591 throw Failure("Duplicate graph value: " + name, DiagnosticCode::ParseError);
592 if (!isSupported(n)) model.info.unsupportedNodes.push_back(n.name + " [" + n.domain + "::" + n.op + "]");
593 }
594 for (const auto& out : model.info.outputs)
595 if (!names.contains(out)) throw Failure("Undefined graph output", DiagnosticCode::ParseError);
596 size_t recursiveNodes = 0;
597 std::function<void(const ModelData&, const std::set<std::string>&, bool)> validateNested;
598 validateNested = [&](const ModelData& g, const std::set<std::string>& outer, bool root) {
599 recursiveNodes += g.nodes.size();
600 if (recursiveNodes > 100000) throw Failure("Recursive node limit exceeded", DiagnosticCode::ParseError);
601 auto available = outer;
602 std::set<std::string> locals;
603 for (const auto& [name, t] : g.constants) locals.insert(name);
604 for (const auto& [name, t] : g.inputs) locals.insert(name);
605 for (const auto& n : g.nodes)
606 for (const auto& out : n.outputs)
607 if (!out.empty() && !locals.insert(out).second)
608 throw Failure("Duplicate nested graph value: " + out, DiagnosticCode::ParseError);
609 available.insert(locals.begin(), locals.end());
610 for (const auto& n : g.nodes) {
611 if (!model.opsets.contains(n.domain))
612 throw Failure("Nested node domain has no opset", DiagnosticCode::ParseError);
613 for (const auto& input : n.inputs)
614 if (!input.empty() && !available.contains(input))
615 throw Failure("Undefined lexical capture: " + input, DiagnosticCode::ParseError);
616 if (!root && !isSupported(n))
617 model.info.unsupportedNodes.push_back(n.name + " [" + n.domain + "::" + n.op + "]");
618 for (const auto& [key, a] : n.attrs)
619 if (a.graph) validateNested(*a.graph, available, false);
620 }
621 for (const auto& out : g.info.outputs)
622 if (!available.contains(out)) throw Failure("Undefined nested output: " + out, DiagnosticCode::ParseError);
623 };
624 validateNested(model, {}, true);
625 model.info.nodeCount = model.nodes.size();
626 return model;
627}
628} // namespace eve::tensor::onnx_detail
629
630// OnnxRuntime.cpp
631namespace eve::tensor::onnx_detail {
632namespace {
633struct Value {
634 const RuntimeTensor* borrowed = nullptr;
635 std::shared_ptr<const RuntimeTensor> owned;
636 std::shared_ptr<std::vector<Value>> sequence;
638 const RuntimeTensor& tensor() const {
639 if (owned) return *owned;
640 if (borrowed) return *borrowed;
641 throw Failure("Expected tensor, received sequence");
642 }
643};
644using Values = std::unordered_map<std::string, Value>;
645struct Context {
646 OnnxCompute* compute;
647 uint64_t seed;
648 bool finite;
649 size_t steps = 0, liveBytes = 0;
650 std::unordered_map<const Node*, std::mt19937> randomStreams;
651};
652Value hold(RuntimeTensor t, Context& c) {
653 validate(t);
654 if (c.finite && t.element == OnnxElement::Float32)
655 for (size_t i = 0; i < count(t.shape); ++i)
656 if (!std::isfinite(read<float>(t, i))) throw Failure("Nonfinite float output");
657 const auto size = t.bytes.size();
658 if (size > 512u * 1024u * 1024u - c.liveBytes) throw Failure("ONNX live tensor memory limit exceeded");
659 // Context encloses every runtime Value; escaping public outputs are owning copies.
660 auto* raw = new RuntimeTensor(std::move(t));
661 c.liveBytes += size;
662 return {nullptr,
663 std::shared_ptr<const RuntimeTensor>(raw,
664 [&c, size](const RuntimeTensor* p) {
665 delete p;
666 c.liveBytes -= size;
667 }),
668 {}};
669}
670std::set<std::string> captures(const ModelData& graph);
671std::set<std::string> dependencies(const Node& n) {
672 std::set<std::string> result;
673 for (const auto& i : n.inputs)
674 if (!i.empty()) result.insert(i);
675 for (const auto& [key, a] : n.attrs)
676 if (a.graph) {
677 auto names = captures(*a.graph);
678 result.insert(names.begin(), names.end());
679 }
680 return result;
681}
682std::set<std::string> captures(const ModelData& graph) {
683 std::set<std::string> locals, result;
684 for (const auto& [name, t] : graph.constants) locals.insert(name);
685 for (const auto& [name, t] : graph.inputs) locals.insert(name);
686 for (const auto& n : graph.nodes)
687 for (const auto& out : n.outputs)
688 if (!out.empty()) locals.insert(out);
689 for (const auto& n : graph.nodes) {
690 auto deps = dependencies(n);
691 for (const auto& d : deps)
692 if (!locals.contains(d)) result.insert(d);
693 }
694 for (const auto& out : graph.info.outputs)
695 if (!locals.contains(out)) result.insert(out);
696 return result;
697}
698void admit(const Node& n) {
699 if (!isSupported(n))
700 throw Failure(n.name + ": Unsupported ONNX node " + n.domain + "::" + n.op, DiagnosticCode::Unsupported,
701 n.name);
702 for (const auto& [key, a] : n.attrs)
703 if (a.graph)
704 for (const auto& child : a.graph->nodes) admit(child);
705}
706std::vector<size_t> plan(const ModelData& g, const std::vector<std::string>& requested) {
707 std::unordered_map<std::string, size_t> producers;
708 for (size_t i = 0; i < g.nodes.size(); ++i)
709 for (const auto& name : g.nodes[i].outputs)
710 if (!name.empty() && !producers.emplace(name, i).second) throw Failure("Duplicate graph output");
711 std::vector<bool> selected(g.nodes.size(), false);
712 std::vector<std::string> pending = requested;
713 while (!pending.empty()) {
714 auto name = std::move(pending.back());
715 pending.pop_back();
716 auto p = producers.find(name);
717 if (p == producers.end() || selected[p->second]) continue;
718 selected[p->second] = true;
719 admit(g.nodes[p->second]);
720 auto deps = dependencies(g.nodes[p->second]);
721 pending.insert(pending.end(), deps.begin(), deps.end());
722 }
723 std::vector<size_t> indegree(g.nodes.size());
724 std::vector<std::vector<size_t>> users(g.nodes.size());
725 size_t total = 0;
726 std::priority_queue<size_t, std::vector<size_t>, std::greater<size_t>> ready;
727 for (size_t i = 0; i < g.nodes.size(); ++i)
728 if (selected[i]) {
729 ++total;
730 std::set<size_t> parents;
731 for (const auto& name : dependencies(g.nodes[i])) {
732 auto p = producers.find(name);
733 if (p != producers.end()) parents.insert(p->second);
734 }
735 indegree[i] = parents.size();
736 for (auto p : parents) users[p].push_back(i);
737 if (parents.empty()) ready.push(i);
738 }
739 std::vector<size_t> order;
740 while (!ready.empty()) {
741 size_t i = ready.top();
742 ready.pop();
743 order.push_back(i);
744 for (auto user : users[i])
745 if (--indegree[user] == 0) ready.push(user);
746 }
747 if (order.size() != total) throw Failure("ONNX graph has cyclic lexical dependencies", DiagnosticCode::ParseError);
748 return order;
749}
750std::vector<Value> run(const ModelData&, Values, const std::vector<std::string>&, Context&, size_t);
751std::vector<Value> control(const Node& n, const std::vector<Value>& in, const Values& values, Context& c,
752 size_t depth) {
753 auto scalar = [&](size_t i) {
754 const auto& t = in.at(i).tensor();
755 if (count(t.shape) != 1) throw Failure("Control input must contain one element");
756 return integer(t);
757 };
758 auto seq = [&](size_t i) -> const std::vector<Value>& {
759 if (!in.at(i).sequence) throw Failure("Expected sequence input");
760 return *in[i].sequence;
761 };
762 auto sequence = [](std::vector<Value> v, OnnxElement type) {
763 return Value{nullptr, {}, std::make_shared<std::vector<Value>>(std::move(v)), type};
764 };
765 if (n.op == "SequenceEmpty") {
766 auto type = static_cast<OnnxElement>(attr(n, "dtype", 1));
768 return {sequence({}, type)};
769 }
770 if (n.op == "SequenceAt") {
771 const auto& s = seq(0);
772 int64_t i = scalar(1);
773 if (i < 0) i += static_cast<int64_t>(s.size());
774 if (i < 0 || static_cast<size_t>(i) >= s.size()) throw Failure("SequenceAt out of bounds");
775 return {s[i]};
776 }
777 if (n.op == "SequenceInsert") {
778 auto s = seq(0);
779 if (s.size() >= 100000) throw Failure("Sequence length limit exceeded");
780 int64_t i = in.size() > 2 ? scalar(2) : static_cast<int64_t>(s.size());
781 if (i < 0) i += static_cast<int64_t>(s.size());
782 if (i < 0 || static_cast<size_t>(i) > s.size()) throw Failure("SequenceInsert out of bounds");
783 const auto& t = in.at(1).tensor();
784 if (in[0].sequenceElement != t.element) throw Failure("Sequence element dtype mismatch");
785 s.insert(s.begin() + i, in[1]);
786 return {sequence(std::move(s), in[0].sequenceElement)};
787 }
788 if (n.op == "SplitToSequence") {
789 const auto& x = in.at(0).tensor();
790 int a = axis(attr(n, "axis", 0), x.shape.size());
791 std::vector<int64_t> lengths;
792 if (in.size() > 1 && (in[1].borrowed || in[1].owned)) {
793 const auto& split = in[1].tensor();
794 lengths = ints(split);
795 if (split.shape.empty()) {
796 if (lengths[0] <= 0) throw Failure("Invalid split size");
797 int64_t width = lengths[0];
798 lengths.clear();
799 for (int64_t i = 0; i < x.shape[a]; i += width) {
800 if (lengths.size() >= 100000) throw Failure("Sequence length limit exceeded");
801 lengths.push_back(std::min(width, x.shape[a] - i));
802 }
803 }
804 } else
805 lengths.assign(x.shape[a], 1);
806 if (lengths.size() > 100000) throw Failure("Sequence length limit exceeded");
807 int64_t total = 0;
808 for (auto size : lengths) {
809 if (size < 0 || size > x.shape[a] - total) throw Failure("Invalid split lengths");
810 total += size;
811 }
812 if (total != x.shape[a]) throw Failure("Split lengths do not cover axis");
813 size_t outer = 1, inner = elementSize(x.element);
814 for (int j = 0; j < a; ++j) outer *= x.shape[j];
815 for (size_t j = a + 1; j < x.shape.size(); ++j) inner *= x.shape[j];
816 std::vector<Value> s;
817 size_t offset = 0;
818 for (auto length : lengths) {
819 auto shape = x.shape;
820 shape[a] = length;
821 if (!attr(n, "keepdims", 1)) {
822 if (in.size() > 1 && (in[1].borrowed || in[1].owned))
823 throw Failure("keepdims=0 with explicit split unsupported", DiagnosticCode::Unsupported);
824 shape.erase(shape.begin() + a);
825 }
826 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * elementSize(x.element))};
827 for (size_t o = 0; o < outer; ++o)
828 if (length)
829 std::memcpy(out.bytes.data() + o * length * inner,
830 x.bytes.data() + (o * x.shape[a] + offset) * inner, length * inner);
831 s.push_back(hold(std::move(out), c));
832 offset += length;
833 }
834 return {sequence(std::move(s), x.element)};
835 }
836 if (n.op == "ConcatFromSequence") {
837 const auto& s = seq(0);
838 if (s.empty()) throw Failure("Cannot concatenate empty sequence");
839 std::vector<RuntimeTensor> tensors;
840 tensors.reserve(s.size());
841 std::vector<const RuntimeTensor*> inputs;
842 for (const auto& v : s) {
843 tensors.push_back(v.tensor());
844 if (attr(n, "new_axis", 0)) {
845 const int a = axis(attr(n, "axis", 0), tensors.back().shape.size() + 1);
846 tensors.back().shape.insert(tensors.back().shape.begin() + a, 1);
847 }
848 }
849 inputs.reserve(tensors.size());
850 for (const auto& t : tensors) inputs.push_back(&t);
851 Node concat = n;
852 concat.op = "Concat";
853 auto out = executeShape(concat, inputs);
854 if (!out) throw Failure("ConcatFromSequence dispatch failed");
855 return {hold(std::move(*out), c)};
856 }
857 if (n.op == "If") {
858 if (in.at(0).tensor().element != OnnxElement::Bool) throw Failure("If condition must be boolean");
859 auto key = scalar(0) ? "then_branch" : "else_branch";
860 const auto& g = n.attrs.at(key).graph;
861 if (!g) throw Failure("Missing If branch");
862 return run(*g, values, g->info.outputs, c, depth + 1);
863 }
864 if (n.op == "Loop") {
865 const auto& body = n.attrs.at("body").graph;
866 if (!body) throw Failure("Missing Loop body");
867 if (in.size() < 2 || body->info.inputs.size() != in.size() || body->info.outputs.size() != in.size() - 1 ||
868 n.outputs.size() != in.size() - 2)
869 throw Failure("Loop scan outputs unsupported", DiagnosticCode::Unsupported);
870 const int64_t trips = (in[0].borrowed || in[0].owned) ? scalar(0) : 10000;
871 if (trips < 0 || trips > 10000) throw Failure("Loop trip budget exceeded");
872 bool condition = (in[1].borrowed || in[1].owned) ? scalar(1) != 0 : true;
873 std::vector<Value> state(in.begin() + 2, in.end());
874 for (int64_t i = 0; i < trips && condition; ++i) {
875 auto scope = values;
876 scope[body->info.inputs[0]] = hold(make(OnnxElement::Int64, {}, std::vector<int64_t>{i}), c);
877 scope[body->info.inputs[1]] =
878 hold(make(OnnxElement::Bool, {}, std::vector<uint8_t>{uint8_t(condition)}), c);
879 for (size_t j = 0; j < state.size(); ++j) scope[body->info.inputs[j + 2]] = state[j];
880 auto result = run(*body, std::move(scope), body->info.outputs, c, depth + 1);
881 const auto& cond = result[0].tensor();
882 if (cond.element != OnnxElement::Bool || count(cond.shape) != 1)
883 throw Failure("Loop returned invalid condition");
884 condition = integer(cond) != 0;
885 state.assign(result.begin() + 1, result.end());
886 }
887 return state;
888 }
889 if (n.op == "RandomUniformLike" || n.op == "RandomNormalLike") {
890 const auto& x = in.at(0).tensor();
891 if (attr(n, "dtype", static_cast<int>(x.element)) != 1)
892 throw Failure("Random output requires FP32", DiagnosticCode::Unsupported);
893 uint64_t seed = c.seed;
894 for (unsigned char ch : n.name) seed = (seed ^ ch) * 1099511628211ull;
895 if (n.attrs.contains("seed")) {
896 uint32_t bits;
897 std::memcpy(&bits, &n.attrs.at("seed").real, 4);
898 seed ^= bits;
899 }
900 auto [stream, inserted] = c.randomStreams.try_emplace(&n, static_cast<uint32_t>(seed ^ (seed >> 32)));
901 auto& rng = stream->second;
902 auto uniform = [&]() { return (double(rng()) + .5) / 4294967296.; };
903 std::vector<float> v(count(x.shape));
904 const float low = n.attrs.contains("low") ? n.attrs.at("low").real : 0,
905 high = n.attrs.contains("high") ? n.attrs.at("high").real : 1,
906 mean = n.attrs.contains("mean") ? n.attrs.at("mean").real : 0,
907 scale = n.attrs.contains("scale") ? n.attrs.at("scale").real : 1;
908 if (!std::isfinite(low) || !std::isfinite(high) || !std::isfinite(mean) || !std::isfinite(scale) ||
909 high < low || scale < 0)
910 throw Failure("Invalid random distribution parameters");
911 for (auto& f : v)
912 f = n.op == "RandomUniformLike" ? static_cast<float>(low + (high - low) * uniform())
913 : static_cast<float>(mean + scale * std::sqrt(-2 * std::log(uniform())) *
914 std::cos(6.283185307179586 * uniform()));
915 return {hold(make(OnnxElement::Float32, x.shape, v), c)};
916 }
917 std::vector<const RuntimeTensor*> tensors;
918 tensors.reserve(in.size());
919 for (const auto& v : in) tensors.push_back(v.borrowed || v.owned ? &v.tensor() : nullptr);
920 auto outputs = execute(n, tensors, c.compute);
921 std::vector<Value> result;
922 result.reserve(outputs.size());
923 for (auto& t : outputs) result.push_back(hold(std::move(t), c));
924 return result;
925}
926std::vector<Value> run(const ModelData& g, Values values, const std::vector<std::string>& requested, Context& c,
927 size_t depth) {
928 if (depth > 16) throw Failure("Execution graph nesting limit exceeded");
929 for (const auto& [name, t] : g.constants)
930 if (!g.inputs.contains(name) || !values.contains(name)) values[name] = {&t, {}, {}};
931 auto order = plan(g, requested);
932 std::unordered_map<std::string, size_t> uses;
933 for (auto i : order)
934 for (const auto& dep : dependencies(g.nodes[i])) ++uses[dep];
935 for (const auto& name : requested) ++uses[name];
936 for (auto i : order) {
937 const auto& n = g.nodes[i];
938 if (++c.steps > 1000000) throw Failure("ONNX execution step budget exceeded");
939 try {
940 std::vector<Value> in;
941 for (const auto& name : n.inputs) {
942 if (name.empty()) {
943 in.push_back({});
944 continue;
945 }
946 auto it = values.find(name);
947 if (it == values.end()) throw Failure("Missing feed or lexical capture: " + name);
948 in.push_back(it->second);
949 }
950 auto outputs = control(n, in, values, c, depth);
951 if (outputs.size() < n.outputs.size()) throw Failure("Operator output arity mismatch");
952 for (size_t j = 0; j < n.outputs.size(); ++j)
953 if (!n.outputs[j].empty() && uses[n.outputs[j]]) values[n.outputs[j]] = std::move(outputs[j]);
954 for (const auto& dep : dependencies(n))
955 if (--uses[dep] == 0) values.erase(dep);
956 } catch (const Failure& e) {
957 throw Failure(n.name + ": " + e.what(), e.code, e.path.empty() ? n.name : e.path);
958 }
959 }
960 std::vector<Value> out;
961 for (const auto& name : requested) {
962 auto it = values.find(name);
963 if (it == values.end()) throw Failure("Missing output: " + name, DiagnosticCode::NotFound);
964 out.push_back(it->second);
965 }
966 return out;
967}
968} // namespace
969std::vector<OnnxNamedTensor> evaluate(const ModelData& model, std::span<const OnnxNamedTensor> feeds,
970 const std::vector<std::string>& requested, OnnxCompute* compute,
972 Context c{compute, options.seed, options.requireFinite};
973 Values inputs;
974 for (const auto& f : feeds) inputs[f.name] = hold({f.tensor.element, f.tensor.shape, f.tensor.bytes}, c);
975 auto outputs = run(model, std::move(inputs), requested, c, 0);
976 std::vector<OnnxNamedTensor> result;
977 size_t bytes = c.liveBytes;
978 for (size_t i = 0; i < outputs.size(); ++i) {
979 const auto& t = outputs[i].tensor();
980 if (t.bytes.size() > 512u * 1024u * 1024u - bytes) throw Failure("ONNX output memory limit exceeded");
981 bytes += t.bytes.size();
982 result.push_back({requested[i], {t.element, t.shape, static_cast<std::vector<uint8_t>>(t.bytes)}});
983 }
984 return result;
985}
986} // namespace eve::tensor::onnx_detail
987
988// OnnxShapeOps.cpp
989namespace eve::tensor::onnx_detail {
990std::vector<int64_t> broadcast(const std::vector<int64_t>& a, const std::vector<int64_t>& b) {
991 std::vector<int64_t> out(std::max(a.size(), b.size()), 1);
992 for (size_t i = 0; i < out.size(); ++i) {
993 const auto x = i < a.size() ? a[a.size() - 1 - i] : 1, y = i < b.size() ? b[b.size() - 1 - i] : 1;
994 if (x != y && x != 1 && y != 1) throw Failure("Broadcast dimension mismatch");
995 out[out.size() - 1 - i] = x == 1 ? y : x;
996 }
997 count(out);
998 return out;
999}
1000size_t broadcastIndex(size_t i, const std::vector<int64_t>& shape, const std::vector<int64_t>& output) {
1001 size_t index = 0, stride = 1;
1002 for (size_t j = 0; j < output.size(); ++j) {
1003 const auto coordinate = i % output[output.size() - 1 - j];
1004 i /= output[output.size() - 1 - j];
1005 if (j < shape.size()) {
1006 const auto d = shape[shape.size() - 1 - j];
1007 if (d != 1) index += coordinate * stride;
1008 stride *= d;
1009 }
1010 }
1011 return index;
1012}
1013std::optional<RuntimeTensor> executeShape(const Node& n, const std::vector<const RuntimeTensor*>& in) {
1014 const auto& x = required(in, 0);
1015 if (n.op == "Slice") {
1016 auto starts = ints(required(in, 1)), ends = ints(required(in, 2));
1017 auto axes = in.size() > 3 && in[3] ? ints(*in[3]) : std::vector<int64_t>(starts.size());
1018 if (in.size() <= 3 || !in[3]) std::iota(axes.begin(), axes.end(), 0);
1019 auto steps = in.size() > 4 && in[4] ? ints(*in[4]) : std::vector<int64_t>(starts.size(), 1);
1020 if (starts.size() != ends.size() || starts.size() != axes.size() || starts.size() != steps.size())
1021 throw Failure("Slice parameter lengths mismatch");
1022 auto shape = x.shape;
1023 std::vector<int64_t> begin(shape.size(), 0), step(shape.size(), 1);
1024 std::set<int> seen;
1025 for (size_t j = 0; j < axes.size(); ++j) {
1026 int a = axis(axes[j], shape.size());
1027 if (!seen.insert(a).second || !steps[j] || steps[j] == INT64_MIN) throw Failure("Invalid Slice axis/step");
1028 const auto d = x.shape[a], st = steps[j];
1029 auto norm = [d, st](int64_t v, bool end) {
1030 if (v < 0) v = v < -d ? (st < 0 ? -1 : 0) : v + d;
1031 return std::clamp(v, st < 0 && end ? int64_t(-1) : int64_t(0),
1032 st < 0 ? std::max(int64_t(0), d - 1) : d);
1033 };
1034 begin[a] = norm(starts[j], false);
1035 const auto e = norm(ends[j], true);
1036 step[a] = st;
1037 const int64_t distance = st > 0 ? e - begin[a] : begin[a] - e, magnitude = st > 0 ? st : -st;
1038 shape[a] = d == 0 || distance <= 0 ? 0 : 1 + (distance - 1) / magnitude;
1039 }
1040 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * elementSize(x.element))};
1041 for (size_t i = 0; i < count(shape); ++i) {
1042 size_t rest = i, source = 0, stride = 1;
1043 for (size_t j = shape.size(); j > 0; --j) {
1044 auto c = rest % shape[j - 1];
1045 rest /= shape[j - 1];
1046 source += (begin[j - 1] + c * step[j - 1]) * stride;
1047 stride *= x.shape[j - 1];
1048 }
1049 std::memcpy(out.bytes.data() + i * elementSize(x.element), x.bytes.data() + source * elementSize(x.element),
1050 elementSize(x.element));
1051 }
1052 return out;
1053 }
1054 if (n.op == "Concat") {
1055 int a = axis(attr(n, "axis", 0), x.shape.size());
1056 auto shape = x.shape;
1057 shape[a] = 0;
1058 for (auto* t : in) {
1059 if (!t || t->element != x.element || t->shape.size() != shape.size())
1060 throw Failure("Concat type/rank mismatch");
1061 for (size_t j = 0; j < shape.size(); ++j)
1062 if (j != a && t->shape[j] != shape[j]) throw Failure("Concat dimension mismatch");
1063 shape[a] += t->shape[a];
1064 }
1065 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * elementSize(x.element))};
1066 size_t outer = 1, inner = elementSize(x.element);
1067 for (int j = 0; j < a; ++j) outer *= shape[j];
1068 for (size_t j = a + 1; j < shape.size(); ++j) inner *= shape[j];
1069 size_t offset = 0;
1070 for (size_t o = 0; o < outer; ++o)
1071 for (auto* t : in) {
1072 const size_t size = t->shape[a] * inner;
1073 if (size) std::memcpy(out.bytes.data() + offset, t->bytes.data() + o * size, size);
1074 offset += size;
1075 }
1076 return out;
1077 }
1078 if (n.op == "Expand") {
1079 auto requested = ints(required(in, 1));
1080 count(requested);
1081 auto shape = broadcast(x.shape, requested);
1082 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * elementSize(x.element))};
1083 for (size_t i = 0; i < count(shape); ++i)
1084 std::memcpy(out.bytes.data() + i * elementSize(x.element),
1085 x.bytes.data() + broadcastIndex(i, x.shape, shape) * elementSize(x.element),
1086 elementSize(x.element));
1087 return out;
1088 }
1089 if (n.op == "ConstantOfShape") {
1090 auto shape = ints(x);
1091 RuntimeTensor value = make(OnnxElement::Float32, {}, std::vector<float>{0});
1092 if (n.attrs.contains("value")) {
1093 if (!n.attrs.at("value").tensor) throw Failure("Missing fill value");
1094 value = *n.attrs.at("value").tensor;
1095 }
1096 if (count(value.shape) != 1) throw Failure("ConstantOfShape requires one fill value");
1097 RuntimeTensor out{value.element, shape, std::vector<uint8_t>(count(shape) * elementSize(value.element))};
1098 for (size_t i = 0; i < out.bytes.size(); i += value.bytes.size())
1099 std::memcpy(out.bytes.data() + i, value.bytes.data(), value.bytes.size());
1100 return out;
1101 }
1102 if (n.op == "Where") {
1103 const auto& a = required(in, 1);
1104 const auto& b = required(in, 2);
1105 if (x.element != OnnxElement::Bool || a.element != b.element) throw Failure("Where type mismatch");
1106 auto shape = broadcast(broadcast(x.shape, a.shape), b.shape);
1107 const auto size = elementSize(a.element);
1108 RuntimeTensor out{a.element, shape, std::vector<uint8_t>(count(shape) * size)};
1109 for (size_t i = 0; i < count(shape); ++i) {
1110 const auto& v = x.bytes[broadcastIndex(i, x.shape, shape)] ? a : b;
1111 std::memcpy(out.bytes.data() + i * size, v.bytes.data() + broadcastIndex(i, v.shape, shape) * size, size);
1112 }
1113 return out;
1114 }
1115 if (n.op == "Not") {
1116 if (x.element != OnnxElement::Bool) throw Failure("Not requires boolean");
1117 auto out = x;
1118 for (auto& b : out.bytes) b = !b;
1119 return out;
1120 }
1121 if (n.op == "Equal" || n.op == "Less" || n.op == "Greater" || n.op == "And") {
1122 const auto& y = required(in, 1);
1123 if (x.element != y.element || (n.op == "And" && x.element != OnnxElement::Bool))
1124 throw Failure("Comparison type mismatch");
1125 auto shape = broadcast(x.shape, y.shape);
1126 RuntimeTensor out{OnnxElement::Bool, shape, std::vector<uint8_t>(count(shape))};
1127 for (size_t i = 0; i < out.bytes.size(); ++i) {
1128 auto a = broadcastIndex(i, x.shape, shape), b = broadcastIndex(i, y.shape, shape);
1129 auto compare = [&](auto u, auto v) {
1130 return n.op == "Equal" ? u == v
1131 : n.op == "Less" ? u < v
1132 : n.op == "Greater" ? u > v
1133 : bool(u) && bool(v);
1134 };
1135 out.bytes[i] = x.element == OnnxElement::Float32 ? compare(read<float>(x, a), read<float>(y, b))
1136 : compare(integer(x, a), integer(y, b));
1137 }
1138 return out;
1139 }
1140 if ((n.op == "Add" || n.op == "Sub" || n.op == "Mul" || n.op == "Div") && x.element != OnnxElement::Float32) {
1141 const auto& y = required(in, 1);
1142 if (x.element != y.element || (x.element != OnnxElement::Int64 && x.element != OnnxElement::Int32))
1143 throw Failure("Integer arithmetic dtype mismatch");
1144 auto shape = broadcast(x.shape, y.shape);
1145 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * elementSize(x.element))};
1146 for (size_t i = 0; i < count(shape); ++i) {
1147 int64_t a = integer(x, broadcastIndex(i, x.shape, shape)),
1148 b = integer(y, broadcastIndex(i, y.shape, shape)), v = 0;
1149 if (n.op == "Add") {
1150 if ((b > 0 && a > INT64_MAX - b) || (b < 0 && a < INT64_MIN - b))
1151 throw Failure("Integer addition overflow");
1152 v = a + b;
1153 }
1154 if (n.op == "Sub") {
1155 if ((b < 0 && a > INT64_MAX + b) || (b > 0 && a < INT64_MIN + b))
1156 throw Failure("Integer subtraction overflow");
1157 v = a - b;
1158 }
1159 if (n.op == "Mul") {
1160 if (a && b &&
1161 (a > 0 ? (b > 0 ? a > INT64_MAX / b : b < INT64_MIN / a)
1162 : (b > 0 ? a < INT64_MIN / b : a < INT64_MAX / b)))
1163 throw Failure("Integer multiplication overflow");
1164 v = a * b;
1165 }
1166 if (n.op == "Div") {
1167 if (!b || (a == INT64_MIN && b == -1)) throw Failure("Invalid integer division");
1168 v = a / b;
1169 }
1170 if (x.element == OnnxElement::Int32 && (v < INT32_MIN || v > INT32_MAX))
1171 throw Failure("Int32 arithmetic overflow");
1172 std::memcpy(out.bytes.data() + i * elementSize(x.element), &v, elementSize(x.element));
1173 }
1174 return out;
1175 }
1176 return std::nullopt;
1177}
1178} // namespace eve::tensor::onnx_detail
double z
double y
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
std::string selected
std::string output
ActiveSource owned
eve::action::ActionSpatialBinding spatial
std::vector< QuestEvent > pending
const std::string & s
glm::vec4 p[6]
eve::Value condition
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
double raw
EvpackChunkInput input
Definition Evpack.cpp:170
int rows
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
int inputs
Definition GridGraph.cpp:23
std::array< double, 10 > q
double r
float v
std::int32_t second
std::int32_t c
std::uint32_t width
JobScope scope
float length
JointPoint2D axis
size_t offset
std::array< float, 3 > scale
bool required
std::map< std::string, Node > nodes
std::vector< std::string > captures
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
std::vector< std::int32_t > order
const std::string * tag
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
std::shared_ptr< OceanGpuSpectrum > owner
std::vector< float > scales
const RuntimeTensor & tensor
std::vector< int64_t > zeros
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
bool finite
OnnxCompute * compute
int wire
std::unordered_map< const Node *, std::mt19937 > randomStreams
size_t liveBytes
OnnxElement sequenceElement
const RuntimeTensor * borrowed
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
float f
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
std::string body
Object::Ptr value
float d
int steps
float t
std::string domain
std::vector< EquipmentStat > stats
std::string attribute
glm::mat4 model
const RoadNode * node
double number
LinkOps ops
std::array< std::array< double, 3 >, 3 > axes
std::string text
ScriptStructure out
std::string_view source
size_t begin
size_t end
std::string element
const SquirrelValueOptions & options
int count
int columns
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
uint32_t index
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
GPU execution boundary for native ONNX; retains no model and retains compiled resources for the lifet...
Definition OnnxCompute.h:25
const OnnxBuffer & buffer() const
Buffer.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Result< ForceVector > checked(ForceVector value)
Definition ForceMath.h:21
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Result< ConvExtent > validateConv(size_t xSize, size_t wSize, bool xSigned, bool wSigned, const ConvShape &, int, std::span< const int32_t >)
Validate conv.
Result< std::vector< int32_t > > conv(ByteView x, ByteView w, const ConvShape &s, int xZero, std::span< const int32_t > wZeros, OnnxCompute *compute)
Integer Conv, supporting groups, asymmetric padding and dilation.
Result< std::vector< uint8_t > > quantize(std::span< const float > input, float scale, int zero, bool sign)
Affine quantization to int8/uint8 bytes, saturating and rounding ties to even.
Result< std::vector< float > > dequantize(ByteView input, std::span< const float > scales, std::span< const int32_t > zeros, size_t inner)
Affine dequantization using scalar or per-axis scale/zero point.
Result< std::vector< int32_t > > matmul(ByteView a, ByteView b, size_t m, size_t k, size_t n, int aZero, int bZero, OnnxCompute *compute)
Integer row-major [M,K] x [K,N], subtracting scalar zero points.
Result< QuantizedActivation > dynamicQuantize(std::span< const float > input)
Quantize finite FP32 activations with ONNX DynamicQuantizeLinear semantics.
void concat(const float *const *ins, const int *const *inDims, const int *inRanks, int n, int axis, float *out, const int *outDims, int outRank)
Concat.
OnnxBuffer gpuConvResident(OnnxCompute &d, OnnxBuffer x, OnnxBuffer w, bool xs, bool ws, const affine::ConvShape &c, int xz, std::span< const int32_t > wz)
Gpu conv resident.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
std::vector< int64_t > ints(const RuntimeTensor &v)
Ints.
int64_t attr(const Node &n, const char *key, int64_t fallback)
Attr.
size_t broadcastIndex(size_t i, const std::vector< int64_t > &shape, const std::vector< int64_t > &output)
Broadcast index.
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
std::vector< RuntimeTensor > executeQuant(const Node &node, const std::vector< const RuntimeTensor * > &inputs, OnnxCompute *compute=nullptr)
Execute quant.
Definition OnnxQuant.cpp:34
RuntimeTensor make(OnnxElement e, std::vector< int64_t > shape, const std::vector< T > &values)
Make.
std::vector< RuntimeTensor > single(RuntimeTensor x)
Transfers one owned runtime tensor into an output list. @cost One small container allocation per outp...
RuntimeTensor dispatchFloat(OnnxCompute &, const std::vector< const RuntimeTensor * > &, const std::vector< int64_t > &, const std::string &, size_t work=0)
Dispatches float.
Definition OnnxMisc.cpp:416
std::vector< OnnxNamedTensor > evaluate(const ModelData &, std::span< const OnnxNamedTensor >, const std::vector< std::string > &, OnnxCompute *, OnnxRunOptions options)
Evaluate.
OnnxBuffer gpuMatmulResident(OnnxCompute &d, OnnxBuffer a, OnnxBuffer b, bool as, bool bs, size_t m, size_t k, size_t n, int az, std::span< const int32_t > bz, size_t bOffset)
Gpu matmul resident.
bool isSupported(const Node &n)
True when supported.
void validate(const RuntimeTensor &v)
Validate.
size_t elementSize(OnnxElement e)
Element size.
ModelData parse(std::span< const uint8_t > bytes)
Parse.
std::vector< int64_t > broadcast(const std::vector< int64_t > &a, const std::vector< int64_t > &b)
Broadcast.
std::optional< RuntimeTensor > executeShape(const Node &, const std::vector< const RuntimeTensor * > &)
Execute shape.
std::vector< RuntimeTensor > execute(const Node &n, const std::vector< const RuntimeTensor * > &in, OnnxCompute *compute)
Execute.
OnnxElement
ONNX wire element types; distinct from block-quantized Tensor storage.
Definition OnnxModel.h:18
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Per-call deterministic RNG and optional strict finite-output diagnostic.
Definition OnnxModel.h:37
Explicit 1D/2D NCHW convolution geometry; missing 1D height is one.
Definition AffineQuant.h:65
glm::uvec4 info