17affine::ByteView
bytes(
const RuntimeTensor&
t) {
19 throw Failure(
"Expected packed int8/uint8 tensor");
25 return std::move(
result.value());
27int zero(
const std::vector<const RuntimeTensor*>& in,
size_t i,
const RuntimeTensor&
owner) {
28 if (i >= in.size() || !in[i])
return 0;
30 throw Failure(
"Expected matching scalar zero point");
31 return static_cast<int>(
integer(*in[i]));
34std::vector<RuntimeTensor>
executeQuant(
const Node&
n,
const std::vector<const RuntimeTensor*>& in,
37 if (
n.op ==
"DynamicQuantizeLinear") {
40 const size_t total =
count(
x.shape);
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;",
49 throw Failure(
"Nonfinite quantization input/range");
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;}";
62 auto q = checked(
compute->enqueue(
source,
inputs, total,
static_cast<uint32_t
>((total + 3) / 4)));
63 std::vector<RuntimeTensor>
result;
67 result.emplace_back(std::move(zeroPoint));
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);
80 for (
auto i : nanPositions)
q.values[i] = 0;
81 std::vector<RuntimeTensor>
result;
88 if (
n.op ==
"QuantizeLinear" ||
n.op ==
"DequantizeLinear") {
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");
97 throw Failure(
"Scale/zero point mismatch");
100 for (
size_t i = 0; i <
zeros.size(); ++i)
zeros[i] =
static_cast<int32_t
>(
integer(*zp, i));
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];
107 if (
n.op ==
"DequantizeLinear")
112 for (
size_t i = 0; i <
values.size(); i += inner) {
113 const size_t channel = (i / inner) %
scales.size();
116 std::copy(
q.begin(),
q.end(),
out.begin() + i);
120 if (
n.op ==
"MatMulInteger") {
122 if (
x.shape.size() < 2 ||
b.shape.size() != 2)
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");
132 throw Failure(
"Expected packed integer matrices");
133 std::vector<int32_t> bz{zero(in, 3,
b)};
141 checked(
affine::matmul(
bytes(
x),
bytes(
b),
rows, k,
columns, zero(in, 2,
x), zero(in, 3,
b),
compute))));
143 if (
n.op ==
"ConvInteger") {
145 if ((
x.shape.size() != 3 &&
x.shape.size() != 4) ||
w.shape.size() !=
x.shape.size())
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));
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);
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));
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]);
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");
185 for (
auto z :
ints(*in[3]))
wz.push_back(
static_cast<int32_t
>(
z));
190 throw Failure(
"Expected packed convolution inputs");
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);
203 std::vector<int64_t>
shape{
s.batch,
s.outputs};
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 +
222 std::string
text()
const {
return {
reinterpret_cast<const char*
>(
bytes.data()),
bytes.size()}; }
226 explicit Reader(std::span<const uint8_t> data) : data_(data) {}
227 bool empty()
const {
return offset_ == data_.size(); }
230 for (
int shift = 0; shift < 70; shift += 7) {
232 const uint8_t
b = data_[offset_++];
234 n |=
static_cast<uint64_t
>(
b & 127) << shift;
235 if (!(
b & 128))
return n;
239 std::span<const uint8_t> take(uint64_t
n) {
241 auto result = data_.subspan(offset_,
static_cast<size_t>(
n));
242 offset_ +=
static_cast<size_t>(
n);
246 const uint64_t
tag = varint();
247 if ((
tag >> 3) == 0 || (
tag >> 3) > 0x1fffffff)
250 f.id =
static_cast<int>(
tag >> 3);
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;
263 std::span<const uint8_t> data_;
266void wire(
const Field&
f,
int expected) {
269void integers(
const Field&
f, std::vector<int64_t>&
out) {
271 out.push_back(std::bit_cast<int64_t>(
f.number));
275 while (!
r.empty())
out.push_back(std::bit_cast<int64_t>(
r.varint()));
278void reals(
const Field&
f, std::vector<float>&
out) {
281 for (
size_t i = 0; i <
f.bytes.size(); i += 4) {
283 std::memcpy(&
x,
f.bytes.data() + i, 4);
287std::pair<std::string, RuntimeTensor>
tensor(std::span<const uint8_t> data) {
291 std::vector<int64_t> iv;
292 std::vector<float> fv;
293 bool raw =
false,
type =
false;
297 case 1: integers(
f,
v.shape);
break;
304 case 4: reals(
f, fv);
break;
306 case 7: integers(
f, iv);
break;
314 v.bytes.assign(
f.bytes.begin(),
f.bytes.end());
334 if (fv.size() !=
n || !iv.empty())
337 if (
n) std::memcpy(
v.bytes.data(), fv.data(),
v.bytes.size());
339 if (iv.size() !=
n || !fv.empty())
342 for (
size_t i = 0; i <
n; ++i) {
343 const auto x = iv[i];
349 std::memcpy(
v.bytes.data() + i *
size, &
x,
size);
354 return {std::move(
name), std::move(
v)};
356ModelData parseGraph(std::span<const uint8_t>
bytes,
size_t depth);
370 a.type =
static_cast<int>(
f.number);
374 std::memcpy(&
a.real,
f.bytes.data(), 4);
379 a.integer = std::bit_cast<int64_t>(
f.number);
389 case 7: reals(
f,
a.reals);
break;
390 case 8: integers(
f,
a.integers);
break;
393 a.strings.push_back(
f.text());
397 a.graph = std::make_shared<ModelData>(parseGraph(
f.bytes,
depth + 1));
405 return {std::move(
name), std::move(
a)};
412 if (
f.id >= 1 &&
f.id <= 5)
wire(
f, 2);
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;
433std::pair<std::string, Input>
input(std::span<const uint8_t>
bytes) {
445 Reader
type(
f.bytes);
446 while (!
type.empty()) {
447 auto t =
type.next();
455 while (!tt.empty()) {
459 value.type =
static_cast<int>(
p.number);
464 while (!
shape.empty()) {
466 if (
d.id != 1)
continue;
470 while (!dim.empty()) {
474 v = std::bit_cast<int64_t>(
x.number);
490ModelData parseGraph(std::span<const uint8_t>
bytes,
size_t depth) {
504 t.second.bytes.retainAcrossRuns();
505 if (
t.first.empty() || !
model.constants.emplace(std::move(
t)).second)
511 model.info.inputs.push_back(
v.first);
512 if (!
model.inputs.emplace(std::move(
v)).second)
517 model.info.outputs.push_back(
input(
f.bytes).first);
526 if constexpr (std::endian::native != std::endian::little)
528 if (
bytes.empty() ||
bytes.size() > 512u * 1024u * 1024u)
532 std::span<const uint8_t>
graph;
537 model.info.irVersion =
static_cast<int64_t
>(
f.number);
549 while (!
ops.empty()) {
563 if (
f.id == 20 ||
f.id == 25 ||
f.id == 26)
566 if (
model.info.irVersion < 3 ||
model.info.irVersion > 10 || !
model.opsets.contains(
"") ||
567 model.opsets.at(
"") < 13 ||
model.opsets.at(
"") > 17)
569 if (
model.opsets.contains(
"com.microsoft") &&
model.opsets.at(
"com.microsoft") != 1)
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) {
581 model.info.initializerBytes +=
v.bytes.size();
584 for (
const auto&
n :
model.nodes) {
586 for (
const auto&
name :
n.inputs)
587 if (!
name.empty() && !names.contains(
name))
589 for (
const auto&
name :
n.outputs)
590 if (!
name.empty() && !names.insert(
name).second)
592 if (!
isSupported(
n))
model.info.unsupportedNodes.push_back(
n.name +
" [" +
n.domain +
"::" +
n.op +
"]");
594 for (
const auto&
out :
model.info.outputs)
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();
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)
609 available.insert(locals.begin(), locals.end());
610 for (
const auto&
n :
g.nodes) {
611 if (!
model.opsets.contains(
n.domain))
613 for (
const auto&
input :
n.inputs)
614 if (!
input.empty() && !available.contains(
input))
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);
621 for (
const auto&
out :
g.info.outputs)
624 validateNested(
model, {},
true);
635 std::shared_ptr<const RuntimeTensor>
owned;
638 const RuntimeTensor&
tensor()
const {
641 throw Failure(
"Expected tensor, received sequence");
644using Values = std::unordered_map<std::string, Value>;
652Value hold(RuntimeTensor
t, Context&
c) {
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");
660 auto*
raw =
new RuntimeTensor(std::move(
t));
663 std::shared_ptr<const RuntimeTensor>(
raw,
664 [&
c,
size](
const RuntimeTensor*
p) {
671std::set<std::string> dependencies(
const Node&
n) {
672 std::set<std::string>
result;
674 if (!i.empty())
result.insert(i);
678 result.insert(names.begin(), names.end());
683 std::set<std::string> locals,
result;
684 for (
const auto& [
name,
t] :
graph.constants) locals.insert(
name);
687 for (const auto&
out :
n.outputs)
688 if (!
out.empty()) locals.insert(
out);
690 auto deps = dependencies(
n);
691 for (
const auto&
d : deps)
692 if (!locals.contains(
d))
result.insert(
d);
698void admit(
const Node&
n) {
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)
711 std::vector<bool>
selected(
g.nodes.size(),
false);
712 std::vector<std::string>
pending = requested;
716 auto p = producers.find(
name);
717 if (
p == producers.end() ||
selected[
p->second])
continue;
719 admit(
g.nodes[
p->second]);
720 auto deps = dependencies(
g.nodes[
p->second]);
723 std::vector<size_t> indegree(
g.nodes.size());
724 std::vector<std::vector<size_t>> users(
g.nodes.size());
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)
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);
735 indegree[i] = parents.size();
736 for (
auto p : parents) users[
p].push_back(i);
737 if (parents.empty()) ready.push(i);
739 std::vector<size_t>
order;
740 while (!ready.empty()) {
741 size_t i = ready.top();
744 for (
auto user : users[i])
745 if (--indegree[user] == 0) ready.push(user);
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,
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");
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;
763 return Value{
nullptr, {}, std::make_shared<std::vector<Value>>(std::move(
v)),
type};
765 if (
n.op ==
"SequenceEmpty") {
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");
777 if (
n.op ==
"SequenceInsert") {
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();
785 s.insert(
s.begin() + i, in[1]);
788 if (
n.op ==
"SplitToSequence") {
789 const auto&
x = in.at(0).tensor();
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];
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));
805 lengths.assign(
x.shape[
a], 1);
806 if (lengths.size() > 100000)
throw Failure(
"Sequence length limit exceeded");
808 for (
auto size : lengths) {
809 if (size < 0 || size >
x.shape[
a] - total)
throw Failure(
"Invalid split lengths");
812 if (total !=
x.shape[
a])
throw Failure(
"Split lengths do not cover axis");
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;
818 for (
auto length : lengths) {
821 if (!
attr(
n,
"keepdims", 1)) {
822 if (in.size() > 1 && (in[1].borrowed || in[1].owned))
827 for (
size_t o = 0; o < outer; ++o)
829 std::memcpy(
out.bytes.data() + o *
length * inner,
831 s.push_back(hold(std::move(
out),
c));
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);
849 inputs.reserve(tensors.size());
850 for (
const auto&
t : tensors)
inputs.push_back(&
t);
854 if (!
out)
throw Failure(
"ConcatFromSequence dispatch failed");
855 return {hold(std::move(*
out),
c)};
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");
864 if (
n.op ==
"Loop") {
865 const auto&
body =
n.attrs.at(
"body").graph;
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)
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) {
879 for (
size_t j = 0; j <
state.size(); ++j)
scope[
body->info.inputs[j + 2]] = state[j];
881 const auto& cond =
result[0].tensor();
883 throw Failure(
"Loop returned invalid condition");
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)
893 uint64_t
seed =
c.seed;
894 for (
unsigned char ch :
n.
name)
seed = (
seed ^ ch) * 1099511628211ull;
895 if (
n.attrs.contains(
"seed")) {
897 std::memcpy(&bits, &
n.attrs.at(
"seed").real, 4);
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");
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()));
917 std::vector<const RuntimeTensor*> tensors;
918 tensors.reserve(in.size());
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));
926std::vector<Value>
run(
const ModelData&
g, Values
values,
const std::vector<std::string>& requested, Context&
c,
928 if (
depth > 16)
throw Failure(
"Execution graph nesting limit exceeded");
929 for (
const auto& [
name,
t] :
g.constants)
931 auto order = plan(
g, requested);
932 std::unordered_map<std::string, size_t> uses;
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");
940 std::vector<Value> in;
947 if (it ==
values.end())
throw Failure(
"Missing feed or lexical capture: " +
name);
948 in.push_back(it->second);
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);
960 std::vector<Value>
out;
961 for (
const auto&
name : requested) {
964 out.push_back(it->second);
974 for (
const auto&
f : feeds)
inputs[
f.name] = hold({
f.tensor.element,
f.tensor.shape,
f.tensor.bytes},
c);
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");
982 result.push_back({requested[i], {
t.element,
t.shape,
static_cast<std::vector<uint8_t>
>(
t.bytes)}});
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;
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];
1005 if (j <
shape.size()) {
1007 if (
d != 1)
index += coordinate * stride;
1013std::optional<RuntimeTensor>
executeShape(
const Node&
n,
const std::vector<const RuntimeTensor*>& in) {
1015 if (
n.op ==
"Slice") {
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");
1025 for (
size_t j = 0; j <
axes.size(); ++j) {
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);
1034 begin[
a] = norm(starts[j],
false);
1035 const auto e = norm(ends[j],
true);
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];
1047 stride *=
x.shape[j - 1];
1054 if (
n.op ==
"Concat") {
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");
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];
1070 for (
size_t o = 0; o < outer; ++o)
1071 for (
auto*
t : in) {
1072 const size_t size =
t->shape[
a] * inner;
1078 if (
n.op ==
"Expand") {
1089 if (
n.op ==
"ConstantOfShape") {
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;
1096 if (
count(
value.shape) != 1)
throw Failure(
"ConstantOfShape requires one fill value");
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());
1102 if (
n.op ==
"Where") {
1115 if (
n.op ==
"Not") {
1118 for (
auto&
b :
out.bytes)
b = !
b;
1121 if (
n.op ==
"Equal" ||
n.op ==
"Less" ||
n.op ==
"Greater" ||
n.op ==
"And") {
1124 throw Failure(
"Comparison type mismatch");
1127 for (
size_t i = 0; i <
out.bytes.size(); ++i) {
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);
1143 throw Failure(
"Integer arithmetic dtype mismatch");
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");
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");
1159 if (
n.op ==
"Mul") {
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");
1166 if (
n.op ==
"Div") {
1167 if (!
b || (
a == INT64_MIN &&
b == -1))
throw Failure(
"Invalid integer division");
1171 throw Failure(
"Int32 arithmetic overflow");
1176 return std::nullopt;
eve::action::ActionSpatialBinding spatial
std::vector< QuestEvent > pending
std::array< double, 10 > q
std::array< float, 3 > scale
std::vector< std::string > captures
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
std::shared_ptr< OceanGpuSpectrum > owner
std::vector< float > scales
const RuntimeTensor & tensor
std::vector< int64_t > zeros
std::unique_ptr< gpgpu::Sequence > sequence
std::unordered_map< const Node *, std::mt19937 > randomStreams
OnnxElement sequenceElement
const RuntimeTensor * borrowed
std::map< std::string, std::vector< std::string > > graph
std::set< std::string > values
std::vector< EquipmentStat > stats
std::array< std::array< double, 3 >, 3 > axes
const SquirrelValueOptions & options
The canonical owning dynamic value used by data-facing protocols.
GPU execution boundary for native ONNX; retains no model and retains compiled resources for the lifet...
const OnnxBuffer & buffer() const
Buffer.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Result< ForceVector > checked(ForceVector value)
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.
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.
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.
DiagnosticCode
Stable machine-readable diagnostic codes.
Per-call deterministic RNG and optional strict finite-output diagnostic.
Explicit 1D/2D NCHW convolution geometry; missing 1D height is one.
RuntimeTensor public API.
std::vector< int64_t > shape