17 if (
n.domain ==
"com.microsoft" &&
n.op ==
"DynamicQuantizeLSTM") {
18 if (
n.inputs.size() != 12 ||
n.outputs.empty() ||
n.outputs.size() > 3)
return false;
19 for (
const auto& [
key,
a] :
n.attrs) {
20 if (
key ==
"direction") {
21 if (
a.type != 3 || (
a.text !=
"forward" &&
a.text !=
"reverse" &&
a.text !=
"bidirectional"))
23 }
else if (
key ==
"hidden_size" ||
key ==
"input_forget") {
24 if (
a.type != 2)
return false;
25 }
else if (
key ==
"clip") {
26 if (
a.type != 1)
return false;
32 if (!
n.domain.empty())
return false;
33 if (
n.op ==
"If" ||
n.op ==
"Loop") {
34 const std::set<std::string> keys =
35 n.op ==
"If" ? std::set<std::string>{
"then_branch",
"else_branch"} : std::set<std::string>{
"body"};
36 if (
n.attrs.size() != keys.size() ||
n.outputs.empty() ||
37 (
n.op ==
"If" ?
n.inputs.size() != 1 :
n.inputs.size() < 2))
39 for (
const auto&
key : keys) {
40 auto it =
n.attrs.find(
key);
41 if (it ==
n.attrs.end() || it->second.type != 5 || !it->second.graph)
return false;
46 static const std::map<std::string, std::set<std::string>> allowed{
47 {
"DynamicQuantizeLinear", {}},
48 {
"QuantizeLinear", {
"axis"}},
49 {
"DequantizeLinear", {
"axis"}},
50 {
"MatMulInteger", {}},
51 {
"ConvInteger", {
"auto_pad",
"dilations",
"group",
"kernel_shape",
"pads",
"strides"}},
52 {
"Constant", {
"value"}},
55 {
"CumSum", {
"exclusive",
"reverse"}},
56 {
"SequenceEmpty", {
"dtype"}},
58 {
"SequenceInsert", {}},
59 {
"SplitToSequence", {
"axis",
"keepdims"}},
60 {
"ConcatFromSequence", {
"axis",
"new_axis"}},
61 {
"RandomUniformLike", {
"dtype",
"seed",
"low",
"high"}},
62 {
"RandomNormalLike", {
"dtype",
"seed",
"mean",
"scale"}},
63 {
"InstanceNormalization", {
"epsilon"}},
64 {
"ConvTranspose", {
"auto_pad",
"dilations",
"group",
"kernel_shape",
"output_padding",
"pads",
"strides"}},
65 {
"Resize", {
"coordinate_transformation_mode",
"mode",
"nearest_mode",
"cubic_coeff_a"}},
67 {
"TopK", {
"axis",
"largest",
"sorted"}},
68 {
"ScatterND", {
"reduction"}},
69 {
"ScatterElements", {
"axis",
"reduction"}},
70 {
"ReduceProd", {
"axes",
"keepdims"}},
71 {
"ReduceMax", {
"axes",
"keepdims"}},
75 {
"ConstantOfShape", {
"value"}},
83 {
"LeakyRelu", {
"alpha"}},
90 {
"Shape", {
"start",
"end"}},
91 {
"Reshape", {
"allowzero"}},
92 {
"Transpose", {
"perm"}},
111 {
"Softmax", {
"axis"}},
112 {
"ReduceMean", {
"axes",
"keepdims"}},
113 {
"ReduceSum", {
"keepdims",
"noop_with_empty_axes"}}};
114 auto op = allowed.find(
n.op);
115 if (op == allowed.end())
return false;
125 if (
n.op ==
"SequenceInsert") {
129 if (
n.op ==
"SplitToSequence")
maximum = 2;
131 if (
n.op ==
"ConvTranspose") {
135 if (
n.op ==
"Resize") {
139 if (
n.op ==
"Range" ||
n.op ==
"ScatterElements" ||
n.op ==
"ScatterND")
minimum =
maximum = 3;
140 if (
n.op ==
"TopK") {
144 if (
n.op ==
"Slice") {
148 if (
n.op ==
"Concat")
maximum = 100000;
150 if (
n.op ==
"Expand" ||
n.op ==
"Equal" ||
n.op ==
"Less" ||
n.op ==
"Greater" ||
n.op ==
"And")
153 if (
n.op ==
"DynamicQuantizeLinear") outputs = 3;
154 if (
n.op ==
"QuantizeLinear" ||
n.op ==
"DequantizeLinear") {
158 if (
n.op ==
"MatMulInteger" ||
n.op ==
"ConvInteger") {
162 if (
n.op ==
"Gather" ||
n.op ==
"Reshape" ||
n.op ==
"Unsqueeze" ||
n.op ==
"MatMul" ||
n.op ==
"Add" ||
163 n.op ==
"Sub" ||
n.op ==
"Mul" ||
n.op ==
"Div" ||
n.op ==
"Pow")
165 if (
n.op ==
"Squeeze" ||
n.op ==
"ReduceSum")
maximum = 2;
166 if (
n.inputs.size() <
minimum ||
n.inputs.size() >
maximum ||
n.outputs.size() != outputs)
return false;
167 for (
const auto& [
key,
a] :
n.attrs) {
168 if (!op->second.contains(
key))
return false;
169 const int expected = (
key ==
"alpha" ||
key ==
"epsilon" ||
key ==
"cubic_coeff_a" ||
key ==
"seed" ||
170 key ==
"low" ||
key ==
"high" ||
key ==
"mean" ||
key ==
"scale")
173 : (
key ==
"auto_pad" ||
key ==
"reduction" ||
key ==
"coordinate_transformation_mode" ||
174 key ==
"mode" ||
key ==
"nearest_mode")
176 : (
key ==
"perm" ||
key ==
"axes" ||
key ==
"dilations" ||
key ==
"kernel_shape" ||
177 key ==
"pads" ||
key ==
"strides" ||
key ==
"output_padding")
180 if (
a.type != expected)
return false;
181 if (
key ==
"reduction" &&
a.text !=
"none")
return false;
182 if (
key ==
"auto_pad" &&
a.text !=
"NOTSET")
return false;
183 if (
key ==
"allowzero" &&
a.integer != 0)
return false;
185 if (
n.op ==
"Pad" &&
n.attrs.contains(
"mode") &&
n.attrs.at(
"mode").text !=
"constant" &&
186 n.attrs.at(
"mode").text !=
"edge" &&
n.attrs.at(
"mode").text !=
"reflect")
188 if (
n.op ==
"Resize") {
189 const auto mode =
n.attrs.contains(
"mode") ?
n.attrs.at(
"mode").text :
"nearest";
190 const auto coordinate =
n.attrs.contains(
"coordinate_transformation_mode")
191 ?
n.attrs.at(
"coordinate_transformation_mode").text
193 const auto nearest =
n.attrs.contains(
"nearest_mode") ?
n.attrs.at(
"nearest_mode").text :
"round_prefer_floor";
194 if (mode ==
"nearest") {
195 if (coordinate !=
"asymmetric" || nearest !=
"floor")
return false;
196 }
else if (mode !=
"linear" || (coordinate !=
"half_pixel" && coordinate !=
"asymmetric"))
202std::vector<int> dims(
const RuntimeTensor&
x) {
203 std::vector<int>
out;
206 out.push_back(
static_cast<int>(
d));
213 if (
n.op ==
"Constant") {
214 auto a =
n.attrs.find(
"value");
215 if (
a ==
n.attrs.end() || !
a->second.tensor)
throw Failure(
"Constant requires tensor value");
216 return single(*
a->second.tensor);
218 if (
n.op.find(
"Quantize") != std::string::npos ||
n.op ==
"DequantizeLinear" ||
n.op ==
"MatMulInteger" ||
219 n.op ==
"ConvInteger")
222 if (
n.op ==
"Identity")
return single(
x);
223 if (
n.op ==
"Shape") {
224 const int64_t rank =
x.shape.size();
225 auto norm = [rank](int64_t i) {
return std::clamp(i < 0 ? i + rank : i, int64_t(0), rank); };
227 std::vector<int64_t>
shape;
231 if (
n.op ==
"Cast") {
237 for (
size_t i = 0; i <
count(
x.shape); ++i) {
241 std::memcpy(
out.bytes.data() + i * 4, &
v, 4);
245 const double f = read<float>(
x, i);
246 if (!std::isfinite(
f) || f < -9223372036854775808.0 || f >= 9223372036854775808.0)
247 throw Failure(
"Cast overflow");
257 if (
n.op ==
"Gather") {
259 const int a =
axis(
attr(
n,
"axis", 0),
x.shape.size());
261 throw Failure(
"Gather indices must be int32/int64");
262 size_t inner = 1, outer = 1;
263 for (
size_t i =
a + 1; i <
x.shape.size(); ++i) inner *=
x.shape[i];
264 for (
int i = 0; i <
a; ++i) outer *=
x.shape[i];
265 std::vector<int64_t>
shape(
x.shape.begin(),
x.shape.begin() +
a);
267 shape.insert(
shape.end(),
x.shape.begin() +
a + 1,
x.shape.end());
270 for (
size_t o = 0; o < outer; ++o)
271 for (
size_t i = 0; i < ni; ++i) {
273 if (j < 0) j +=
x.shape[
a];
274 if (j < 0 || j >=
x.shape[
a])
throw Failure(
"Gather index out of range");
276 std::memcpy(
out.bytes.data() + (o * ni + i) * stride,
277 x.bytes.data() + (o *
x.shape[
a] + j) * stride, stride);
281 if (
n.op ==
"Reshape" ||
n.op ==
"Unsqueeze" ||
n.op ==
"Squeeze") {
283 if (
n.op ==
"Reshape") {
287 for (
size_t i = 0; i <
shape.size(); ++i) {
289 if (i >=
x.shape.size())
throw Failure(
"Reshape zero axis out of range");
292 if (
shape[i] == -1) {
293 if (infer != -1)
throw Failure(
"Multiple inferred dimensions");
294 infer =
static_cast<int>(i);
297 (
shape[i] && known > 128u * 1024u * 1024u /
static_cast<size_t>(
shape[i])))
298 throw Failure(
"Reshape overflow");
299 known *=
static_cast<size_t>(
shape[i]);
303 if (!known ||
count(
x.shape) % known)
throw Failure(
"Invalid inferred shape");
307 std::vector<int64_t>
axes;
308 if (in.size() > 1 && in[1])
310 else if (
n.op ==
"Unsqueeze")
311 throw Failure(
"Unsqueeze needs axes");
313 for (
size_t i = 0; i <
shape.size(); ++i)
315 const size_t rank =
shape.size() + (
n.op ==
"Unsqueeze" ?
axes.size() : 0);
319 if (
n.op ==
"Unsqueeze") {
323 if (
shape[*it] != 1)
throw Failure(
"Squeeze dimension not one");
332 if (
n.op ==
"Transpose") {
335 for (
size_t i =
x.shape.size(); i > 0; --i)
order.push_back(i - 1);
336 if (
order.size() !=
x.shape.size())
throw Failure(
"Invalid transpose rank");
337 std::set<int64_t>
used;
338 std::vector<int64_t>
shape;
340 if (a < 0 || a >=
static_cast<int64_t
>(
x.shape.size()) || !
used.insert(
a).second)
341 throw Failure(
"Invalid transpose permutation");
346 std::vector<size_t> strides(
x.shape.size(), 1);
347 for (
size_t i =
x.shape.size(); i > 1; --i) strides[i - 2] = strides[i - 1] *
x.shape[i - 1];
349 size_t rest = i,
source = 0;
350 for (
size_t j =
shape.size(); j > 0; --j) {
352 rest /=
shape[j - 1];
358 if (
auto indexResult =
executeIndex(
n, in))
return std::move(*indexResult);
364 if (
n.op ==
"Softmax") {
366 std::vector<float>
out(
a.size());
371 static const std::map<std::string, OpType> unary{
375 auto op = unary.find(
n.op);
377 std::vector<float>
out(
a.size());
386std::string prefix(
bool as,
bool bs) {
387 std::ostringstream
s;
388 s <<
"#version 450\nlayout(local_size_x=64) in;\n"
389 "layout(std430,binding=0) readonly buffer A {uint a[];};\n"
390 "layout(std430,binding=1) readonly buffer B {uint b[];};\n"
391 "layout(std430,binding=2) readonly buffer Z {int zp[];};\n"
392 "layout(std430,binding=3) writeonly buffer Y {int y[];};\n"
393 "int av(uint i){int v=int((a[i/4]>>((i%4)*8))&255u);return "
394 << (as ?
"v>=128?v-256:v" :
"v")
396 "int bv(uint i){int v=int((b[i/4]>>((i%4)*8))&255u);return "
397 << (bs ?
"v>=128?v-256:v" :
"v") <<
";}\n";
402class Synchronous final :
public OnnxCompute {
406 explicit Synchronous(OnnxCompute&
t) :
target(
t) {}
407 Result<std::vector<uint8_t>> dispatch(
const OnnxKernel& k)
override {
return target.dispatch(k); }
409OnnxBuffer hostBuffer(std::span<const uint8_t>
bytes) {
410 auto p = std::make_shared<const std::vector<uint8_t>>(
bytes.begin(),
bytes.end());
411 return {
p, {},
p->size()};
413std::vector<int32_t> integerOutput(
const OnnxBuffer&
result) {
414 if (!
result.host ||
result.host->size() % 4)
throw Failure(
"Invalid synchronous integer output");
415 std::vector<int32_t>
out(
result.host->size() / 4);
421 int az, std::span<const int32_t> bz) {
423 return integerOutput(
gpuMatmulResident(sync, hostBuffer(
a.bytes), hostBuffer(
b.bytes),
a.signedValues,
424 b.signedValues,
m, k,
n, az, bz));
427 std::span<const int32_t>
wz) {
429 return integerOutput(
430 gpuConvResident(sync, hostBuffer(
x.bytes), hostBuffer(
w.bytes),
x.signedValues,
w.signedValues,
c, xz,
wz));
433 std::span<const int32_t>
z,
size_t size,
size_t terms) {
434 if (terms > INT32_MAX / 65025 || !
size ||
size > 64u * 65535u)
436 std::vector<uint8_t>
bytes(
z.size_bytes());
438 auto host = std::make_shared<const std::vector<uint8_t>>(std::move(
bytes));
439 const std::array<OnnxBuffer, 3>
inputs{{std::move(
a), std::move(
b), {
host, {},
host->size()}}};
441 if (!
r.ok())
throw Failure(
r.error()->message(),
r.error()->code());
442 return std::move(
r.value());
445 int az, std::span<const int32_t> bz,
size_t bOffset) {
446 if (bz.size() != 1 && bz.size() !=
n)
throw Failure(
"GPU matmul zero-point extent mismatch");
447 std::ostringstream
s;
448 s << prefix(as, bs) <<
"void main(){uint i=gl_GlobalInvocationID.x;if(i>=" <<
m *
n <<
"u)return;"
449 <<
"uint r=i/" <<
n <<
"u,c=i%" <<
n <<
"u;int v=0;for(uint j=0;j<" << k <<
"u;++j)"
450 <<
"v+=(av(r*" << k <<
"u+j)-(" << az <<
"))*(bv(" << bOffset <<
"u+j*" <<
n <<
"u+c)-zp["
451 << (bz.size() == 1 ?
"0" :
"c") <<
"]);y[i]=v;}";
456 int xz, std::span<const int32_t>
wz) {
458 (int64_t(
c.height) +
c.padTop +
c.padBottom - int64_t(
c.dilationH) * (
c.kernelH - 1) - 1) /
c.strideH + 1;
460 (int64_t(
c.width) +
c.padLeft +
c.padRight - int64_t(
c.dilationW) * (
c.kernelW - 1) - 1) /
c.strideW + 1;
461 if ((oh - 1) *
c.strideH > INT32_MAX || (ow - 1) *
c.strideW > INT32_MAX ||
462 (oh - 1) *
c.strideH -
c.padTop + int64_t(
c.kernelH - 1) *
c.dilationH > INT32_MAX ||
463 (ow - 1) *
c.strideW -
c.padLeft + int64_t(
c.kernelW - 1) *
c.dilationW > INT32_MAX)
465 const size_t size = size_t(
c.batch) *
c.outputs * oh * ow;
466 const int cg =
c.channels /
c.groups;
467 std::ostringstream
s;
468 s << prefix(xs, ws) <<
"void main(){uint i=gl_GlobalInvocationID.x;if(i>=" <<
size <<
"u)return;"
469 <<
"int xx=int(i%" << ow <<
"u),yy=int(i/" << ow <<
"u%" << oh <<
"u),o=int(i/" << ow * oh <<
"u%" <<
c.outputs
470 <<
"u),batch=int(i/" << ow * oh *
c.outputs <<
"u);int v=0;"
471 <<
"for(int ch=0;ch<" << cg <<
";++ch)for(int ky=0;ky<" <<
c.kernelH <<
";++ky)for(int kx=0;kx<" <<
c.kernelW
473 <<
"int iy=yy*" <<
c.strideH <<
"-" <<
c.padTop <<
"+ky*" <<
c.dilationH <<
",ix=xx*" <<
c.strideW <<
"-"
474 <<
c.padLeft <<
"+kx*" <<
c.dilationW <<
";"
475 <<
"if(iy<0||ix<0||iy>=" <<
c.height <<
"||ix>=" <<
c.width <<
")continue;"
476 <<
"uint ai=uint(((batch*" <<
c.channels <<
"+o/" <<
c.outputs /
c.groups <<
"*" << cg <<
"+ch)*" <<
c.height
477 <<
"+iy)*" <<
c.width <<
"+ix);"
478 <<
"uint bi=uint(((o*" << cg <<
"+ch)*" <<
c.kernelH <<
"+ky)*" <<
c.kernelW <<
"+kx);"
479 <<
"v+=(av(ai)-(" << xz <<
"))*(bv(bi)-zp[" << (
wz.size() == 1 ?
"0" :
"o") <<
"]);}y[i]=v;}";
486std::optional<std::vector<RuntimeTensor>>
executeIndex(
const Node&
n,
const std::vector<const RuntimeTensor*>& in) {
489 if (
n.op ==
"Range") {
491 const auto& delta =
required(in, 2);
493 x.element != delta.element)
494 throw Failure(
"Range requires matching scalars");
496 const double start = read<float>(
x, 0), stop = read<float>(
end, 0),
step = read<float>(delta, 0);
497 if (!std::isfinite(
start) || !std::isfinite(stop) || !std::isfinite(
step) ||
step == 0)
498 throw Failure(
"Invalid Range");
500 if (
length > 128u * 1024u * 1024u)
throw Failure(
"Range too large");
501 std::vector<float>
v(
static_cast<size_t>(
length));
502 for (
size_t i = 0; i <
v.size(); ++i)
v[i] =
static_cast<float>(
start + i *
step);
503 return one(
make(
x.element, {static_cast<int64_t>(v.size())},
v));
506 throw Failure(
"Range integer dtype unsupported");
512 if (
length > 128u * 1024u * 1024u)
throw Failure(
"Range too large");
516 for (
size_t i = 0; i <
length; ++i) {
520 return one(std::move(
out));
522 if (
n.op ==
"TopK") {
524 if (
count(kt.shape) != 1)
throw Failure(
"TopK requires one K");
527 if (k < 0 || k >
size)
throw Failure(
"Invalid TopK K");
528 size_t outer = 1, inner = 1;
529 for (
int j = 0; j <
a; ++j) outer *=
x.shape[j];
530 for (
size_t j =
a + 1; j <
x.shape.size(); ++j) inner *=
x.shape[j];
535 for (
size_t o = 0; o < outer; ++o)
536 for (
size_t i = 0; i < inner; ++i) {
539 std::stable_sort(
order.begin(),
order.end(), [&](int64_t
aa, int64_t bb) {
540 auto compare = [&](auto u, auto v) { return attr(n,
"largest", 1) ? u > v : u < v; };
541 const size_t ai = (o *
size +
aa) * inner + i, bi = (o *
size + bb) * inner + i;
545 for (int64_t j = 0; j < k; ++j) {
546 size_t dst = (o * k + j) * inner + i, src = (o *
size +
order[j]) * inner + i;
552 std::vector<RuntimeTensor> outputs;
554 outputs.emplace_back(std::move(
values));
558 if (
n.op ==
"ScatterElements" ||
n.op ==
"ScatterND") {
560 const auto& updates =
required(in, 2);
562 throw Failure(
"Scatter dtype mismatch");
565 if (
n.op ==
"ScatterElements") {
566 if (
idx.shape != updates.shape ||
idx.shape.size() !=
x.shape.size())
567 throw Failure(
"ScatterElements shape mismatch");
569 for (
size_t j = 0; j <
x.shape.size(); ++j)
570 if (j !=
a &&
idx.shape[j] >
x.shape[j])
throw Failure(
"Scatter index shape exceeds data");
571 for (
size_t i = 0; i <
count(
idx.shape); ++i) {
572 size_t rest = i,
source = 0, stride = 1;
573 for (
size_t j =
x.shape.size(); j > 0; --j) {
574 int64_t
c = rest %
idx.shape[j - 1];
575 rest /=
idx.shape[j - 1];
578 if (
c < 0)
c +=
x.shape[j - 1];
580 if (c < 0 || c >=
x.shape[j - 1])
throw Failure(
"Scatter index out of range");
582 stride *=
x.shape[j - 1];
587 if (
idx.shape.empty() ||
idx.shape.back() < 1 ||
static_cast<size_t>(
idx.shape.back()) >
x.shape.size())
588 throw Failure(
"ScatterND index rank mismatch");
589 const size_t depth =
idx.shape.back();
590 std::vector<int64_t> expected(
idx.shape.begin(),
idx.shape.end() - 1);
591 expected.insert(expected.end(),
x.shape.begin() +
depth,
x.shape.end());
592 if (expected != updates.shape)
throw Failure(
"ScatterND updates shape mismatch");
594 for (
size_t j =
depth; j <
x.shape.size(); ++j) chunk *=
x.shape[j];
597 for (
size_t j = 0; j <
depth; ++j) {
599 if (
c < 0)
c +=
x.shape[j];
600 if (c < 0 || c >=
x.shape[j])
throw Failure(
"ScatterND index out of range");
604 std::memcpy(
out.bytes.data() +
target * chunk *
bytes, updates.bytes.data() + i * chunk *
bytes,
608 return one(std::move(
out));
610 if (
n.op ==
"ReduceProd" ||
n.op ==
"ReduceMax") {
613 for (
size_t i = 0; i <
x.shape.size(); ++i)
axes.push_back(i);
614 std::set<int> reduced;
617 auto mapShape =
x.shape;
618 std::vector<int64_t>
shape;
619 for (
size_t j = 0; j <
x.shape.size(); ++j) {
620 if (reduced.contains(
static_cast<int>(j))) {
622 if (
attr(
n,
"keepdims", 1))
shape.push_back(1);
624 shape.push_back(
x.shape[j]);
627 std::vector<float>
out(
count(
shape),
n.op ==
"ReduceProd" ? 1.f : -
std::numeric_limits<float>::infinity());
628 for (
size_t i = 0; i <
count(
x.shape); ++i) {
630 const float v = read<float>(
x, i);
636 throw Failure(
"Integer reduction dtype unsupported");
637 std::vector<int64_t>
out(
count(
shape),
n.op ==
"ReduceProd" ? 1 : INT64_MIN);
638 for (
size_t i = 0; i <
count(
x.shape); ++i) {
641 if (
n.op ==
"ReduceMax")
645 (
a > 0 ? (
b > 0 ?
a > INT64_MAX /
b :
b < INT64_MIN /
a)
646 : (
b > 0 ?
a < INT64_MIN /
b :
a < INT64_MAX /
b)))
647 throw
Failure(
"ReduceProd overflow");
652 std::vector<int32_t> narrow;
654 if (v < INT32_MIN || v > INT32_MAX)
throw Failure(
"Int32 reduction overflow");
655 narrow.push_back(
static_cast<int32_t
>(
v));
668 if (!
r.ok())
throw Failure(
r.error()->message(),
r.error()->code());
669 return std::move(
r.value());
671void shape(
const RuntimeTensor&
t,
const std::vector<int64_t>& expected) {
672 if (
t.shape != expected)
throw Failure(
"LSTM input shape mismatch");
674std::vector<float> optionalFloats(
const std::vector<const RuntimeTensor*>& in,
size_t i,
675 const std::vector<int64_t>& dims) {
676 if (i >= in.size() || !in[i])
return std::vector<float>(
count(dims), 0);
685 Weights(
const RuntimeTensor&
t,
const RuntimeTensor&
s,
const RuntimeTensor&
z,
size_t d,
size_t g,
size_t r)
688 throw Failure(
"LSTM weights must be 8-bit");
689 if (
t.element !=
z.element ||
s.shape !=
z.shape ||
690 (
s.shape != std::vector<int64_t>{static_cast<int64_t>(d)} &&
691 s.shape != std::vector<int64_t>{static_cast<int64_t>(d), static_cast<int64_t>(g)}))
692 throw Failure(
"LSTM quantization parameter shape mismatch");
693 shape(
t, {
static_cast<int64_t
>(
d),
static_cast<int64_t
>(
r),
static_cast<int64_t
>(
g)});
695 if (!(
v > 0) || !std::isfinite(
v))
throw Failure(
"Invalid LSTM weight scale");
697 std::vector<float> multiply(
const affine::QuantizedActivation&
a,
size_t batch,
size_t direction,
699 std::vector<float>
out(batch * gates);
702 std::vector<int32_t>
z(
scales.size() == directions ? 1 :
gates);
703 for (
size_t i = 0; i <
z.size(); ++i)
z[i] =
static_cast<int32_t
>(zeros[
direction *
z.size() + i]);
704 ByteStorage activation(
a.values);
706 batch, rows, gates,
a.zeroPoint,
z,
direction * rows * gates));
707 std::vector<int32_t> sums(batch * gates);
708 std::memcpy(sums.data(),
static_cast<const ByteStorage&
>(accumulator).data(),
709 sums.size() *
sizeof(int32_t));
710 for (
size_t b = 0;
b < batch; ++
b)
712 out[
b * gates +
g] =
static_cast<float>(sums[
b * gates +
g]) *
a.scale *
717 for (
size_t b = 0;
b < batch; ++
b)
718 for (
size_t g = 0;
g <
gates; ++
g) {
721 for (
size_t k = 0; k <
rows; ++k) {
723 const int w = sign &&
byte >= 128 ?
byte - 256 : byte;
724 sum +=
static_cast<int64_t
>(int(
a.values[
b * rows + k]) -
a.zeroPoint) * (
w - zeros[
p]);
726 if (sum < INT32_MIN || sum > INT32_MAX)
throw Failure(
"LSTM integer accumulator overflow");
727 out[
b *
gates +
g] =
static_cast<float>(sum) *
a.scale * scales[
p];
736 if (xt.shape.size() != 3)
throw Failure(
"LSTM X must be [time,batch,input]");
738 const int64_t
time = xt.shape[0], batch = xt.shape[1],
input = xt.shape[2], hidden =
attr(
n,
"hidden_size", 0);
739 const auto direction =
n.attrs.contains(
"direction") ?
n.attrs.at(
"direction").text :
"forward";
740 const int64_t dirs =
direction ==
"bidirectional" ? 2 : 1;
741 if (
time <= 0 || batch <= 0 ||
input <= 0 || hidden <= 0 || hidden > 16384)
742 throw Failure(
"Invalid LSTM dimensions");
743 const size_t gates = 4 * hidden;
744 const size_t projectionSize =
count({
time, batch,
static_cast<int64_t
>(
gates)});
745 if (projectionSize > 128u * 1024u * 1024u)
throw Failure(
"LSTM projection exceeds memory limit");
748 auto biases = optionalFloats(in, 3, {dirs, 8 * hidden});
749 auto h = optionalFloats(in, 5, {dirs, batch, hidden}),
c = optionalFloats(in, 6, {dirs, batch, hidden});
750 auto p = optionalFloats(in, 7, {dirs, 3 * hidden});
751 std::vector<int64_t> lengths(batch,
time);
752 if (in.size() > 4 && in[4]) {
754 shape(*in[4], {batch});
755 lengths =
ints(*in[4]);
757 for (
auto len : lengths)
758 if (len < 0 || len >
time)
throw Failure(
"Invalid LSTM sequence length");
759 const int64_t coupled =
attr(
n,
"input_forget", 0);
760 if (coupled != 0 && coupled != 1)
throw Failure(
"Invalid coupled gate flag");
761 const float clip =
n.attrs.contains(
"clip") ?
n.attrs.at(
"clip").real : std::numeric_limits<float>::max();
762 if (!(
clip > 0) || !std::isfinite(
clip))
throw Failure(
"Invalid LSTM clipping threshold");
763 auto sigmoid = [
clip](
float z) {
return 1.f / (1.f + std::exp(-std::clamp(
z, -
clip,
clip))); };
764 auto tanh = [
clip](
float z) {
return std::tanh(std::clamp(
z, -
clip,
clip)); };
765 std::vector<float>
y(
count({
time, dirs, batch, hidden}), 0);
767 for (int64_t
d = 0;
d < dirs; ++
d) {
769 const bool reverse =
direction ==
"reverse" ||
d == 1;
772 const auto recurrent =
r.multiply(qh, batch,
d,
compute);
773 for (int64_t
b = 0;
b < batch; ++
b) {
774 if (
step >= lengths[
b])
continue;
775 const int64_t
t = reverse ? lengths[
b] - 1 -
step :
step;
776 const size_t state = (
d * batch +
b) * hidden;
777 for (int64_t j = 0; j < hidden; ++j) {
778 auto gate = [&](
int g) {
779 const size_t channel =
g * hidden + j;
780 return projected[(
t * batch +
b) *
gates + channel] + recurrent[
b *
gates + channel] +
781 biases[
d * 8 * hidden + channel] + biases[
d * 8 * hidden +
gates + channel];
783 const float i = sigmoid(gate(0) +
p[
d * 3 * hidden + j] *
c[
state + j]);
785 coupled ? 1 - i : sigmoid(gate(2) +
p[
d * 3 * hidden + 2 * hidden + j] *
c[
state + j]);
787 const float o = sigmoid(gate(1) +
p[
d * 3 * hidden + hidden + j] *
c[
state + j]);
789 y[((
t * dirs +
d) * batch +
b) * hidden + j] =
h[
state + j];
794 std::vector<RuntimeTensor>
result;
std::vector< std::uint32_t > indices
std::vector< float > positions
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
std::vector< float > scales
const RuntimeTensor & tensor
std::vector< int64_t > zeros
std::set< std::string > values
RoadLaneDirection direction
std::array< std::array< double, 3 >, 3 > axes
GPU execution boundary for native ONNX; retains no model and retains compiled resources for the lifet...
Result< ForceVector > checked(ForceVector value)
Result< QuantizedActivation > dynamicQuantize(std::span< const float > input)
Quantize finite FP32 activations with ONNX DynamicQuantizeLinear semantics.
void softmax(const float *in, const int *dims, int rank, int axis, bool logMode, float *out)
Softmax.
void unaryOp(OpType type, const float *in, int count, float *out, float s0, float s1)
Unary op.
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::optional< RuntimeTensor > executeMisc(const Node &, const std::vector< const RuntimeTensor * > &, OnnxCompute *)
Execute misc.
std::vector< int64_t > ints(const RuntimeTensor &v)
Ints.
std::vector< int32_t > gpuConv(OnnxCompute &d, affine::ByteView x, affine::ByteView w, const affine::ConvShape &c, int xz, std::span< const int32_t > wz)
Gpu conv.
int64_t attr(const Node &n, const char *key, int64_t fallback)
Attr.
std::optional< RuntimeTensor > executeNumeric(const Node &, const std::vector< const RuntimeTensor * > &, OnnxCompute *)
Execute numeric.
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.
std::optional< RuntimeTensor > executeNeural(const Node &, const std::vector< const RuntimeTensor * > &, OnnxCompute *)
Execute neural.
RuntimeTensor make(OnnxElement e, std::vector< int64_t > shape, const std::vector< T > &values)
Make.
std::vector< int32_t > gpuMatmul(OnnxCompute &d, affine::ByteView a, affine::ByteView b, size_t m, size_t k, size_t n, int az, std::span< const int32_t > bz)
Gpu matmul.
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.
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.
size_t elementSize(OnnxElement e)
Element size.
std::vector< RuntimeTensor > executeQuantLstm(const Node &n, const std::vector< const RuntimeTensor * > &in, OnnxCompute *compute)
Execute quant lstm.
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.
std::optional< std::vector< RuntimeTensor > > executeIndex(const Node &n, const std::vector< const RuntimeTensor * > &in)
Execute index.
OnnxBuffer enqueueInteger(OnnxCompute &d, const std::string &source, OnnxBuffer a, OnnxBuffer b, std::span< const int32_t > z, size_t size, size_t terms)
OnnxElement
ONNX wire element types; distinct from block-quantized Tensor storage.
Immutable buffer shared by graph aliases; exactly one storage is authoritative.
Borrowed packed 8-bit values, valid for the duration of a synchronous call.
Explicit 1D/2D NCHW convolution geometry; missing 1D height is one.
RuntimeTensor public API.
std::vector< int64_t > shape