载入中...
搜索中...
未找到
OnnxMisc.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <limits>
4#include <set>
5#include <sstream>
8
9// OnnxMisc.cpp
11std::optional<RuntimeTensor> executeMisc(const Node& n, const std::vector<const RuntimeTensor*>& in,
13 const auto& x = required(in, 0);
14 if (n.op == "Clip") {
15 if (x.element != OnnxElement::Float32)
16 throw Failure("Clip currently requires FP32", DiagnosticCode::Unsupported);
17 auto low = make(x.element, {}, std::vector<float>{-std::numeric_limits<float>::infinity()}),
18 high = make(x.element, {}, std::vector<float>{std::numeric_limits<float>::infinity()});
19 const auto& a = in.size() > 1 && in[1] ? *in[1] : low;
20 const auto& b = in.size() > 2 && in[2] ? *in[2] : high;
21 if (a.element != x.element || b.element != x.element || count(a.shape) != 1 || count(b.shape) != 1)
22 throw Failure("Clip bounds must be matching scalars");
23 if (compute) return dispatchFloat(*compute, {&x, &a, &b}, x.shape, "y[i]=min(max(x0[i],x1[0]),x2[0]);");
24 auto v = floats(x);
25 for (auto& f : v) f = std::min(std::max(f, read<float>(a, 0)), read<float>(b, 0));
26 return make(x.element, x.shape, v);
27 }
28 if (n.op == "CumSum") {
29 const auto& at = required(in, 1);
30 if (count(at.shape) != 1) throw Failure("CumSum axis must be scalar");
31 const int a = axis(integer(at), x.shape.size());
32 if (x.element != OnnxElement::Float32)
33 throw Failure("CumSum currently requires FP32", DiagnosticCode::Unsupported);
34 const bool reverse = attr(n, "reverse", 0) != 0, exclusive = attr(n, "exclusive", 0) != 0;
35 size_t outer = 1, inner = 1;
36 for (int j = 0; j < a; ++j) outer *= x.shape[j];
37 for (size_t j = a + 1; j < x.shape.size(); ++j) inner *= x.shape[j];
38 const auto width = x.shape[a];
39 if (compute && outer && inner && width) {
40 std::ostringstream s;
41 s << "uint base=i/" << inner << "u*" << inner * width << "u+i%" << inner
42 << "u;precise float sum=0.0;for(uint j=0;j<" << width << "u;++j){uint index=base+"
43 << (reverse ? "(" + std::to_string(width - 1) + "u-j)" : "j") << "*" << inner << "u;"
44 << (exclusive ? "y[index]=sum;sum+=x0[index];" : "sum+=x0[index];y[index]=sum;") << "}";
45 return dispatchFloat(*compute, {&x}, x.shape, s.str(), outer * inner);
46 }
47 auto out = floats(x);
48 for (size_t o = 0; o < outer; ++o)
49 for (size_t i = 0; i < inner; ++i) {
50 float sum = 0;
51 for (int64_t j = 0; j < width; ++j) {
52 size_t p = (o * width + (reverse ? width - 1 - j : j)) * inner + i;
53 const float v = out[p];
54 if (exclusive) {
55 out[p] = sum;
56 sum += v;
57 } else {
58 sum += v;
59 out[p] = sum;
60 }
61 }
62 }
63 return make(x.element, x.shape, out);
64 }
65 if (n.op == "Pad") {
66 const auto pads = ints(required(in, 1));
67 if (pads.size() != 2 * x.shape.size()) throw Failure("Pad rank mismatch");
68 auto shape = x.shape;
69 const auto mode = n.attrs.contains("mode") ? n.attrs.at("mode").text : "constant";
70 for (size_t j = 0; j < shape.size(); ++j) {
71 if (pads[j] < -INT32_MAX || pads[j] > INT32_MAX || pads[j + shape.size()] < -INT32_MAX ||
72 pads[j + shape.size()] > INT32_MAX)
73 throw Failure("Pad extent out of range");
74 shape[j] += pads[j] + pads[j + shape.size()];
75 if (mode != "constant" && x.shape[j] <= 0)
76 throw Failure("Edge/reflect padding requires nonempty dimensions");
77 if (mode == "reflect" && (pads[j] >= x.shape[j] || pads[j + shape.size()] >= x.shape[j]))
78 throw Failure("Reflect padding exceeds input dimension");
79 }
80 const auto size = elementSize(x.element);
81 std::vector<uint8_t> fill(size, 0);
82 if (in.size() > 2 && in[2]) {
83 if (in[2]->element != x.element || count(in[2]->shape) != 1)
84 throw Failure("Pad value dtype/shape mismatch");
85 fill = in[2]->bytes;
86 }
87 RuntimeTensor out{x.element, shape, std::vector<uint8_t>(count(shape) * size)};
88 for (size_t i = 0; i < count(shape); ++i) {
89 size_t rest = i, source = 0, stride = 1;
90 bool outside = false;
91 for (size_t j = shape.size(); j > 0; --j) {
92 int64_t p = static_cast<int64_t>(rest % shape[j - 1]) - pads[j - 1];
93 rest /= shape[j - 1];
94 if (p < 0 || p >= x.shape[j - 1]) {
95 if (mode == "constant")
96 outside = true;
97 else if (mode == "edge")
98 p = std::clamp(p, int64_t(0), x.shape[j - 1] - 1);
99 else
100 p = p < 0 ? -p : 2 * x.shape[j - 1] - 2 - p;
101 }
102 if (!outside) source += p * stride;
103 stride *= x.shape[j - 1];
104 }
105 std::memcpy(out.bytes.data() + i * size, outside ? fill.data() : x.bytes.data() + source * size, size);
106 }
107 return out;
108 }
109 return std::nullopt;
110}
111} // namespace eve::tensor::onnx_detail
112
113// OnnxModel.cpp
114namespace eve::tensor {
118OnnxModel::OnnxModel(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
119OnnxModel::~OnnxModel() = default;
120OnnxModelInfo OnnxModel::info() const { return impl_->model.info; }
122 try {
123 auto impl = std::make_unique<Impl>();
124 impl->model = onnx_detail::parse(bytes);
125 return Result<std::unique_ptr<OnnxModel>>::success(std::unique_ptr<OnnxModel>(new OnnxModel(std::move(impl))));
126 } catch (const onnx_detail::Failure& e) {
127 return Result<std::unique_ptr<OnnxModel>>::failure(
128 Diagnostic::error(e.code, e.what(), {}, {}, "tensor.onnx.import"));
129 } catch (const std::exception& e) {
130 return Result<std::unique_ptr<OnnxModel>>::failure(
131 Diagnostic::error(DiagnosticCode::Failed, e.what(), {}, {}, "tensor.onnx.import"));
132 }
133}
134Result<std::vector<OnnxNamedTensor>> OnnxModel::run(std::span<const OnnxNamedTensor> feeds,
135 std::span<const std::string> requested,
136 OnnxRunOptions options) const {
137 return runInternal(feeds, requested, nullptr, options);
138}
139Result<OnnxGpuResult> OnnxModel::runGpu(std::span<const OnnxNamedTensor> feeds, OnnxCompute& compute,
140 std::span<const std::string> requested, OnnxRunOptions options) const {
141 class Counter final : public OnnxCompute {
142 public:
144 size_t count = 0;
145 explicit Counter(OnnxCompute& t) : target(t) {}
146 Result<std::vector<uint8_t>> dispatch(const OnnxKernel& k) override {
147 auto r = target.dispatch(k);
148 if (r.ok()) ++count;
149 return r;
150 }
151 Result<OnnxBuffer> enqueue(const std::string& source, std::span<const OnnxBuffer> inputs, size_t bytes,
152 uint32_t work) override {
153 auto r = target.enqueue(source, inputs, bytes, work);
154 if (r.ok()) ++count;
155 return r;
156 }
157 } counter(compute);
158 compute.beginRun();
159 struct RunScope {
161 ~RunScope() { device.endRun(); }
162 } scope{compute};
163 auto r = runInternal(feeds, requested, &counter, options);
164 if (!r.ok()) return Result<OnnxGpuResult>::failure(r.status());
165 return Result<OnnxGpuResult>::success({std::move(r.value()), counter.count, compute.transferStats()});
166}
167Result<std::vector<OnnxNamedTensor>> OnnxModel::runInternal(std::span<const OnnxNamedTensor> feeds,
168 std::span<const std::string> requested,
170 using namespace onnx_detail;
171 std::string nodeName;
172 try {
173 const auto& model = impl_->model;
174 const std::vector<std::string> targets =
175 requested.empty() ? model.info.outputs : std::vector<std::string>(requested.begin(), requested.end());
176 std::set<std::string> seenFeeds;
177 for (const auto& f : feeds) {
178 nodeName = f.name;
179 if (count(f.tensor.shape) * elementSize(f.tensor.element) != f.tensor.bytes.size())
180 throw Failure("Tensor byte count mismatch");
181 auto input = model.inputs.find(f.name);
182 if (input == model.inputs.end() || !seenFeeds.insert(f.name).second)
183 throw Failure("Unknown or duplicate feed");
184 if (static_cast<int>(f.tensor.element) != input->second.type ||
185 f.tensor.shape.size() != input->second.shape.size())
186 throw Failure("Feed type/rank mismatch");
187 for (size_t i = 0; i < f.tensor.shape.size(); ++i)
188 if (input->second.shape[i] >= 0 && input->second.shape[i] != f.tensor.shape[i])
189 throw Failure("Feed dimension mismatch");
190 }
191 nodeName.clear();
192 auto result = evaluate(model, feeds, targets, compute, options);
193 return Result<std::vector<OnnxNamedTensor>>::success(std::move(result));
194 } catch (const Failure& e) {
195 return Result<std::vector<OnnxNamedTensor>>::failure(
196 Diagnostic::error(e.code, e.what(), e.path.empty() ? nodeName : e.path, {}, "tensor.onnx.run"));
197 } catch (const std::exception& e) {
198 return Result<std::vector<OnnxNamedTensor>>::failure(
199 Diagnostic::error(DiagnosticCode::Failed, e.what(), nodeName, {}, "tensor.onnx.run"));
200 }
201}
202} // namespace eve::tensor
203
204// OnnxNeural.cpp
205namespace eve::tensor::onnx_detail {
206std::optional<RuntimeTensor> executeNeural(const Node& n, const std::vector<const RuntimeTensor*>& in,
208 const auto& x = required(in, 0);
209 if (x.element != OnnxElement::Float32) return std::nullopt;
210 if (n.op == "InstanceNormalization") {
211 const auto& scale = required(in, 1);
212 const auto& bias = required(in, 2);
213 if (x.shape.size() < 3 || scale.shape != std::vector<int64_t>{x.shape[1]} || bias.shape != scale.shape ||
214 scale.element != x.element || bias.element != x.element)
215 throw Failure("InstanceNormalization shape/type mismatch");
216 const float epsilon = n.attrs.contains("epsilon") ? n.attrs.at("epsilon").real : 1e-5f;
217 if (!(epsilon > 0) || !std::isfinite(epsilon)) throw Failure("Invalid normalization epsilon");
218 size_t spatial = 1;
219 for (size_t j = 2; j < x.shape.size(); ++j) spatial *= x.shape[j];
220 if (!spatial) throw Failure("Empty InstanceNormalization");
221 if (compute) {
222 std::ostringstream s;
223 s.precision(9);
224 s << std::scientific;
225 s << "uint base=i*" << spatial << "u;precise float mean=0.0;for(uint j=0;j<" << spatial
226 << "u;++j)mean+=x0[base+j];mean/=" << spatial << ".0;precise float var=0.0;for(uint j=0;j<" << spatial
227 << "u;++j){float d=x0[base+j]-mean;var+=d*d;}float inv=inversesqrt(var/" << spatial << ".0+" << epsilon
228 << ");for(uint j=0;j<" << spatial << "u;++j)y[base+j]=(x0[base+j]-mean)*inv*x1[i%" << x.shape[1]
229 << "u]+x2[i%" << x.shape[1] << "u];";
230 return dispatchFloat(*compute, {&x, &scale, &bias}, x.shape, s.str(), count(x.shape) / spatial);
231 }
232 auto out = floats(x);
233 for (size_t i = 0; i < out.size() / spatial; ++i) {
234 float mean = 0, var = 0;
235 for (size_t j = 0; j < spatial; ++j) mean += out[i * spatial + j];
236 mean /= spatial;
237 for (size_t j = 0; j < spatial; ++j) {
238 float d = out[i * spatial + j] - mean;
239 var += d * d;
240 }
241 const float multiplier = read<float>(scale, i % x.shape[1]) / std::sqrt(var / spatial + epsilon),
242 offset = read<float>(bias, i % x.shape[1]);
243 for (size_t j = 0; j < spatial; ++j)
244 out[i * spatial + j] = (out[i * spatial + j] - mean) * multiplier + offset;
245 }
246 return make(x.element, x.shape, out);
247 }
248 if (n.op == "ConvTranspose") {
249 const auto& w = required(in, 1);
250 if (x.shape.size() != 3 || w.shape.size() != 3 || w.element != x.element || w.shape[0] != x.shape[1])
251 throw Failure("ConvTranspose requires NCL / CIO weights", DiagnosticCode::Unsupported);
252 const auto strides = attrs(n, "strides", {1}), pads = attrs(n, "pads", {0, 0}),
253 dilations = attrs(n, "dilations", {1}), extra = attrs(n, "output_padding", {0});
254 if (strides.size() != 1 || pads.size() != 2 || dilations.size() != 1 || extra.size() != 1)
255 throw Failure("ConvTranspose attribute rank mismatch");
256 const int64_t stride = strides[0], dilation = dilations[0], groups = attr(n, "group", 1), channels = x.shape[1],
257 length = x.shape[2], kernel = w.shape[2], cout = w.shape[1];
258 if (stride <= 0 || stride > 65536 || dilation <= 0 || dilation > 65536 || groups <= 0 || channels % groups ||
259 pads[0] < 0 || pads[1] < 0 || extra[0] < 0 || extra[0] >= std::max(stride, dilation) || length <= 0 ||
260 kernel <= 0 || cout <= 0)
261 throw Failure("Invalid ConvTranspose geometry");
262 if (n.attrs.contains("kernel_shape") && attrs(n, "kernel_shape", {}) != std::vector<int64_t>{kernel})
263 throw Failure("ConvTranspose kernel_shape mismatch");
264 const int64_t width = stride * (length - 1) + extra[0] + dilation * (kernel - 1) + 1 - pads[0] - pads[1],
265 outputs = cout * groups;
266 if (width <= 0 || width > INT32_MAX) throw Failure("Invalid ConvTranspose output extent");
267 std::vector<int64_t> shape{x.shape[0], outputs, width};
268 count(shape);
269 RuntimeTensor zeroBias = make(OnnxElement::Float32, {outputs}, std::vector<float>(outputs, 0));
270 const auto& bias = in.size() > 2 && in[2] ? *in[2] : zeroBias;
271 if (bias.element != x.element || bias.shape != zeroBias.shape) throw Failure("ConvTranspose bias mismatch");
272 if (compute) {
273 std::ostringstream s;
274 s << "uint pos=i%" << width << "u,o=i/" << width << "u%" << outputs << "u,batch=i/" << width * outputs
275 << "u;precise float v=x2[o];for(uint c=0;c<" << channels / groups << "u;++c)for(uint j=0;j<" << kernel
276 << "u;++j){int z=int(pos)+" << pads[0] << "-int(j)*" << dilation << ";if(z<0||z%" << stride << "!=0||z/"
277 << stride << ">=" << length << ")continue;uint ch=o/" << cout << "u*" << channels / groups
278 << "u+c;v+=x0[(batch*" << channels << "u+ch)*" << length << "u+uint(z/" << stride << ")]*x1[(ch*" << cout
279 << "u+o%" << cout << "u)*" << kernel << "u+j];}y[i]=v;";
280 return dispatchFloat(*compute, {&x, &w, &bias}, shape, s.str());
281 }
282 std::vector<float> out(count(shape));
283 for (int64_t batch = 0; batch < x.shape[0]; ++batch)
284 for (int64_t o = 0; o < outputs; ++o)
285 for (int64_t pos = 0; pos < width; ++pos) {
286 float v = read<float>(bias, o);
287 for (int64_t c = 0; c < channels / groups; ++c)
288 for (int64_t j = 0; j < kernel; ++j) {
289 int64_t z = pos + pads[0] - j * dilation;
290 if (z < 0 || z % stride || z / stride >= length) continue;
291 int64_t ch = o / cout * (channels / groups) + c;
292 v += read<float>(x, (batch * channels + ch) * length + z / stride) *
293 read<float>(w, (ch * cout + o % cout) * kernel + j);
294 }
295 out[(batch * outputs + o) * width + pos] = v;
296 }
297 return make(x.element, shape, out);
298 }
299 if (n.op == "Resize") {
300 if (in.size() > 1 && in[1] && !in[1]->bytes.empty())
301 throw Failure("Resize ROI unsupported", DiagnosticCode::Unsupported);
302 std::vector<double> scales;
303 auto shape = x.shape;
304 if (in.size() > 2 && in[2] && !in[2]->bytes.empty()) {
305 auto s = floats(*in[2]);
306 scales.assign(s.begin(), s.end());
307 if (scales.size() != shape.size()) throw Failure("Resize scales rank mismatch");
308 for (size_t j = 0; j < shape.size(); ++j) {
309 if (!(scales[j] > 0) || !std::isfinite(scales[j]) || std::floor(shape[j] * scales[j]) > INT32_MAX)
310 throw Failure("Invalid Resize scale");
311 shape[j] = static_cast<int64_t>(std::floor(shape[j] * scales[j]));
312 }
313 } else {
314 shape = ints(required(in, 3));
315 if (shape.size() != x.shape.size()) throw Failure("Resize sizes rank mismatch");
316 for (size_t j = 0; j < shape.size(); ++j) {
317 if (x.shape[j] <= 0) throw Failure("Empty Resize input");
318 scales.push_back(double(shape[j]) / x.shape[j]);
319 }
320 }
321 count(shape);
322 const auto mode = n.attrs.contains("mode") ? n.attrs.at("mode").text : "nearest",
323 coordinate = n.attrs.contains("coordinate_transformation_mode")
324 ? n.attrs.at("coordinate_transformation_mode").text
325 : "half_pixel";
326 for (auto d : x.shape)
327 if (d <= 0) throw Failure("Empty Resize input");
328 if (mode == "nearest") {
329 if (compute) {
330 std::ostringstream s;
331 s.precision(17);
332 s << "uint rest=i,source=0u;";
333 size_t stride = 1;
334 for (size_t j = shape.size(); j > 0; --j) {
335 s << "source+=uint(min(floor(float(rest%" << shape[j - 1] << "u)/" << std::scientific
336 << scales[j - 1] << ")," << double(x.shape[j - 1] - 1) << "))*" << stride
337 << "u;rest/=" << shape[j - 1] << "u;";
338 stride *= x.shape[j - 1];
339 }
340 s << "y[i]=x0[source];";
341 return dispatchFloat(*compute, {&x}, shape, s.str());
342 }
343 std::vector<float> out(count(shape));
344 for (size_t i = 0; i < out.size(); ++i) {
345 size_t rest = i, source = 0, stride = 1;
346 for (size_t j = shape.size(); j > 0; --j) {
347 source += std::min(int64_t(std::floor((rest % shape[j - 1]) / scales[j - 1])), x.shape[j - 1] - 1) *
348 stride;
349 rest /= shape[j - 1];
350 stride *= x.shape[j - 1];
351 }
352 out[i] = read<float>(x, source);
353 }
354 return make(x.element, shape, out);
355 }
356 // The speech model interpolates its final axis only. Reject other geometries explicitly.
357 for (size_t j = 0; j + 1 < shape.size(); ++j)
358 if (shape[j] != x.shape[j])
359 throw Failure("Linear Resize supports final axis only", DiagnosticCode::Unsupported);
360 if (shape.empty()) throw Failure("Resize scalar unsupported");
361 const auto width = shape.back(), old = x.shape.back();
362 if (!width) return RuntimeTensor{x.element, shape, {}};
363 auto position = [&](int64_t p) {
364 return coordinate == "half_pixel" ? (p + .5) / scales.back() - .5 : p / scales.back();
365 };
366 if (compute) {
367 std::ostringstream s;
368 s.precision(17);
369 s << std::scientific;
370 s << "uint base=i/" << width << "u*" << old
371 << "u;float p=" << (coordinate == "half_pixel" ? "(float(i%" : "float(i%") << width
372 << (coordinate == "half_pixel" ? "u)+0.5)/" : "u)/") << scales.back()
373 << (coordinate == "half_pixel" ? "-0.5" : "") << ";float t=floor(p),f=p-t;uint a=uint(clamp(t,0.0,"
374 << double(old - 1) << ")),b=uint(clamp(t+1.0,0.0," << double(old - 1)
375 << "));y[i]=x0[base+a]*(1.0-f)+x0[base+b]*f;";
376 return dispatchFloat(*compute, {&x}, shape, s.str());
377 }
378 std::vector<float> out(count(shape));
379 for (size_t i = 0; i < out.size(); ++i) {
380 double p = position(i % width), lo = std::floor(p), f = p - lo;
381 size_t base = i / width * old;
382 out[i] = static_cast<float>(read<float>(x, base + std::clamp(int64_t(lo), int64_t(0), old - 1)) * (1 - f) +
383 read<float>(x, base + std::clamp(int64_t(lo + 1), int64_t(0), old - 1)) * f);
384 }
385 return make(x.element, shape, out);
386 }
387 return std::nullopt;
388}
389} // namespace eve::tensor::onnx_detail
390
391// OnnxNumeric.cpp
392namespace eve::tensor::onnx_detail {
393namespace {
394std::string literal(float v) {
395 std::ostringstream s;
396 s.precision(9);
397 s << std::scientific << v;
398 return s.str();
399}
400std::string indexCode(const std::vector<int64_t>& input, const std::vector<int64_t>& output, const char* index) {
401 std::string result = "0u";
402 size_t src = 1, dst = 1;
403 for (size_t j = 0; j < output.size(); ++j) {
404 if (j < input.size()) {
405 const auto dim = input[input.size() - 1 - j];
406 if (dim != 1)
407 result += "+(" + std::string(index) + "/" + std::to_string(dst) + "u%" + std::to_string(dim) + "u)*" +
408 std::to_string(src) + "u";
409 src *= dim;
410 }
411 dst *= output[output.size() - 1 - j];
412 }
413 return result;
414}
415} // namespace
416RuntimeTensor dispatchFloat(OnnxCompute& compute, const std::vector<const RuntimeTensor*>& inputs,
417 const std::vector<int64_t>& shape, const std::string& body, size_t work) {
418 RuntimeTensor out{OnnxElement::Float32, shape, std::vector<uint8_t>(count(shape) * 4)};
419 if (out.bytes.empty()) return out;
420 if (!work) work = count(shape);
421 if (work > 65535u * 64u) throw Failure("GPU float dispatch limit exceeded", DiagnosticCode::Unsupported);
422 OnnxKernel k;
423 std::vector<OnnxBuffer> buffers;
424 k.outputBytes = out.bytes.size();
425 k.workItems = static_cast<uint32_t>(work);
426 k.source = "#version 450\nlayout(local_size_x=64)in;\n";
427 for (size_t i = 0; i < inputs.size(); ++i) {
429 throw Failure("GPU float input type mismatch");
430 buffers.push_back(inputs[i]->bytes.buffer());
431 k.source += "layout(std430,binding=" + std::to_string(i) + ")readonly buffer B" + std::to_string(i) +
432 (inputs[i]->element == OnnxElement::Int32 ? "{int x" : "{float x") + std::to_string(i) + "[];};\n";
433 }
434 k.source +=
435 "layout(std430,binding=" + std::to_string(inputs.size()) +
436 ")writeonly buffer Y{float y[];};\nvoid main(){uint i=gl_GlobalInvocationID.x;if(i>=" + std::to_string(work) +
437 "u)return;" + body + "}";
438 auto r = compute.enqueue(k.source, buffers, k.outputBytes, k.workItems);
439 if (!r.ok()) throw Failure(r.error()->message(), r.error()->code());
440 if (r.value().size != out.bytes.size()) throw Failure("GPU output size mismatch");
441 out.bytes = std::move(r.value());
442 return out;
443}
444std::optional<RuntimeTensor> executeNumeric(const Node& n, const std::vector<const RuntimeTensor*>& in,
446 const auto& x = required(in, 0);
447 if (x.element != OnnxElement::Float32) return std::nullopt;
448 if (n.op == "MatMul") {
449 const auto& b = required(in, 1);
450 if (b.element != x.element || x.shape.empty() || b.shape.empty()) throw Failure("MatMul type/rank mismatch");
451 auto as = x.shape, bs = b.shape;
452 const bool av = as.size() == 1, bv = bs.size() == 1;
453 if (av) as.insert(as.begin(), 1);
454 if (bv) bs.push_back(1);
455 const auto m = as[as.size() - 2], k = as.back(), cols = bs.back();
456 if (k != bs[bs.size() - 2]) throw Failure("MatMul inner dimension mismatch");
457 std::vector<int64_t> ab(as.begin(), as.end() - 2), bb(bs.begin(), bs.end() - 2);
458 auto batches = broadcast(ab, bb);
459 auto shape = batches;
460 shape.push_back(m);
461 shape.push_back(cols);
462 count(shape);
463 if (av) shape.erase(shape.end() - 2);
464 if (bv) shape.pop_back();
465 if (compute && m && cols) {
466 std::string body = "uint batch=i/" + std::to_string(m * cols) + "u,r=i/" + std::to_string(cols) + "u%" +
467 std::to_string(m) + "u,c=i%" + std::to_string(cols) +
468 "u;precise float v=0.0;for(uint j=0;j<" + std::to_string(k) + "u;++j)v+=x0[(" +
469 indexCode(ab, batches, "batch") + ")*" + std::to_string(m * k) + "u+r*" +
470 std::to_string(k) + "u+j]*x1[(" + indexCode(bb, batches, "batch") + ")*" +
471 std::to_string(k * cols) + "u+j*" + std::to_string(cols) + "u+c];y[i]=v;";
472 return dispatchFloat(*compute, {&x, &b}, shape, body);
473 }
474 std::vector<float> out(count(shape), 0);
475 for (size_t batch = 0; batch < count(batches); ++batch)
476 for (int64_t r = 0; r < m; ++r)
477 for (int64_t c = 0; c < cols; ++c) {
478 float sum = 0;
479 for (int64_t j = 0; j < k; ++j)
480 sum += read<float>(x, broadcastIndex(batch, ab, batches) * m * k + r * k + j) *
481 read<float>(b, broadcastIndex(batch, bb, batches) * k * cols + j * cols + c);
482 out[(batch * m + r) * cols + c] = sum;
483 }
485 }
486 static const std::set<std::string> binary{"Add", "Sub", "Mul", "Div", "Pow"};
487 if (binary.contains(n.op)) {
488 const auto& b = required(in, 1);
489 if (b.element != x.element) throw Failure("Float arithmetic dtype mismatch");
490 auto shape = broadcast(x.shape, b.shape);
491 if (compute) {
492 const std::string a = "x0[" + indexCode(x.shape, shape, "i") + "]",
493 v = "x1[" + indexCode(b.shape, shape, "i") + "]";
494 const std::string e = n.op == "Pow" ? "pow(" + a + "," + v + ")"
495 : a +
496 (n.op == "Add" ? "+"
497 : n.op == "Sub" ? "-"
498 : n.op == "Mul" ? "*"
499 : "/") +
500 v;
501 if (n.op == "Pow")
502 return dispatchFloat(*compute, {&x, &b}, shape,
503 "float a=" + a + ",b=" + v +
504 ";float value;if(b==0.0)value=1.0;else "
505 "if(a==0.0)value=b>0.0?0.0:uintBitsToFloat(0x7f800000u);else "
506 "if(a<0.0)value=b==floor(b)?pow(-a,b)*(mod(abs(b),2.0)==0.0?1.0:-1.0):"
507 "uintBitsToFloat(0x7fc00000u);else value=pow(a,b);y[i]=value;");
508 return dispatchFloat(*compute, {&x, &b}, shape, "y[i]=" + e + ";");
509 }
510 std::vector<float> out(count(shape));
511 for (size_t i = 0; i < out.size(); ++i) {
512 const float a = read<float>(x, broadcastIndex(i, x.shape, shape)),
513 v = read<float>(b, broadcastIndex(i, b.shape, shape));
514 out[i] = n.op == "Add" ? a + v
515 : n.op == "Sub" ? a - v
516 : n.op == "Mul" ? a * v
517 : n.op == "Div" ? a / v
518 : std::pow(a, v);
519 }
521 }
522 if (n.op == "ReduceMean" || n.op == "ReduceSum") {
523 auto axes = n.op == "ReduceMean" ? attrs(n, "axes", {})
524 : in.size() > 1 && in[1] ? ints(*in[1])
525 : std::vector<int64_t>{};
526 if (axes.empty() && n.op == "ReduceSum" && attr(n, "noop_with_empty_axes", 0)) return x;
527 if (axes.empty())
528 for (size_t i = 0; i < x.shape.size(); ++i) axes.push_back(i);
529 std::set<int> set;
530 for (auto a : axes)
531 if (!set.insert(axis(a, x.shape.size())).second) throw Failure("Duplicate reduction axis");
532 std::vector<int64_t> outerShape, reducedShape, shape;
533 std::vector<size_t> outerStrides, reducedStrides;
534 size_t stride = count(x.shape);
535 for (size_t j = 0; j < x.shape.size(); ++j) {
536 if (!x.shape[j]) throw Failure("Empty reduction unsupported", DiagnosticCode::Unsupported);
537 stride /= x.shape[j];
538 if (set.contains(static_cast<int>(j))) {
539 reducedShape.push_back(x.shape[j]);
540 reducedStrides.push_back(stride);
541 if (attr(n, "keepdims", 1)) shape.push_back(1);
542 } else {
543 outerShape.push_back(x.shape[j]);
544 outerStrides.push_back(stride);
545 shape.push_back(x.shape[j]);
546 }
547 }
548 auto offset = [](size_t i, const std::vector<int64_t>& dims, const std::vector<size_t>& strides) {
549 size_t p = 0;
550 for (size_t j = dims.size(); j > 0; --j) {
551 p += (i % dims[j - 1]) * strides[j - 1];
552 i /= dims[j - 1];
553 }
554 return p;
555 };
556 auto code = [](const char* var, const std::vector<int64_t>& dims, const std::vector<size_t>& strides) {
557 std::string s = "0u";
558 size_t divisor = 1;
559 for (size_t j = dims.size(); j > 0; --j) {
560 s += "+(" + std::string(var) + "/" + std::to_string(divisor) + "u%" + std::to_string(dims[j - 1]) +
561 "u)*" + std::to_string(strides[j - 1]) + "u";
562 divisor *= dims[j - 1];
563 }
564 return s;
565 };
566 const size_t terms = count(reducedShape);
567 if (compute)
568 return dispatchFloat(*compute, {&x}, shape,
569 "uint base=" + code("i", outerShape, outerStrides) +
570 ";precise float v=0.0;for(uint j=0;j<" + std::to_string(terms) +
571 "u;++j)v+=x0[base+(" + code("j", reducedShape, reducedStrides) + ")];y[i]=v" +
572 (n.op == "ReduceMean" ? "/" + std::to_string(terms) + ".0" : "") + ";");
573 std::vector<float> out(count(shape));
574 for (size_t i = 0; i < out.size(); ++i) {
575 float v = 0;
576 for (size_t j = 0; j < terms; ++j)
577 v += read<float>(x, offset(i, outerShape, outerStrides) + offset(j, reducedShape, reducedStrides));
578 out[i] = n.op == "ReduceMean" ? v / terms : v;
579 }
581 }
582 if (n.op == "Softmax" && compute) {
583 int a = axis(attr(n, "axis", -1), x.shape.size());
584 size_t inner = 1, outer = 1;
585 for (int j = 0; j < a; ++j) outer *= x.shape[j];
586 for (size_t j = a + 1; j < x.shape.size(); ++j) inner *= x.shape[j];
587 const auto channels = x.shape[a];
588 if (!channels || !inner) return RuntimeTensor{x.element, x.shape, {}};
589 auto ch = std::to_string(channels), ins = std::to_string(inner);
590 return dispatchFloat(*compute, {&x}, x.shape,
591 "uint base=i/" + ins + "u*" + ins + "u*" + ch + "u+i%" + ins +
592 "u;float m=-3.402823466e38;for(uint j=0;j<" + ch + "u;++j)m=max(m,x0[base+j*" + ins +
593 "u]);float sum=0.0;for(uint j=0;j<" + ch + "u;++j)sum+=exp(x0[base+j*" + ins +
594 "u]-m);for(uint j=0;j<" + ch + "u;++j)y[base+j*" + ins + "u]=exp(x0[base+j*" + ins +
595 "u]-m)/sum;",
596 outer * inner);
597 }
598 static const std::map<std::string, std::string> unary{{"Sqrt", "sqrt(v)"},
599 {"Exp", "exp(v)"},
600 {"Log", "log(v)"},
601 {"Sin", "sin(v)"},
602 {"Cos", "cos(v)"},
603 {"Relu", "max(v,0.0)"},
604 {"Sigmoid", "1.0/(1.0+exp(-v))"},
605 {"Tanh", "isnan(v)?v:tanh(clamp(v,-10.0,10.0))"},
606 {"Neg", "-v"},
607 {"Abs", "abs(v)"},
608 {"Reciprocal", "1.0/v"},
609 {"Floor", "floor(v)"},
610 {"Round", "roundEven(v)"},
611 {"Atan", "isinf(v)?sign(v)*1.5707963267948966:atan(v)"}};
612 if (n.op == "LeakyRelu" || unary.contains(n.op)) {
613 const float alpha = n.attrs.contains("alpha") ? n.attrs.at("alpha").real : 0.01f;
614 if (!std::isfinite(alpha)) throw Failure("Invalid LeakyRelu alpha");
615 if (compute)
616 return dispatchFloat(
617 *compute, {&x}, x.shape,
618 "float v=x0[i];y[i]=" + (n.op == "LeakyRelu" ? "v>=0.0?v:v*" + literal(alpha) : unary.at(n.op)) + ";");
619 if (n.op != "LeakyRelu" && n.op != "Reciprocal" && n.op != "Floor" && n.op != "Round" && n.op != "Atan")
620 return std::nullopt;
621 auto out = floats(x);
622 for (auto& v : out) {
623 if (n.op == "LeakyRelu")
624 v = v >= 0 ? v : alpha * v;
625 else if (n.op == "Reciprocal")
626 v = 1 / v;
627 else if (n.op == "Floor")
628 v = std::floor(v);
629 else if (n.op == "Atan")
630 v = std::atan(v);
631 else {
632 float lo = std::floor(v), f = v - lo;
633 v = lo + (f > 0.5f || (f == 0.5f && std::fmod(lo, 2.f) != 0));
634 }
635 }
636 return make(OnnxElement::Float32, x.shape, out);
637 }
638 return std::nullopt;
639}
640} // namespace eve::tensor::onnx_detail
double z
double m[16]
double x
LogicalId target
float w
Definition AnimClip.cpp:738
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string output
eve::action::ActionSpatialBinding spatial
const std::string & s
void * impl
glm::vec4 p[6]
EvpackChunkInput input
Definition Evpack.cpp:170
int cols
std::vector< FieldTarget > targets
DiagnosticCode code
vkb::Device & device
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
int inputs
Definition GridGraph.cpp:23
std::uint32_t ab
double r
float v
std::int32_t c
std::uint32_t width
JobScope scope
float length
JointPoint2D axis
size_t offset
std::array< float, 3 > position
std::array< float, 3 > scale
bool required
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
std::vector< float > scales
uint32_t groups
Definition OnnxGpgpu.cpp:39
OnnxCompute * compute
float f
std::string path
Definition PlayHost.cpp:111
std::string body
float d
float t
glm::mat4 model
std::array< std::array< double, 3 >, 3 > axes
ScriptStructure out
std::string_view source
eve::Value literal
float bias
Definition Shadow.cpp:149
std::string element
const SquirrelValueOptions & options
int count
float size
Definition TreeMesh.cpp:158
std::size_t at
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
GPU execution boundary for native ONNX; retains no model and retains compiled resources for the lifet...
Definition OnnxCompute.h:25
virtual void endRun() noexcept
Retire temporary activations/recordings; compiled resources may survive for later calls.
Definition OnnxCompute.h:71
Native ONNX import and CPU/GPU execution using tensor kernels, without ONNX Runtime.
Definition OnnxModel.h:63
Result< std::vector< OnnxNamedTensor > > run(std::span< const OnnxNamedTensor > feeds, std::span< const std::string > requested={}, OnnxRunOptions options={}) const
Execute selected named values, or graph outputs when requested is empty.
Definition OnnxMisc.cpp:134
Result< OnnxGpuResult > runGpu(std::span< const OnnxNamedTensor > feeds, OnnxCompute &compute, std::span< const std::string > requested={}, OnnxRunOptions options={}) const
Execute with GPU matrix, convolution, normalization, activation and resampling kernels.
Definition OnnxMisc.cpp:139
OnnxModelInfo info() const
Return owning graph diagnostics; importing does not imply full operator support.
Definition OnnxMisc.cpp:120
static Result< std::unique_ptr< OnnxModel > > load(std::span< const uint8_t > bytes)
Import bounded in-memory ONNX ModelProto; copies all retained data.
Definition OnnxMisc.cpp:121
~OnnxModel()
Destroy model-owned graph and packed initializers; outputs remain valid.
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.
Definition OnnxMisc.cpp:11
std::vector< int64_t > ints(const RuntimeTensor &v)
Ints.
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.
Definition OnnxMisc.cpp:444
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::optional< RuntimeTensor > executeNeural(const Node &, const std::vector< const RuntimeTensor * > &, OnnxCompute *)
Execute neural.
Definition OnnxMisc.cpp:206
RuntimeTensor make(OnnxElement e, std::vector< int64_t > shape, const std::vector< T > &values)
Make.
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
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.
Synchronous GPU kernel request; all inputs are borrowed only until dispatch returns.
Definition OnnxCompute.h:12
Owning admission report; unsupported nodes remain inspectable but cannot execute.
Definition OnnxModel.h:48
onnx_detail::ModelData model
Definition OnnxMisc.cpp:116
Per-call deterministic RNG and optional strict finite-output diagnostic.
Definition OnnxModel.h:37