var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x2)(function(x2) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x2 + '" is not supported'); }); var __esm = (fn3, res, err) => function __init() { if (err) throw err[0]; try { return fn3 && (res = (0, fn3[__getOwnPropNames(fn3)[0]])(fn3 = 0)), res; } catch (e) { throw err = [e], e; } }; var __commonJS = (cb2, mod2) => function __require2() { try { return mod2 || (0, cb2[__getOwnPropNames(cb2)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; } catch (e) { throw mod2 = 0, e; } }; var __copyProps = (to4, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to4, key) && key !== except) __defProp(to4, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to4; }; var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, mod2 )); // node_modules/@xenova/transformers/src/utils/core.js function dispatchCallback(progress_callback, data) { if (progress_callback) progress_callback(data); } function reverseDictionary(data) { return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function isTypedArray(val) { return val?.prototype?.__proto__?.constructor?.name === "TypedArray"; } function isIntegralNumber(x2) { return Number.isInteger(x2) || typeof x2 === "bigint"; } function exists(x2) { return x2 !== void 0 && x2 !== null; } function calculateDimensions(arr) { const dimensions = []; let current = arr; while (Array.isArray(current)) { dimensions.push(current.length); current = current[0]; } return dimensions; } function pop(obj, key, defaultValue = void 0) { const value = obj[key]; if (value !== void 0) { delete obj[key]; return value; } if (defaultValue === void 0) { throw Error(`Key ${key} does not exist in object.`); } return defaultValue; } function mergeArrays(...arrs) { return Array.prototype.concat.apply([], arrs); } function product(...a) { return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e]))); } function calculateReflectOffset(i, w) { return Math.abs((i + w) % (2 * w) - w); } var Callable; var init_core = __esm({ "node_modules/@xenova/transformers/src/utils/core.js"() { Callable = /** @type {any} */ class { /** * Creates a new instance of the Callable class. */ constructor() { let closure = function(...args) { return closure._call(...args); }; return Object.setPrototypeOf(closure, new.target.prototype); } /** * This method should be implemented in subclasses to provide the * functionality of the callable object. * * @param {any[]} args * @throws {Error} If the subclass does not implement the `_call` method. */ _call(...args) { throw Error("Must implement _call method in subclass"); } }; } }); // (disabled):fs var require_fs = __commonJS({ "(disabled):fs"() { } }); // (disabled):path var require_path = __commonJS({ "(disabled):path"() { } }); // (disabled):url var require_url = __commonJS({ "(disabled):url"() { } }); // (disabled):node_modules/@xenova/transformers/node_modules/onnxruntime-node/dist/index.js var require_dist = __commonJS({ "(disabled):node_modules/@xenova/transformers/node_modules/onnxruntime-node/dist/index.js"() { } }); // node_modules/@xenova/transformers/node_modules/onnxruntime-common/dist/ort-common.node.js var require_ort_common_node = __commonJS({ "node_modules/@xenova/transformers/node_modules/onnxruntime-common/dist/ort-common.node.js"(exports2) { (() => { "use strict"; var e = { d: (t2, r2) => { for (var n2 in r2) e.o(r2, n2) && !e.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: r2[n2] }); }, o: (e2, t2) => Object.prototype.hasOwnProperty.call(e2, t2), r: (e2) => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true }); } }, t = {}; e.r(t), e.d(t, { InferenceSession: () => c, Tensor: () => g, env: () => i, registerBackend: () => o }); const r = {}, n = [], o = (e2, t2, o2) => { if (!t2 || "function" != typeof t2.init || "function" != typeof t2.createSessionHandler) throw new TypeError("not a valid backend"); { const i2 = r[e2]; if (void 0 === i2) r[e2] = { backend: t2, priority: o2 }; else { if (i2.priority > o2) return; if (i2.priority === o2 && i2.backend !== t2) throw new Error(`cannot register backend "${e2}" using priority ${o2}`); } if (o2 >= 0) { const t3 = n.indexOf(e2); -1 !== t3 && n.splice(t3, 1); for (let t4 = 0; t4 < n.length; t4++) if (r[n[t4]].priority <= o2) return void n.splice(t4, 0, e2); n.push(e2); } } }, i = new class { constructor() { this.wasm = {}, this.webgl = {}, this.logLevelInternal = "warning"; } set logLevel(e2) { if (void 0 !== e2) { if ("string" != typeof e2 || -1 === ["verbose", "info", "warning", "error", "fatal"].indexOf(e2)) throw new Error(`Unsupported logging level: ${e2}`); this.logLevelInternal = e2; } } get logLevel() { return this.logLevelInternal; } }(), a = "undefined" != typeof BigInt64Array && "function" == typeof BigInt64Array.from, s = "undefined" != typeof BigUint64Array && "function" == typeof BigUint64Array.from, d = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), f = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]); a && (d.set("int64", BigInt64Array), f.set(BigInt64Array, "int64")), s && (d.set("uint64", BigUint64Array), f.set(BigUint64Array, "uint64")); class h { constructor(e2, t2, r2) { let n2, o2, i2; if ("string" == typeof e2) if (n2 = e2, i2 = r2, "string" === e2) { if (!Array.isArray(t2)) throw new TypeError("A string tensor's data must be a string array."); o2 = t2; } else { const r3 = d.get(e2); if (void 0 === r3) throw new TypeError(`Unsupported tensor type: ${e2}.`); if (Array.isArray(t2)) o2 = r3.from(t2); else { if (!(t2 instanceof r3)) throw new TypeError(`A ${n2} tensor's data must be type of ${r3}`); o2 = t2; } } else if (i2 = t2, Array.isArray(e2)) { if (0 === e2.length) throw new TypeError("Tensor type cannot be inferred from an empty array."); const t3 = typeof e2[0]; if ("string" === t3) n2 = "string", o2 = e2; else { if ("boolean" !== t3) throw new TypeError(`Invalid element type of data array: ${t3}.`); n2 = "bool", o2 = Uint8Array.from(e2); } } else { const t3 = f.get(e2.constructor); if (void 0 === t3) throw new TypeError(`Unsupported type for tensor data: ${e2.constructor}.`); n2 = t3, o2 = e2; } if (void 0 === i2) i2 = [o2.length]; else if (!Array.isArray(i2)) throw new TypeError("A tensor's dims must be a number array"); const a2 = ((e3) => { let t3 = 1; for (let r3 = 0; r3 < e3.length; r3++) { const n3 = e3[r3]; if ("number" != typeof n3 || !Number.isSafeInteger(n3)) throw new TypeError(`dims[${r3}] must be an integer, got: ${n3}`); if (n3 < 0) throw new RangeError(`dims[${r3}] must be a non-negative integer, got: ${n3}`); t3 *= n3; } return t3; })(i2); if (a2 !== o2.length) throw new Error(`Tensor's size(${a2}) does not match data length(${o2.length}).`); this.dims = i2, this.type = n2, this.data = o2, this.size = a2; } static bufferToTensor(e2, t2) { if (void 0 === e2) throw new Error("Image buffer must be defined"); if (void 0 === t2.height || void 0 === t2.width) throw new Error("Image height and width must be defined"); const { height: r2, width: n2 } = t2, o2 = t2.norm; let i2, a2; i2 = void 0 === o2 || void 0 === o2.mean ? 255 : o2.mean, a2 = void 0 === o2 || void 0 === o2.bias ? 0 : o2.bias; const s2 = void 0 !== t2.bitmapFormat ? t2.bitmapFormat : "RGBA", d2 = void 0 !== t2.tensorFormat && void 0 !== t2.tensorFormat ? t2.tensorFormat : "RGB", f2 = r2 * n2, g2 = "RGBA" === d2 ? new Float32Array(4 * f2) : new Float32Array(3 * f2); let m3 = 4, c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = f2, b = 2 * f2, v = -1; "RGB" === s2 && (m3 = 3, c2 = 0, l2 = 1, w2 = 2, u = -1), "RGBA" === d2 ? v = 3 * f2 : "RBG" === d2 ? (p = 0, b = f2, y = 2 * f2) : "BGR" === d2 && (b = 0, y = f2, p = 2 * f2); for (let t3 = 0; t3 < f2; t3++, c2 += m3, w2 += m3, l2 += m3, u += m3) g2[p++] = (e2[c2] + a2) / i2, g2[y++] = (e2[l2] + a2) / i2, g2[b++] = (e2[w2] + a2) / i2, -1 !== v && -1 !== u && (g2[v++] = (e2[u] + a2) / i2); return new h("float32", g2, "RGBA" === d2 ? [1, 4, r2, n2] : [1, 3, r2, n2]); } static async fromImage(e2, t2) { const r2 = "undefined" != typeof HTMLImageElement && e2 instanceof HTMLImageElement, n2 = "undefined" != typeof ImageData && e2 instanceof ImageData, o2 = "undefined" != typeof ImageBitmap && e2 instanceof ImageBitmap, i2 = "undefined" != typeof String && (e2 instanceof String || "string" == typeof e2); let a2, s2 = {}; if (r2) { const r3 = document.createElement("canvas"), n3 = r3.getContext("2d"); if (null == n3) throw new Error("Can not access image data"); { let o3 = e2.naturalHeight, i3 = e2.naturalWidth; if (void 0 !== t2 && void 0 !== t2.resizedHeight && void 0 !== t2.resizedWidth && (o3 = t2.resizedHeight, i3 = t2.resizedWidth), void 0 !== t2) { if (s2 = t2, void 0 !== t2.tensorFormat) throw new Error("Image input config format must be RGBA for HTMLImageElement"); if (s2.tensorFormat = "RGBA", void 0 !== t2.height && t2.height !== o3) throw new Error("Image input config height doesn't match HTMLImageElement height"); if (s2.height = o3, void 0 !== t2.width && t2.width !== i3) throw new Error("Image input config width doesn't match HTMLImageElement width"); s2.width = i3; } else s2.tensorFormat = "RGBA", s2.height = o3, s2.width = i3; r3.width = i3, r3.height = o3, n3.drawImage(e2, 0, 0, i3, o3), a2 = n3.getImageData(0, 0, i3, o3).data; } } else { if (!n2) { if (o2) { if (void 0 === t2) throw new Error("Please provide image config with format for Imagebitmap"); if (void 0 !== t2.bitmapFormat) throw new Error("Image input config format must be defined for ImageBitmap"); const r3 = document.createElement("canvas").getContext("2d"); if (null != r3) { const n3 = e2.height, o3 = e2.width; if (r3.drawImage(e2, 0, 0, o3, n3), a2 = r3.getImageData(0, 0, o3, n3).data, void 0 !== t2) { if (void 0 !== t2.height && t2.height !== n3) throw new Error("Image input config height doesn't match ImageBitmap height"); if (s2.height = n3, void 0 !== t2.width && t2.width !== o3) throw new Error("Image input config width doesn't match ImageBitmap width"); s2.width = o3; } else s2.height = n3, s2.width = o3; return h.bufferToTensor(a2, s2); } throw new Error("Can not access image data"); } if (i2) return new Promise(((r3, n3) => { const o3 = document.createElement("canvas"), i3 = o3.getContext("2d"); if (!e2 || !i3) return n3(); const a3 = new Image(); a3.crossOrigin = "Anonymous", a3.src = e2, a3.onload = () => { o3.width = a3.width, o3.height = a3.height, i3.drawImage(a3, 0, 0, o3.width, o3.height); const e3 = i3.getImageData(0, 0, o3.width, o3.height); if (void 0 !== t2) { if (void 0 !== t2.height && t2.height !== o3.height) throw new Error("Image input config height doesn't match ImageBitmap height"); if (s2.height = o3.height, void 0 !== t2.width && t2.width !== o3.width) throw new Error("Image input config width doesn't match ImageBitmap width"); s2.width = o3.width; } else s2.height = o3.height, s2.width = o3.width; r3(h.bufferToTensor(e3.data, s2)); }; })); throw new Error("Input data provided is not supported - aborted tensor creation"); } { const r3 = "RGBA"; let n3, o3; if (void 0 !== t2 && void 0 !== t2.resizedWidth && void 0 !== t2.resizedHeight ? (n3 = t2.resizedHeight, o3 = t2.resizedWidth) : (n3 = e2.height, o3 = e2.width), void 0 !== t2) { if (s2 = t2, void 0 !== t2.bitmapFormat && t2.bitmapFormat !== r3) throw new Error("Image input config format must be RGBA for ImageData"); s2.bitmapFormat = "RGBA"; } else s2.bitmapFormat = "RGBA"; if (s2.height = n3, s2.width = o3, void 0 !== t2) { const t3 = document.createElement("canvas"); t3.width = o3, t3.height = n3; const r4 = t3.getContext("2d"); if (null == r4) throw new Error("Can not access image data"); r4.putImageData(e2, 0, 0), a2 = r4.getImageData(0, 0, o3, n3).data; } else a2 = e2.data; } } if (void 0 !== a2) return h.bufferToTensor(a2, s2); throw new Error("Input data provided is not supported - aborted tensor creation"); } toImageData(e2) { var t2, r2; const n2 = document.createElement("canvas").getContext("2d"); let o2; if (null == n2) throw new Error("Can not access image data"); { const i2 = this.dims[3], a2 = this.dims[2], s2 = this.dims[1], d2 = void 0 !== e2 && void 0 !== e2.format ? e2.format : "RGB", f2 = void 0 !== e2 && void 0 !== (null === (t2 = e2.norm) || void 0 === t2 ? void 0 : t2.mean) ? e2.norm.mean : 255, h2 = void 0 !== e2 && void 0 !== (null === (r2 = e2.norm) || void 0 === r2 ? void 0 : r2.bias) ? e2.norm.bias : 0, g2 = a2 * i2; if (void 0 !== e2) { if (void 0 !== e2.height && e2.height !== a2) throw new Error("Image output config height doesn't match tensor height"); if (void 0 !== e2.width && e2.width !== i2) throw new Error("Image output config width doesn't match tensor width"); if (void 0 !== e2.format && 4 === s2 && "RGBA" !== e2.format || 3 === s2 && "RGB" !== e2.format && "BGR" !== e2.format) throw new Error("Tensor format doesn't match input tensor dims"); } const m3 = 4; let c2 = 0, l2 = 1, w2 = 2, u = 3, p = 0, y = g2, b = 2 * g2, v = -1; "RGBA" === d2 ? (p = 0, y = g2, b = 2 * g2, v = 3 * g2) : "RGB" === d2 ? (p = 0, y = g2, b = 2 * g2) : "RBG" === d2 && (p = 0, b = g2, y = 2 * g2), o2 = n2.createImageData(i2, a2); for (let e3 = 0; e3 < a2 * i2; c2 += m3, l2 += m3, w2 += m3, u += m3, e3++) o2.data[c2] = (this.data[p++] - h2) * f2, o2.data[l2] = (this.data[y++] - h2) * f2, o2.data[w2] = (this.data[b++] - h2) * f2, o2.data[u] = -1 === v ? 255 : (this.data[v++] - h2) * f2; } return o2; } reshape(e2) { return new h(this.type, this.data, e2); } } const g = h; class m2 { constructor(e2) { this.handler = e2; } async run(e2, t2, r2) { const n2 = {}; let o2 = {}; if ("object" != typeof e2 || null === e2 || e2 instanceof g || Array.isArray(e2)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let i2 = true; if ("object" == typeof t2) { if (null === t2) throw new TypeError("Unexpected argument[1]: cannot be null."); if (t2 instanceof g) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(t2)) { if (0 === t2.length) throw new TypeError("'fetches' cannot be an empty array."); i2 = false; for (const e3 of t2) { if ("string" != typeof e3) throw new TypeError("'fetches' must be a string array or an object."); if (-1 === this.outputNames.indexOf(e3)) throw new RangeError(`'fetches' contains invalid output name: ${e3}.`); n2[e3] = null; } if ("object" == typeof r2 && null !== r2) o2 = r2; else if (void 0 !== r2) throw new TypeError("'options' must be an object."); } else { let e3 = false; const a3 = Object.getOwnPropertyNames(t2); for (const r3 of this.outputNames) if (-1 !== a3.indexOf(r3)) { const o3 = t2[r3]; (null === o3 || o3 instanceof g) && (e3 = true, i2 = false, n2[r3] = o3); } if (e3) { if ("object" == typeof r2 && null !== r2) o2 = r2; else if (void 0 !== r2) throw new TypeError("'options' must be an object."); } else o2 = t2; } } else if (void 0 !== t2) throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (const t3 of this.inputNames) if (void 0 === e2[t3]) throw new Error(`input '${t3}' is missing in 'feeds'.`); if (i2) for (const e3 of this.outputNames) n2[e3] = null; const a2 = await this.handler.run(e2, n2, o2), s2 = {}; for (const e3 in a2) Object.hasOwnProperty.call(a2, e3) && (s2[e3] = new g(a2[e3].type, a2[e3].data, a2[e3].dims)); return s2; } static async create(e2, t2, o2, i2) { let a2, s2 = {}; if ("string" == typeof e2) { if (a2 = e2, "object" == typeof t2 && null !== t2) s2 = t2; else if (void 0 !== t2) throw new TypeError("'options' must be an object."); } else if (e2 instanceof Uint8Array) { if (a2 = e2, "object" == typeof t2 && null !== t2) s2 = t2; else if (void 0 !== t2) throw new TypeError("'options' must be an object."); } else { if (!(e2 instanceof ArrayBuffer || "undefined" != typeof SharedArrayBuffer && e2 instanceof SharedArrayBuffer)) throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); { const r2 = e2; let n2 = 0, d3 = e2.byteLength; if ("object" == typeof t2 && null !== t2) s2 = t2; else if ("number" == typeof t2) { if (n2 = t2, !Number.isSafeInteger(n2)) throw new RangeError("'byteOffset' must be an integer."); if (n2 < 0 || n2 >= r2.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${r2.byteLength}).`); if (d3 = e2.byteLength - n2, "number" == typeof o2) { if (d3 = o2, !Number.isSafeInteger(d3)) throw new RangeError("'byteLength' must be an integer."); if (d3 <= 0 || n2 + d3 > r2.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${r2.byteLength - n2}].`); if ("object" == typeof i2 && null !== i2) s2 = i2; else if (void 0 !== i2) throw new TypeError("'options' must be an object."); } else if (void 0 !== o2) throw new TypeError("'byteLength' must be a number."); } else if (void 0 !== t2) throw new TypeError("'options' must be an object."); a2 = new Uint8Array(r2, n2, d3); } } const d2 = (s2.executionProviders || []).map(((e3) => "string" == typeof e3 ? e3 : e3.name)), f2 = await (async (e3) => { const t3 = 0 === e3.length ? n : e3, o3 = []; for (const e4 of t3) { const t4 = r[e4]; if (t4) { if (t4.initialized) return t4.backend; if (t4.aborted) continue; const r2 = !!t4.initPromise; try { return r2 || (t4.initPromise = t4.backend.init()), await t4.initPromise, t4.initialized = true, t4.backend; } catch (n2) { r2 || o3.push({ name: e4, err: n2 }), t4.aborted = true; } finally { delete t4.initPromise; } } } throw new Error(`no available backend found. ERR: ${o3.map(((e4) => `[${e4.name}] ${e4.err}`)).join(", ")}`); })(d2), h2 = await f2.createSessionHandler(a2, s2); return new m2(h2); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } } const c = m2; var l = exports2; for (var w in t) l[w] = t[w]; t.__esModule && Object.defineProperty(l, "__esModule", { value: true }); })(); } }); // node_modules/@xenova/transformers/node_modules/onnxruntime-web/dist/ort-web.min.js var require_ort_web_min = __commonJS({ "node_modules/@xenova/transformers/node_modules/onnxruntime-web/dist/ort-web.min.js"(exports, module) { !(function(t, e) { if ("object" == typeof exports && "object" == typeof module) module.exports = e(require_ort_common_node()); else if ("function" == typeof define && define.amd) define([], e); else { var n = "object" == typeof exports ? e(require_ort_common_node()) : e(t.ort); for (var r in n) ("object" == typeof exports ? exports : t)[r] = n[r]; } })(self, ((__WEBPACK_EXTERNAL_MODULE__1670__) => (() => { var __webpack_modules__ = { 3474: (t, e, n) => { var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) { function e2() { return $2.buffer != C && H3($2.buffer), F2; } function r2() { return $2.buffer != C && H3($2.buffer), N2; } function i() { return $2.buffer != C && H3($2.buffer), L; } function o() { return $2.buffer != C && H3($2.buffer), R; } function a() { return $2.buffer != C && H3($2.buffer), j3; } var s, u, c; t2 = t2 || {}, s || (s = void 0 !== t2 ? t2 : {}), s.ready = new Promise((function(t3, e3) { u = t3, c = e3; })); var l, p, f, d, h, g, b = Object.assign({}, s), m2 = "./this.program", y = (t3, e3) => { throw e3; }, _ = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x2 = s.ENVIRONMENT_IS_PTHREAD || false, T3 = ""; function S(t3) { return s.locateFile ? s.locateFile(t3, T3) : T3 + t3; } if (w) { let e3; T3 = v ? n(908).dirname(T3) + "/" : "//", g = () => { h || (d = n(1384), h = n(908)); }, l = function(t3, e4) { return g(), t3 = h.normalize(t3), d.readFileSync(t3, e4 ? void 0 : "utf8"); }, f = (t3) => ((t3 = l(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), p = (t3, e4, n2) => { g(), t3 = h.normalize(t3), d.readFile(t3, (function(t4, r3) { t4 ? n2(t4) : e4(r3.buffer); })); }, 1 < process.argv.length && (m2 = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", (function(t3) { if (!(t3 instanceof ut2)) throw t3; })), process.on("unhandledRejection", (function(t3) { throw t3; })), y = (t3, e4) => { if (J3()) throw process.exitCode = t3, e4; e4 instanceof ut2 || P2("exiting due to exception: " + e4), process.exit(t3); }, s.inspect = function() { return "[Emscripten Module object]"; }; try { e3 = n(9925); } catch (t3) { throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), t3; } n.g.Worker = e3.Worker; } else (_ || v) && (v ? T3 = self.location.href : "undefined" != typeof document && document.currentScript && (T3 = document.currentScript.src), _scriptDir && (T3 = _scriptDir), T3 = 0 !== T3.indexOf("blob:") ? T3.substr(0, T3.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", w || (l = (t3) => { var e3 = new XMLHttpRequest(); return e3.open("GET", t3, false), e3.send(null), e3.responseText; }, v && (f = (t3) => { var e3 = new XMLHttpRequest(); return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response); }), p = (t3, e3, n2) => { var r3 = new XMLHttpRequest(); r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => { 200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2(); }, r3.onerror = n2, r3.send(null); })); w && "undefined" == typeof performance && (n.g.performance = n(6953).performance); var O2 = console.log.bind(console), A2 = console.warn.bind(console); w && (g(), O2 = (t3) => d.writeSync(1, t3 + "\n"), A2 = (t3) => d.writeSync(2, t3 + "\n")); var E2, I2 = s.print || O2, P2 = s.printErr || A2; Object.assign(s, b), b = null, s.thisProgram && (m2 = s.thisProgram), s.quit && (y = s.quit), s.wasmBinary && (E2 = s.wasmBinary); var D3 = s.noExitRuntime || false; "object" != typeof WebAssembly && it3("no native wasm support detected"); var $2, k4, C, F2, N2, L, R, j3, M3 = false, U3 = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; function V3(t3, e3, n2) { var r3 = (e3 >>>= 0) + n2; for (n2 = e3; t3[n2] && !(n2 >= r3); ) ++n2; if (16 < n2 - e3 && t3.buffer && U3) return U3.decode(t3.buffer instanceof SharedArrayBuffer ? t3.slice(e3, n2) : t3.subarray(e3, n2)); for (r3 = ""; e3 < n2; ) { var i2 = t3[e3++]; if (128 & i2) { var o2 = 63 & t3[e3++]; if (192 == (224 & i2)) r3 += String.fromCharCode((31 & i2) << 6 | o2); else { var a2 = 63 & t3[e3++]; 65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2)); } } else r3 += String.fromCharCode(i2); } return r3; } function B3(t3, e3) { return (t3 >>>= 0) ? V3(r2(), t3, e3) : ""; } function z3(t3, e3, n2, r3) { if (!(0 < r3)) return 0; var i2 = n2 >>>= 0; r3 = n2 + r3 - 1; for (var o2 = 0; o2 < t3.length; ++o2) { var a2 = t3.charCodeAt(o2); if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) { if (n2 >= r3) break; e3[n2++ >>> 0] = a2; } else { if (2047 >= a2) { if (n2 + 1 >= r3) break; e3[n2++ >>> 0] = 192 | a2 >> 6; } else { if (65535 >= a2) { if (n2 + 2 >= r3) break; e3[n2++ >>> 0] = 224 | a2 >> 12; } else { if (n2 + 3 >= r3) break; e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63; } e3[n2++ >>> 0] = 128 | a2 >> 6 & 63; } e3[n2++ >>> 0] = 128 | 63 & a2; } } return e3[n2 >>> 0] = 0, n2 - i2; } function G3(t3) { for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) { var r3 = t3.charCodeAt(n2); 127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3; } return e3; } function H3(t3) { C = t3, s.HEAP8 = F2 = new Int8Array(t3), s.HEAP16 = new Int16Array(t3), s.HEAP32 = L = new Int32Array(t3), s.HEAPU8 = N2 = new Uint8Array(t3), s.HEAPU16 = new Uint16Array(t3), s.HEAPU32 = R = new Uint32Array(t3), s.HEAPF32 = new Float32Array(t3), s.HEAPF64 = j3 = new Float64Array(t3); } x2 && (C = s.buffer); var W2 = s.INITIAL_MEMORY || 16777216; if (x2) $2 = s.wasmMemory, C = s.buffer; else if (s.wasmMemory) $2 = s.wasmMemory; else if (!(($2 = new WebAssembly.Memory({ initial: W2 / 65536, maximum: 65536, shared: true })).buffer instanceof SharedArrayBuffer)) throw P2("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), w && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory"); $2 && (C = $2.buffer), W2 = C.byteLength, H3(C); var q3, X = [], Y3 = [], K = [], Z2 = []; function J3() { return D3 || false; } function Q2() { var t3 = s.preRun.shift(); X.unshift(t3); } var tt4, et2 = 0, nt3 = null, rt4 = null; function it3(t3) { throw x2 ? postMessage({ cmd: "onAbort", arg: t3 }) : s.onAbort && s.onAbort(t3), P2(t3 = "Aborted(" + t3 + ")"), M3 = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), c(t3), t3; } function ot4() { return tt4.startsWith("data:application/octet-stream;base64,"); } function at3() { var t3 = tt4; try { if (t3 == tt4 && E2) return new Uint8Array(E2); if (f) return f(t3); throw "both async and sync fetching of the wasm failed"; } catch (t4) { it3(t4); } } tt4 = "ort-wasm-threaded.wasm", ot4() || (tt4 = S(tt4)); var st2 = {}; function ut2(t3) { this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3; } function ct2(t3) { (t3 = dt4.Vb[t3]) || it3(), dt4.mc(t3); } function lt2(t3) { var e3 = dt4.Cc(); if (!e3) return 6; dt4.ac.push(e3), dt4.Vb[t3.Ub] = e3, e3.Ub = t3.Ub; var n2 = { cmd: "run", start_routine: t3.Ic, arg: t3.zc, pthread_ptr: t3.Ub }; return e3.$b = () => { n2.time = performance.now(), e3.postMessage(n2, t3.Nc); }, e3.loaded && (e3.$b(), delete e3.$b), 0; } function pt2(t3) { if (x2) return qt3(1, 1, t3); J3() || (dt4.oc(), s.onExit && s.onExit(t3), M3 = true), y(t3, new ut2(t3)); } function ft2(t3, e3) { if (!e3 && x2) throw bt3(t3), "unwind"; J3() || x2 || (me3(), ht4(K), be4(0), re2[1].length && ie3(1, 10), re2[2].length && ie3(2, 10), dt4.oc()), pt2(t3); } var dt4 = { Yb: [], ac: [], qc: [], Vb: {}, fc: function() { x2 && dt4.Ec(); }, Pc: function() { }, Ec: function() { dt4.receiveObjectTransfer = dt4.Gc, dt4.threadInitTLS = dt4.pc, dt4.setExitStatus = dt4.nc, D3 = false; }, nc: function() { }, oc: function() { for (var t3 of Object.values(dt4.Vb)) dt4.mc(t3); for (t3 of dt4.Yb) t3.terminate(); dt4.Yb = []; }, mc: function(t3) { var e3 = t3.Ub; delete dt4.Vb[e3], dt4.Yb.push(t3), dt4.ac.splice(dt4.ac.indexOf(t3), 1), t3.Ub = 0, xe(e3); }, Gc: function() { }, pc: function() { dt4.qc.forEach(((t3) => t3())); }, Fc: function(t3, e3) { t3.onmessage = (n2) => { var r3 = (n2 = n2.data).cmd; if (t3.Ub && (dt4.Bc = t3.Ub), n2.targetThread && n2.targetThread != de2()) { var i2 = dt4.Vb[n2.Qc]; i2 ? i2.postMessage(n2, n2.transferList) : P2('Internal error! Worker sent a message "' + r3 + '" to target pthread ' + n2.targetThread + ", but that thread no longer exists!"); } else "processProxyingQueue" === r3 ? Vt3(n2.queue) : "spawnThread" === r3 ? lt2(n2) : "cleanupThread" === r3 ? ct2(n2.thread) : "killThread" === r3 ? (n2 = n2.thread, r3 = dt4.Vb[n2], delete dt4.Vb[n2], r3.terminate(), xe(n2), dt4.ac.splice(dt4.ac.indexOf(r3), 1), r3.Ub = 0) : "cancelThread" === r3 ? dt4.Vb[n2.thread].postMessage({ cmd: "cancel" }) : "loaded" === r3 ? (t3.loaded = true, e3 && e3(t3), t3.$b && (t3.$b(), delete t3.$b)) : "print" === r3 ? I2("Thread " + n2.threadId + ": " + n2.text) : "printErr" === r3 ? P2("Thread " + n2.threadId + ": " + n2.text) : "alert" === r3 ? alert("Thread " + n2.threadId + ": " + n2.text) : "setimmediate" === n2.target ? t3.postMessage(n2) : "onAbort" === r3 ? s.onAbort && s.onAbort(n2.arg) : r3 && P2("worker sent an unknown command " + r3); dt4.Bc = void 0; }, t3.onerror = (t4) => { throw P2("worker sent an error! " + t4.filename + ":" + t4.lineno + ": " + t4.message), t4; }, w && (t3.on("message", (function(e4) { t3.onmessage({ data: e4 }); })), t3.on("error", (function(e4) { t3.onerror(e4); })), t3.on("detachedExit", (function() { }))), t3.postMessage({ cmd: "load", urlOrBlob: s.mainScriptUrlOrBlob || _scriptDir, wasmMemory: $2, wasmModule: k4 }); }, yc: function() { var t3 = S("ort-wasm-threaded.worker.js"); dt4.Yb.push(new Worker(t3)); }, Cc: function() { return 0 == dt4.Yb.length && (dt4.yc(), dt4.Fc(dt4.Yb[0])), dt4.Yb.pop(); } }; function ht4(t3) { for (; 0 < t3.length; ) t3.shift()(s); } function gt4(t3) { var e3 = Ae3(); return t3 = t3(), Ee3(e3), t3; } function bt3(t3) { if (x2) return qt3(2, 0, t3); try { ft2(t3); } catch (t4) { t4 instanceof ut2 || "unwind" == t4 || y(1, t4); } } s.PThread = dt4, s.establishStackSpace = function() { var t3 = de2(), e3 = i()[t3 + 44 >> 2 >>> 0]; t3 = i()[t3 + 48 >> 2 >>> 0], Oe4(e3, e3 - t3), Ee3(e3); }; var mt2 = []; function yt3(t3) { var e3 = mt2[t3]; return e3 || (t3 >= mt2.length && (mt2.length = t3 + 1), mt2[t3] = e3 = q3.get(t3)), e3; } s.invokeEntryPoint = function(t3, e3) { t3 = yt3(t3)(e3), J3() ? dt4.nc(t3) : Te2(t3); }; var _t3, vt3, wt = [], xt3 = 0, Tt4 = 0; function St3(t3) { this.Zb = t3, this.Sb = t3 - 24, this.xc = function(t4) { o()[this.Sb + 4 >> 2 >>> 0] = t4; }, this.bc = function() { return o()[this.Sb + 4 >> 2 >>> 0]; }, this.wc = function(t4) { o()[this.Sb + 8 >> 2 >>> 0] = t4; }, this.Dc = function() { return o()[this.Sb + 8 >> 2 >>> 0]; }, this.rc = function() { i()[this.Sb >> 2 >>> 0] = 0; }, this.hc = function(t4) { t4 = t4 ? 1 : 0, e2()[this.Sb + 12 >> 0 >>> 0] = t4; }, this.uc = function() { return 0 != e2()[this.Sb + 12 >> 0 >>> 0]; }, this.ic = function(t4) { t4 = t4 ? 1 : 0, e2()[this.Sb + 13 >> 0 >>> 0] = t4; }, this.kc = function() { return 0 != e2()[this.Sb + 13 >> 0 >>> 0]; }, this.fc = function(t4, e3) { this.cc(0), this.xc(t4), this.wc(e3), this.rc(), this.hc(false), this.ic(false); }, this.sc = function() { Atomics.add(i(), this.Sb >> 2, 1); }, this.Hc = function() { return 1 === Atomics.sub(i(), this.Sb >> 2, 1); }, this.cc = function(t4) { o()[this.Sb + 16 >> 2 >>> 0] = t4; }, this.tc = function() { return o()[this.Sb + 16 >> 2 >>> 0]; }, this.vc = function() { if (De3(this.bc())) return o()[this.Zb >> 2 >>> 0]; var t4 = this.tc(); return 0 !== t4 ? t4 : this.Zb; }; } function Ot(t3) { return ge3(new St3(t3).Sb); } function At2(t3, e3, n2, r3) { return x2 ? qt3(3, 1, t3, e3, n2, r3) : Et3(t3, e3, n2, r3); } function Et3(t3, e3, n2, r3) { if ("undefined" == typeof SharedArrayBuffer) return P2("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; var i2 = []; return x2 && 0 === i2.length ? At2(t3, e3, n2, r3) : (t3 = { Ic: n2, Ub: t3, zc: r3, Nc: i2 }, x2 ? (t3.Oc = "spawnThread", postMessage(t3, i2), 0) : lt2(t3)); } function It2(t3, e3, n2) { return x2 ? qt3(4, 1, t3, e3, n2) : 0; } function Pt4(t3, e3) { if (x2) return qt3(5, 1, t3, e3); } function Dt2(t3, e3) { if (x2) return qt3(6, 1, t3, e3); } function $t4(t3, e3, n2) { if (x2) return qt3(7, 1, t3, e3, n2); } function kt4(t3, e3, n2) { return x2 ? qt3(8, 1, t3, e3, n2) : 0; } function Ct2(t3, e3) { if (x2) return qt3(9, 1, t3, e3); } function Ft4(t3, e3, n2) { if (x2) return qt3(10, 1, t3, e3, n2); } function Nt4(t3, e3, n2, r3) { if (x2) return qt3(11, 1, t3, e3, n2, r3); } function Lt3(t3, e3, n2, r3) { if (x2) return qt3(12, 1, t3, e3, n2, r3); } function Rt2(t3, e3, n2, r3) { if (x2) return qt3(13, 1, t3, e3, n2, r3); } function jt3(t3) { if (x2) return qt3(14, 1, t3); } function Mt2(t3, e3) { if (x2) return qt3(15, 1, t3, e3); } function Ut4(t3, e3, n2) { if (x2) return qt3(16, 1, t3, e3, n2); } function Vt3(t3) { Atomics.store(i(), t3 >> 2, 1), de2() && we2(t3), Atomics.compareExchange(i(), t3 >> 2, 1, 0); } function Bt2(t3) { return o()[t3 >>> 2] + 4294967296 * i()[t3 + 4 >>> 2]; } function zt2(t3, e3, n2, r3, i2, o2) { return x2 ? qt3(17, 1, t3, e3, n2, r3, i2, o2) : -52; } function Gt3(t3, e3, n2, r3, i2, o2) { if (x2) return qt3(18, 1, t3, e3, n2, r3, i2, o2); } function Ht4(t3) { var n2 = G3(t3) + 1, r3 = he3(n2); return r3 && z3(t3, e2(), r3, n2), r3; } function Wt4(t3, e3, n2) { function r3(t4) { return (t4 = t4.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t4[1] : "GMT"; } if (x2) return qt3(19, 1, t3, e3, n2); var a2 = (/* @__PURE__ */ new Date()).getFullYear(), s2 = new Date(a2, 0, 1), u2 = new Date(a2, 6, 1); a2 = s2.getTimezoneOffset(); var c2 = u2.getTimezoneOffset(), l2 = Math.max(a2, c2); i()[t3 >> 2 >>> 0] = 60 * l2, i()[e3 >> 2 >>> 0] = Number(a2 != c2), t3 = r3(s2), e3 = r3(u2), t3 = Ht4(t3), e3 = Ht4(e3), c2 < a2 ? (o()[n2 >> 2 >>> 0] = t3, o()[n2 + 4 >> 2 >>> 0] = e3) : (o()[n2 >> 2 >>> 0] = e3, o()[n2 + 4 >> 2 >>> 0] = t3); } function qt3(t3, e3) { var n2 = arguments.length - 2, r3 = arguments; return gt4((() => { for (var i2 = Ie4(8 * n2), o2 = i2 >> 3, s2 = 0; s2 < n2; s2++) { var u2 = r3[2 + s2]; a()[o2 + s2 >>> 0] = u2; } return ve2(t3, n2, i2, e3); })); } s.executeNotifiedProxyingQueue = Vt3, vt3 = w ? () => { var t3 = process.hrtime(); return 1e3 * t3[0] + t3[1] / 1e6; } : x2 ? () => performance.now() - s.__performance_now_clock_drift : () => performance.now(); var Xt4, Yt4 = [], Kt4 = {}; function Zt3() { if (!Xt4) { var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: m2 || "./this.program" }; for (t3 in Kt4) void 0 === Kt4[t3] ? delete e3[t3] : e3[t3] = Kt4[t3]; var n2 = []; for (t3 in e3) n2.push(t3 + "=" + e3[t3]); Xt4 = n2; } return Xt4; } function Jt4(t3, n2) { if (x2) return qt3(20, 1, t3, n2); var r3 = 0; return Zt3().forEach((function(i2, a2) { var s2 = n2 + r3; for (a2 = o()[t3 + 4 * a2 >> 2 >>> 0] = s2, s2 = 0; s2 < i2.length; ++s2) e2()[a2++ >> 0 >>> 0] = i2.charCodeAt(s2); e2()[a2 >> 0 >>> 0] = 0, r3 += i2.length + 1; })), 0; } function Qt3(t3, e3) { if (x2) return qt3(21, 1, t3, e3); var n2 = Zt3(); o()[t3 >> 2 >>> 0] = n2.length; var r3 = 0; return n2.forEach((function(t4) { r3 += t4.length + 1; })), o()[e3 >> 2 >>> 0] = r3, 0; } function te3(t3) { return x2 ? qt3(22, 1, t3) : 52; } function ee3(t3, e3, n2, r3) { return x2 ? qt3(23, 1, t3, e3, n2, r3) : 52; } function ne2(t3, e3, n2, r3, i2) { return x2 ? qt3(24, 1, t3, e3, n2, r3, i2) : 70; } var re2 = [null, [], []]; function ie3(t3, e3) { var n2 = re2[t3]; 0 === e3 || 10 === e3 ? ((1 === t3 ? I2 : P2)(V3(n2, 0)), n2.length = 0) : n2.push(e3); } function oe2(t3, e3, n2, i2) { if (x2) return qt3(25, 1, t3, e3, n2, i2); for (var a2 = 0, s2 = 0; s2 < n2; s2++) { var u2 = o()[e3 >> 2 >>> 0], c2 = o()[e3 + 4 >> 2 >>> 0]; e3 += 8; for (var l2 = 0; l2 < c2; l2++) ie3(t3, r2()[u2 + l2 >>> 0]); a2 += c2; } return o()[i2 >> 2 >>> 0] = a2, 0; } var ae2 = 0; function se2(t3) { return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400); } var ue3 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ce3 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function le3(t3, n2, r3, o2) { function a2(t4, e3, n3) { for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e3; ) t4 = n3[0] + t4; return t4; } function s2(t4, e3) { return a2(t4, e3, "0"); } function u2(t4, e3) { function n3(t5) { return 0 > t5 ? -1 : 0 < t5 ? 1 : 0; } var r4; return 0 === (r4 = n3(t4.getFullYear() - e3.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e3.getMonth())) && (r4 = n3(t4.getDate() - e3.getDate())), r4; } function c2(t4) { switch (t4.getDay()) { case 0: return new Date(t4.getFullYear() - 1, 11, 29); case 1: return t4; case 2: return new Date(t4.getFullYear(), 0, 3); case 3: return new Date(t4.getFullYear(), 0, 2); case 4: return new Date(t4.getFullYear(), 0, 1); case 5: return new Date(t4.getFullYear() - 1, 11, 31); case 6: return new Date(t4.getFullYear() - 1, 11, 30); } } function l2(t4) { var e3 = t4.Wb; for (t4 = new Date(new Date(t4.Xb + 1900, 0, 1).getTime()); 0 < e3; ) { var n3 = t4.getMonth(), r4 = (se2(t4.getFullYear()) ? ue3 : ce3)[n3]; if (!(e3 > r4 - t4.getDate())) { t4.setDate(t4.getDate() + e3); break; } e3 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1)); } return n3 = new Date(t4.getFullYear() + 1, 0, 4), e3 = c2(new Date(t4.getFullYear(), 0, 4)), n3 = c2(n3), 0 >= u2(e3, t4) ? 0 >= u2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1; } var p2 = i()[o2 + 40 >> 2 >>> 0]; for (var f2 in o2 = { Lc: i()[o2 >> 2 >>> 0], Kc: i()[o2 + 4 >> 2 >>> 0], dc: i()[o2 + 8 >> 2 >>> 0], jc: i()[o2 + 12 >> 2 >>> 0], ec: i()[o2 + 16 >> 2 >>> 0], Xb: i()[o2 + 20 >> 2 >>> 0], Tb: i()[o2 + 24 >> 2 >>> 0], Wb: i()[o2 + 28 >> 2 >>> 0], Rc: i()[o2 + 32 >> 2 >>> 0], Jc: i()[o2 + 36 >> 2 >>> 0], Mc: p2 ? B3(p2) : "" }, r3 = B3(r3), p2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) r3 = r3.replace(new RegExp(f2, "g"), p2[f2]); var d2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), h2 = "January February March April May June July August September October November December".split(" "); for (f2 in p2 = { "%a": function(t4) { return d2[t4.Tb].substring(0, 3); }, "%A": function(t4) { return d2[t4.Tb]; }, "%b": function(t4) { return h2[t4.ec].substring(0, 3); }, "%B": function(t4) { return h2[t4.ec]; }, "%C": function(t4) { return s2((t4.Xb + 1900) / 100 | 0, 2); }, "%d": function(t4) { return s2(t4.jc, 2); }, "%e": function(t4) { return a2(t4.jc, 2, " "); }, "%g": function(t4) { return l2(t4).toString().substring(2); }, "%G": function(t4) { return l2(t4); }, "%H": function(t4) { return s2(t4.dc, 2); }, "%I": function(t4) { return 0 == (t4 = t4.dc) ? t4 = 12 : 12 < t4 && (t4 -= 12), s2(t4, 2); }, "%j": function(t4) { for (var e3 = 0, n3 = 0; n3 <= t4.ec - 1; e3 += (se2(t4.Xb + 1900) ? ue3 : ce3)[n3++]) ; return s2(t4.jc + e3, 3); }, "%m": function(t4) { return s2(t4.ec + 1, 2); }, "%M": function(t4) { return s2(t4.Kc, 2); }, "%n": function() { return "\n"; }, "%p": function(t4) { return 0 <= t4.dc && 12 > t4.dc ? "AM" : "PM"; }, "%S": function(t4) { return s2(t4.Lc, 2); }, "%t": function() { return " "; }, "%u": function(t4) { return t4.Tb || 7; }, "%U": function(t4) { return s2(Math.floor((t4.Wb + 7 - t4.Tb) / 7), 2); }, "%V": function(t4) { var e3 = Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7); if (2 >= (t4.Tb + 371 - t4.Wb - 2) % 7 && e3++, e3) 53 == e3 && (4 == (n3 = (t4.Tb + 371 - t4.Wb) % 7) || 3 == n3 && se2(t4.Xb) || (e3 = 1)); else { e3 = 52; var n3 = (t4.Tb + 7 - t4.Wb - 1) % 7; (4 == n3 || 5 == n3 && se2(t4.Xb % 400 - 1)) && e3++; } return s2(e3, 2); }, "%w": function(t4) { return t4.Tb; }, "%W": function(t4) { return s2(Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7), 2); }, "%y": function(t4) { return (t4.Xb + 1900).toString().substring(2); }, "%Y": function(t4) { return t4.Xb + 1900; }, "%z": function(t4) { var e3 = 0 <= (t4 = t4.Jc); return t4 = Math.abs(t4) / 60, (e3 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4); }, "%Z": function(t4) { return t4.Mc; }, "%%": function() { return "%"; } }, r3 = r3.replace(/%%/g, "\0\0"), p2) r3.includes(f2) && (r3 = r3.replace(new RegExp(f2, "g"), p2[f2](o2))); return f2 = (function(t4) { var e3 = Array(G3(t4) + 1); return z3(t4, e3, 0, e3.length), e3; })(r3 = r3.replace(/\0\0/g, "%")), f2.length > n2 ? 0 : ((function(t4, n3) { e2().set(t4, n3 >>> 0); })(f2, t3), f2.length - 1); } dt4.fc(); var pe2 = [null, pt2, bt3, At2, It2, Pt4, Dt2, $t4, kt4, Ct2, Ft4, Nt4, Lt3, Rt2, jt3, Mt2, Ut4, zt2, Gt3, Wt4, Jt4, Qt3, te3, ee3, ne2, oe2], fe4 = { b: function(t3) { return he3(t3 + 24) + 24; }, n: function(t3) { return (t3 = new St3(t3)).uc() || (t3.hc(true), xt3--), t3.ic(false), wt.push(t3), t3.sc(), t3.vc(); }, ma: function(t3) { throw P2("Unexpected exception thrown, this is not properly supported - aborting"), M3 = true, t3; }, x: function() { Se2(0); var t3 = wt.pop(); if (t3.Hc() && !t3.kc()) { var e3 = t3.Dc(); e3 && yt3(e3)(t3.Zb), Ot(t3.Zb); } Tt4 = 0; }, e: function() { var t3 = Tt4; if (!t3) return ae2 = 0; var e3 = new St3(t3); e3.cc(t3); var n2 = e3.bc(); if (!n2) return ae2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (Pe3(o2, n2, e3.Sb + 16)) return ae2 = o2, t3; } return ae2 = n2, t3; }, l: function() { var t3 = Tt4; if (!t3) return ae2 = 0; var e3 = new St3(t3); e3.cc(t3); var n2 = e3.bc(); if (!n2) return ae2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (Pe3(o2, n2, e3.Sb + 16)) return ae2 = o2, t3; } return ae2 = n2, t3; }, h: function() { var t3 = Tt4; if (!t3) return ae2 = 0; var e3 = new St3(t3); e3.cc(t3); var n2 = e3.bc(); if (!n2) return ae2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (Pe3(o2, n2, e3.Sb + 16)) return ae2 = o2, t3; } return ae2 = n2, t3; }, t: Ot, M: function() { var t3 = wt.pop(); t3 || it3("no exception to throw"); var e3 = t3.Zb; throw t3.kc() || (wt.push(t3), t3.ic(true), t3.hc(false), xt3++), Tt4 = e3, e3; }, c: function(t3, e3, n2) { throw new St3(t3).fc(e3, n2), Tt4 = t3, xt3++, t3; }, pa: function() { return xt3; }, Fa: function(t3) { ye2(t3, !v, 1, !_), dt4.pc(); }, T: function(t3) { x2 ? postMessage({ cmd: "cleanupThread", thread: t3 }) : ct2(t3); }, xa: Et3, j: function(t3) { throw Tt4 || (Tt4 = t3), t3; }, H: It2, Ma: Pt4, ua: Dt2, wa: $t4, oa: kt4, Ka: Ct2, Ca: Ft4, Ja: Nt4, V: Lt3, va: Rt2, sa: jt3, La: Mt2, ta: Ut4, Ta: function() { }, X: function() { it3("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); }, Ua: function() { it3("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); }, W: function() { return Date.now(); }, ya: function() { return 2097152; }, Oa: function() { return true; }, za: function(t3, e3, n2, r3) { if (t3 == e3) setTimeout((() => Vt3(r3))); else if (x2) postMessage({ targetThread: t3, cmd: "processProxyingQueue", queue: r3 }); else { if (!(t3 = dt4.Vb[t3])) return; t3.postMessage({ cmd: "processProxyingQueue", queue: r3 }); } return 1; }, Ea: function() { return -1; }, Pa: function(t3, e3) { t3 = new Date(1e3 * Bt2(t3)), i()[e3 >> 2 >>> 0] = t3.getUTCSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), t3 = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i()[e3 + 28 >> 2 >>> 0] = t3; }, Qa: function(t3, e3) { t3 = new Date(1e3 * Bt2(t3)), i()[e3 >> 2 >>> 0] = t3.getSeconds(), i()[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), i()[e3 + 8 >> 2 >>> 0] = t3.getHours(), i()[e3 + 12 >> 2 >>> 0] = t3.getDate(), i()[e3 + 16 >> 2 >>> 0] = t3.getMonth(), i()[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, i()[e3 + 24 >> 2 >>> 0] = t3.getDay(); var n2 = new Date(t3.getFullYear(), 0, 1), r3 = (t3.getTime() - n2.getTime()) / 864e5 | 0; i()[e3 + 28 >> 2 >>> 0] = r3, i()[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(), r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(), t3 = 0 | (r3 != (n2 = n2.getTimezoneOffset()) && t3.getTimezoneOffset() == Math.min(n2, r3)), i()[e3 + 32 >> 2 >>> 0] = t3; }, Ra: function(t3) { var e3 = new Date(i()[t3 + 20 >> 2 >>> 0] + 1900, i()[t3 + 16 >> 2 >>> 0], i()[t3 + 12 >> 2 >>> 0], i()[t3 + 8 >> 2 >>> 0], i()[t3 + 4 >> 2 >>> 0], i()[t3 >> 2 >>> 0], 0), n2 = i()[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), o2 = new Date(e3.getFullYear(), 0, 1), a2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), s2 = o2.getTimezoneOffset(), u2 = Math.min(s2, a2); return 0 > n2 ? i()[t3 + 32 >> 2 >>> 0] = Number(a2 != s2 && u2 == r3) : 0 < n2 != (u2 == r3) && (a2 = Math.max(s2, a2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? u2 : a2) - r3))), i()[t3 + 24 >> 2 >>> 0] = e3.getDay(), n2 = (e3.getTime() - o2.getTime()) / 864e5 | 0, i()[t3 + 28 >> 2 >>> 0] = n2, i()[t3 >> 2 >>> 0] = e3.getSeconds(), i()[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), i()[t3 + 8 >> 2 >>> 0] = e3.getHours(), i()[t3 + 12 >> 2 >>> 0] = e3.getDate(), i()[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0; }, Aa: zt2, Ba: Gt3, Sa: function t3(e3, n2, r3) { t3.Ac || (t3.Ac = true, Wt4(e3, n2, r3)); }, y: function() { it3(""); }, U: function() { if (!w && !v) { var t3 = "Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"; _t3 || (_t3 = {}), _t3[t3] || (_t3[t3] = 1, w && (t3 = "warning: " + t3), P2(t3)); } }, ra: function() { return 4294901760; }, B: vt3, Ia: function(t3, e3, n2) { r2().copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0); }, F: function() { return w ? n(3993).cpus().length : navigator.hardwareConcurrency; }, Da: function(t3, e3, n2) { Yt4.length = e3, n2 >>= 3; for (var r3 = 0; r3 < e3; r3++) Yt4[r3] = a()[n2 + r3 >>> 0]; return (0 > t3 ? st2[-t3 - 1] : pe2[t3]).apply(null, Yt4); }, qa: function(t3) { var e3 = r2().length; if ((t3 >>>= 0) <= e3 || 4294901760 < t3) return false; for (var n2 = 1; 4 >= n2; n2 *= 2) { var i2 = e3 * (1 + 0.2 / n2); i2 = Math.min(i2, t3 + 100663296); var o2 = Math; i2 = Math.max(t3, i2), o2 = o2.min.call(o2, 4294901760, i2 + (65536 - i2 % 65536) % 65536); t: { try { $2.grow(o2 - C.byteLength + 65535 >>> 16), H3($2.buffer); var a2 = 1; break t; } catch (t4) { } a2 = void 0; } if (a2) return true; } return false; }, Na: function() { throw "unwind"; }, Ga: Jt4, Ha: Qt3, J: ft2, I: te3, S: ee3, ga: ne2, R: oe2, d: function() { return ae2; }, na: function t3(r3, i2) { t3.lc || (t3.lc = (function() { if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) { var t4 = new Uint8Array(1); return () => (crypto.getRandomValues(t4), t4[0]); } if (w) try { var e3 = n(Object((function() { var t5 = new Error("Cannot find module 'crypto'"); throw t5.code = "MODULE_NOT_FOUND", t5; })())); return () => e3.randomBytes(1)[0]; } catch (t5) { } return () => it3("randomDevice"); })()); for (var o2 = 0; o2 < i2; o2++) e2()[r3 + o2 >> 0 >>> 0] = t3.lc(); return 0; }, ia: function(t3, e3, n2) { var r3 = Ae3(); try { return yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ja: function(t3, e3, n2) { var r3 = Ae3(); try { return yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, K: function(t3) { var e3 = Ae3(); try { return yt3(t3)(); } catch (t4) { if (Ee3(e3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, f: function(t3, e3) { var n2 = Ae3(); try { return yt3(t3)(e3); } catch (t4) { if (Ee3(n2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, P: function(t3, e3, n2) { var r3 = Ae3(); try { return yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, Q: function(t3, e3, n2) { var r3 = Ae3(); try { return yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, k: function(t3, e3, n2) { var r3 = Ae3(); try { return yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, p: function(t3, e3, n2, r3) { var i2 = Ae3(); try { return yt3(t3)(e3, n2, r3); } catch (t4) { if (Ee3(i2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, q: function(t3, e3, n2, r3, i2) { var o2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2); } catch (t4) { if (Ee3(o2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, N: function(t3, e3, n2, r3, i2, o2) { var a2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (Ee3(a2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, s: function(t3, e3, n2, r3, i2, o2) { var a2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (Ee3(a2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, w: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2, o2, a2); } catch (t4) { if (Ee3(s2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, L: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (Ee3(u2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, E: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { var f2 = Ae3(); try { return yt3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); } catch (t4) { if (Ee3(f2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Ae3(); try { return Me4(t3, e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (Ee3(u2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, _: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Ae3(); try { return ke3(t3, e3, n2, r3, i2, o2, a2); } catch (t4) { if (Ee3(s2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, Z: function(t3, e3, n2, r3, i2) { var o2 = Ae3(); try { return Ue4(t3, e3, n2, r3, i2); } catch (t4) { if (Ee3(o2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ca: function(t3, e3, n2, r3) { var i2 = Ae3(); try { return Re2(t3, e3, n2, r3); } catch (t4) { if (Ee3(i2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, $: function(t3) { var e3 = Ae3(); try { return $e3(t3); } catch (t4) { if (Ee3(e3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ba: function(t3, e3) { var n2 = Ae3(); try { return je3(t3, e3); } catch (t4) { if (Ee3(n2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, Y: function(t3, e3, n2) { var r3 = Ae3(); try { return Ce4(t3, e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, g: function(t3) { var e3 = Ae3(); try { yt3(t3)(); } catch (t4) { if (Ee3(e3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, r: function(t3, e3) { var n2 = Ae3(); try { yt3(t3)(e3); } catch (t4) { if (Ee3(n2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, i: function(t3, e3, n2) { var r3 = Ae3(); try { yt3(t3)(e3, n2); } catch (t4) { if (Ee3(r3), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ha: function(t3, e3, n2, r3) { var i2 = Ae3(); try { yt3(t3)(e3, n2, r3); } catch (t4) { if (Ee3(i2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, m: function(t3, e3, n2, r3) { var i2 = Ae3(); try { yt3(t3)(e3, n2, r3); } catch (t4) { if (Ee3(i2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, v: function(t3, e3, n2, r3, i2) { var o2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2); } catch (t4) { if (Ee3(o2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, u: function(t3, e3, n2, r3, i2, o2) { var a2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (Ee3(a2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, O: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2, a2); } catch (t4) { if (Ee3(s2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, A: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (Ee3(u2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ka: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) { var c2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2, a2, s2, u2); } catch (t4) { if (Ee3(c2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) { var p2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2); } catch (t4) { if (Ee3(p2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) { var b2 = Ae3(); try { yt3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2); } catch (t4) { if (Ee3(b2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, fa: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Ae3(); try { Fe3(t3, e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (Ee3(u2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, da: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { var f2 = Ae3(); try { Le3(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); } catch (t4) { if (Ee3(f2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, ea: function(t3, e3, n2, r3, i2, o2) { var a2 = Ae3(); try { Ne3(t3, e3, n2, r3, i2, o2); } catch (t4) { if (Ee3(a2), t4 !== t4 + 0) throw t4; Se2(1, 0); } }, o: function(t3) { return t3; }, a: $2 || s.wasmMemory, G: function(t3) { ae2 = t3; }, la: le3, z: function(t3, e3, n2, r3) { return le3(t3, e3, n2, r3); } }; !(function() { function t3(t4, e4) { s.asm = t4.exports, dt4.qc.push(s.asm.sb), q3 = s.asm.ub, Y3.unshift(s.asm.Va), k4 = e4, x2 || (et2--, s.monitorRunDependencies && s.monitorRunDependencies(et2), 0 == et2 && (null !== nt3 && (clearInterval(nt3), nt3 = null), rt4 && (t4 = rt4, rt4 = null, t4()))); } function e3(e4) { t3(e4.instance, e4.module); } function n2(t4) { return (function() { if (!E2 && (_ || v)) { if ("function" == typeof fetch && !tt4.startsWith("file://")) return fetch(tt4, { credentials: "same-origin" }).then((function(t5) { if (!t5.ok) throw "failed to load wasm binary file at '" + tt4 + "'"; return t5.arrayBuffer(); })).catch((function() { return at3(); })); if (p) return new Promise((function(t5, e4) { p(tt4, (function(e5) { t5(new Uint8Array(e5)); }), e4); })); } return Promise.resolve().then((function() { return at3(); })); })().then((function(t5) { return WebAssembly.instantiate(t5, r3); })).then((function(t5) { return t5; })).then(t4, (function(t5) { P2("failed to asynchronously prepare wasm: " + t5), it3(t5); })); } var r3 = { a: fe4 }; if (x2 || (et2++, s.monitorRunDependencies && s.monitorRunDependencies(et2)), s.instantiateWasm) try { return s.instantiateWasm(r3, t3); } catch (t4) { return P2("Module.instantiateWasm callback failed with error: " + t4), false; } (E2 || "function" != typeof WebAssembly.instantiateStreaming || ot4() || tt4.startsWith("file://") || w || "function" != typeof fetch ? n2(e3) : fetch(tt4, { credentials: "same-origin" }).then((function(t4) { return WebAssembly.instantiateStreaming(t4, r3).then(e3, (function(t5) { return P2("wasm streaming compile failed: " + t5), P2("falling back to ArrayBuffer instantiation"), n2(e3); })); }))).catch(c); })(), s.___wasm_call_ctors = function() { return (s.___wasm_call_ctors = s.asm.Va).apply(null, arguments); }, s._OrtInit = function() { return (s._OrtInit = s.asm.Wa).apply(null, arguments); }, s._OrtCreateSessionOptions = function() { return (s._OrtCreateSessionOptions = s.asm.Xa).apply(null, arguments); }, s._OrtAppendExecutionProvider = function() { return (s._OrtAppendExecutionProvider = s.asm.Ya).apply(null, arguments); }, s._OrtAddSessionConfigEntry = function() { return (s._OrtAddSessionConfigEntry = s.asm.Za).apply(null, arguments); }, s._OrtReleaseSessionOptions = function() { return (s._OrtReleaseSessionOptions = s.asm._a).apply(null, arguments); }, s._OrtCreateSession = function() { return (s._OrtCreateSession = s.asm.$a).apply(null, arguments); }, s._OrtReleaseSession = function() { return (s._OrtReleaseSession = s.asm.ab).apply(null, arguments); }, s._OrtGetInputCount = function() { return (s._OrtGetInputCount = s.asm.bb).apply(null, arguments); }, s._OrtGetOutputCount = function() { return (s._OrtGetOutputCount = s.asm.cb).apply(null, arguments); }, s._OrtGetInputName = function() { return (s._OrtGetInputName = s.asm.db).apply(null, arguments); }, s._OrtGetOutputName = function() { return (s._OrtGetOutputName = s.asm.eb).apply(null, arguments); }, s._OrtFree = function() { return (s._OrtFree = s.asm.fb).apply(null, arguments); }, s._OrtCreateTensor = function() { return (s._OrtCreateTensor = s.asm.gb).apply(null, arguments); }, s._OrtGetTensorData = function() { return (s._OrtGetTensorData = s.asm.hb).apply(null, arguments); }, s._OrtReleaseTensor = function() { return (s._OrtReleaseTensor = s.asm.ib).apply(null, arguments); }, s._OrtCreateRunOptions = function() { return (s._OrtCreateRunOptions = s.asm.jb).apply(null, arguments); }, s._OrtAddRunConfigEntry = function() { return (s._OrtAddRunConfigEntry = s.asm.kb).apply(null, arguments); }, s._OrtReleaseRunOptions = function() { return (s._OrtReleaseRunOptions = s.asm.lb).apply(null, arguments); }, s._OrtRun = function() { return (s._OrtRun = s.asm.mb).apply(null, arguments); }, s._OrtEndProfiling = function() { return (s._OrtEndProfiling = s.asm.nb).apply(null, arguments); }; var de2 = s._pthread_self = function() { return (de2 = s._pthread_self = s.asm.ob).apply(null, arguments); }, he3 = s._malloc = function() { return (he3 = s._malloc = s.asm.pb).apply(null, arguments); }, ge3 = s._free = function() { return (ge3 = s._free = s.asm.qb).apply(null, arguments); }, be4 = s._fflush = function() { return (be4 = s._fflush = s.asm.rb).apply(null, arguments); }; s.__emscripten_tls_init = function() { return (s.__emscripten_tls_init = s.asm.sb).apply(null, arguments); }; var me3 = s.___funcs_on_exit = function() { return (me3 = s.___funcs_on_exit = s.asm.tb).apply(null, arguments); }, ye2 = s.__emscripten_thread_init = function() { return (ye2 = s.__emscripten_thread_init = s.asm.vb).apply(null, arguments); }; s.__emscripten_thread_crashed = function() { return (s.__emscripten_thread_crashed = s.asm.wb).apply(null, arguments); }; var _e3, ve2 = s._emscripten_run_in_main_runtime_thread_js = function() { return (ve2 = s._emscripten_run_in_main_runtime_thread_js = s.asm.xb).apply(null, arguments); }, we2 = s.__emscripten_proxy_execute_task_queue = function() { return (we2 = s.__emscripten_proxy_execute_task_queue = s.asm.yb).apply(null, arguments); }, xe = s.__emscripten_thread_free_data = function() { return (xe = s.__emscripten_thread_free_data = s.asm.zb).apply(null, arguments); }, Te2 = s.__emscripten_thread_exit = function() { return (Te2 = s.__emscripten_thread_exit = s.asm.Ab).apply(null, arguments); }, Se2 = s._setThrew = function() { return (Se2 = s._setThrew = s.asm.Bb).apply(null, arguments); }, Oe4 = s._emscripten_stack_set_limits = function() { return (Oe4 = s._emscripten_stack_set_limits = s.asm.Cb).apply(null, arguments); }, Ae3 = s.stackSave = function() { return (Ae3 = s.stackSave = s.asm.Db).apply(null, arguments); }, Ee3 = s.stackRestore = function() { return (Ee3 = s.stackRestore = s.asm.Eb).apply(null, arguments); }, Ie4 = s.stackAlloc = function() { return (Ie4 = s.stackAlloc = s.asm.Fb).apply(null, arguments); }, Pe3 = s.___cxa_can_catch = function() { return (Pe3 = s.___cxa_can_catch = s.asm.Gb).apply(null, arguments); }, De3 = s.___cxa_is_pointer_type = function() { return (De3 = s.___cxa_is_pointer_type = s.asm.Hb).apply(null, arguments); }, $e3 = s.dynCall_j = function() { return ($e3 = s.dynCall_j = s.asm.Ib).apply(null, arguments); }, ke3 = s.dynCall_iiiiij = function() { return (ke3 = s.dynCall_iiiiij = s.asm.Jb).apply(null, arguments); }, Ce4 = s.dynCall_jii = function() { return (Ce4 = s.dynCall_jii = s.asm.Kb).apply(null, arguments); }, Fe3 = s.dynCall_viiiiij = function() { return (Fe3 = s.dynCall_viiiiij = s.asm.Lb).apply(null, arguments); }, Ne3 = s.dynCall_vjji = function() { return (Ne3 = s.dynCall_vjji = s.asm.Mb).apply(null, arguments); }, Le3 = s.dynCall_viiijjjii = function() { return (Le3 = s.dynCall_viiijjjii = s.asm.Nb).apply(null, arguments); }, Re2 = s.dynCall_iij = function() { return (Re2 = s.dynCall_iij = s.asm.Ob).apply(null, arguments); }, je3 = s.dynCall_ji = function() { return (je3 = s.dynCall_ji = s.asm.Pb).apply(null, arguments); }, Me4 = s.dynCall_iiiiiij = function() { return (Me4 = s.dynCall_iiiiiij = s.asm.Qb).apply(null, arguments); }, Ue4 = s.dynCall_iiij = function() { return (Ue4 = s.dynCall_iiij = s.asm.Rb).apply(null, arguments); }; function Ve4() { function t3() { if (!_e3 && (_e3 = true, s.calledRun = true, !M3) && (x2 || ht4(Y3), u(s), s.onRuntimeInitialized && s.onRuntimeInitialized(), !x2)) { if (s.postRun) for ("function" == typeof s.postRun && (s.postRun = [s.postRun]); s.postRun.length; ) { var t4 = s.postRun.shift(); Z2.unshift(t4); } ht4(Z2); } } if (!(0 < et2)) if (x2) u(s), x2 || ht4(Y3), postMessage({ cmd: "loaded" }); else { if (s.preRun) for ("function" == typeof s.preRun && (s.preRun = [s.preRun]); s.preRun.length; ) Q2(); ht4(X), 0 < et2 || (s.setStatus ? (s.setStatus("Running..."), setTimeout((function() { setTimeout((function() { s.setStatus(""); }), 1), t3(); }), 1)) : t3()); } } if (s.UTF8ToString = B3, s.stringToUTF8 = function(t3, e3, n2) { return z3(t3, r2(), e3, n2); }, s.lengthBytesUTF8 = G3, s.keepRuntimeAlive = J3, s.wasmMemory = $2, s.stackSave = Ae3, s.stackRestore = Ee3, s.stackAlloc = Ie4, s.ExitStatus = ut2, s.PThread = dt4, rt4 = function t3() { _e3 || Ve4(), _e3 || (rt4 = t3); }, s.preInit) for ("function" == typeof s.preInit && (s.preInit = [s.preInit]); 0 < s.preInit.length; ) s.preInit.pop()(); return Ve4(), t2.ready; }); t.exports = r; }, 932: (t, e, n) => { var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) { var e2, r2, i; t2 = t2 || {}, e2 || (e2 = void 0 !== t2 ? t2 : {}), e2.ready = new Promise((function(t3, e3) { r2 = t3, i = e3; })); var o, a, s, u, c, l, p = Object.assign({}, e2), f = "./this.program", d = (t3, e3) => { throw e3; }, h = "object" == typeof window, g = "function" == typeof importScripts, b = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, m2 = ""; b ? (m2 = g ? n(908).dirname(m2) + "/" : "//", l = () => { c || (u = n(1384), c = n(908)); }, o = function(t3, e3) { return l(), t3 = c.normalize(t3), u.readFileSync(t3, e3 ? void 0 : "utf8"); }, s = (t3) => ((t3 = o(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), a = (t3, e3, n2) => { l(), t3 = c.normalize(t3), u.readFile(t3, (function(t4, r3) { t4 ? n2(t4) : e3(r3.buffer); })); }, 1 < process.argv.length && (f = process.argv[1].replace(/\\/g, "/")), process.argv.slice(2), process.on("uncaughtException", (function(t3) { if (!(t3 instanceof K)) throw t3; })), process.on("unhandledRejection", (function(t3) { throw t3; })), d = (t3, e3) => { if (w || 0 < U3) throw process.exitCode = t3, e3; e3 instanceof K || v("exiting due to exception: " + e3), process.exit(t3); }, e2.inspect = function() { return "[Emscripten Module object]"; }) : (h || g) && (g ? m2 = self.location.href : "undefined" != typeof document && document.currentScript && (m2 = document.currentScript.src), _scriptDir && (m2 = _scriptDir), m2 = 0 !== m2.indexOf("blob:") ? m2.substr(0, m2.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", o = (t3) => { var e3 = new XMLHttpRequest(); return e3.open("GET", t3, false), e3.send(null), e3.responseText; }, g && (s = (t3) => { var e3 = new XMLHttpRequest(); return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response); }), a = (t3, e3, n2) => { var r3 = new XMLHttpRequest(); r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => { 200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2(); }, r3.onerror = n2, r3.send(null); }); var y, _ = e2.print || console.log.bind(console), v = e2.printErr || console.warn.bind(console); Object.assign(e2, p), p = null, e2.thisProgram && (f = e2.thisProgram), e2.quit && (d = e2.quit), e2.wasmBinary && (y = e2.wasmBinary); var w = e2.noExitRuntime || false; "object" != typeof WebAssembly && W2("no native wasm support detected"); var x2, T3, S, O2, A2, E2, I2 = false, P2 = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0; function D3(t3, e3, n2) { var r3 = (e3 >>>= 0) + n2; for (n2 = e3; t3[n2] && !(n2 >= r3); ) ++n2; if (16 < n2 - e3 && t3.buffer && P2) return P2.decode(t3.subarray(e3, n2)); for (r3 = ""; e3 < n2; ) { var i2 = t3[e3++]; if (128 & i2) { var o2 = 63 & t3[e3++]; if (192 == (224 & i2)) r3 += String.fromCharCode((31 & i2) << 6 | o2); else { var a2 = 63 & t3[e3++]; 65536 > (i2 = 224 == (240 & i2) ? (15 & i2) << 12 | o2 << 6 | a2 : (7 & i2) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i2) : (i2 -= 65536, r3 += String.fromCharCode(55296 | i2 >> 10, 56320 | 1023 & i2)); } } else r3 += String.fromCharCode(i2); } return r3; } function $2(t3, e3) { return (t3 >>>= 0) ? D3(O2, t3, e3) : ""; } function k4(t3, e3, n2, r3) { if (!(0 < r3)) return 0; var i2 = n2 >>>= 0; r3 = n2 + r3 - 1; for (var o2 = 0; o2 < t3.length; ++o2) { var a2 = t3.charCodeAt(o2); if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) { if (n2 >= r3) break; e3[n2++ >>> 0] = a2; } else { if (2047 >= a2) { if (n2 + 1 >= r3) break; e3[n2++ >>> 0] = 192 | a2 >> 6; } else { if (65535 >= a2) { if (n2 + 2 >= r3) break; e3[n2++ >>> 0] = 224 | a2 >> 12; } else { if (n2 + 3 >= r3) break; e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63; } e3[n2++ >>> 0] = 128 | a2 >> 6 & 63; } e3[n2++ >>> 0] = 128 | 63 & a2; } } return e3[n2 >>> 0] = 0, n2 - i2; } function C(t3) { for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) { var r3 = t3.charCodeAt(n2); 127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3; } return e3; } function F2() { var t3 = x2.buffer; T3 = t3, e2.HEAP8 = S = new Int8Array(t3), e2.HEAP16 = new Int16Array(t3), e2.HEAP32 = A2 = new Int32Array(t3), e2.HEAPU8 = O2 = new Uint8Array(t3), e2.HEAPU16 = new Uint16Array(t3), e2.HEAPU32 = E2 = new Uint32Array(t3), e2.HEAPF32 = new Float32Array(t3), e2.HEAPF64 = new Float64Array(t3); } var N2, L = [], R = [], j3 = [], M3 = [], U3 = 0; function V3() { var t3 = e2.preRun.shift(); L.unshift(t3); } var B3, z3 = 0, G3 = null, H3 = null; function W2(t3) { throw e2.onAbort && e2.onAbort(t3), v(t3 = "Aborted(" + t3 + ")"), I2 = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), i(t3), t3; } function q3() { return B3.startsWith("data:application/octet-stream;base64,"); } if (B3 = "ort-wasm.wasm", !q3()) { var X = B3; B3 = e2.locateFile ? e2.locateFile(X, m2) : m2 + X; } function Y3() { var t3 = B3; try { if (t3 == B3 && y) return new Uint8Array(y); if (s) return s(t3); throw "both async and sync fetching of the wasm failed"; } catch (t4) { W2(t4); } } function K(t3) { this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3; } function Z2(t3) { for (; 0 < t3.length; ) t3.shift()(e2); } var J3 = [], Q2 = 0, tt4 = 0; function et2(t3) { this.Db = t3, this.zb = t3 - 24, this.Ub = function(t4) { E2[this.zb + 4 >> 2 >>> 0] = t4; }, this.Eb = function() { return E2[this.zb + 4 >> 2 >>> 0]; }, this.Sb = function(t4) { E2[this.zb + 8 >> 2 >>> 0] = t4; }, this.Wb = function() { return E2[this.zb + 8 >> 2 >>> 0]; }, this.Tb = function() { A2[this.zb >> 2 >>> 0] = 0; }, this.Ib = function(t4) { S[this.zb + 12 >> 0 >>> 0] = t4 ? 1 : 0; }, this.Pb = function() { return 0 != S[this.zb + 12 >> 0 >>> 0]; }, this.Jb = function(t4) { S[this.zb + 13 >> 0 >>> 0] = t4 ? 1 : 0; }, this.Lb = function() { return 0 != S[this.zb + 13 >> 0 >>> 0]; }, this.Rb = function(t4, e3) { this.Fb(0), this.Ub(t4), this.Sb(e3), this.Tb(), this.Ib(false), this.Jb(false); }, this.Nb = function() { A2[this.zb >> 2 >>> 0] += 1; }, this.Xb = function() { var t4 = A2[this.zb >> 2 >>> 0]; return A2[this.zb >> 2 >>> 0] = t4 - 1, 1 === t4; }, this.Fb = function(t4) { E2[this.zb + 16 >> 2 >>> 0] = t4; }, this.Ob = function() { return E2[this.zb + 16 >> 2 >>> 0]; }, this.Qb = function() { if (Et3(this.Eb())) return E2[this.Db >> 2 >>> 0]; var t4 = this.Ob(); return 0 !== t4 ? t4 : this.Db; }; } function nt3(t3) { return _t3(new et2(t3).zb); } var rt4 = []; function it3(t3) { var e3 = rt4[t3]; return e3 || (t3 >= rt4.length && (rt4.length = t3 + 1), rt4[t3] = e3 = N2.get(t3)), e3; } function ot4(t3) { var e3 = C(t3) + 1, n2 = yt3(e3); return n2 && k4(t3, S, n2, e3), n2; } var at3 = {}; function st2() { if (!ut2) { var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: f || "./this.program" }; for (t3 in at3) void 0 === at3[t3] ? delete e3[t3] : e3[t3] = at3[t3]; var n2 = []; for (t3 in e3) n2.push(t3 + "=" + e3[t3]); ut2 = n2; } return ut2; } var ut2, ct2 = [null, [], []]; function lt2(t3, e3) { var n2 = ct2[t3]; 0 === e3 || 10 === e3 ? ((1 === t3 ? _ : v)(D3(n2, 0)), n2.length = 0) : n2.push(e3); } var pt2 = 0; function ft2(t3) { return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400); } var dt4 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ht4 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; function gt4(t3, e3, n2, r3) { function i2(t4, e4, n3) { for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e4; ) t4 = n3[0] + t4; return t4; } function o2(t4, e4) { return i2(t4, e4, "0"); } function a2(t4, e4) { function n3(t5) { return 0 > t5 ? -1 : 0 < t5 ? 1 : 0; } var r4; return 0 === (r4 = n3(t4.getFullYear() - e4.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e4.getMonth())) && (r4 = n3(t4.getDate() - e4.getDate())), r4; } function s2(t4) { switch (t4.getDay()) { case 0: return new Date(t4.getFullYear() - 1, 11, 29); case 1: return t4; case 2: return new Date(t4.getFullYear(), 0, 3); case 3: return new Date(t4.getFullYear(), 0, 2); case 4: return new Date(t4.getFullYear(), 0, 1); case 5: return new Date(t4.getFullYear() - 1, 11, 31); case 6: return new Date(t4.getFullYear() - 1, 11, 30); } } function u2(t4) { var e4 = t4.Bb; for (t4 = new Date(new Date(t4.Cb + 1900, 0, 1).getTime()); 0 < e4; ) { var n3 = t4.getMonth(), r4 = (ft2(t4.getFullYear()) ? dt4 : ht4)[n3]; if (!(e4 > r4 - t4.getDate())) { t4.setDate(t4.getDate() + e4); break; } e4 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1)); } return n3 = new Date(t4.getFullYear() + 1, 0, 4), e4 = s2(new Date(t4.getFullYear(), 0, 4)), n3 = s2(n3), 0 >= a2(e4, t4) ? 0 >= a2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1; } var c2 = A2[r3 + 40 >> 2 >>> 0]; for (var l2 in r3 = { $b: A2[r3 >> 2 >>> 0], Zb: A2[r3 + 4 >> 2 >>> 0], Gb: A2[r3 + 8 >> 2 >>> 0], Kb: A2[r3 + 12 >> 2 >>> 0], Hb: A2[r3 + 16 >> 2 >>> 0], Cb: A2[r3 + 20 >> 2 >>> 0], Ab: A2[r3 + 24 >> 2 >>> 0], Bb: A2[r3 + 28 >> 2 >>> 0], bc: A2[r3 + 32 >> 2 >>> 0], Yb: A2[r3 + 36 >> 2 >>> 0], ac: c2 ? $2(c2) : "" }, n2 = $2(n2), c2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) n2 = n2.replace(new RegExp(l2, "g"), c2[l2]); var p2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), f2 = "January February March April May June July August September October November December".split(" "); for (l2 in c2 = { "%a": function(t4) { return p2[t4.Ab].substring(0, 3); }, "%A": function(t4) { return p2[t4.Ab]; }, "%b": function(t4) { return f2[t4.Hb].substring(0, 3); }, "%B": function(t4) { return f2[t4.Hb]; }, "%C": function(t4) { return o2((t4.Cb + 1900) / 100 | 0, 2); }, "%d": function(t4) { return o2(t4.Kb, 2); }, "%e": function(t4) { return i2(t4.Kb, 2, " "); }, "%g": function(t4) { return u2(t4).toString().substring(2); }, "%G": function(t4) { return u2(t4); }, "%H": function(t4) { return o2(t4.Gb, 2); }, "%I": function(t4) { return 0 == (t4 = t4.Gb) ? t4 = 12 : 12 < t4 && (t4 -= 12), o2(t4, 2); }, "%j": function(t4) { for (var e4 = 0, n3 = 0; n3 <= t4.Hb - 1; e4 += (ft2(t4.Cb + 1900) ? dt4 : ht4)[n3++]) ; return o2(t4.Kb + e4, 3); }, "%m": function(t4) { return o2(t4.Hb + 1, 2); }, "%M": function(t4) { return o2(t4.Zb, 2); }, "%n": function() { return "\n"; }, "%p": function(t4) { return 0 <= t4.Gb && 12 > t4.Gb ? "AM" : "PM"; }, "%S": function(t4) { return o2(t4.$b, 2); }, "%t": function() { return " "; }, "%u": function(t4) { return t4.Ab || 7; }, "%U": function(t4) { return o2(Math.floor((t4.Bb + 7 - t4.Ab) / 7), 2); }, "%V": function(t4) { var e4 = Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7); if (2 >= (t4.Ab + 371 - t4.Bb - 2) % 7 && e4++, e4) 53 == e4 && (4 == (n3 = (t4.Ab + 371 - t4.Bb) % 7) || 3 == n3 && ft2(t4.Cb) || (e4 = 1)); else { e4 = 52; var n3 = (t4.Ab + 7 - t4.Bb - 1) % 7; (4 == n3 || 5 == n3 && ft2(t4.Cb % 400 - 1)) && e4++; } return o2(e4, 2); }, "%w": function(t4) { return t4.Ab; }, "%W": function(t4) { return o2(Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7), 2); }, "%y": function(t4) { return (t4.Cb + 1900).toString().substring(2); }, "%Y": function(t4) { return t4.Cb + 1900; }, "%z": function(t4) { var e4 = 0 <= (t4 = t4.Yb); return t4 = Math.abs(t4) / 60, (e4 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4); }, "%Z": function(t4) { return t4.ac; }, "%%": function() { return "%"; } }, n2 = n2.replace(/%%/g, "\0\0"), c2) n2.includes(l2) && (n2 = n2.replace(new RegExp(l2, "g"), c2[l2](r3))); return l2 = (function(t4) { var e4 = Array(C(t4) + 1); return k4(t4, e4, 0, e4.length), e4; })(n2 = n2.replace(/\0\0/g, "%")), l2.length > e3 ? 0 : (S.set(l2, t3 >>> 0), l2.length - 1); } var bt3 = { a: function(t3) { return yt3(t3 + 24) + 24; }, m: function(t3) { return (t3 = new et2(t3)).Pb() || (t3.Ib(true), Q2--), t3.Jb(false), J3.push(t3), t3.Nb(), t3.Qb(); }, ia: function(t3) { throw v("Unexpected exception thrown, this is not properly supported - aborting"), I2 = true, t3; }, w: function() { xt3(0); var t3 = J3.pop(); if (t3.Xb() && !t3.Lb()) { var e3 = t3.Wb(); e3 && it3(e3)(t3.Db), nt3(t3.Db); } tt4 = 0; }, d: function() { var t3 = tt4; if (!t3) return pt2 = 0; var e3 = new et2(t3); e3.Fb(t3); var n2 = e3.Eb(); if (!n2) return pt2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (At2(o2, n2, e3.zb + 16)) return pt2 = o2, t3; } return pt2 = n2, t3; }, k: function() { var t3 = tt4; if (!t3) return pt2 = 0; var e3 = new et2(t3); e3.Fb(t3); var n2 = e3.Eb(); if (!n2) return pt2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (At2(o2, n2, e3.zb + 16)) return pt2 = o2, t3; } return pt2 = n2, t3; }, g: function() { var t3 = tt4; if (!t3) return pt2 = 0; var e3 = new et2(t3); e3.Fb(t3); var n2 = e3.Eb(); if (!n2) return pt2 = 0, t3; for (var r3 = Array.prototype.slice.call(arguments), i2 = 0; i2 < r3.length; i2++) { var o2 = r3[i2]; if (0 === o2 || o2 === n2) break; if (At2(o2, n2, e3.zb + 16)) return pt2 = o2, t3; } return pt2 = n2, t3; }, s: nt3, L: function() { var t3 = J3.pop(); t3 || W2("no exception to throw"); var e3 = t3.Db; throw t3.Lb() || (J3.push(t3), t3.Jb(true), t3.Ib(false), Q2++), tt4 = e3, e3; }, b: function(t3, e3, n2) { throw new et2(t3).Rb(e3, n2), tt4 = t3, Q2++, t3; }, la: function() { return Q2; }, i: function(t3) { throw tt4 || (tt4 = t3), t3; }, H: function() { return 0; }, Ba: function() { }, pa: function() { }, ra: function() { }, ka: function() { return 0; }, za: function() { }, ua: function() { }, ya: function() { }, R: function() { }, qa: function() { }, na: function() { }, Aa: function() { }, oa: function() { }, Ha: function() { }, Ja: function() { W2("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); }, Ia: function() { W2("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking"); }, S: function() { return Date.now(); }, Ca: function() { return true; }, Da: function(t3, e3) { t3 = new Date(1e3 * (E2[t3 >>> 2] + 4294967296 * A2[t3 + 4 >>> 2])), A2[e3 >> 2 >>> 0] = t3.getUTCSeconds(), A2[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), A2[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), A2[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), A2[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), A2[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, A2[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), A2[e3 + 28 >> 2 >>> 0] = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0; }, Ea: function(t3, e3) { t3 = new Date(1e3 * (E2[t3 >>> 2] + 4294967296 * A2[t3 + 4 >>> 2])), A2[e3 >> 2 >>> 0] = t3.getSeconds(), A2[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), A2[e3 + 8 >> 2 >>> 0] = t3.getHours(), A2[e3 + 12 >> 2 >>> 0] = t3.getDate(), A2[e3 + 16 >> 2 >>> 0] = t3.getMonth(), A2[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, A2[e3 + 24 >> 2 >>> 0] = t3.getDay(); var n2 = new Date(t3.getFullYear(), 0, 1); A2[e3 + 28 >> 2 >>> 0] = (t3.getTime() - n2.getTime()) / 864e5 | 0, A2[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(); var r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(); n2 = n2.getTimezoneOffset(), A2[e3 + 32 >> 2 >>> 0] = 0 | (r3 != n2 && t3.getTimezoneOffset() == Math.min(n2, r3)); }, Fa: function(t3) { var e3 = new Date(A2[t3 + 20 >> 2 >>> 0] + 1900, A2[t3 + 16 >> 2 >>> 0], A2[t3 + 12 >> 2 >>> 0], A2[t3 + 8 >> 2 >>> 0], A2[t3 + 4 >> 2 >>> 0], A2[t3 >> 2 >>> 0], 0), n2 = A2[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), i2 = new Date(e3.getFullYear(), 0, 1), o2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), a2 = i2.getTimezoneOffset(), s2 = Math.min(a2, o2); return 0 > n2 ? A2[t3 + 32 >> 2 >>> 0] = Number(o2 != a2 && s2 == r3) : 0 < n2 != (s2 == r3) && (o2 = Math.max(a2, o2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? s2 : o2) - r3))), A2[t3 + 24 >> 2 >>> 0] = e3.getDay(), A2[t3 + 28 >> 2 >>> 0] = (e3.getTime() - i2.getTime()) / 864e5 | 0, A2[t3 >> 2 >>> 0] = e3.getSeconds(), A2[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), A2[t3 + 8 >> 2 >>> 0] = e3.getHours(), A2[t3 + 12 >> 2 >>> 0] = e3.getDate(), A2[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0; }, sa: function() { return -52; }, ta: function() { }, Ga: function t3(e3, n2, r3) { t3.Vb || (t3.Vb = true, (function(t4, e4, n3) { function r4(t5) { return (t5 = t5.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t5[1] : "GMT"; } var i2 = (/* @__PURE__ */ new Date()).getFullYear(), o2 = new Date(i2, 0, 1), a2 = new Date(i2, 6, 1); i2 = o2.getTimezoneOffset(); var s2 = a2.getTimezoneOffset(); A2[t4 >> 2 >>> 0] = 60 * Math.max(i2, s2), A2[e4 >> 2 >>> 0] = Number(i2 != s2), t4 = r4(o2), e4 = r4(a2), t4 = ot4(t4), e4 = ot4(e4), s2 < i2 ? (E2[n3 >> 2 >>> 0] = t4, E2[n3 + 4 >> 2 >>> 0] = e4) : (E2[n3 >> 2 >>> 0] = e4, E2[n3 + 4 >> 2 >>> 0] = t4); })(e3, n2, r3)); }, B: function() { W2(""); }, ma: function() { return 4294901760; }, I: b ? () => { var t3 = process.hrtime(); return 1e3 * t3[0] + t3[1] / 1e6; } : () => performance.now(), xa: function(t3, e3, n2) { O2.copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0); }, G: function(t3) { var e3 = O2.length; if (4294901760 < (t3 >>>= 0)) return false; for (var n2 = 1; 4 >= n2; n2 *= 2) { var r3 = e3 * (1 + 0.2 / n2); r3 = Math.min(r3, t3 + 100663296); var i2 = Math; r3 = Math.max(t3, r3), i2 = i2.min.call(i2, 4294901760, r3 + (65536 - r3 % 65536) % 65536); t: { try { x2.grow(i2 - T3.byteLength + 65535 >>> 16), F2(); var o2 = 1; break t; } catch (t4) { } o2 = void 0; } if (o2) return true; } return false; }, va: function(t3, e3) { var n2 = 0; return st2().forEach((function(r3, i2) { var o2 = e3 + n2; for (i2 = E2[t3 + 4 * i2 >> 2 >>> 0] = o2, o2 = 0; o2 < r3.length; ++o2) S[i2++ >> 0 >>> 0] = r3.charCodeAt(o2); S[i2 >> 0 >>> 0] = 0, n2 += r3.length + 1; })), 0; }, wa: function(t3, e3) { var n2 = st2(); E2[t3 >> 2 >>> 0] = n2.length; var r3 = 0; return n2.forEach((function(t4) { r3 += t4.length + 1; })), E2[e3 >> 2 >>> 0] = r3, 0; }, ba: function(t3) { w || 0 < U3 || (wt(), Z2(j3), vt3(0), ct2[1].length && lt2(1, 10), ct2[2].length && lt2(2, 10)), w || 0 < U3 || (e2.onExit && e2.onExit(t3), I2 = true), d(t3, new K(t3)); }, E: function() { return 52; }, Q: function() { return 52; }, ca: function() { return 70; }, P: function(t3, e3, n2, r3) { for (var i2 = 0, o2 = 0; o2 < n2; o2++) { var a2 = E2[e3 >> 2 >>> 0], s2 = E2[e3 + 4 >> 2 >>> 0]; e3 += 8; for (var u2 = 0; u2 < s2; u2++) lt2(t3, O2[a2 + u2 >>> 0]); i2 += s2; } return E2[r3 >> 2 >>> 0] = i2, 0; }, c: function() { return pt2; }, ja: function t3(e3, r3) { t3.Mb || (t3.Mb = (function() { if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) { var t4 = new Uint8Array(1); return () => (crypto.getRandomValues(t4), t4[0]); } if (b) try { var e4 = n(Object((function() { var t5 = new Error("Cannot find module 'crypto'"); throw t5.code = "MODULE_NOT_FOUND", t5; })())); return () => e4.randomBytes(1)[0]; } catch (t5) { } return () => W2("randomDevice"); })()); for (var i2 = 0; i2 < r3; i2++) S[e3 + i2 >> 0 >>> 0] = t3.Mb(); return 0; }, ea: function(t3, e3, n2) { var r3 = Tt4(); try { return it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, fa: function(t3, e3, n2) { var r3 = Tt4(); try { return it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, J: function(t3) { var e3 = Tt4(); try { return it3(t3)(); } catch (t4) { if (St3(e3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, e: function(t3, e3) { var n2 = Tt4(); try { return it3(t3)(e3); } catch (t4) { if (St3(n2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, N: function(t3, e3, n2) { var r3 = Tt4(); try { return it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, O: function(t3, e3, n2) { var r3 = Tt4(); try { return it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, j: function(t3, e3, n2) { var r3 = Tt4(); try { return it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, o: function(t3, e3, n2, r3) { var i2 = Tt4(); try { return it3(t3)(e3, n2, r3); } catch (t4) { if (St3(i2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, p: function(t3, e3, n2, r3, i2) { var o2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2); } catch (t4) { if (St3(o2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, M: function(t3, e3, n2, r3, i2, o2) { var a2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (St3(a2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, r: function(t3, e3, n2, r3, i2, o2) { var a2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (St3(a2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, v: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2, o2, a2); } catch (t4) { if (St3(s2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, K: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (St3(u2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, D: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { var f2 = Tt4(); try { return it3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); } catch (t4) { if (St3(f2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, X: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Tt4(); try { return Lt3(t3, e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (St3(u2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, V: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Tt4(); try { return Pt4(t3, e3, n2, r3, i2, o2, a2); } catch (t4) { if (St3(s2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, U: function(t3, e3, n2, r3, i2) { var o2 = Tt4(); try { return Rt2(t3, e3, n2, r3, i2); } catch (t4) { if (St3(o2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, Z: function(t3, e3, n2, r3) { var i2 = Tt4(); try { return Ft4(t3, e3, n2, r3); } catch (t4) { if (St3(i2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, W: function(t3) { var e3 = Tt4(); try { return It2(t3); } catch (t4) { if (St3(e3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, Y: function(t3, e3) { var n2 = Tt4(); try { return Nt4(t3, e3); } catch (t4) { if (St3(n2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, T: function(t3, e3, n2) { var r3 = Tt4(); try { return Dt2(t3, e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, f: function(t3) { var e3 = Tt4(); try { it3(t3)(); } catch (t4) { if (St3(e3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, q: function(t3, e3) { var n2 = Tt4(); try { it3(t3)(e3); } catch (t4) { if (St3(n2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, h: function(t3, e3, n2) { var r3 = Tt4(); try { it3(t3)(e3, n2); } catch (t4) { if (St3(r3), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, da: function(t3, e3, n2, r3) { var i2 = Tt4(); try { it3(t3)(e3, n2, r3); } catch (t4) { if (St3(i2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, l: function(t3, e3, n2, r3) { var i2 = Tt4(); try { it3(t3)(e3, n2, r3); } catch (t4) { if (St3(i2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, t: function(t3, e3, n2, r3, i2) { var o2 = Tt4(); try { it3(t3)(e3, n2, r3, i2); } catch (t4) { if (St3(o2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, u: function(t3, e3, n2, r3, i2, o2) { var a2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2); } catch (t4) { if (St3(a2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, x: function(t3, e3, n2, r3, i2, o2, a2) { var s2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2, a2); } catch (t4) { if (St3(s2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, z: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (St3(u2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, ga: function(t3, e3, n2, r3, i2, o2, a2, s2, u2) { var c2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2, a2, s2, u2); } catch (t4) { if (St3(c2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, A: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2) { var p2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2); } catch (t4) { if (St3(p2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, C: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) { var b2 = Tt4(); try { it3(t3)(e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2); } catch (t4) { if (St3(b2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, aa: function(t3, e3, n2, r3, i2, o2, a2, s2) { var u2 = Tt4(); try { $t4(t3, e3, n2, r3, i2, o2, a2, s2); } catch (t4) { if (St3(u2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, _: function(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2) { var f2 = Tt4(); try { Ct2(t3, e3, n2, r3, i2, o2, a2, s2, u2, c2, l2, p2); } catch (t4) { if (St3(f2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, $: function(t3, e3, n2, r3, i2, o2) { var a2 = Tt4(); try { kt4(t3, e3, n2, r3, i2, o2); } catch (t4) { if (St3(a2), t4 !== t4 + 0) throw t4; xt3(1, 0); } }, n: function(t3) { return t3; }, F: function(t3) { pt2 = t3; }, ha: gt4, y: function(t3, e3, n2, r3) { return gt4(t3, e3, n2, r3); } }; !(function() { function t3(t4) { e2.asm = t4.exports, x2 = e2.asm.Ka, F2(), N2 = e2.asm.ib, R.unshift(e2.asm.La), z3--, e2.monitorRunDependencies && e2.monitorRunDependencies(z3), 0 == z3 && (null !== G3 && (clearInterval(G3), G3 = null), H3 && (t4 = H3, H3 = null, t4())); } function n2(e3) { t3(e3.instance); } function r3(t4) { return (function() { if (!y && (h || g)) { if ("function" == typeof fetch && !B3.startsWith("file://")) return fetch(B3, { credentials: "same-origin" }).then((function(t5) { if (!t5.ok) throw "failed to load wasm binary file at '" + B3 + "'"; return t5.arrayBuffer(); })).catch((function() { return Y3(); })); if (a) return new Promise((function(t5, e3) { a(B3, (function(e4) { t5(new Uint8Array(e4)); }), e3); })); } return Promise.resolve().then((function() { return Y3(); })); })().then((function(t5) { return WebAssembly.instantiate(t5, o2); })).then((function(t5) { return t5; })).then(t4, (function(t5) { v("failed to asynchronously prepare wasm: " + t5), W2(t5); })); } var o2 = { a: bt3 }; if (z3++, e2.monitorRunDependencies && e2.monitorRunDependencies(z3), e2.instantiateWasm) try { return e2.instantiateWasm(o2, t3); } catch (t4) { return v("Module.instantiateWasm callback failed with error: " + t4), false; } (y || "function" != typeof WebAssembly.instantiateStreaming || q3() || B3.startsWith("file://") || b || "function" != typeof fetch ? r3(n2) : fetch(B3, { credentials: "same-origin" }).then((function(t4) { return WebAssembly.instantiateStreaming(t4, o2).then(n2, (function(t5) { return v("wasm streaming compile failed: " + t5), v("falling back to ArrayBuffer instantiation"), r3(n2); })); }))).catch(i); })(), e2.___wasm_call_ctors = function() { return (e2.___wasm_call_ctors = e2.asm.La).apply(null, arguments); }, e2._OrtInit = function() { return (e2._OrtInit = e2.asm.Ma).apply(null, arguments); }, e2._OrtCreateSessionOptions = function() { return (e2._OrtCreateSessionOptions = e2.asm.Na).apply(null, arguments); }, e2._OrtAppendExecutionProvider = function() { return (e2._OrtAppendExecutionProvider = e2.asm.Oa).apply(null, arguments); }, e2._OrtAddSessionConfigEntry = function() { return (e2._OrtAddSessionConfigEntry = e2.asm.Pa).apply(null, arguments); }, e2._OrtReleaseSessionOptions = function() { return (e2._OrtReleaseSessionOptions = e2.asm.Qa).apply(null, arguments); }, e2._OrtCreateSession = function() { return (e2._OrtCreateSession = e2.asm.Ra).apply(null, arguments); }, e2._OrtReleaseSession = function() { return (e2._OrtReleaseSession = e2.asm.Sa).apply(null, arguments); }, e2._OrtGetInputCount = function() { return (e2._OrtGetInputCount = e2.asm.Ta).apply(null, arguments); }, e2._OrtGetOutputCount = function() { return (e2._OrtGetOutputCount = e2.asm.Ua).apply(null, arguments); }, e2._OrtGetInputName = function() { return (e2._OrtGetInputName = e2.asm.Va).apply(null, arguments); }, e2._OrtGetOutputName = function() { return (e2._OrtGetOutputName = e2.asm.Wa).apply(null, arguments); }, e2._OrtFree = function() { return (e2._OrtFree = e2.asm.Xa).apply(null, arguments); }, e2._OrtCreateTensor = function() { return (e2._OrtCreateTensor = e2.asm.Ya).apply(null, arguments); }, e2._OrtGetTensorData = function() { return (e2._OrtGetTensorData = e2.asm.Za).apply(null, arguments); }, e2._OrtReleaseTensor = function() { return (e2._OrtReleaseTensor = e2.asm._a).apply(null, arguments); }, e2._OrtCreateRunOptions = function() { return (e2._OrtCreateRunOptions = e2.asm.$a).apply(null, arguments); }, e2._OrtAddRunConfigEntry = function() { return (e2._OrtAddRunConfigEntry = e2.asm.ab).apply(null, arguments); }, e2._OrtReleaseRunOptions = function() { return (e2._OrtReleaseRunOptions = e2.asm.bb).apply(null, arguments); }, e2._OrtRun = function() { return (e2._OrtRun = e2.asm.cb).apply(null, arguments); }, e2._OrtEndProfiling = function() { return (e2._OrtEndProfiling = e2.asm.db).apply(null, arguments); }; var mt2, yt3 = e2._malloc = function() { return (yt3 = e2._malloc = e2.asm.eb).apply(null, arguments); }, _t3 = e2._free = function() { return (_t3 = e2._free = e2.asm.fb).apply(null, arguments); }, vt3 = e2._fflush = function() { return (vt3 = e2._fflush = e2.asm.gb).apply(null, arguments); }, wt = e2.___funcs_on_exit = function() { return (wt = e2.___funcs_on_exit = e2.asm.hb).apply(null, arguments); }, xt3 = e2._setThrew = function() { return (xt3 = e2._setThrew = e2.asm.jb).apply(null, arguments); }, Tt4 = e2.stackSave = function() { return (Tt4 = e2.stackSave = e2.asm.kb).apply(null, arguments); }, St3 = e2.stackRestore = function() { return (St3 = e2.stackRestore = e2.asm.lb).apply(null, arguments); }, Ot = e2.stackAlloc = function() { return (Ot = e2.stackAlloc = e2.asm.mb).apply(null, arguments); }, At2 = e2.___cxa_can_catch = function() { return (At2 = e2.___cxa_can_catch = e2.asm.nb).apply(null, arguments); }, Et3 = e2.___cxa_is_pointer_type = function() { return (Et3 = e2.___cxa_is_pointer_type = e2.asm.ob).apply(null, arguments); }, It2 = e2.dynCall_j = function() { return (It2 = e2.dynCall_j = e2.asm.pb).apply(null, arguments); }, Pt4 = e2.dynCall_iiiiij = function() { return (Pt4 = e2.dynCall_iiiiij = e2.asm.qb).apply(null, arguments); }, Dt2 = e2.dynCall_jii = function() { return (Dt2 = e2.dynCall_jii = e2.asm.rb).apply(null, arguments); }, $t4 = e2.dynCall_viiiiij = function() { return ($t4 = e2.dynCall_viiiiij = e2.asm.sb).apply(null, arguments); }, kt4 = e2.dynCall_vjji = function() { return (kt4 = e2.dynCall_vjji = e2.asm.tb).apply(null, arguments); }, Ct2 = e2.dynCall_viiijjjii = function() { return (Ct2 = e2.dynCall_viiijjjii = e2.asm.ub).apply(null, arguments); }, Ft4 = e2.dynCall_iij = function() { return (Ft4 = e2.dynCall_iij = e2.asm.vb).apply(null, arguments); }, Nt4 = e2.dynCall_ji = function() { return (Nt4 = e2.dynCall_ji = e2.asm.wb).apply(null, arguments); }, Lt3 = e2.dynCall_iiiiiij = function() { return (Lt3 = e2.dynCall_iiiiiij = e2.asm.xb).apply(null, arguments); }, Rt2 = e2.dynCall_iiij = function() { return (Rt2 = e2.dynCall_iiij = e2.asm.yb).apply(null, arguments); }; function jt3() { function t3() { if (!mt2 && (mt2 = true, e2.calledRun = true, !I2)) { if (Z2(R), r2(e2), e2.onRuntimeInitialized && e2.onRuntimeInitialized(), e2.postRun) for ("function" == typeof e2.postRun && (e2.postRun = [e2.postRun]); e2.postRun.length; ) { var t4 = e2.postRun.shift(); M3.unshift(t4); } Z2(M3); } } if (!(0 < z3)) { if (e2.preRun) for ("function" == typeof e2.preRun && (e2.preRun = [e2.preRun]); e2.preRun.length; ) V3(); Z2(L), 0 < z3 || (e2.setStatus ? (e2.setStatus("Running..."), setTimeout((function() { setTimeout((function() { e2.setStatus(""); }), 1), t3(); }), 1)) : t3()); } } if (e2.UTF8ToString = $2, e2.stringToUTF8 = function(t3, e3, n2) { return k4(t3, O2, e3, n2); }, e2.lengthBytesUTF8 = C, e2.stackSave = Tt4, e2.stackRestore = St3, e2.stackAlloc = Ot, H3 = function t3() { mt2 || jt3(), mt2 || (H3 = t3); }, e2.preInit) for ("function" == typeof e2.preInit && (e2.preInit = [e2.preInit]); 0 < e2.preInit.length; ) e2.preInit.pop()(); return jt3(), t2.ready; }); t.exports = r; }, 4537: (t) => { "use strict"; t.exports = function(t2, e) { for (var n = new Array(arguments.length - 1), r = 0, i = 2, o = true; i < arguments.length; ) n[r++] = arguments[i++]; return new Promise((function(i2, a) { n[r] = function(t3) { if (o) if (o = false, t3) a(t3); else { for (var e2 = new Array(arguments.length - 1), n2 = 0; n2 < e2.length; ) e2[n2++] = arguments[n2]; i2.apply(null, e2); } }; try { t2.apply(e || null, n); } catch (t3) { o && (o = false, a(t3)); } })); }; }, 7419: (t, e) => { "use strict"; var n = e; n.length = function(t2) { var e2 = t2.length; if (!e2) return 0; for (var n2 = 0; --e2 % 4 > 1 && "=" === t2.charAt(e2); ) ++n2; return Math.ceil(3 * t2.length) / 4 - n2; }; for (var r = new Array(64), i = new Array(123), o = 0; o < 64; ) i[r[o] = o < 26 ? o + 65 : o < 52 ? o + 71 : o < 62 ? o - 4 : o - 59 | 43] = o++; n.encode = function(t2, e2, n2) { for (var i2, o2 = null, a2 = [], s = 0, u = 0; e2 < n2; ) { var c = t2[e2++]; switch (u) { case 0: a2[s++] = r[c >> 2], i2 = (3 & c) << 4, u = 1; break; case 1: a2[s++] = r[i2 | c >> 4], i2 = (15 & c) << 2, u = 2; break; case 2: a2[s++] = r[i2 | c >> 6], a2[s++] = r[63 & c], u = 0; } s > 8191 && ((o2 || (o2 = [])).push(String.fromCharCode.apply(String, a2)), s = 0); } return u && (a2[s++] = r[i2], a2[s++] = 61, 1 === u && (a2[s++] = 61)), o2 ? (s && o2.push(String.fromCharCode.apply(String, a2.slice(0, s))), o2.join("")) : String.fromCharCode.apply(String, a2.slice(0, s)); }; var a = "invalid encoding"; n.decode = function(t2, e2, n2) { for (var r2, o2 = n2, s = 0, u = 0; u < t2.length; ) { var c = t2.charCodeAt(u++); if (61 === c && s > 1) break; if (void 0 === (c = i[c])) throw Error(a); switch (s) { case 0: r2 = c, s = 1; break; case 1: e2[n2++] = r2 << 2 | (48 & c) >> 4, r2 = c, s = 2; break; case 2: e2[n2++] = (15 & r2) << 4 | (60 & c) >> 2, r2 = c, s = 3; break; case 3: e2[n2++] = (3 & r2) << 6 | c, s = 0; } } if (1 === s) throw Error(a); return n2 - o2; }, n.test = function(t2) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t2); }; }, 9211: (t) => { "use strict"; function e() { this._listeners = {}; } t.exports = e, e.prototype.on = function(t2, e2, n) { return (this._listeners[t2] || (this._listeners[t2] = [])).push({ fn: e2, ctx: n || this }), this; }, e.prototype.off = function(t2, e2) { if (void 0 === t2) this._listeners = {}; else if (void 0 === e2) this._listeners[t2] = []; else for (var n = this._listeners[t2], r = 0; r < n.length; ) n[r].fn === e2 ? n.splice(r, 1) : ++r; return this; }, e.prototype.emit = function(t2) { var e2 = this._listeners[t2]; if (e2) { for (var n = [], r = 1; r < arguments.length; ) n.push(arguments[r++]); for (r = 0; r < e2.length; ) e2[r].fn.apply(e2[r++].ctx, n); } return this; }; }, 945: (t) => { "use strict"; function e(t2) { return "undefined" != typeof Float32Array ? (function() { var e2 = new Float32Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[3]; function i2(t3, r3, i3) { e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3]; } function o2(t3, r3, i3) { e2[0] = t3, r3[i3] = n2[3], r3[i3 + 1] = n2[2], r3[i3 + 2] = n2[1], r3[i3 + 3] = n2[0]; } function a(t3, r3) { return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], e2[0]; } function s(t3, r3) { return n2[3] = t3[r3], n2[2] = t3[r3 + 1], n2[1] = t3[r3 + 2], n2[0] = t3[r3 + 3], e2[0]; } t2.writeFloatLE = r2 ? i2 : o2, t2.writeFloatBE = r2 ? o2 : i2, t2.readFloatLE = r2 ? a : s, t2.readFloatBE = r2 ? s : a; })() : (function() { function e2(t3, e3, n2, r2) { var i2 = e3 < 0 ? 1 : 0; if (i2 && (e3 = -e3), 0 === e3) t3(1 / e3 > 0 ? 0 : 2147483648, n2, r2); else if (isNaN(e3)) t3(2143289344, n2, r2); else if (e3 > 34028234663852886e22) t3((i2 << 31 | 2139095040) >>> 0, n2, r2); else if (e3 < 11754943508222875e-54) t3((i2 << 31 | Math.round(e3 / 1401298464324817e-60)) >>> 0, n2, r2); else { var o2 = Math.floor(Math.log(e3) / Math.LN2); t3((i2 << 31 | o2 + 127 << 23 | 8388607 & Math.round(e3 * Math.pow(2, -o2) * 8388608)) >>> 0, n2, r2); } } function a(t3, e3, n2) { var r2 = t3(e3, n2), i2 = 2 * (r2 >> 31) + 1, o2 = r2 >>> 23 & 255, a2 = 8388607 & r2; return 255 === o2 ? a2 ? NaN : i2 * (1 / 0) : 0 === o2 ? 1401298464324817e-60 * i2 * a2 : i2 * Math.pow(2, o2 - 150) * (a2 + 8388608); } t2.writeFloatLE = e2.bind(null, n), t2.writeFloatBE = e2.bind(null, r), t2.readFloatLE = a.bind(null, i), t2.readFloatBE = a.bind(null, o); })(), "undefined" != typeof Float64Array ? (function() { var e2 = new Float64Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[7]; function i2(t3, r3, i3) { e2[0] = t3, r3[i3] = n2[0], r3[i3 + 1] = n2[1], r3[i3 + 2] = n2[2], r3[i3 + 3] = n2[3], r3[i3 + 4] = n2[4], r3[i3 + 5] = n2[5], r3[i3 + 6] = n2[6], r3[i3 + 7] = n2[7]; } function o2(t3, r3, i3) { e2[0] = t3, r3[i3] = n2[7], r3[i3 + 1] = n2[6], r3[i3 + 2] = n2[5], r3[i3 + 3] = n2[4], r3[i3 + 4] = n2[3], r3[i3 + 5] = n2[2], r3[i3 + 6] = n2[1], r3[i3 + 7] = n2[0]; } function a(t3, r3) { return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], n2[4] = t3[r3 + 4], n2[5] = t3[r3 + 5], n2[6] = t3[r3 + 6], n2[7] = t3[r3 + 7], e2[0]; } function s(t3, r3) { return n2[7] = t3[r3], n2[6] = t3[r3 + 1], n2[5] = t3[r3 + 2], n2[4] = t3[r3 + 3], n2[3] = t3[r3 + 4], n2[2] = t3[r3 + 5], n2[1] = t3[r3 + 6], n2[0] = t3[r3 + 7], e2[0]; } t2.writeDoubleLE = r2 ? i2 : o2, t2.writeDoubleBE = r2 ? o2 : i2, t2.readDoubleLE = r2 ? a : s, t2.readDoubleBE = r2 ? s : a; })() : (function() { function e2(t3, e3, n2, r2, i2, o2) { var a2 = r2 < 0 ? 1 : 0; if (a2 && (r2 = -r2), 0 === r2) t3(0, i2, o2 + e3), t3(1 / r2 > 0 ? 0 : 2147483648, i2, o2 + n2); else if (isNaN(r2)) t3(0, i2, o2 + e3), t3(2146959360, i2, o2 + n2); else if (r2 > 17976931348623157e292) t3(0, i2, o2 + e3), t3((a2 << 31 | 2146435072) >>> 0, i2, o2 + n2); else { var s; if (r2 < 22250738585072014e-324) t3((s = r2 / 5e-324) >>> 0, i2, o2 + e3), t3((a2 << 31 | s / 4294967296) >>> 0, i2, o2 + n2); else { var u = Math.floor(Math.log(r2) / Math.LN2); 1024 === u && (u = 1023), t3(4503599627370496 * (s = r2 * Math.pow(2, -u)) >>> 0, i2, o2 + e3), t3((a2 << 31 | u + 1023 << 20 | 1048576 * s & 1048575) >>> 0, i2, o2 + n2); } } } function a(t3, e3, n2, r2, i2) { var o2 = t3(r2, i2 + e3), a2 = t3(r2, i2 + n2), s = 2 * (a2 >> 31) + 1, u = a2 >>> 20 & 2047, c = 4294967296 * (1048575 & a2) + o2; return 2047 === u ? c ? NaN : s * (1 / 0) : 0 === u ? 5e-324 * s * c : s * Math.pow(2, u - 1075) * (c + 4503599627370496); } t2.writeDoubleLE = e2.bind(null, n, 0, 4), t2.writeDoubleBE = e2.bind(null, r, 4, 0), t2.readDoubleLE = a.bind(null, i, 0, 4), t2.readDoubleBE = a.bind(null, o, 4, 0); })(), t2; } function n(t2, e2, n2) { e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24; } function r(t2, e2, n2) { e2[n2] = t2 >>> 24, e2[n2 + 1] = t2 >>> 16 & 255, e2[n2 + 2] = t2 >>> 8 & 255, e2[n2 + 3] = 255 & t2; } function i(t2, e2) { return (t2[e2] | t2[e2 + 1] << 8 | t2[e2 + 2] << 16 | t2[e2 + 3] << 24) >>> 0; } function o(t2, e2) { return (t2[e2] << 24 | t2[e2 + 1] << 16 | t2[e2 + 2] << 8 | t2[e2 + 3]) >>> 0; } t.exports = e(e); }, 7199: (module) => { "use strict"; function inquire(moduleName) { try { var mod = eval("quire".replace(/^/, "re"))(moduleName); if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (t) { } return null; } module.exports = inquire; }, 6662: (t) => { "use strict"; t.exports = function(t2, e, n) { var r = n || 8192, i = r >>> 1, o = null, a = r; return function(n2) { if (n2 < 1 || n2 > i) return t2(n2); a + n2 > r && (o = t2(r), a = 0); var s = e.call(o, a, a += n2); return 7 & a && (a = 1 + (7 | a)), s; }; }; }, 4997: (t, e) => { "use strict"; var n = e; n.length = function(t2) { for (var e2 = 0, n2 = 0, r = 0; r < t2.length; ++r) (n2 = t2.charCodeAt(r)) < 128 ? e2 += 1 : n2 < 2048 ? e2 += 2 : 55296 == (64512 & n2) && 56320 == (64512 & t2.charCodeAt(r + 1)) ? (++r, e2 += 4) : e2 += 3; return e2; }, n.read = function(t2, e2, n2) { if (n2 - e2 < 1) return ""; for (var r, i = null, o = [], a = 0; e2 < n2; ) (r = t2[e2++]) < 128 ? o[a++] = r : r > 191 && r < 224 ? o[a++] = (31 & r) << 6 | 63 & t2[e2++] : r > 239 && r < 365 ? (r = ((7 & r) << 18 | (63 & t2[e2++]) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++]) - 65536, o[a++] = 55296 + (r >> 10), o[a++] = 56320 + (1023 & r)) : o[a++] = (15 & r) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++], a > 8191 && ((i || (i = [])).push(String.fromCharCode.apply(String, o)), a = 0); return i ? (a && i.push(String.fromCharCode.apply(String, o.slice(0, a))), i.join("")) : String.fromCharCode.apply(String, o.slice(0, a)); }, n.write = function(t2, e2, n2) { for (var r, i, o = n2, a = 0; a < t2.length; ++a) (r = t2.charCodeAt(a)) < 128 ? e2[n2++] = r : r < 2048 ? (e2[n2++] = r >> 6 | 192, e2[n2++] = 63 & r | 128) : 55296 == (64512 & r) && 56320 == (64512 & (i = t2.charCodeAt(a + 1))) ? (r = 65536 + ((1023 & r) << 10) + (1023 & i), ++a, e2[n2++] = r >> 18 | 240, e2[n2++] = r >> 12 & 63 | 128, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128) : (e2[n2++] = r >> 12 | 224, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128); return n2 - o; }; }, 3442: (t, e) => { "use strict"; e.__esModule = true; var n = (function() { function t2(e2) { if (!e2) throw new TypeError("Invalid argument; `value` has no value."); this.value = t2.EMPTY, e2 && t2.isGuid(e2) && (this.value = e2); } return t2.isGuid = function(e2) { var n2 = e2.toString(); return e2 && (e2 instanceof t2 || t2.validator.test(n2)); }, t2.create = function() { return new t2([t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-")); }, t2.createEmpty = function() { return new t2("emptyguid"); }, t2.parse = function(e2) { return new t2(e2); }, t2.raw = function() { return [t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-"); }, t2.gen = function(t3) { for (var e2 = "", n2 = 0; n2 < t3; n2++) e2 += (65536 * (1 + Math.random()) | 0).toString(16).substring(1); return e2; }, t2.prototype.equals = function(e2) { return t2.isGuid(e2) && this.value === e2.toString(); }, t2.prototype.isEmpty = function() { return this.value === t2.EMPTY; }, t2.prototype.toString = function() { return this.value; }, t2.prototype.toJSON = function() { return { value: this.value }; }, t2.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), t2.EMPTY = "00000000-0000-0000-0000-000000000000", t2; })(); e.Guid = n; }, 3720: (t) => { t.exports = n; var e = null; try { e = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; } catch (t2) { } function n(t2, e2, n2) { this.low = 0 | t2, this.high = 0 | e2, this.unsigned = !!n2; } function r(t2) { return true === (t2 && t2.__isLong__); } n.prototype.__isLong__, Object.defineProperty(n.prototype, "__isLong__", { value: true }), n.isLong = r; var i = {}, o = {}; function a(t2, e2) { var n2, r2, a2; return e2 ? (a2 = 0 <= (t2 >>>= 0) && t2 < 256) && (r2 = o[t2]) ? r2 : (n2 = u(t2, (0 | t2) < 0 ? -1 : 0, true), a2 && (o[t2] = n2), n2) : (a2 = -128 <= (t2 |= 0) && t2 < 128) && (r2 = i[t2]) ? r2 : (n2 = u(t2, t2 < 0 ? -1 : 0, false), a2 && (i[t2] = n2), n2); } function s(t2, e2) { if (isNaN(t2)) return e2 ? m2 : b; if (e2) { if (t2 < 0) return m2; if (t2 >= d) return x2; } else { if (t2 <= -h) return T3; if (t2 + 1 >= h) return w; } return t2 < 0 ? s(-t2, e2).neg() : u(t2 % f | 0, t2 / f | 0, e2); } function u(t2, e2, r2) { return new n(t2, e2, r2); } n.fromInt = a, n.fromNumber = s, n.fromBits = u; var c = Math.pow; function l(t2, e2, n2) { if (0 === t2.length) throw Error("empty string"); if ("NaN" === t2 || "Infinity" === t2 || "+Infinity" === t2 || "-Infinity" === t2) return b; if ("number" == typeof e2 ? (n2 = e2, e2 = false) : e2 = !!e2, (n2 = n2 || 10) < 2 || 36 < n2) throw RangeError("radix"); var r2; if ((r2 = t2.indexOf("-")) > 0) throw Error("interior hyphen"); if (0 === r2) return l(t2.substring(1), e2, n2).neg(); for (var i2 = s(c(n2, 8)), o2 = b, a2 = 0; a2 < t2.length; a2 += 8) { var u2 = Math.min(8, t2.length - a2), p2 = parseInt(t2.substring(a2, a2 + u2), n2); if (u2 < 8) { var f2 = s(c(n2, u2)); o2 = o2.mul(f2).add(s(p2)); } else o2 = (o2 = o2.mul(i2)).add(s(p2)); } return o2.unsigned = e2, o2; } function p(t2, e2) { return "number" == typeof t2 ? s(t2, e2) : "string" == typeof t2 ? l(t2, e2) : u(t2.low, t2.high, "boolean" == typeof e2 ? e2 : t2.unsigned); } n.fromString = l, n.fromValue = p; var f = 4294967296, d = f * f, h = d / 2, g = a(1 << 24), b = a(0); n.ZERO = b; var m2 = a(0, true); n.UZERO = m2; var y = a(1); n.ONE = y; var _ = a(1, true); n.UONE = _; var v = a(-1); n.NEG_ONE = v; var w = u(-1, 2147483647, false); n.MAX_VALUE = w; var x2 = u(-1, -1, true); n.MAX_UNSIGNED_VALUE = x2; var T3 = u(0, -2147483648, false); n.MIN_VALUE = T3; var S = n.prototype; S.toInt = function() { return this.unsigned ? this.low >>> 0 : this.low; }, S.toNumber = function() { return this.unsigned ? (this.high >>> 0) * f + (this.low >>> 0) : this.high * f + (this.low >>> 0); }, S.toString = function(t2) { if ((t2 = t2 || 10) < 2 || 36 < t2) throw RangeError("radix"); if (this.isZero()) return "0"; if (this.isNegative()) { if (this.eq(T3)) { var e2 = s(t2), n2 = this.div(e2), r2 = n2.mul(e2).sub(this); return n2.toString(t2) + r2.toInt().toString(t2); } return "-" + this.neg().toString(t2); } for (var i2 = s(c(t2, 6), this.unsigned), o2 = this, a2 = ""; ; ) { var u2 = o2.div(i2), l2 = (o2.sub(u2.mul(i2)).toInt() >>> 0).toString(t2); if ((o2 = u2).isZero()) return l2 + a2; for (; l2.length < 6; ) l2 = "0" + l2; a2 = "" + l2 + a2; } }, S.getHighBits = function() { return this.high; }, S.getHighBitsUnsigned = function() { return this.high >>> 0; }, S.getLowBits = function() { return this.low; }, S.getLowBitsUnsigned = function() { return this.low >>> 0; }, S.getNumBitsAbs = function() { if (this.isNegative()) return this.eq(T3) ? 64 : this.neg().getNumBitsAbs(); for (var t2 = 0 != this.high ? this.high : this.low, e2 = 31; e2 > 0 && 0 == (t2 & 1 << e2); e2--) ; return 0 != this.high ? e2 + 33 : e2 + 1; }, S.isZero = function() { return 0 === this.high && 0 === this.low; }, S.eqz = S.isZero, S.isNegative = function() { return !this.unsigned && this.high < 0; }, S.isPositive = function() { return this.unsigned || this.high >= 0; }, S.isOdd = function() { return 1 == (1 & this.low); }, S.isEven = function() { return 0 == (1 & this.low); }, S.equals = function(t2) { return r(t2) || (t2 = p(t2)), (this.unsigned === t2.unsigned || this.high >>> 31 != 1 || t2.high >>> 31 != 1) && this.high === t2.high && this.low === t2.low; }, S.eq = S.equals, S.notEquals = function(t2) { return !this.eq(t2); }, S.neq = S.notEquals, S.ne = S.notEquals, S.lessThan = function(t2) { return this.comp(t2) < 0; }, S.lt = S.lessThan, S.lessThanOrEqual = function(t2) { return this.comp(t2) <= 0; }, S.lte = S.lessThanOrEqual, S.le = S.lessThanOrEqual, S.greaterThan = function(t2) { return this.comp(t2) > 0; }, S.gt = S.greaterThan, S.greaterThanOrEqual = function(t2) { return this.comp(t2) >= 0; }, S.gte = S.greaterThanOrEqual, S.ge = S.greaterThanOrEqual, S.compare = function(t2) { if (r(t2) || (t2 = p(t2)), this.eq(t2)) return 0; var e2 = this.isNegative(), n2 = t2.isNegative(); return e2 && !n2 ? -1 : !e2 && n2 ? 1 : this.unsigned ? t2.high >>> 0 > this.high >>> 0 || t2.high === this.high && t2.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(t2).isNegative() ? -1 : 1; }, S.comp = S.compare, S.negate = function() { return !this.unsigned && this.eq(T3) ? T3 : this.not().add(y); }, S.neg = S.negate, S.add = function(t2) { r(t2) || (t2 = p(t2)); var e2 = this.high >>> 16, n2 = 65535 & this.high, i2 = this.low >>> 16, o2 = 65535 & this.low, a2 = t2.high >>> 16, s2 = 65535 & t2.high, c2 = t2.low >>> 16, l2 = 0, f2 = 0, d2 = 0, h2 = 0; return d2 += (h2 += o2 + (65535 & t2.low)) >>> 16, f2 += (d2 += i2 + c2) >>> 16, l2 += (f2 += n2 + s2) >>> 16, l2 += e2 + a2, u((d2 &= 65535) << 16 | (h2 &= 65535), (l2 &= 65535) << 16 | (f2 &= 65535), this.unsigned); }, S.subtract = function(t2) { return r(t2) || (t2 = p(t2)), this.add(t2.neg()); }, S.sub = S.subtract, S.multiply = function(t2) { if (this.isZero()) return b; if (r(t2) || (t2 = p(t2)), e) return u(e.mul(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned); if (t2.isZero()) return b; if (this.eq(T3)) return t2.isOdd() ? T3 : b; if (t2.eq(T3)) return this.isOdd() ? T3 : b; if (this.isNegative()) return t2.isNegative() ? this.neg().mul(t2.neg()) : this.neg().mul(t2).neg(); if (t2.isNegative()) return this.mul(t2.neg()).neg(); if (this.lt(g) && t2.lt(g)) return s(this.toNumber() * t2.toNumber(), this.unsigned); var n2 = this.high >>> 16, i2 = 65535 & this.high, o2 = this.low >>> 16, a2 = 65535 & this.low, c2 = t2.high >>> 16, l2 = 65535 & t2.high, f2 = t2.low >>> 16, d2 = 65535 & t2.low, h2 = 0, m3 = 0, y2 = 0, _2 = 0; return y2 += (_2 += a2 * d2) >>> 16, m3 += (y2 += o2 * d2) >>> 16, y2 &= 65535, m3 += (y2 += a2 * f2) >>> 16, h2 += (m3 += i2 * d2) >>> 16, m3 &= 65535, h2 += (m3 += o2 * f2) >>> 16, m3 &= 65535, h2 += (m3 += a2 * l2) >>> 16, h2 += n2 * d2 + i2 * f2 + o2 * l2 + a2 * c2, u((y2 &= 65535) << 16 | (_2 &= 65535), (h2 &= 65535) << 16 | (m3 &= 65535), this.unsigned); }, S.mul = S.multiply, S.divide = function(t2) { if (r(t2) || (t2 = p(t2)), t2.isZero()) throw Error("division by zero"); var n2, i2, o2; if (e) return this.unsigned || -2147483648 !== this.high || -1 !== t2.low || -1 !== t2.high ? u((this.unsigned ? e.div_u : e.div_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this; if (this.isZero()) return this.unsigned ? m2 : b; if (this.unsigned) { if (t2.unsigned || (t2 = t2.toUnsigned()), t2.gt(this)) return m2; if (t2.gt(this.shru(1))) return _; o2 = m2; } else { if (this.eq(T3)) return t2.eq(y) || t2.eq(v) ? T3 : t2.eq(T3) ? y : (n2 = this.shr(1).div(t2).shl(1)).eq(b) ? t2.isNegative() ? y : v : (i2 = this.sub(t2.mul(n2)), o2 = n2.add(i2.div(t2))); if (t2.eq(T3)) return this.unsigned ? m2 : b; if (this.isNegative()) return t2.isNegative() ? this.neg().div(t2.neg()) : this.neg().div(t2).neg(); if (t2.isNegative()) return this.div(t2.neg()).neg(); o2 = b; } for (i2 = this; i2.gte(t2); ) { n2 = Math.max(1, Math.floor(i2.toNumber() / t2.toNumber())); for (var a2 = Math.ceil(Math.log(n2) / Math.LN2), l2 = a2 <= 48 ? 1 : c(2, a2 - 48), f2 = s(n2), d2 = f2.mul(t2); d2.isNegative() || d2.gt(i2); ) d2 = (f2 = s(n2 -= l2, this.unsigned)).mul(t2); f2.isZero() && (f2 = y), o2 = o2.add(f2), i2 = i2.sub(d2); } return o2; }, S.div = S.divide, S.modulo = function(t2) { return r(t2) || (t2 = p(t2)), e ? u((this.unsigned ? e.rem_u : e.rem_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this.sub(this.div(t2).mul(t2)); }, S.mod = S.modulo, S.rem = S.modulo, S.not = function() { return u(~this.low, ~this.high, this.unsigned); }, S.and = function(t2) { return r(t2) || (t2 = p(t2)), u(this.low & t2.low, this.high & t2.high, this.unsigned); }, S.or = function(t2) { return r(t2) || (t2 = p(t2)), u(this.low | t2.low, this.high | t2.high, this.unsigned); }, S.xor = function(t2) { return r(t2) || (t2 = p(t2)), u(this.low ^ t2.low, this.high ^ t2.high, this.unsigned); }, S.shiftLeft = function(t2) { return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low << t2, this.high << t2 | this.low >>> 32 - t2, this.unsigned) : u(0, this.low << t2 - 32, this.unsigned); }, S.shl = S.shiftLeft, S.shiftRight = function(t2) { return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low >>> t2 | this.high << 32 - t2, this.high >> t2, this.unsigned) : u(this.high >> t2 - 32, this.high >= 0 ? 0 : -1, this.unsigned); }, S.shr = S.shiftRight, S.shiftRightUnsigned = function(t2) { if (r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63)) return this; var e2 = this.high; return t2 < 32 ? u(this.low >>> t2 | e2 << 32 - t2, e2 >>> t2, this.unsigned) : u(32 === t2 ? e2 : e2 >>> t2 - 32, 0, this.unsigned); }, S.shru = S.shiftRightUnsigned, S.shr_u = S.shiftRightUnsigned, S.toSigned = function() { return this.unsigned ? u(this.low, this.high, false) : this; }, S.toUnsigned = function() { return this.unsigned ? this : u(this.low, this.high, true); }, S.toBytes = function(t2) { return t2 ? this.toBytesLE() : this.toBytesBE(); }, S.toBytesLE = function() { var t2 = this.high, e2 = this.low; return [255 & e2, e2 >>> 8 & 255, e2 >>> 16 & 255, e2 >>> 24, 255 & t2, t2 >>> 8 & 255, t2 >>> 16 & 255, t2 >>> 24]; }, S.toBytesBE = function() { var t2 = this.high, e2 = this.low; return [t2 >>> 24, t2 >>> 16 & 255, t2 >>> 8 & 255, 255 & t2, e2 >>> 24, e2 >>> 16 & 255, e2 >>> 8 & 255, 255 & e2]; }, n.fromBytes = function(t2, e2, r2) { return r2 ? n.fromBytesLE(t2, e2) : n.fromBytesBE(t2, e2); }, n.fromBytesLE = function(t2, e2) { return new n(t2[0] | t2[1] << 8 | t2[2] << 16 | t2[3] << 24, t2[4] | t2[5] << 8 | t2[6] << 16 | t2[7] << 24, e2); }, n.fromBytesBE = function(t2, e2) { return new n(t2[4] << 24 | t2[5] << 16 | t2[6] << 8 | t2[7], t2[0] << 24 | t2[1] << 16 | t2[2] << 8 | t2[3], e2); }; }, 1446: (t, e, n) => { "use strict"; var r, i, o, a = n(2100), s = a.Reader, u = a.Writer, c = a.util, l = a.roots.default || (a.roots.default = {}); l.onnx = ((o = {}).Version = (r = {}, (i = Object.create(r))[r[0] = "_START_VERSION"] = 0, i[r[1] = "IR_VERSION_2017_10_10"] = 1, i[r[2] = "IR_VERSION_2017_10_30"] = 2, i[r[3] = "IR_VERSION_2017_11_3"] = 3, i[r[4] = "IR_VERSION_2019_1_22"] = 4, i[r[5] = "IR_VERSION"] = 5, i), o.AttributeProto = (function() { function t2(t3) { if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.name = "", t2.prototype.refAttrName = "", t2.prototype.docString = "", t2.prototype.type = 0, t2.prototype.f = 0, t2.prototype.i = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.s = c.newBuffer([]), t2.prototype.t = null, t2.prototype.g = null, t2.prototype.floats = c.emptyArray, t2.prototype.ints = c.emptyArray, t2.prototype.strings = c.emptyArray, t2.prototype.tensors = c.emptyArray, t2.prototype.graphs = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.f && t3.hasOwnProperty("f") && e2.uint32(21).float(t3.f), null != t3.i && t3.hasOwnProperty("i") && e2.uint32(24).int64(t3.i), null != t3.s && t3.hasOwnProperty("s") && e2.uint32(34).bytes(t3.s), null != t3.t && t3.hasOwnProperty("t") && l.onnx.TensorProto.encode(t3.t, e2.uint32(42).fork()).ldelim(), null != t3.g && t3.hasOwnProperty("g") && l.onnx.GraphProto.encode(t3.g, e2.uint32(50).fork()).ldelim(), null != t3.floats && t3.floats.length) { e2.uint32(58).fork(); for (var n2 = 0; n2 < t3.floats.length; ++n2) e2.float(t3.floats[n2]); e2.ldelim(); } if (null != t3.ints && t3.ints.length) { for (e2.uint32(66).fork(), n2 = 0; n2 < t3.ints.length; ++n2) e2.int64(t3.ints[n2]); e2.ldelim(); } if (null != t3.strings && t3.strings.length) for (n2 = 0; n2 < t3.strings.length; ++n2) e2.uint32(74).bytes(t3.strings[n2]); if (null != t3.tensors && t3.tensors.length) for (n2 = 0; n2 < t3.tensors.length; ++n2) l.onnx.TensorProto.encode(t3.tensors[n2], e2.uint32(82).fork()).ldelim(); if (null != t3.graphs && t3.graphs.length) for (n2 = 0; n2 < t3.graphs.length; ++n2) l.onnx.GraphProto.encode(t3.graphs[n2], e2.uint32(90).fork()).ldelim(); return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(106).string(t3.docString), null != t3.type && t3.hasOwnProperty("type") && e2.uint32(160).int32(t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && e2.uint32(170).string(t3.refAttrName), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.AttributeProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.name = t3.string(); break; case 21: r2.refAttrName = t3.string(); break; case 13: r2.docString = t3.string(); break; case 20: r2.type = t3.int32(); break; case 2: r2.f = t3.float(); break; case 3: r2.i = t3.int64(); break; case 4: r2.s = t3.bytes(); break; case 5: r2.t = l.onnx.TensorProto.decode(t3, t3.uint32()); break; case 6: r2.g = l.onnx.GraphProto.decode(t3, t3.uint32()); break; case 7: if (r2.floats && r2.floats.length || (r2.floats = []), 2 == (7 & i2)) for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.floats.push(t3.float()); else r2.floats.push(t3.float()); break; case 8: if (r2.ints && r2.ints.length || (r2.ints = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.ints.push(t3.int64()); else r2.ints.push(t3.int64()); break; case 9: r2.strings && r2.strings.length || (r2.strings = []), r2.strings.push(t3.bytes()); break; case 10: r2.tensors && r2.tensors.length || (r2.tensors = []), r2.tensors.push(l.onnx.TensorProto.decode(t3, t3.uint32())); break; case 11: r2.graphs && r2.graphs.length || (r2.graphs = []), r2.graphs.push(l.onnx.GraphProto.decode(t3, t3.uint32())); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected"; if (null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && !c.isString(t3.refAttrName)) return "refAttrName: string expected"; if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected"; if (null != t3.type && t3.hasOwnProperty("type")) switch (t3.type) { default: return "type: enum value expected"; case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: } if (null != t3.f && t3.hasOwnProperty("f") && "number" != typeof t3.f) return "f: number expected"; if (null != t3.i && t3.hasOwnProperty("i") && !(c.isInteger(t3.i) || t3.i && c.isInteger(t3.i.low) && c.isInteger(t3.i.high))) return "i: integer|Long expected"; if (null != t3.s && t3.hasOwnProperty("s") && !(t3.s && "number" == typeof t3.s.length || c.isString(t3.s))) return "s: buffer expected"; if (null != t3.t && t3.hasOwnProperty("t") && (n2 = l.onnx.TensorProto.verify(t3.t))) return "t." + n2; if (null != t3.g && t3.hasOwnProperty("g") && (n2 = l.onnx.GraphProto.verify(t3.g))) return "g." + n2; if (null != t3.floats && t3.hasOwnProperty("floats")) { if (!Array.isArray(t3.floats)) return "floats: array expected"; for (var e2 = 0; e2 < t3.floats.length; ++e2) if ("number" != typeof t3.floats[e2]) return "floats: number[] expected"; } if (null != t3.ints && t3.hasOwnProperty("ints")) { if (!Array.isArray(t3.ints)) return "ints: array expected"; for (e2 = 0; e2 < t3.ints.length; ++e2) if (!(c.isInteger(t3.ints[e2]) || t3.ints[e2] && c.isInteger(t3.ints[e2].low) && c.isInteger(t3.ints[e2].high))) return "ints: integer|Long[] expected"; } if (null != t3.strings && t3.hasOwnProperty("strings")) { if (!Array.isArray(t3.strings)) return "strings: array expected"; for (e2 = 0; e2 < t3.strings.length; ++e2) if (!(t3.strings[e2] && "number" == typeof t3.strings[e2].length || c.isString(t3.strings[e2]))) return "strings: buffer[] expected"; } if (null != t3.tensors && t3.hasOwnProperty("tensors")) { if (!Array.isArray(t3.tensors)) return "tensors: array expected"; for (e2 = 0; e2 < t3.tensors.length; ++e2) if (n2 = l.onnx.TensorProto.verify(t3.tensors[e2])) return "tensors." + n2; } if (null != t3.graphs && t3.hasOwnProperty("graphs")) { if (!Array.isArray(t3.graphs)) return "graphs: array expected"; for (e2 = 0; e2 < t3.graphs.length; ++e2) { var n2; if (n2 = l.onnx.GraphProto.verify(t3.graphs[e2])) return "graphs." + n2; } } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.AttributeProto) return t3; var e2 = new l.onnx.AttributeProto(); switch (null != t3.name && (e2.name = String(t3.name)), null != t3.refAttrName && (e2.refAttrName = String(t3.refAttrName)), null != t3.docString && (e2.docString = String(t3.docString)), t3.type) { case "UNDEFINED": case 0: e2.type = 0; break; case "FLOAT": case 1: e2.type = 1; break; case "INT": case 2: e2.type = 2; break; case "STRING": case 3: e2.type = 3; break; case "TENSOR": case 4: e2.type = 4; break; case "GRAPH": case 5: e2.type = 5; break; case "FLOATS": case 6: e2.type = 6; break; case "INTS": case 7: e2.type = 7; break; case "STRINGS": case 8: e2.type = 8; break; case "TENSORS": case 9: e2.type = 9; break; case "GRAPHS": case 10: e2.type = 10; } if (null != t3.f && (e2.f = Number(t3.f)), null != t3.i && (c.Long ? (e2.i = c.Long.fromValue(t3.i)).unsigned = false : "string" == typeof t3.i ? e2.i = parseInt(t3.i, 10) : "number" == typeof t3.i ? e2.i = t3.i : "object" == typeof t3.i && (e2.i = new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber())), null != t3.s && ("string" == typeof t3.s ? c.base64.decode(t3.s, e2.s = c.newBuffer(c.base64.length(t3.s)), 0) : t3.s.length && (e2.s = t3.s)), null != t3.t) { if ("object" != typeof t3.t) throw TypeError(".onnx.AttributeProto.t: object expected"); e2.t = l.onnx.TensorProto.fromObject(t3.t); } if (null != t3.g) { if ("object" != typeof t3.g) throw TypeError(".onnx.AttributeProto.g: object expected"); e2.g = l.onnx.GraphProto.fromObject(t3.g); } if (t3.floats) { if (!Array.isArray(t3.floats)) throw TypeError(".onnx.AttributeProto.floats: array expected"); e2.floats = []; for (var n2 = 0; n2 < t3.floats.length; ++n2) e2.floats[n2] = Number(t3.floats[n2]); } if (t3.ints) { if (!Array.isArray(t3.ints)) throw TypeError(".onnx.AttributeProto.ints: array expected"); for (e2.ints = [], n2 = 0; n2 < t3.ints.length; ++n2) c.Long ? (e2.ints[n2] = c.Long.fromValue(t3.ints[n2])).unsigned = false : "string" == typeof t3.ints[n2] ? e2.ints[n2] = parseInt(t3.ints[n2], 10) : "number" == typeof t3.ints[n2] ? e2.ints[n2] = t3.ints[n2] : "object" == typeof t3.ints[n2] && (e2.ints[n2] = new c.LongBits(t3.ints[n2].low >>> 0, t3.ints[n2].high >>> 0).toNumber()); } if (t3.strings) { if (!Array.isArray(t3.strings)) throw TypeError(".onnx.AttributeProto.strings: array expected"); for (e2.strings = [], n2 = 0; n2 < t3.strings.length; ++n2) "string" == typeof t3.strings[n2] ? c.base64.decode(t3.strings[n2], e2.strings[n2] = c.newBuffer(c.base64.length(t3.strings[n2])), 0) : t3.strings[n2].length && (e2.strings[n2] = t3.strings[n2]); } if (t3.tensors) { if (!Array.isArray(t3.tensors)) throw TypeError(".onnx.AttributeProto.tensors: array expected"); for (e2.tensors = [], n2 = 0; n2 < t3.tensors.length; ++n2) { if ("object" != typeof t3.tensors[n2]) throw TypeError(".onnx.AttributeProto.tensors: object expected"); e2.tensors[n2] = l.onnx.TensorProto.fromObject(t3.tensors[n2]); } } if (t3.graphs) { if (!Array.isArray(t3.graphs)) throw TypeError(".onnx.AttributeProto.graphs: array expected"); for (e2.graphs = [], n2 = 0; n2 < t3.graphs.length; ++n2) { if ("object" != typeof t3.graphs[n2]) throw TypeError(".onnx.AttributeProto.graphs: object expected"); e2.graphs[n2] = l.onnx.GraphProto.fromObject(t3.graphs[n2]); } } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.floats = [], n2.ints = [], n2.strings = [], n2.tensors = [], n2.graphs = []), e2.defaults) { if (n2.name = "", n2.f = 0, c.Long) { var r2 = new c.Long(0, 0, false); n2.i = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; } else n2.i = e2.longs === String ? "0" : 0; e2.bytes === String ? n2.s = "" : (n2.s = [], e2.bytes !== Array && (n2.s = c.newBuffer(n2.s))), n2.t = null, n2.g = null, n2.docString = "", n2.type = e2.enums === String ? "UNDEFINED" : 0, n2.refAttrName = ""; } if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.f && t3.hasOwnProperty("f") && (n2.f = e2.json && !isFinite(t3.f) ? String(t3.f) : t3.f), null != t3.i && t3.hasOwnProperty("i") && ("number" == typeof t3.i ? n2.i = e2.longs === String ? String(t3.i) : t3.i : n2.i = e2.longs === String ? c.Long.prototype.toString.call(t3.i) : e2.longs === Number ? new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber() : t3.i), null != t3.s && t3.hasOwnProperty("s") && (n2.s = e2.bytes === String ? c.base64.encode(t3.s, 0, t3.s.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.s) : t3.s), null != t3.t && t3.hasOwnProperty("t") && (n2.t = l.onnx.TensorProto.toObject(t3.t, e2)), null != t3.g && t3.hasOwnProperty("g") && (n2.g = l.onnx.GraphProto.toObject(t3.g, e2)), t3.floats && t3.floats.length) { n2.floats = []; for (var i2 = 0; i2 < t3.floats.length; ++i2) n2.floats[i2] = e2.json && !isFinite(t3.floats[i2]) ? String(t3.floats[i2]) : t3.floats[i2]; } if (t3.ints && t3.ints.length) for (n2.ints = [], i2 = 0; i2 < t3.ints.length; ++i2) "number" == typeof t3.ints[i2] ? n2.ints[i2] = e2.longs === String ? String(t3.ints[i2]) : t3.ints[i2] : n2.ints[i2] = e2.longs === String ? c.Long.prototype.toString.call(t3.ints[i2]) : e2.longs === Number ? new c.LongBits(t3.ints[i2].low >>> 0, t3.ints[i2].high >>> 0).toNumber() : t3.ints[i2]; if (t3.strings && t3.strings.length) for (n2.strings = [], i2 = 0; i2 < t3.strings.length; ++i2) n2.strings[i2] = e2.bytes === String ? c.base64.encode(t3.strings[i2], 0, t3.strings[i2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.strings[i2]) : t3.strings[i2]; if (t3.tensors && t3.tensors.length) for (n2.tensors = [], i2 = 0; i2 < t3.tensors.length; ++i2) n2.tensors[i2] = l.onnx.TensorProto.toObject(t3.tensors[i2], e2); if (t3.graphs && t3.graphs.length) for (n2.graphs = [], i2 = 0; i2 < t3.graphs.length; ++i2) n2.graphs[i2] = l.onnx.GraphProto.toObject(t3.graphs[i2], e2); return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.type && t3.hasOwnProperty("type") && (n2.type = e2.enums === String ? l.onnx.AttributeProto.AttributeType[t3.type] : t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && (n2.refAttrName = t3.refAttrName), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2.AttributeType = (function() { var t3 = {}, e2 = Object.create(t3); return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "INT"] = 2, e2[t3[3] = "STRING"] = 3, e2[t3[4] = "TENSOR"] = 4, e2[t3[5] = "GRAPH"] = 5, e2[t3[6] = "FLOATS"] = 6, e2[t3[7] = "INTS"] = 7, e2[t3[8] = "STRINGS"] = 8, e2[t3[9] = "TENSORS"] = 9, e2[t3[10] = "GRAPHS"] = 10, e2; })(), t2; })(), o.ValueInfoProto = (function() { function t2(t3) { if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.name = "", t2.prototype.type = null, t2.prototype.docString = "", t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { return e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.type && t3.hasOwnProperty("type") && l.onnx.TypeProto.encode(t3.type, e2.uint32(18).fork()).ldelim(), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(26).string(t3.docString), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ValueInfoProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.name = t3.string(); break; case 2: r2.type = l.onnx.TypeProto.decode(t3, t3.uint32()); break; case 3: r2.docString = t3.string(); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected"; if (null != t3.type && t3.hasOwnProperty("type")) { var e2 = l.onnx.TypeProto.verify(t3.type); if (e2) return "type." + e2; } return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.ValueInfoProto) return t3; var e2 = new l.onnx.ValueInfoProto(); if (null != t3.name && (e2.name = String(t3.name)), null != t3.type) { if ("object" != typeof t3.type) throw TypeError(".onnx.ValueInfoProto.type: object expected"); e2.type = l.onnx.TypeProto.fromObject(t3.type); } return null != t3.docString && (e2.docString = String(t3.docString)), e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; return e2.defaults && (n2.name = "", n2.type = null, n2.docString = ""), null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.type && t3.hasOwnProperty("type") && (n2.type = l.onnx.TypeProto.toObject(t3.type, e2)), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.NodeProto = (function() { function t2(t3) { if (this.input = [], this.output = [], this.attribute = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.name = "", t2.prototype.opType = "", t2.prototype.domain = "", t2.prototype.attribute = c.emptyArray, t2.prototype.docString = "", t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.input && t3.input.length) for (var n2 = 0; n2 < t3.input.length; ++n2) e2.uint32(10).string(t3.input[n2]); if (null != t3.output && t3.output.length) for (n2 = 0; n2 < t3.output.length; ++n2) e2.uint32(18).string(t3.output[n2]); if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(26).string(t3.name), null != t3.opType && t3.hasOwnProperty("opType") && e2.uint32(34).string(t3.opType), null != t3.attribute && t3.attribute.length) for (n2 = 0; n2 < t3.attribute.length; ++n2) l.onnx.AttributeProto.encode(t3.attribute[n2], e2.uint32(42).fork()).ldelim(); return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(58).string(t3.domain), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.NodeProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.input && r2.input.length || (r2.input = []), r2.input.push(t3.string()); break; case 2: r2.output && r2.output.length || (r2.output = []), r2.output.push(t3.string()); break; case 3: r2.name = t3.string(); break; case 4: r2.opType = t3.string(); break; case 7: r2.domain = t3.string(); break; case 5: r2.attribute && r2.attribute.length || (r2.attribute = []), r2.attribute.push(l.onnx.AttributeProto.decode(t3, t3.uint32())); break; case 6: r2.docString = t3.string(); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.input && t3.hasOwnProperty("input")) { if (!Array.isArray(t3.input)) return "input: array expected"; for (var e2 = 0; e2 < t3.input.length; ++e2) if (!c.isString(t3.input[e2])) return "input: string[] expected"; } if (null != t3.output && t3.hasOwnProperty("output")) { if (!Array.isArray(t3.output)) return "output: array expected"; for (e2 = 0; e2 < t3.output.length; ++e2) if (!c.isString(t3.output[e2])) return "output: string[] expected"; } if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected"; if (null != t3.opType && t3.hasOwnProperty("opType") && !c.isString(t3.opType)) return "opType: string expected"; if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) return "domain: string expected"; if (null != t3.attribute && t3.hasOwnProperty("attribute")) { if (!Array.isArray(t3.attribute)) return "attribute: array expected"; for (e2 = 0; e2 < t3.attribute.length; ++e2) { var n2 = l.onnx.AttributeProto.verify(t3.attribute[e2]); if (n2) return "attribute." + n2; } } return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.NodeProto) return t3; var e2 = new l.onnx.NodeProto(); if (t3.input) { if (!Array.isArray(t3.input)) throw TypeError(".onnx.NodeProto.input: array expected"); e2.input = []; for (var n2 = 0; n2 < t3.input.length; ++n2) e2.input[n2] = String(t3.input[n2]); } if (t3.output) { if (!Array.isArray(t3.output)) throw TypeError(".onnx.NodeProto.output: array expected"); for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) e2.output[n2] = String(t3.output[n2]); } if (null != t3.name && (e2.name = String(t3.name)), null != t3.opType && (e2.opType = String(t3.opType)), null != t3.domain && (e2.domain = String(t3.domain)), t3.attribute) { if (!Array.isArray(t3.attribute)) throw TypeError(".onnx.NodeProto.attribute: array expected"); for (e2.attribute = [], n2 = 0; n2 < t3.attribute.length; ++n2) { if ("object" != typeof t3.attribute[n2]) throw TypeError(".onnx.NodeProto.attribute: object expected"); e2.attribute[n2] = l.onnx.AttributeProto.fromObject(t3.attribute[n2]); } } return null != t3.docString && (e2.docString = String(t3.docString)), e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.input = [], n2.output = [], n2.attribute = []), e2.defaults && (n2.name = "", n2.opType = "", n2.docString = "", n2.domain = ""), t3.input && t3.input.length) { n2.input = []; for (var r2 = 0; r2 < t3.input.length; ++r2) n2.input[r2] = t3.input[r2]; } if (t3.output && t3.output.length) for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) n2.output[r2] = t3.output[r2]; if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.opType && t3.hasOwnProperty("opType") && (n2.opType = t3.opType), t3.attribute && t3.attribute.length) for (n2.attribute = [], r2 = 0; r2 < t3.attribute.length; ++r2) n2.attribute[r2] = l.onnx.AttributeProto.toObject(t3.attribute[r2], e2); return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.ModelProto = (function() { function t2(t3) { if (this.opsetImport = [], this.metadataProps = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.irVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.opsetImport = c.emptyArray, t2.prototype.producerName = "", t2.prototype.producerVersion = "", t2.prototype.domain = "", t2.prototype.modelVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.docString = "", t2.prototype.graph = null, t2.prototype.metadataProps = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.irVersion && t3.hasOwnProperty("irVersion") && e2.uint32(8).int64(t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && e2.uint32(18).string(t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && e2.uint32(26).string(t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(34).string(t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && e2.uint32(40).int64(t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && l.onnx.GraphProto.encode(t3.graph, e2.uint32(58).fork()).ldelim(), null != t3.opsetImport && t3.opsetImport.length) for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) l.onnx.OperatorSetIdProto.encode(t3.opsetImport[n2], e2.uint32(66).fork()).ldelim(); if (null != t3.metadataProps && t3.metadataProps.length) for (n2 = 0; n2 < t3.metadataProps.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.metadataProps[n2], e2.uint32(114).fork()).ldelim(); return e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ModelProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.irVersion = t3.int64(); break; case 8: r2.opsetImport && r2.opsetImport.length || (r2.opsetImport = []), r2.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t3, t3.uint32())); break; case 2: r2.producerName = t3.string(); break; case 3: r2.producerVersion = t3.string(); break; case 4: r2.domain = t3.string(); break; case 5: r2.modelVersion = t3.int64(); break; case 6: r2.docString = t3.string(); break; case 7: r2.graph = l.onnx.GraphProto.decode(t3, t3.uint32()); break; case 14: r2.metadataProps && r2.metadataProps.length || (r2.metadataProps = []), r2.metadataProps.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && !(c.isInteger(t3.irVersion) || t3.irVersion && c.isInteger(t3.irVersion.low) && c.isInteger(t3.irVersion.high))) return "irVersion: integer|Long expected"; if (null != t3.opsetImport && t3.hasOwnProperty("opsetImport")) { if (!Array.isArray(t3.opsetImport)) return "opsetImport: array expected"; for (var e2 = 0; e2 < t3.opsetImport.length; ++e2) if (n2 = l.onnx.OperatorSetIdProto.verify(t3.opsetImport[e2])) return "opsetImport." + n2; } if (null != t3.producerName && t3.hasOwnProperty("producerName") && !c.isString(t3.producerName)) return "producerName: string expected"; if (null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && !c.isString(t3.producerVersion)) return "producerVersion: string expected"; if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) return "domain: string expected"; if (null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && !(c.isInteger(t3.modelVersion) || t3.modelVersion && c.isInteger(t3.modelVersion.low) && c.isInteger(t3.modelVersion.high))) return "modelVersion: integer|Long expected"; if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected"; if (null != t3.graph && t3.hasOwnProperty("graph") && (n2 = l.onnx.GraphProto.verify(t3.graph))) return "graph." + n2; if (null != t3.metadataProps && t3.hasOwnProperty("metadataProps")) { if (!Array.isArray(t3.metadataProps)) return "metadataProps: array expected"; for (e2 = 0; e2 < t3.metadataProps.length; ++e2) { var n2; if (n2 = l.onnx.StringStringEntryProto.verify(t3.metadataProps[e2])) return "metadataProps." + n2; } } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.ModelProto) return t3; var e2 = new l.onnx.ModelProto(); if (null != t3.irVersion && (c.Long ? (e2.irVersion = c.Long.fromValue(t3.irVersion)).unsigned = false : "string" == typeof t3.irVersion ? e2.irVersion = parseInt(t3.irVersion, 10) : "number" == typeof t3.irVersion ? e2.irVersion = t3.irVersion : "object" == typeof t3.irVersion && (e2.irVersion = new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber())), t3.opsetImport) { if (!Array.isArray(t3.opsetImport)) throw TypeError(".onnx.ModelProto.opsetImport: array expected"); e2.opsetImport = []; for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) { if ("object" != typeof t3.opsetImport[n2]) throw TypeError(".onnx.ModelProto.opsetImport: object expected"); e2.opsetImport[n2] = l.onnx.OperatorSetIdProto.fromObject(t3.opsetImport[n2]); } } if (null != t3.producerName && (e2.producerName = String(t3.producerName)), null != t3.producerVersion && (e2.producerVersion = String(t3.producerVersion)), null != t3.domain && (e2.domain = String(t3.domain)), null != t3.modelVersion && (c.Long ? (e2.modelVersion = c.Long.fromValue(t3.modelVersion)).unsigned = false : "string" == typeof t3.modelVersion ? e2.modelVersion = parseInt(t3.modelVersion, 10) : "number" == typeof t3.modelVersion ? e2.modelVersion = t3.modelVersion : "object" == typeof t3.modelVersion && (e2.modelVersion = new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber())), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.graph) { if ("object" != typeof t3.graph) throw TypeError(".onnx.ModelProto.graph: object expected"); e2.graph = l.onnx.GraphProto.fromObject(t3.graph); } if (t3.metadataProps) { if (!Array.isArray(t3.metadataProps)) throw TypeError(".onnx.ModelProto.metadataProps: array expected"); for (e2.metadataProps = [], n2 = 0; n2 < t3.metadataProps.length; ++n2) { if ("object" != typeof t3.metadataProps[n2]) throw TypeError(".onnx.ModelProto.metadataProps: object expected"); e2.metadataProps[n2] = l.onnx.StringStringEntryProto.fromObject(t3.metadataProps[n2]); } } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.opsetImport = [], n2.metadataProps = []), e2.defaults) { if (c.Long) { var r2 = new c.Long(0, 0, false); n2.irVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; } else n2.irVersion = e2.longs === String ? "0" : 0; n2.producerName = "", n2.producerVersion = "", n2.domain = "", c.Long ? (r2 = new c.Long(0, 0, false), n2.modelVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.modelVersion = e2.longs === String ? "0" : 0, n2.docString = "", n2.graph = null; } if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && ("number" == typeof t3.irVersion ? n2.irVersion = e2.longs === String ? String(t3.irVersion) : t3.irVersion : n2.irVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.irVersion) : e2.longs === Number ? new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber() : t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && (n2.producerName = t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && (n2.producerVersion = t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && ("number" == typeof t3.modelVersion ? n2.modelVersion = e2.longs === String ? String(t3.modelVersion) : t3.modelVersion : n2.modelVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.modelVersion) : e2.longs === Number ? new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber() : t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && (n2.graph = l.onnx.GraphProto.toObject(t3.graph, e2)), t3.opsetImport && t3.opsetImport.length) { n2.opsetImport = []; for (var i2 = 0; i2 < t3.opsetImport.length; ++i2) n2.opsetImport[i2] = l.onnx.OperatorSetIdProto.toObject(t3.opsetImport[i2], e2); } if (t3.metadataProps && t3.metadataProps.length) for (n2.metadataProps = [], i2 = 0; i2 < t3.metadataProps.length; ++i2) n2.metadataProps[i2] = l.onnx.StringStringEntryProto.toObject(t3.metadataProps[i2], e2); return n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.StringStringEntryProto = (function() { function t2(t3) { if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.key = "", t2.prototype.value = "", t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { return e2 || (e2 = u.create()), null != t3.key && t3.hasOwnProperty("key") && e2.uint32(10).string(t3.key), null != t3.value && t3.hasOwnProperty("value") && e2.uint32(18).string(t3.value), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.StringStringEntryProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.key = t3.string(); break; case 2: r2.value = t3.string(); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.key && t3.hasOwnProperty("key") && !c.isString(t3.key) ? "key: string expected" : null != t3.value && t3.hasOwnProperty("value") && !c.isString(t3.value) ? "value: string expected" : null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.StringStringEntryProto) return t3; var e2 = new l.onnx.StringStringEntryProto(); return null != t3.key && (e2.key = String(t3.key)), null != t3.value && (e2.value = String(t3.value)), e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; return e2.defaults && (n2.key = "", n2.value = ""), null != t3.key && t3.hasOwnProperty("key") && (n2.key = t3.key), null != t3.value && t3.hasOwnProperty("value") && (n2.value = t3.value), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.TensorAnnotation = (function() { function t2(t3) { if (this.quantParameterTensorNames = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.tensorName = "", t2.prototype.quantParameterTensorNames = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.tensorName && t3.hasOwnProperty("tensorName") && e2.uint32(10).string(t3.tensorName), null != t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.quantParameterTensorNames[n2], e2.uint32(18).fork()).ldelim(); return e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorAnnotation(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.tensorName = t3.string(); break; case 2: r2.quantParameterTensorNames && r2.quantParameterTensorNames.length || (r2.quantParameterTensorNames = []), r2.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.tensorName && t3.hasOwnProperty("tensorName") && !c.isString(t3.tensorName)) return "tensorName: string expected"; if (null != t3.quantParameterTensorNames && t3.hasOwnProperty("quantParameterTensorNames")) { if (!Array.isArray(t3.quantParameterTensorNames)) return "quantParameterTensorNames: array expected"; for (var e2 = 0; e2 < t3.quantParameterTensorNames.length; ++e2) { var n2 = l.onnx.StringStringEntryProto.verify(t3.quantParameterTensorNames[e2]); if (n2) return "quantParameterTensorNames." + n2; } } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.TensorAnnotation) return t3; var e2 = new l.onnx.TensorAnnotation(); if (null != t3.tensorName && (e2.tensorName = String(t3.tensorName)), t3.quantParameterTensorNames) { if (!Array.isArray(t3.quantParameterTensorNames)) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected"); e2.quantParameterTensorNames = []; for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) { if ("object" != typeof t3.quantParameterTensorNames[n2]) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected"); e2.quantParameterTensorNames[n2] = l.onnx.StringStringEntryProto.fromObject(t3.quantParameterTensorNames[n2]); } } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.quantParameterTensorNames = []), e2.defaults && (n2.tensorName = ""), null != t3.tensorName && t3.hasOwnProperty("tensorName") && (n2.tensorName = t3.tensorName), t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) { n2.quantParameterTensorNames = []; for (var r2 = 0; r2 < t3.quantParameterTensorNames.length; ++r2) n2.quantParameterTensorNames[r2] = l.onnx.StringStringEntryProto.toObject(t3.quantParameterTensorNames[r2], e2); } return n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.GraphProto = (function() { function t2(t3) { if (this.node = [], this.initializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.node = c.emptyArray, t2.prototype.name = "", t2.prototype.initializer = c.emptyArray, t2.prototype.docString = "", t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.valueInfo = c.emptyArray, t2.prototype.quantizationAnnotation = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.node && t3.node.length) for (var n2 = 0; n2 < t3.node.length; ++n2) l.onnx.NodeProto.encode(t3.node[n2], e2.uint32(10).fork()).ldelim(); if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(18).string(t3.name), null != t3.initializer && t3.initializer.length) for (n2 = 0; n2 < t3.initializer.length; ++n2) l.onnx.TensorProto.encode(t3.initializer[n2], e2.uint32(42).fork()).ldelim(); if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(82).string(t3.docString), null != t3.input && t3.input.length) for (n2 = 0; n2 < t3.input.length; ++n2) l.onnx.ValueInfoProto.encode(t3.input[n2], e2.uint32(90).fork()).ldelim(); if (null != t3.output && t3.output.length) for (n2 = 0; n2 < t3.output.length; ++n2) l.onnx.ValueInfoProto.encode(t3.output[n2], e2.uint32(98).fork()).ldelim(); if (null != t3.valueInfo && t3.valueInfo.length) for (n2 = 0; n2 < t3.valueInfo.length; ++n2) l.onnx.ValueInfoProto.encode(t3.valueInfo[n2], e2.uint32(106).fork()).ldelim(); if (null != t3.quantizationAnnotation && t3.quantizationAnnotation.length) for (n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) l.onnx.TensorAnnotation.encode(t3.quantizationAnnotation[n2], e2.uint32(114).fork()).ldelim(); return e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.GraphProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.node && r2.node.length || (r2.node = []), r2.node.push(l.onnx.NodeProto.decode(t3, t3.uint32())); break; case 2: r2.name = t3.string(); break; case 5: r2.initializer && r2.initializer.length || (r2.initializer = []), r2.initializer.push(l.onnx.TensorProto.decode(t3, t3.uint32())); break; case 10: r2.docString = t3.string(); break; case 11: r2.input && r2.input.length || (r2.input = []), r2.input.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); break; case 12: r2.output && r2.output.length || (r2.output = []), r2.output.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); break; case 13: r2.valueInfo && r2.valueInfo.length || (r2.valueInfo = []), r2.valueInfo.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32())); break; case 14: r2.quantizationAnnotation && r2.quantizationAnnotation.length || (r2.quantizationAnnotation = []), r2.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t3, t3.uint32())); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.node && t3.hasOwnProperty("node")) { if (!Array.isArray(t3.node)) return "node: array expected"; for (var e2 = 0; e2 < t3.node.length; ++e2) if (n2 = l.onnx.NodeProto.verify(t3.node[e2])) return "node." + n2; } if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected"; if (null != t3.initializer && t3.hasOwnProperty("initializer")) { if (!Array.isArray(t3.initializer)) return "initializer: array expected"; for (e2 = 0; e2 < t3.initializer.length; ++e2) if (n2 = l.onnx.TensorProto.verify(t3.initializer[e2])) return "initializer." + n2; } if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected"; if (null != t3.input && t3.hasOwnProperty("input")) { if (!Array.isArray(t3.input)) return "input: array expected"; for (e2 = 0; e2 < t3.input.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.input[e2])) return "input." + n2; } if (null != t3.output && t3.hasOwnProperty("output")) { if (!Array.isArray(t3.output)) return "output: array expected"; for (e2 = 0; e2 < t3.output.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.output[e2])) return "output." + n2; } if (null != t3.valueInfo && t3.hasOwnProperty("valueInfo")) { if (!Array.isArray(t3.valueInfo)) return "valueInfo: array expected"; for (e2 = 0; e2 < t3.valueInfo.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.valueInfo[e2])) return "valueInfo." + n2; } if (null != t3.quantizationAnnotation && t3.hasOwnProperty("quantizationAnnotation")) { if (!Array.isArray(t3.quantizationAnnotation)) return "quantizationAnnotation: array expected"; for (e2 = 0; e2 < t3.quantizationAnnotation.length; ++e2) { var n2; if (n2 = l.onnx.TensorAnnotation.verify(t3.quantizationAnnotation[e2])) return "quantizationAnnotation." + n2; } } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.GraphProto) return t3; var e2 = new l.onnx.GraphProto(); if (t3.node) { if (!Array.isArray(t3.node)) throw TypeError(".onnx.GraphProto.node: array expected"); e2.node = []; for (var n2 = 0; n2 < t3.node.length; ++n2) { if ("object" != typeof t3.node[n2]) throw TypeError(".onnx.GraphProto.node: object expected"); e2.node[n2] = l.onnx.NodeProto.fromObject(t3.node[n2]); } } if (null != t3.name && (e2.name = String(t3.name)), t3.initializer) { if (!Array.isArray(t3.initializer)) throw TypeError(".onnx.GraphProto.initializer: array expected"); for (e2.initializer = [], n2 = 0; n2 < t3.initializer.length; ++n2) { if ("object" != typeof t3.initializer[n2]) throw TypeError(".onnx.GraphProto.initializer: object expected"); e2.initializer[n2] = l.onnx.TensorProto.fromObject(t3.initializer[n2]); } } if (null != t3.docString && (e2.docString = String(t3.docString)), t3.input) { if (!Array.isArray(t3.input)) throw TypeError(".onnx.GraphProto.input: array expected"); for (e2.input = [], n2 = 0; n2 < t3.input.length; ++n2) { if ("object" != typeof t3.input[n2]) throw TypeError(".onnx.GraphProto.input: object expected"); e2.input[n2] = l.onnx.ValueInfoProto.fromObject(t3.input[n2]); } } if (t3.output) { if (!Array.isArray(t3.output)) throw TypeError(".onnx.GraphProto.output: array expected"); for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) { if ("object" != typeof t3.output[n2]) throw TypeError(".onnx.GraphProto.output: object expected"); e2.output[n2] = l.onnx.ValueInfoProto.fromObject(t3.output[n2]); } } if (t3.valueInfo) { if (!Array.isArray(t3.valueInfo)) throw TypeError(".onnx.GraphProto.valueInfo: array expected"); for (e2.valueInfo = [], n2 = 0; n2 < t3.valueInfo.length; ++n2) { if ("object" != typeof t3.valueInfo[n2]) throw TypeError(".onnx.GraphProto.valueInfo: object expected"); e2.valueInfo[n2] = l.onnx.ValueInfoProto.fromObject(t3.valueInfo[n2]); } } if (t3.quantizationAnnotation) { if (!Array.isArray(t3.quantizationAnnotation)) throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected"); for (e2.quantizationAnnotation = [], n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) { if ("object" != typeof t3.quantizationAnnotation[n2]) throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected"); e2.quantizationAnnotation[n2] = l.onnx.TensorAnnotation.fromObject(t3.quantizationAnnotation[n2]); } } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.node = [], n2.initializer = [], n2.input = [], n2.output = [], n2.valueInfo = [], n2.quantizationAnnotation = []), e2.defaults && (n2.name = "", n2.docString = ""), t3.node && t3.node.length) { n2.node = []; for (var r2 = 0; r2 < t3.node.length; ++r2) n2.node[r2] = l.onnx.NodeProto.toObject(t3.node[r2], e2); } if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), t3.initializer && t3.initializer.length) for (n2.initializer = [], r2 = 0; r2 < t3.initializer.length; ++r2) n2.initializer[r2] = l.onnx.TensorProto.toObject(t3.initializer[r2], e2); if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.input && t3.input.length) for (n2.input = [], r2 = 0; r2 < t3.input.length; ++r2) n2.input[r2] = l.onnx.ValueInfoProto.toObject(t3.input[r2], e2); if (t3.output && t3.output.length) for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) n2.output[r2] = l.onnx.ValueInfoProto.toObject(t3.output[r2], e2); if (t3.valueInfo && t3.valueInfo.length) for (n2.valueInfo = [], r2 = 0; r2 < t3.valueInfo.length; ++r2) n2.valueInfo[r2] = l.onnx.ValueInfoProto.toObject(t3.valueInfo[r2], e2); if (t3.quantizationAnnotation && t3.quantizationAnnotation.length) for (n2.quantizationAnnotation = [], r2 = 0; r2 < t3.quantizationAnnotation.length; ++r2) n2.quantizationAnnotation[r2] = l.onnx.TensorAnnotation.toObject(t3.quantizationAnnotation[r2], e2); return n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o.TensorProto = (function() { function t2(t3) { if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.dims = c.emptyArray, t2.prototype.dataType = 0, t2.prototype.segment = null, t2.prototype.floatData = c.emptyArray, t2.prototype.int32Data = c.emptyArray, t2.prototype.stringData = c.emptyArray, t2.prototype.int64Data = c.emptyArray, t2.prototype.name = "", t2.prototype.docString = "", t2.prototype.rawData = c.newBuffer([]), t2.prototype.externalData = c.emptyArray, t2.prototype.dataLocation = 0, t2.prototype.doubleData = c.emptyArray, t2.prototype.uint64Data = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.dims && t3.dims.length) { e2.uint32(10).fork(); for (var n2 = 0; n2 < t3.dims.length; ++n2) e2.int64(t3.dims[n2]); e2.ldelim(); } if (null != t3.dataType && t3.hasOwnProperty("dataType") && e2.uint32(16).int32(t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && l.onnx.TensorProto.Segment.encode(t3.segment, e2.uint32(26).fork()).ldelim(), null != t3.floatData && t3.floatData.length) { for (e2.uint32(34).fork(), n2 = 0; n2 < t3.floatData.length; ++n2) e2.float(t3.floatData[n2]); e2.ldelim(); } if (null != t3.int32Data && t3.int32Data.length) { for (e2.uint32(42).fork(), n2 = 0; n2 < t3.int32Data.length; ++n2) e2.int32(t3.int32Data[n2]); e2.ldelim(); } if (null != t3.stringData && t3.stringData.length) for (n2 = 0; n2 < t3.stringData.length; ++n2) e2.uint32(50).bytes(t3.stringData[n2]); if (null != t3.int64Data && t3.int64Data.length) { for (e2.uint32(58).fork(), n2 = 0; n2 < t3.int64Data.length; ++n2) e2.int64(t3.int64Data[n2]); e2.ldelim(); } if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(66).string(t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && e2.uint32(74).bytes(t3.rawData), null != t3.doubleData && t3.doubleData.length) { for (e2.uint32(82).fork(), n2 = 0; n2 < t3.doubleData.length; ++n2) e2.double(t3.doubleData[n2]); e2.ldelim(); } if (null != t3.uint64Data && t3.uint64Data.length) { for (e2.uint32(90).fork(), n2 = 0; n2 < t3.uint64Data.length; ++n2) e2.uint64(t3.uint64Data[n2]); e2.ldelim(); } if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(98).string(t3.docString), null != t3.externalData && t3.externalData.length) for (n2 = 0; n2 < t3.externalData.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.externalData[n2], e2.uint32(106).fork()).ldelim(); return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && e2.uint32(112).int32(t3.dataLocation), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: if (r2.dims && r2.dims.length || (r2.dims = []), 2 == (7 & i2)) for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.dims.push(t3.int64()); else r2.dims.push(t3.int64()); break; case 2: r2.dataType = t3.int32(); break; case 3: r2.segment = l.onnx.TensorProto.Segment.decode(t3, t3.uint32()); break; case 4: if (r2.floatData && r2.floatData.length || (r2.floatData = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.floatData.push(t3.float()); else r2.floatData.push(t3.float()); break; case 5: if (r2.int32Data && r2.int32Data.length || (r2.int32Data = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.int32Data.push(t3.int32()); else r2.int32Data.push(t3.int32()); break; case 6: r2.stringData && r2.stringData.length || (r2.stringData = []), r2.stringData.push(t3.bytes()); break; case 7: if (r2.int64Data && r2.int64Data.length || (r2.int64Data = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.int64Data.push(t3.int64()); else r2.int64Data.push(t3.int64()); break; case 8: r2.name = t3.string(); break; case 12: r2.docString = t3.string(); break; case 9: r2.rawData = t3.bytes(); break; case 13: r2.externalData && r2.externalData.length || (r2.externalData = []), r2.externalData.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32())); break; case 14: r2.dataLocation = t3.int32(); break; case 10: if (r2.doubleData && r2.doubleData.length || (r2.doubleData = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.doubleData.push(t3.double()); else r2.doubleData.push(t3.double()); break; case 11: if (r2.uint64Data && r2.uint64Data.length || (r2.uint64Data = []), 2 == (7 & i2)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.uint64Data.push(t3.uint64()); else r2.uint64Data.push(t3.uint64()); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.dims && t3.hasOwnProperty("dims")) { if (!Array.isArray(t3.dims)) return "dims: array expected"; for (var e2 = 0; e2 < t3.dims.length; ++e2) if (!(c.isInteger(t3.dims[e2]) || t3.dims[e2] && c.isInteger(t3.dims[e2].low) && c.isInteger(t3.dims[e2].high))) return "dims: integer|Long[] expected"; } if (null != t3.dataType && t3.hasOwnProperty("dataType") && !c.isInteger(t3.dataType)) return "dataType: integer expected"; if (null != t3.segment && t3.hasOwnProperty("segment") && (n2 = l.onnx.TensorProto.Segment.verify(t3.segment))) return "segment." + n2; if (null != t3.floatData && t3.hasOwnProperty("floatData")) { if (!Array.isArray(t3.floatData)) return "floatData: array expected"; for (e2 = 0; e2 < t3.floatData.length; ++e2) if ("number" != typeof t3.floatData[e2]) return "floatData: number[] expected"; } if (null != t3.int32Data && t3.hasOwnProperty("int32Data")) { if (!Array.isArray(t3.int32Data)) return "int32Data: array expected"; for (e2 = 0; e2 < t3.int32Data.length; ++e2) if (!c.isInteger(t3.int32Data[e2])) return "int32Data: integer[] expected"; } if (null != t3.stringData && t3.hasOwnProperty("stringData")) { if (!Array.isArray(t3.stringData)) return "stringData: array expected"; for (e2 = 0; e2 < t3.stringData.length; ++e2) if (!(t3.stringData[e2] && "number" == typeof t3.stringData[e2].length || c.isString(t3.stringData[e2]))) return "stringData: buffer[] expected"; } if (null != t3.int64Data && t3.hasOwnProperty("int64Data")) { if (!Array.isArray(t3.int64Data)) return "int64Data: array expected"; for (e2 = 0; e2 < t3.int64Data.length; ++e2) if (!(c.isInteger(t3.int64Data[e2]) || t3.int64Data[e2] && c.isInteger(t3.int64Data[e2].low) && c.isInteger(t3.int64Data[e2].high))) return "int64Data: integer|Long[] expected"; } if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected"; if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected"; if (null != t3.rawData && t3.hasOwnProperty("rawData") && !(t3.rawData && "number" == typeof t3.rawData.length || c.isString(t3.rawData))) return "rawData: buffer expected"; if (null != t3.externalData && t3.hasOwnProperty("externalData")) { if (!Array.isArray(t3.externalData)) return "externalData: array expected"; for (e2 = 0; e2 < t3.externalData.length; ++e2) { var n2; if (n2 = l.onnx.StringStringEntryProto.verify(t3.externalData[e2])) return "externalData." + n2; } } if (null != t3.dataLocation && t3.hasOwnProperty("dataLocation")) switch (t3.dataLocation) { default: return "dataLocation: enum value expected"; case 0: case 1: } if (null != t3.doubleData && t3.hasOwnProperty("doubleData")) { if (!Array.isArray(t3.doubleData)) return "doubleData: array expected"; for (e2 = 0; e2 < t3.doubleData.length; ++e2) if ("number" != typeof t3.doubleData[e2]) return "doubleData: number[] expected"; } if (null != t3.uint64Data && t3.hasOwnProperty("uint64Data")) { if (!Array.isArray(t3.uint64Data)) return "uint64Data: array expected"; for (e2 = 0; e2 < t3.uint64Data.length; ++e2) if (!(c.isInteger(t3.uint64Data[e2]) || t3.uint64Data[e2] && c.isInteger(t3.uint64Data[e2].low) && c.isInteger(t3.uint64Data[e2].high))) return "uint64Data: integer|Long[] expected"; } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.TensorProto) return t3; var e2 = new l.onnx.TensorProto(); if (t3.dims) { if (!Array.isArray(t3.dims)) throw TypeError(".onnx.TensorProto.dims: array expected"); e2.dims = []; for (var n2 = 0; n2 < t3.dims.length; ++n2) c.Long ? (e2.dims[n2] = c.Long.fromValue(t3.dims[n2])).unsigned = false : "string" == typeof t3.dims[n2] ? e2.dims[n2] = parseInt(t3.dims[n2], 10) : "number" == typeof t3.dims[n2] ? e2.dims[n2] = t3.dims[n2] : "object" == typeof t3.dims[n2] && (e2.dims[n2] = new c.LongBits(t3.dims[n2].low >>> 0, t3.dims[n2].high >>> 0).toNumber()); } if (null != t3.dataType && (e2.dataType = 0 | t3.dataType), null != t3.segment) { if ("object" != typeof t3.segment) throw TypeError(".onnx.TensorProto.segment: object expected"); e2.segment = l.onnx.TensorProto.Segment.fromObject(t3.segment); } if (t3.floatData) { if (!Array.isArray(t3.floatData)) throw TypeError(".onnx.TensorProto.floatData: array expected"); for (e2.floatData = [], n2 = 0; n2 < t3.floatData.length; ++n2) e2.floatData[n2] = Number(t3.floatData[n2]); } if (t3.int32Data) { if (!Array.isArray(t3.int32Data)) throw TypeError(".onnx.TensorProto.int32Data: array expected"); for (e2.int32Data = [], n2 = 0; n2 < t3.int32Data.length; ++n2) e2.int32Data[n2] = 0 | t3.int32Data[n2]; } if (t3.stringData) { if (!Array.isArray(t3.stringData)) throw TypeError(".onnx.TensorProto.stringData: array expected"); for (e2.stringData = [], n2 = 0; n2 < t3.stringData.length; ++n2) "string" == typeof t3.stringData[n2] ? c.base64.decode(t3.stringData[n2], e2.stringData[n2] = c.newBuffer(c.base64.length(t3.stringData[n2])), 0) : t3.stringData[n2].length && (e2.stringData[n2] = t3.stringData[n2]); } if (t3.int64Data) { if (!Array.isArray(t3.int64Data)) throw TypeError(".onnx.TensorProto.int64Data: array expected"); for (e2.int64Data = [], n2 = 0; n2 < t3.int64Data.length; ++n2) c.Long ? (e2.int64Data[n2] = c.Long.fromValue(t3.int64Data[n2])).unsigned = false : "string" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = parseInt(t3.int64Data[n2], 10) : "number" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = t3.int64Data[n2] : "object" == typeof t3.int64Data[n2] && (e2.int64Data[n2] = new c.LongBits(t3.int64Data[n2].low >>> 0, t3.int64Data[n2].high >>> 0).toNumber()); } if (null != t3.name && (e2.name = String(t3.name)), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.rawData && ("string" == typeof t3.rawData ? c.base64.decode(t3.rawData, e2.rawData = c.newBuffer(c.base64.length(t3.rawData)), 0) : t3.rawData.length && (e2.rawData = t3.rawData)), t3.externalData) { if (!Array.isArray(t3.externalData)) throw TypeError(".onnx.TensorProto.externalData: array expected"); for (e2.externalData = [], n2 = 0; n2 < t3.externalData.length; ++n2) { if ("object" != typeof t3.externalData[n2]) throw TypeError(".onnx.TensorProto.externalData: object expected"); e2.externalData[n2] = l.onnx.StringStringEntryProto.fromObject(t3.externalData[n2]); } } switch (t3.dataLocation) { case "DEFAULT": case 0: e2.dataLocation = 0; break; case "EXTERNAL": case 1: e2.dataLocation = 1; } if (t3.doubleData) { if (!Array.isArray(t3.doubleData)) throw TypeError(".onnx.TensorProto.doubleData: array expected"); for (e2.doubleData = [], n2 = 0; n2 < t3.doubleData.length; ++n2) e2.doubleData[n2] = Number(t3.doubleData[n2]); } if (t3.uint64Data) { if (!Array.isArray(t3.uint64Data)) throw TypeError(".onnx.TensorProto.uint64Data: array expected"); for (e2.uint64Data = [], n2 = 0; n2 < t3.uint64Data.length; ++n2) c.Long ? (e2.uint64Data[n2] = c.Long.fromValue(t3.uint64Data[n2])).unsigned = true : "string" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = parseInt(t3.uint64Data[n2], 10) : "number" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = t3.uint64Data[n2] : "object" == typeof t3.uint64Data[n2] && (e2.uint64Data[n2] = new c.LongBits(t3.uint64Data[n2].low >>> 0, t3.uint64Data[n2].high >>> 0).toNumber(true)); } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.dims = [], n2.floatData = [], n2.int32Data = [], n2.stringData = [], n2.int64Data = [], n2.doubleData = [], n2.uint64Data = [], n2.externalData = []), e2.defaults && (n2.dataType = 0, n2.segment = null, n2.name = "", e2.bytes === String ? n2.rawData = "" : (n2.rawData = [], e2.bytes !== Array && (n2.rawData = c.newBuffer(n2.rawData))), n2.docString = "", n2.dataLocation = e2.enums === String ? "DEFAULT" : 0), t3.dims && t3.dims.length) { n2.dims = []; for (var r2 = 0; r2 < t3.dims.length; ++r2) "number" == typeof t3.dims[r2] ? n2.dims[r2] = e2.longs === String ? String(t3.dims[r2]) : t3.dims[r2] : n2.dims[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.dims[r2]) : e2.longs === Number ? new c.LongBits(t3.dims[r2].low >>> 0, t3.dims[r2].high >>> 0).toNumber() : t3.dims[r2]; } if (null != t3.dataType && t3.hasOwnProperty("dataType") && (n2.dataType = t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && (n2.segment = l.onnx.TensorProto.Segment.toObject(t3.segment, e2)), t3.floatData && t3.floatData.length) for (n2.floatData = [], r2 = 0; r2 < t3.floatData.length; ++r2) n2.floatData[r2] = e2.json && !isFinite(t3.floatData[r2]) ? String(t3.floatData[r2]) : t3.floatData[r2]; if (t3.int32Data && t3.int32Data.length) for (n2.int32Data = [], r2 = 0; r2 < t3.int32Data.length; ++r2) n2.int32Data[r2] = t3.int32Data[r2]; if (t3.stringData && t3.stringData.length) for (n2.stringData = [], r2 = 0; r2 < t3.stringData.length; ++r2) n2.stringData[r2] = e2.bytes === String ? c.base64.encode(t3.stringData[r2], 0, t3.stringData[r2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.stringData[r2]) : t3.stringData[r2]; if (t3.int64Data && t3.int64Data.length) for (n2.int64Data = [], r2 = 0; r2 < t3.int64Data.length; ++r2) "number" == typeof t3.int64Data[r2] ? n2.int64Data[r2] = e2.longs === String ? String(t3.int64Data[r2]) : t3.int64Data[r2] : n2.int64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.int64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.int64Data[r2].low >>> 0, t3.int64Data[r2].high >>> 0).toNumber() : t3.int64Data[r2]; if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && (n2.rawData = e2.bytes === String ? c.base64.encode(t3.rawData, 0, t3.rawData.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.rawData) : t3.rawData), t3.doubleData && t3.doubleData.length) for (n2.doubleData = [], r2 = 0; r2 < t3.doubleData.length; ++r2) n2.doubleData[r2] = e2.json && !isFinite(t3.doubleData[r2]) ? String(t3.doubleData[r2]) : t3.doubleData[r2]; if (t3.uint64Data && t3.uint64Data.length) for (n2.uint64Data = [], r2 = 0; r2 < t3.uint64Data.length; ++r2) "number" == typeof t3.uint64Data[r2] ? n2.uint64Data[r2] = e2.longs === String ? String(t3.uint64Data[r2]) : t3.uint64Data[r2] : n2.uint64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.uint64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.uint64Data[r2].low >>> 0, t3.uint64Data[r2].high >>> 0).toNumber(true) : t3.uint64Data[r2]; if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.externalData && t3.externalData.length) for (n2.externalData = [], r2 = 0; r2 < t3.externalData.length; ++r2) n2.externalData[r2] = l.onnx.StringStringEntryProto.toObject(t3.externalData[r2], e2); return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && (n2.dataLocation = e2.enums === String ? l.onnx.TensorProto.DataLocation[t3.dataLocation] : t3.dataLocation), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2.DataType = (function() { var t3 = {}, e2 = Object.create(t3); return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "UINT8"] = 2, e2[t3[3] = "INT8"] = 3, e2[t3[4] = "UINT16"] = 4, e2[t3[5] = "INT16"] = 5, e2[t3[6] = "INT32"] = 6, e2[t3[7] = "INT64"] = 7, e2[t3[8] = "STRING"] = 8, e2[t3[9] = "BOOL"] = 9, e2[t3[10] = "FLOAT16"] = 10, e2[t3[11] = "DOUBLE"] = 11, e2[t3[12] = "UINT32"] = 12, e2[t3[13] = "UINT64"] = 13, e2[t3[14] = "COMPLEX64"] = 14, e2[t3[15] = "COMPLEX128"] = 15, e2[t3[16] = "BFLOAT16"] = 16, e2; })(), t2.Segment = (function() { function t3(t4) { if (t4) for (var e2 = Object.keys(t4), n2 = 0; n2 < e2.length; ++n2) null != t4[e2[n2]] && (this[e2[n2]] = t4[e2[n2]]); } return t3.prototype.begin = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.end = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.create = function(e2) { return new t3(e2); }, t3.encode = function(t4, e2) { return e2 || (e2 = u.create()), null != t4.begin && t4.hasOwnProperty("begin") && e2.uint32(8).int64(t4.begin), null != t4.end && t4.hasOwnProperty("end") && e2.uint32(16).int64(t4.end), e2; }, t3.encodeDelimited = function(t4, e2) { return this.encode(t4, e2).ldelim(); }, t3.decode = function(t4, e2) { t4 instanceof s || (t4 = s.create(t4)); for (var n2 = void 0 === e2 ? t4.len : t4.pos + e2, r2 = new l.onnx.TensorProto.Segment(); t4.pos < n2; ) { var i2 = t4.uint32(); switch (i2 >>> 3) { case 1: r2.begin = t4.int64(); break; case 2: r2.end = t4.int64(); break; default: t4.skipType(7 & i2); } } return r2; }, t3.decodeDelimited = function(t4) { return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); }, t3.verify = function(t4) { return "object" != typeof t4 || null === t4 ? "object expected" : null != t4.begin && t4.hasOwnProperty("begin") && !(c.isInteger(t4.begin) || t4.begin && c.isInteger(t4.begin.low) && c.isInteger(t4.begin.high)) ? "begin: integer|Long expected" : null != t4.end && t4.hasOwnProperty("end") && !(c.isInteger(t4.end) || t4.end && c.isInteger(t4.end.low) && c.isInteger(t4.end.high)) ? "end: integer|Long expected" : null; }, t3.fromObject = function(t4) { if (t4 instanceof l.onnx.TensorProto.Segment) return t4; var e2 = new l.onnx.TensorProto.Segment(); return null != t4.begin && (c.Long ? (e2.begin = c.Long.fromValue(t4.begin)).unsigned = false : "string" == typeof t4.begin ? e2.begin = parseInt(t4.begin, 10) : "number" == typeof t4.begin ? e2.begin = t4.begin : "object" == typeof t4.begin && (e2.begin = new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber())), null != t4.end && (c.Long ? (e2.end = c.Long.fromValue(t4.end)).unsigned = false : "string" == typeof t4.end ? e2.end = parseInt(t4.end, 10) : "number" == typeof t4.end ? e2.end = t4.end : "object" == typeof t4.end && (e2.end = new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber())), e2; }, t3.toObject = function(t4, e2) { e2 || (e2 = {}); var n2 = {}; if (e2.defaults) { if (c.Long) { var r2 = new c.Long(0, 0, false); n2.begin = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; } else n2.begin = e2.longs === String ? "0" : 0; c.Long ? (r2 = new c.Long(0, 0, false), n2.end = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.end = e2.longs === String ? "0" : 0; } return null != t4.begin && t4.hasOwnProperty("begin") && ("number" == typeof t4.begin ? n2.begin = e2.longs === String ? String(t4.begin) : t4.begin : n2.begin = e2.longs === String ? c.Long.prototype.toString.call(t4.begin) : e2.longs === Number ? new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber() : t4.begin), null != t4.end && t4.hasOwnProperty("end") && ("number" == typeof t4.end ? n2.end = e2.longs === String ? String(t4.end) : t4.end : n2.end = e2.longs === String ? c.Long.prototype.toString.call(t4.end) : e2.longs === Number ? new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber() : t4.end), n2; }, t3.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t3; })(), t2.DataLocation = (function() { var t3 = {}, e2 = Object.create(t3); return e2[t3[0] = "DEFAULT"] = 0, e2[t3[1] = "EXTERNAL"] = 1, e2; })(), t2; })(), o.TensorShapeProto = (function() { function t2(t3) { if (this.dim = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.dim = c.emptyArray, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { if (e2 || (e2 = u.create()), null != t3.dim && t3.dim.length) for (var n2 = 0; n2 < t3.dim.length; ++n2) l.onnx.TensorShapeProto.Dimension.encode(t3.dim[n2], e2.uint32(10).fork()).ldelim(); return e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorShapeProto(); t3.pos < n2; ) { var i2 = t3.uint32(); i2 >>> 3 == 1 ? (r2.dim && r2.dim.length || (r2.dim = []), r2.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t3, t3.uint32()))) : t3.skipType(7 & i2); } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.dim && t3.hasOwnProperty("dim")) { if (!Array.isArray(t3.dim)) return "dim: array expected"; for (var e2 = 0; e2 < t3.dim.length; ++e2) { var n2 = l.onnx.TensorShapeProto.Dimension.verify(t3.dim[e2]); if (n2) return "dim." + n2; } } return null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.TensorShapeProto) return t3; var e2 = new l.onnx.TensorShapeProto(); if (t3.dim) { if (!Array.isArray(t3.dim)) throw TypeError(".onnx.TensorShapeProto.dim: array expected"); e2.dim = []; for (var n2 = 0; n2 < t3.dim.length; ++n2) { if ("object" != typeof t3.dim[n2]) throw TypeError(".onnx.TensorShapeProto.dim: object expected"); e2.dim[n2] = l.onnx.TensorShapeProto.Dimension.fromObject(t3.dim[n2]); } } return e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if ((e2.arrays || e2.defaults) && (n2.dim = []), t3.dim && t3.dim.length) { n2.dim = []; for (var r2 = 0; r2 < t3.dim.length; ++r2) n2.dim[r2] = l.onnx.TensorShapeProto.Dimension.toObject(t3.dim[r2], e2); } return n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2.Dimension = (function() { function t3(t4) { if (t4) for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]); } var e2; return t3.prototype.dimValue = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.dimParam = "", t3.prototype.denotation = "", Object.defineProperty(t3.prototype, "value", { get: c.oneOfGetter(e2 = ["dimValue", "dimParam"]), set: c.oneOfSetter(e2) }), t3.create = function(e3) { return new t3(e3); }, t3.encode = function(t4, e3) { return e3 || (e3 = u.create()), null != t4.dimValue && t4.hasOwnProperty("dimValue") && e3.uint32(8).int64(t4.dimValue), null != t4.dimParam && t4.hasOwnProperty("dimParam") && e3.uint32(18).string(t4.dimParam), null != t4.denotation && t4.hasOwnProperty("denotation") && e3.uint32(26).string(t4.denotation), e3; }, t3.encodeDelimited = function(t4, e3) { return this.encode(t4, e3).ldelim(); }, t3.decode = function(t4, e3) { t4 instanceof s || (t4 = s.create(t4)); for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TensorShapeProto.Dimension(); t4.pos < n2; ) { var i2 = t4.uint32(); switch (i2 >>> 3) { case 1: r2.dimValue = t4.int64(); break; case 2: r2.dimParam = t4.string(); break; case 3: r2.denotation = t4.string(); break; default: t4.skipType(7 & i2); } } return r2; }, t3.decodeDelimited = function(t4) { return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); }, t3.verify = function(t4) { if ("object" != typeof t4 || null === t4) return "object expected"; var e3 = {}; if (null != t4.dimValue && t4.hasOwnProperty("dimValue") && (e3.value = 1, !(c.isInteger(t4.dimValue) || t4.dimValue && c.isInteger(t4.dimValue.low) && c.isInteger(t4.dimValue.high)))) return "dimValue: integer|Long expected"; if (null != t4.dimParam && t4.hasOwnProperty("dimParam")) { if (1 === e3.value) return "value: multiple values"; if (e3.value = 1, !c.isString(t4.dimParam)) return "dimParam: string expected"; } return null != t4.denotation && t4.hasOwnProperty("denotation") && !c.isString(t4.denotation) ? "denotation: string expected" : null; }, t3.fromObject = function(t4) { if (t4 instanceof l.onnx.TensorShapeProto.Dimension) return t4; var e3 = new l.onnx.TensorShapeProto.Dimension(); return null != t4.dimValue && (c.Long ? (e3.dimValue = c.Long.fromValue(t4.dimValue)).unsigned = false : "string" == typeof t4.dimValue ? e3.dimValue = parseInt(t4.dimValue, 10) : "number" == typeof t4.dimValue ? e3.dimValue = t4.dimValue : "object" == typeof t4.dimValue && (e3.dimValue = new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber())), null != t4.dimParam && (e3.dimParam = String(t4.dimParam)), null != t4.denotation && (e3.denotation = String(t4.denotation)), e3; }, t3.toObject = function(t4, e3) { e3 || (e3 = {}); var n2 = {}; return e3.defaults && (n2.denotation = ""), null != t4.dimValue && t4.hasOwnProperty("dimValue") && ("number" == typeof t4.dimValue ? n2.dimValue = e3.longs === String ? String(t4.dimValue) : t4.dimValue : n2.dimValue = e3.longs === String ? c.Long.prototype.toString.call(t4.dimValue) : e3.longs === Number ? new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber() : t4.dimValue, e3.oneofs && (n2.value = "dimValue")), null != t4.dimParam && t4.hasOwnProperty("dimParam") && (n2.dimParam = t4.dimParam, e3.oneofs && (n2.value = "dimParam")), null != t4.denotation && t4.hasOwnProperty("denotation") && (n2.denotation = t4.denotation), n2; }, t3.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t3; })(), t2; })(), o.TypeProto = (function() { function t2(t3) { if (t3) for (var e3 = Object.keys(t3), n2 = 0; n2 < e3.length; ++n2) null != t3[e3[n2]] && (this[e3[n2]] = t3[e3[n2]]); } var e2; return t2.prototype.tensorType = null, t2.prototype.denotation = "", Object.defineProperty(t2.prototype, "value", { get: c.oneOfGetter(e2 = ["tensorType"]), set: c.oneOfSetter(e2) }), t2.create = function(e3) { return new t2(e3); }, t2.encode = function(t3, e3) { return e3 || (e3 = u.create()), null != t3.tensorType && t3.hasOwnProperty("tensorType") && l.onnx.TypeProto.Tensor.encode(t3.tensorType, e3.uint32(10).fork()).ldelim(), null != t3.denotation && t3.hasOwnProperty("denotation") && e3.uint32(50).string(t3.denotation), e3; }, t2.encodeDelimited = function(t3, e3) { return this.encode(t3, e3).ldelim(); }, t2.decode = function(t3, e3) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e3 ? t3.len : t3.pos + e3, r2 = new l.onnx.TypeProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.tensorType = l.onnx.TypeProto.Tensor.decode(t3, t3.uint32()); break; case 6: r2.denotation = t3.string(); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { if ("object" != typeof t3 || null === t3) return "object expected"; if (null != t3.tensorType && t3.hasOwnProperty("tensorType")) { var e3 = l.onnx.TypeProto.Tensor.verify(t3.tensorType); if (e3) return "tensorType." + e3; } return null != t3.denotation && t3.hasOwnProperty("denotation") && !c.isString(t3.denotation) ? "denotation: string expected" : null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.TypeProto) return t3; var e3 = new l.onnx.TypeProto(); if (null != t3.tensorType) { if ("object" != typeof t3.tensorType) throw TypeError(".onnx.TypeProto.tensorType: object expected"); e3.tensorType = l.onnx.TypeProto.Tensor.fromObject(t3.tensorType); } return null != t3.denotation && (e3.denotation = String(t3.denotation)), e3; }, t2.toObject = function(t3, e3) { e3 || (e3 = {}); var n2 = {}; return e3.defaults && (n2.denotation = ""), null != t3.tensorType && t3.hasOwnProperty("tensorType") && (n2.tensorType = l.onnx.TypeProto.Tensor.toObject(t3.tensorType, e3), e3.oneofs && (n2.value = "tensorType")), null != t3.denotation && t3.hasOwnProperty("denotation") && (n2.denotation = t3.denotation), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2.Tensor = (function() { function t3(t4) { if (t4) for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]); } return t3.prototype.elemType = 0, t3.prototype.shape = null, t3.create = function(e3) { return new t3(e3); }, t3.encode = function(t4, e3) { return e3 || (e3 = u.create()), null != t4.elemType && t4.hasOwnProperty("elemType") && e3.uint32(8).int32(t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && l.onnx.TensorShapeProto.encode(t4.shape, e3.uint32(18).fork()).ldelim(), e3; }, t3.encodeDelimited = function(t4, e3) { return this.encode(t4, e3).ldelim(); }, t3.decode = function(t4, e3) { t4 instanceof s || (t4 = s.create(t4)); for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TypeProto.Tensor(); t4.pos < n2; ) { var i2 = t4.uint32(); switch (i2 >>> 3) { case 1: r2.elemType = t4.int32(); break; case 2: r2.shape = l.onnx.TensorShapeProto.decode(t4, t4.uint32()); break; default: t4.skipType(7 & i2); } } return r2; }, t3.decodeDelimited = function(t4) { return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32()); }, t3.verify = function(t4) { if ("object" != typeof t4 || null === t4) return "object expected"; if (null != t4.elemType && t4.hasOwnProperty("elemType") && !c.isInteger(t4.elemType)) return "elemType: integer expected"; if (null != t4.shape && t4.hasOwnProperty("shape")) { var e3 = l.onnx.TensorShapeProto.verify(t4.shape); if (e3) return "shape." + e3; } return null; }, t3.fromObject = function(t4) { if (t4 instanceof l.onnx.TypeProto.Tensor) return t4; var e3 = new l.onnx.TypeProto.Tensor(); if (null != t4.elemType && (e3.elemType = 0 | t4.elemType), null != t4.shape) { if ("object" != typeof t4.shape) throw TypeError(".onnx.TypeProto.Tensor.shape: object expected"); e3.shape = l.onnx.TensorShapeProto.fromObject(t4.shape); } return e3; }, t3.toObject = function(t4, e3) { e3 || (e3 = {}); var n2 = {}; return e3.defaults && (n2.elemType = 0, n2.shape = null), null != t4.elemType && t4.hasOwnProperty("elemType") && (n2.elemType = t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && (n2.shape = l.onnx.TensorShapeProto.toObject(t4.shape, e3)), n2; }, t3.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t3; })(), t2; })(), o.OperatorSetIdProto = (function() { function t2(t3) { if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]); } return t2.prototype.domain = "", t2.prototype.version = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.create = function(e2) { return new t2(e2); }, t2.encode = function(t3, e2) { return e2 || (e2 = u.create()), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(10).string(t3.domain), null != t3.version && t3.hasOwnProperty("version") && e2.uint32(16).int64(t3.version), e2; }, t2.encodeDelimited = function(t3, e2) { return this.encode(t3, e2).ldelim(); }, t2.decode = function(t3, e2) { t3 instanceof s || (t3 = s.create(t3)); for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.OperatorSetIdProto(); t3.pos < n2; ) { var i2 = t3.uint32(); switch (i2 >>> 3) { case 1: r2.domain = t3.string(); break; case 2: r2.version = t3.int64(); break; default: t3.skipType(7 & i2); } } return r2; }, t2.decodeDelimited = function(t3) { return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32()); }, t2.verify = function(t3) { return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain) ? "domain: string expected" : null != t3.version && t3.hasOwnProperty("version") && !(c.isInteger(t3.version) || t3.version && c.isInteger(t3.version.low) && c.isInteger(t3.version.high)) ? "version: integer|Long expected" : null; }, t2.fromObject = function(t3) { if (t3 instanceof l.onnx.OperatorSetIdProto) return t3; var e2 = new l.onnx.OperatorSetIdProto(); return null != t3.domain && (e2.domain = String(t3.domain)), null != t3.version && (c.Long ? (e2.version = c.Long.fromValue(t3.version)).unsigned = false : "string" == typeof t3.version ? e2.version = parseInt(t3.version, 10) : "number" == typeof t3.version ? e2.version = t3.version : "object" == typeof t3.version && (e2.version = new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber())), e2; }, t2.toObject = function(t3, e2) { e2 || (e2 = {}); var n2 = {}; if (e2.defaults) if (n2.domain = "", c.Long) { var r2 = new c.Long(0, 0, false); n2.version = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2; } else n2.version = e2.longs === String ? "0" : 0; return null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.version && t3.hasOwnProperty("version") && ("number" == typeof t3.version ? n2.version = e2.longs === String ? String(t3.version) : t3.version : n2.version = e2.longs === String ? c.Long.prototype.toString.call(t3.version) : e2.longs === Number ? new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber() : t3.version), n2; }, t2.prototype.toJSON = function() { return this.constructor.toObject(this, a.util.toJSONOptions); }, t2; })(), o), t.exports = l; }, 2100: (t, e, n) => { "use strict"; t.exports = n(9482); }, 9482: (t, e, n) => { "use strict"; var r = e; function i() { r.util._configure(), r.Writer._configure(r.BufferWriter), r.Reader._configure(r.BufferReader); } r.build = "minimal", r.Writer = n(1173), r.BufferWriter = n(3155), r.Reader = n(1408), r.BufferReader = n(593), r.util = n(9693), r.rpc = n(5994), r.roots = n(5054), r.configure = i, i(); }, 1408: (t, e, n) => { "use strict"; t.exports = u; var r, i = n(9693), o = i.LongBits, a = i.utf8; function s(t2, e2) { return RangeError("index out of range: " + t2.pos + " + " + (e2 || 1) + " > " + t2.len); } function u(t2) { this.buf = t2, this.pos = 0, this.len = t2.length; } var c, l = "undefined" != typeof Uint8Array ? function(t2) { if (t2 instanceof Uint8Array || Array.isArray(t2)) return new u(t2); throw Error("illegal buffer"); } : function(t2) { if (Array.isArray(t2)) return new u(t2); throw Error("illegal buffer"); }, p = function() { return i.Buffer ? function(t2) { return (u.create = function(t3) { return i.Buffer.isBuffer(t3) ? new r(t3) : l(t3); })(t2); } : l; }; function f() { var t2 = new o(0, 0), e2 = 0; if (!(this.len - this.pos > 4)) { for (; e2 < 3; ++e2) { if (this.pos >= this.len) throw s(this); if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) return t2; } return t2.lo = (t2.lo | (127 & this.buf[this.pos++]) << 7 * e2) >>> 0, t2; } for (; e2 < 4; ++e2) if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) return t2; if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 28) >>> 0, t2.hi = (t2.hi | (127 & this.buf[this.pos]) >> 4) >>> 0, this.buf[this.pos++] < 128) return t2; if (e2 = 0, this.len - this.pos > 4) { for (; e2 < 5; ++e2) if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) return t2; } else for (; e2 < 5; ++e2) { if (this.pos >= this.len) throw s(this); if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) return t2; } throw Error("invalid varint encoding"); } function d(t2, e2) { return (t2[e2 - 4] | t2[e2 - 3] << 8 | t2[e2 - 2] << 16 | t2[e2 - 1] << 24) >>> 0; } function h() { if (this.pos + 8 > this.len) throw s(this, 8); return new o(d(this.buf, this.pos += 4), d(this.buf, this.pos += 4)); } u.create = p(), u.prototype._slice = i.Array.prototype.subarray || i.Array.prototype.slice, u.prototype.uint32 = (c = 4294967295, function() { if (c = (127 & this.buf[this.pos]) >>> 0, this.buf[this.pos++] < 128) return c; if (c = (c | (127 & this.buf[this.pos]) << 7) >>> 0, this.buf[this.pos++] < 128) return c; if (c = (c | (127 & this.buf[this.pos]) << 14) >>> 0, this.buf[this.pos++] < 128) return c; if (c = (c | (127 & this.buf[this.pos]) << 21) >>> 0, this.buf[this.pos++] < 128) return c; if (c = (c | (15 & this.buf[this.pos]) << 28) >>> 0, this.buf[this.pos++] < 128) return c; if ((this.pos += 5) > this.len) throw this.pos = this.len, s(this, 10); return c; }), u.prototype.int32 = function() { return 0 | this.uint32(); }, u.prototype.sint32 = function() { var t2 = this.uint32(); return t2 >>> 1 ^ -(1 & t2) | 0; }, u.prototype.bool = function() { return 0 !== this.uint32(); }, u.prototype.fixed32 = function() { if (this.pos + 4 > this.len) throw s(this, 4); return d(this.buf, this.pos += 4); }, u.prototype.sfixed32 = function() { if (this.pos + 4 > this.len) throw s(this, 4); return 0 | d(this.buf, this.pos += 4); }, u.prototype.float = function() { if (this.pos + 4 > this.len) throw s(this, 4); var t2 = i.float.readFloatLE(this.buf, this.pos); return this.pos += 4, t2; }, u.prototype.double = function() { if (this.pos + 8 > this.len) throw s(this, 4); var t2 = i.float.readDoubleLE(this.buf, this.pos); return this.pos += 8, t2; }, u.prototype.bytes = function() { var t2 = this.uint32(), e2 = this.pos, n2 = this.pos + t2; if (n2 > this.len) throw s(this, t2); return this.pos += t2, Array.isArray(this.buf) ? this.buf.slice(e2, n2) : e2 === n2 ? new this.buf.constructor(0) : this._slice.call(this.buf, e2, n2); }, u.prototype.string = function() { var t2 = this.bytes(); return a.read(t2, 0, t2.length); }, u.prototype.skip = function(t2) { if ("number" == typeof t2) { if (this.pos + t2 > this.len) throw s(this, t2); this.pos += t2; } else do { if (this.pos >= this.len) throw s(this); } while (128 & this.buf[this.pos++]); return this; }, u.prototype.skipType = function(t2) { switch (t2) { case 0: this.skip(); break; case 1: this.skip(8); break; case 2: this.skip(this.uint32()); break; case 3: for (; 4 != (t2 = 7 & this.uint32()); ) this.skipType(t2); break; case 5: this.skip(4); break; default: throw Error("invalid wire type " + t2 + " at offset " + this.pos); } return this; }, u._configure = function(t2) { r = t2, u.create = p(), r._configure(); var e2 = i.Long ? "toLong" : "toNumber"; i.merge(u.prototype, { int64: function() { return f.call(this)[e2](false); }, uint64: function() { return f.call(this)[e2](true); }, sint64: function() { return f.call(this).zzDecode()[e2](false); }, fixed64: function() { return h.call(this)[e2](true); }, sfixed64: function() { return h.call(this)[e2](false); } }); }; }, 593: (t, e, n) => { "use strict"; t.exports = o; var r = n(1408); (o.prototype = Object.create(r.prototype)).constructor = o; var i = n(9693); function o(t2) { r.call(this, t2); } o._configure = function() { i.Buffer && (o.prototype._slice = i.Buffer.prototype.slice); }, o.prototype.string = function() { var t2 = this.uint32(); return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + t2, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + t2, this.len)); }, o._configure(); }, 5054: (t) => { "use strict"; t.exports = {}; }, 5994: (t, e, n) => { "use strict"; e.Service = n(7948); }, 7948: (t, e, n) => { "use strict"; t.exports = i; var r = n(9693); function i(t2, e2, n2) { if ("function" != typeof t2) throw TypeError("rpcImpl must be a function"); r.EventEmitter.call(this), this.rpcImpl = t2, this.requestDelimited = Boolean(e2), this.responseDelimited = Boolean(n2); } (i.prototype = Object.create(r.EventEmitter.prototype)).constructor = i, i.prototype.rpcCall = function t2(e2, n2, i2, o, a) { if (!o) throw TypeError("request must be specified"); var s = this; if (!a) return r.asPromise(t2, s, e2, n2, i2, o); if (s.rpcImpl) try { return s.rpcImpl(e2, n2[s.requestDelimited ? "encodeDelimited" : "encode"](o).finish(), (function(t3, n3) { if (t3) return s.emit("error", t3, e2), a(t3); if (null !== n3) { if (!(n3 instanceof i2)) try { n3 = i2[s.responseDelimited ? "decodeDelimited" : "decode"](n3); } catch (t4) { return s.emit("error", t4, e2), a(t4); } return s.emit("data", n3, e2), a(null, n3); } s.end(true); })); } catch (t3) { return s.emit("error", t3, e2), void setTimeout((function() { a(t3); }), 0); } else setTimeout((function() { a(Error("already ended")); }), 0); }, i.prototype.end = function(t2) { return this.rpcImpl && (t2 || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this; }; }, 1945: (t, e, n) => { "use strict"; t.exports = i; var r = n(9693); function i(t2, e2) { this.lo = t2 >>> 0, this.hi = e2 >>> 0; } var o = i.zero = new i(0, 0); o.toNumber = function() { return 0; }, o.zzEncode = o.zzDecode = function() { return this; }, o.length = function() { return 1; }; var a = i.zeroHash = "\0\0\0\0\0\0\0\0"; i.fromNumber = function(t2) { if (0 === t2) return o; var e2 = t2 < 0; e2 && (t2 = -t2); var n2 = t2 >>> 0, r2 = (t2 - n2) / 4294967296 >>> 0; return e2 && (r2 = ~r2 >>> 0, n2 = ~n2 >>> 0, ++n2 > 4294967295 && (n2 = 0, ++r2 > 4294967295 && (r2 = 0))), new i(n2, r2); }, i.from = function(t2) { if ("number" == typeof t2) return i.fromNumber(t2); if (r.isString(t2)) { if (!r.Long) return i.fromNumber(parseInt(t2, 10)); t2 = r.Long.fromString(t2); } return t2.low || t2.high ? new i(t2.low >>> 0, t2.high >>> 0) : o; }, i.prototype.toNumber = function(t2) { if (!t2 && this.hi >>> 31) { var e2 = 1 + ~this.lo >>> 0, n2 = ~this.hi >>> 0; return e2 || (n2 = n2 + 1 >>> 0), -(e2 + 4294967296 * n2); } return this.lo + 4294967296 * this.hi; }, i.prototype.toLong = function(t2) { return r.Long ? new r.Long(0 | this.lo, 0 | this.hi, Boolean(t2)) : { low: 0 | this.lo, high: 0 | this.hi, unsigned: Boolean(t2) }; }; var s = String.prototype.charCodeAt; i.fromHash = function(t2) { return t2 === a ? o : new i((s.call(t2, 0) | s.call(t2, 1) << 8 | s.call(t2, 2) << 16 | s.call(t2, 3) << 24) >>> 0, (s.call(t2, 4) | s.call(t2, 5) << 8 | s.call(t2, 6) << 16 | s.call(t2, 7) << 24) >>> 0); }, i.prototype.toHash = function() { return String.fromCharCode(255 & this.lo, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, 255 & this.hi, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24); }, i.prototype.zzEncode = function() { var t2 = this.hi >> 31; return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ t2) >>> 0, this.lo = (this.lo << 1 ^ t2) >>> 0, this; }, i.prototype.zzDecode = function() { var t2 = -(1 & this.lo); return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ t2) >>> 0, this.hi = (this.hi >>> 1 ^ t2) >>> 0, this; }, i.prototype.length = function() { var t2 = this.lo, e2 = (this.lo >>> 28 | this.hi << 4) >>> 0, n2 = this.hi >>> 24; return 0 === n2 ? 0 === e2 ? t2 < 16384 ? t2 < 128 ? 1 : 2 : t2 < 2097152 ? 3 : 4 : e2 < 16384 ? e2 < 128 ? 5 : 6 : e2 < 2097152 ? 7 : 8 : n2 < 128 ? 9 : 10; }; }, 9693: function(t, e, n) { "use strict"; var r = e; function i(t2, e2, n2) { for (var r2 = Object.keys(e2), i2 = 0; i2 < r2.length; ++i2) void 0 !== t2[r2[i2]] && n2 || (t2[r2[i2]] = e2[r2[i2]]); return t2; } function o(t2) { function e2(t3, n2) { if (!(this instanceof e2)) return new e2(t3, n2); Object.defineProperty(this, "message", { get: function() { return t3; } }), Error.captureStackTrace ? Error.captureStackTrace(this, e2) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), n2 && i(this, n2); } return (e2.prototype = Object.create(Error.prototype)).constructor = e2, Object.defineProperty(e2.prototype, "name", { get: function() { return t2; } }), e2.prototype.toString = function() { return this.name + ": " + this.message; }, e2; } r.asPromise = n(4537), r.base64 = n(7419), r.EventEmitter = n(9211), r.float = n(945), r.inquire = n(7199), r.utf8 = n(4997), r.pool = n(6662), r.LongBits = n(1945), r.isNode = Boolean(void 0 !== n.g && n.g && n.g.process && n.g.process.versions && n.g.process.versions.node), r.global = r.isNode && n.g || "undefined" != typeof window && window || "undefined" != typeof self && self || this, r.emptyArray = Object.freeze ? Object.freeze([]) : [], r.emptyObject = Object.freeze ? Object.freeze({}) : {}, r.isInteger = Number.isInteger || function(t2) { return "number" == typeof t2 && isFinite(t2) && Math.floor(t2) === t2; }, r.isString = function(t2) { return "string" == typeof t2 || t2 instanceof String; }, r.isObject = function(t2) { return t2 && "object" == typeof t2; }, r.isset = r.isSet = function(t2, e2) { var n2 = t2[e2]; return !(null == n2 || !t2.hasOwnProperty(e2)) && ("object" != typeof n2 || (Array.isArray(n2) ? n2.length : Object.keys(n2).length) > 0); }, r.Buffer = (function() { try { var t2 = r.inquire("buffer").Buffer; return t2.prototype.utf8Write ? t2 : null; } catch (t3) { return null; } })(), r._Buffer_from = null, r._Buffer_allocUnsafe = null, r.newBuffer = function(t2) { return "number" == typeof t2 ? r.Buffer ? r._Buffer_allocUnsafe(t2) : new r.Array(t2) : r.Buffer ? r._Buffer_from(t2) : "undefined" == typeof Uint8Array ? t2 : new Uint8Array(t2); }, r.Array = "undefined" != typeof Uint8Array ? Uint8Array : Array, r.Long = r.global.dcodeIO && r.global.dcodeIO.Long || r.global.Long || r.inquire("long"), r.key2Re = /^true|false|0|1$/, r.key32Re = /^-?(?:0|[1-9][0-9]*)$/, r.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/, r.longToHash = function(t2) { return t2 ? r.LongBits.from(t2).toHash() : r.LongBits.zeroHash; }, r.longFromHash = function(t2, e2) { var n2 = r.LongBits.fromHash(t2); return r.Long ? r.Long.fromBits(n2.lo, n2.hi, e2) : n2.toNumber(Boolean(e2)); }, r.merge = i, r.lcFirst = function(t2) { return t2.charAt(0).toLowerCase() + t2.substring(1); }, r.newError = o, r.ProtocolError = o("ProtocolError"), r.oneOfGetter = function(t2) { for (var e2 = {}, n2 = 0; n2 < t2.length; ++n2) e2[t2[n2]] = 1; return function() { for (var t3 = Object.keys(this), n3 = t3.length - 1; n3 > -1; --n3) if (1 === e2[t3[n3]] && void 0 !== this[t3[n3]] && null !== this[t3[n3]]) return t3[n3]; }; }, r.oneOfSetter = function(t2) { return function(e2) { for (var n2 = 0; n2 < t2.length; ++n2) t2[n2] !== e2 && delete this[t2[n2]]; }; }, r.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }, r._configure = function() { var t2 = r.Buffer; t2 ? (r._Buffer_from = t2.from !== Uint8Array.from && t2.from || function(e2, n2) { return new t2(e2, n2); }, r._Buffer_allocUnsafe = t2.allocUnsafe || function(e2) { return new t2(e2); }) : r._Buffer_from = r._Buffer_allocUnsafe = null; }; }, 1173: (t, e, n) => { "use strict"; t.exports = p; var r, i = n(9693), o = i.LongBits, a = i.base64, s = i.utf8; function u(t2, e2, n2) { this.fn = t2, this.len = e2, this.next = void 0, this.val = n2; } function c() { } function l(t2) { this.head = t2.head, this.tail = t2.tail, this.len = t2.len, this.next = t2.states; } function p() { this.len = 0, this.head = new u(c, 0, 0), this.tail = this.head, this.states = null; } var f = function() { return i.Buffer ? function() { return (p.create = function() { return new r(); })(); } : function() { return new p(); }; }; function d(t2, e2, n2) { e2[n2] = 255 & t2; } function h(t2, e2) { this.len = t2, this.next = void 0, this.val = e2; } function g(t2, e2, n2) { for (; t2.hi; ) e2[n2++] = 127 & t2.lo | 128, t2.lo = (t2.lo >>> 7 | t2.hi << 25) >>> 0, t2.hi >>>= 7; for (; t2.lo > 127; ) e2[n2++] = 127 & t2.lo | 128, t2.lo = t2.lo >>> 7; e2[n2++] = t2.lo; } function b(t2, e2, n2) { e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24; } p.create = f(), p.alloc = function(t2) { return new i.Array(t2); }, i.Array !== Array && (p.alloc = i.pool(p.alloc, i.Array.prototype.subarray)), p.prototype._push = function(t2, e2, n2) { return this.tail = this.tail.next = new u(t2, e2, n2), this.len += e2, this; }, h.prototype = Object.create(u.prototype), h.prototype.fn = function(t2, e2, n2) { for (; t2 > 127; ) e2[n2++] = 127 & t2 | 128, t2 >>>= 7; e2[n2] = t2; }, p.prototype.uint32 = function(t2) { return this.len += (this.tail = this.tail.next = new h((t2 >>>= 0) < 128 ? 1 : t2 < 16384 ? 2 : t2 < 2097152 ? 3 : t2 < 268435456 ? 4 : 5, t2)).len, this; }, p.prototype.int32 = function(t2) { return t2 < 0 ? this._push(g, 10, o.fromNumber(t2)) : this.uint32(t2); }, p.prototype.sint32 = function(t2) { return this.uint32((t2 << 1 ^ t2 >> 31) >>> 0); }, p.prototype.uint64 = function(t2) { var e2 = o.from(t2); return this._push(g, e2.length(), e2); }, p.prototype.int64 = p.prototype.uint64, p.prototype.sint64 = function(t2) { var e2 = o.from(t2).zzEncode(); return this._push(g, e2.length(), e2); }, p.prototype.bool = function(t2) { return this._push(d, 1, t2 ? 1 : 0); }, p.prototype.fixed32 = function(t2) { return this._push(b, 4, t2 >>> 0); }, p.prototype.sfixed32 = p.prototype.fixed32, p.prototype.fixed64 = function(t2) { var e2 = o.from(t2); return this._push(b, 4, e2.lo)._push(b, 4, e2.hi); }, p.prototype.sfixed64 = p.prototype.fixed64, p.prototype.float = function(t2) { return this._push(i.float.writeFloatLE, 4, t2); }, p.prototype.double = function(t2) { return this._push(i.float.writeDoubleLE, 8, t2); }; var m2 = i.Array.prototype.set ? function(t2, e2, n2) { e2.set(t2, n2); } : function(t2, e2, n2) { for (var r2 = 0; r2 < t2.length; ++r2) e2[n2 + r2] = t2[r2]; }; p.prototype.bytes = function(t2) { var e2 = t2.length >>> 0; if (!e2) return this._push(d, 1, 0); if (i.isString(t2)) { var n2 = p.alloc(e2 = a.length(t2)); a.decode(t2, n2, 0), t2 = n2; } return this.uint32(e2)._push(m2, e2, t2); }, p.prototype.string = function(t2) { var e2 = s.length(t2); return e2 ? this.uint32(e2)._push(s.write, e2, t2) : this._push(d, 1, 0); }, p.prototype.fork = function() { return this.states = new l(this), this.head = this.tail = new u(c, 0, 0), this.len = 0, this; }, p.prototype.reset = function() { return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new u(c, 0, 0), this.len = 0), this; }, p.prototype.ldelim = function() { var t2 = this.head, e2 = this.tail, n2 = this.len; return this.reset().uint32(n2), n2 && (this.tail.next = t2.next, this.tail = e2, this.len += n2), this; }, p.prototype.finish = function() { for (var t2 = this.head.next, e2 = this.constructor.alloc(this.len), n2 = 0; t2; ) t2.fn(t2.val, e2, n2), n2 += t2.len, t2 = t2.next; return e2; }, p._configure = function(t2) { r = t2, p.create = f(), r._configure(); }; }, 3155: (t, e, n) => { "use strict"; t.exports = o; var r = n(1173); (o.prototype = Object.create(r.prototype)).constructor = o; var i = n(9693); function o() { r.call(this); } function a(t2, e2, n2) { t2.length < 40 ? i.utf8.write(t2, e2, n2) : e2.utf8Write ? e2.utf8Write(t2, n2) : e2.write(t2, n2); } o._configure = function() { o.alloc = i._Buffer_allocUnsafe, o.writeBytesBuffer = i.Buffer && i.Buffer.prototype instanceof Uint8Array && "set" === i.Buffer.prototype.set.name ? function(t2, e2, n2) { e2.set(t2, n2); } : function(t2, e2, n2) { if (t2.copy) t2.copy(e2, n2, 0, t2.length); else for (var r2 = 0; r2 < t2.length; ) e2[n2++] = t2[r2++]; }; }, o.prototype.bytes = function(t2) { i.isString(t2) && (t2 = i._Buffer_from(t2, "base64")); var e2 = t2.length >>> 0; return this.uint32(e2), e2 && this._push(o.writeBytesBuffer, e2, t2), this; }, o.prototype.string = function(t2) { var e2 = i.Buffer.byteLength(t2); return this.uint32(e2), e2 && this._push(a, e2, t2), this; }, o._configure(); }, 7714: (t, e, n) => { "use strict"; e.R = void 0; const r = n(6919), i = n(7448); e.R = new class { async init() { } async createSessionHandler(t2, e2) { const n2 = new r.Session(e2); return await n2.loadModel(t2), new i.OnnxjsSessionHandler(n2); } }(); }, 4200: (t, e, n) => { "use strict"; e.c8 = e.rX = void 0; const r = n(1670), i = n(5381), o = n(2157), a = n(2306); e.rX = () => { if (("number" != typeof r.env.wasm.initTimeout || r.env.wasm.initTimeout < 0) && (r.env.wasm.initTimeout = 0), "boolean" != typeof r.env.wasm.simd && (r.env.wasm.simd = true), "boolean" != typeof r.env.wasm.proxy && (r.env.wasm.proxy = false), "number" != typeof r.env.wasm.numThreads || !Number.isInteger(r.env.wasm.numThreads) || r.env.wasm.numThreads <= 0) { const t2 = "undefined" == typeof navigator ? (0, i.cpus)().length : navigator.hardwareConcurrency; r.env.wasm.numThreads = Math.min(4, Math.ceil((t2 || 1) / 2)); } }, e.c8 = new class { async init() { (0, e.rX)(), await (0, o.initWasm)(); } async createSessionHandler(t2, e2) { const n2 = new a.OnnxruntimeWebAssemblySessionHandler(); return await n2.loadModel(t2, e2), Promise.resolve(n2); } }(); }, 6018: function(t, e, n) { "use strict"; var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2); var i2 = Object.getOwnPropertyDescriptor(e2, n2); i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { return e2[n2]; } }), Object.defineProperty(t2, r2, i2); } : function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; }), i = this && this.__exportStar || function(t2, e2) { for (var n2 in t2) "default" === n2 || Object.prototype.hasOwnProperty.call(e2, n2) || r(e2, t2, n2); }; Object.defineProperty(e, "__esModule", { value: true }), i(n(1670), e); const o = n(1670); { const t2 = n(7714).R; (0, o.registerBackend)("webgl", t2, -10); } { const t2 = n(4200).c8; (0, o.registerBackend)("cpu", t2, 10), (0, o.registerBackend)("wasm", t2, 10), (0, o.registerBackend)("xnnpack", t2, 9); } }, 246: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createAttributeWithCacheKey = void 0; class n { constructor(t2) { Object.assign(this, t2); } get cacheKey() { return this._cacheKey || (this._cacheKey = Object.getOwnPropertyNames(this).sort().map(((t2) => `${this[t2]}`)).join(";")), this._cacheKey; } } e.createAttributeWithCacheKey = (t2) => new n(t2); }, 7778: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.Attribute = void 0; const r = n(1446), i = n(9395), o = n(9162), a = n(2517); var s = i.onnxruntime.experimental.fbs; class u { constructor(t2) { if (this._attributes = /* @__PURE__ */ new Map(), null != t2) { for (const e2 of t2) e2 instanceof r.onnx.AttributeProto ? this._attributes.set(e2.name, [u.getValue(e2), u.getType(e2)]) : e2 instanceof s.Attribute && this._attributes.set(e2.name(), [u.getValue(e2), u.getType(e2)]); if (this._attributes.size < t2.length) throw new Error("duplicated attribute names"); } } set(t2, e2, n2) { this._attributes.set(t2, [n2, e2]); } delete(t2) { this._attributes.delete(t2); } getFloat(t2, e2) { return this.get(t2, "float", e2); } getInt(t2, e2) { return this.get(t2, "int", e2); } getString(t2, e2) { return this.get(t2, "string", e2); } getTensor(t2, e2) { return this.get(t2, "tensor", e2); } getFloats(t2, e2) { return this.get(t2, "floats", e2); } getInts(t2, e2) { return this.get(t2, "ints", e2); } getStrings(t2, e2) { return this.get(t2, "strings", e2); } getTensors(t2, e2) { return this.get(t2, "tensors", e2); } get(t2, e2, n2) { const r2 = this._attributes.get(t2); if (void 0 === r2) { if (void 0 !== n2) return n2; throw new Error(`required attribute not found: ${t2}`); } if (r2[1] !== e2) throw new Error(`type mismatch: expected ${e2} but got ${r2[1]}`); return r2[0]; } static getType(t2) { const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type(); switch (e2) { case r.onnx.AttributeProto.AttributeType.FLOAT: return "float"; case r.onnx.AttributeProto.AttributeType.INT: return "int"; case r.onnx.AttributeProto.AttributeType.STRING: return "string"; case r.onnx.AttributeProto.AttributeType.TENSOR: return "tensor"; case r.onnx.AttributeProto.AttributeType.FLOATS: return "floats"; case r.onnx.AttributeProto.AttributeType.INTS: return "ints"; case r.onnx.AttributeProto.AttributeType.STRINGS: return "strings"; case r.onnx.AttributeProto.AttributeType.TENSORS: return "tensors"; default: throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[e2]}`); } } static getValue(t2) { const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type(); if (e2 === r.onnx.AttributeProto.AttributeType.GRAPH || e2 === r.onnx.AttributeProto.AttributeType.GRAPHS) throw new Error("graph attribute is not supported yet"); const n2 = this.getValueNoCheck(t2); if (e2 === r.onnx.AttributeProto.AttributeType.INT && a.LongUtil.isLong(n2)) return a.LongUtil.longToNumber(n2); if (e2 === r.onnx.AttributeProto.AttributeType.INTS) { const t3 = n2, e3 = new Array(t3.length); for (let n3 = 0; n3 < t3.length; n3++) { const r2 = t3[n3]; e3[n3] = a.LongUtil.longToNumber(r2); } return e3; } if (e2 === r.onnx.AttributeProto.AttributeType.TENSOR) return t2 instanceof r.onnx.AttributeProto ? o.Tensor.fromProto(n2) : o.Tensor.fromOrtTensor(n2); if (e2 === r.onnx.AttributeProto.AttributeType.TENSORS) { if (t2 instanceof r.onnx.AttributeProto) return n2.map(((t3) => o.Tensor.fromProto(t3))); if (t2 instanceof s.Attribute) return n2.map(((t3) => o.Tensor.fromOrtTensor(t3))); } if (e2 === r.onnx.AttributeProto.AttributeType.STRING && t2 instanceof r.onnx.AttributeProto) { const t3 = n2; return (0, a.decodeUtf8String)(t3); } return e2 === r.onnx.AttributeProto.AttributeType.STRINGS && t2 instanceof r.onnx.AttributeProto ? n2.map(a.decodeUtf8String) : n2; } static getValueNoCheck(t2) { return t2 instanceof r.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(t2) : this.getValueNoCheckFromOrtFormat(t2); } static getValueNoCheckFromOnnxFormat(t2) { switch (t2.type) { case r.onnx.AttributeProto.AttributeType.FLOAT: return t2.f; case r.onnx.AttributeProto.AttributeType.INT: return t2.i; case r.onnx.AttributeProto.AttributeType.STRING: return t2.s; case r.onnx.AttributeProto.AttributeType.TENSOR: return t2.t; case r.onnx.AttributeProto.AttributeType.GRAPH: return t2.g; case r.onnx.AttributeProto.AttributeType.FLOATS: return t2.floats; case r.onnx.AttributeProto.AttributeType.INTS: return t2.ints; case r.onnx.AttributeProto.AttributeType.STRINGS: return t2.strings; case r.onnx.AttributeProto.AttributeType.TENSORS: return t2.tensors; case r.onnx.AttributeProto.AttributeType.GRAPHS: return t2.graphs; default: throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t2.type]}`); } } static getValueNoCheckFromOrtFormat(t2) { switch (t2.type()) { case s.AttributeType.FLOAT: return t2.f(); case s.AttributeType.INT: return t2.i(); case s.AttributeType.STRING: return t2.s(); case s.AttributeType.TENSOR: return t2.t(); case s.AttributeType.GRAPH: return t2.g(); case s.AttributeType.FLOATS: return t2.floatsArray(); case s.AttributeType.INTS: { const e2 = []; for (let n2 = 0; n2 < t2.intsLength(); n2++) e2.push(t2.ints(n2)); return e2; } case s.AttributeType.STRINGS: { const e2 = []; for (let n2 = 0; n2 < t2.stringsLength(); n2++) e2.push(t2.strings(n2)); return e2; } case s.AttributeType.TENSORS: { const e2 = []; for (let n2 = 0; n2 < t2.tensorsLength(); n2++) e2.push(t2.tensors(n2)); return e2; } default: throw new Error(`unsupported attribute type: ${s.AttributeType[t2.type()]}`); } } } e.Attribute = u; }, 7091: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.resolveBackend = e.backend = void 0; const r = n(5038), i = /* @__PURE__ */ new Map(); async function o(t2) { const n2 = e.backend; if (void 0 !== n2[t2] && (function(t3) { const e2 = t3; return "initialize" in e2 && "function" == typeof e2.initialize && "createSessionHandler" in e2 && "function" == typeof e2.createSessionHandler && "dispose" in e2 && "function" == typeof e2.dispose; })(n2[t2])) { const e2 = n2[t2]; let r2 = e2.initialize(); if ("object" == typeof r2 && "then" in r2 && (r2 = await r2), r2) return i.set(t2, e2), e2; } } e.backend = { webgl: new r.WebGLBackend() }, e.resolveBackend = async function t2(e2) { if (!e2) return t2(["webgl"]); { const t3 = "string" == typeof e2 ? [e2] : e2; for (const e3 of t3) { const t4 = i.get(e3); if (t4) return t4; const n2 = await o(e3); if (n2) return n2; } } throw new Error("no available backend to use"); }; }, 5038: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.WebGLBackend = void 0; const r = n(1670), i = n(6231), o = n(6416), a = n(7305); e.WebGLBackend = class { get contextId() { return r.env.webgl.contextId; } set contextId(t2) { r.env.webgl.contextId = t2; } get matmulMaxBatchSize() { return r.env.webgl.matmulMaxBatchSize; } set matmulMaxBatchSize(t2) { r.env.webgl.matmulMaxBatchSize = t2; } get textureCacheMode() { return r.env.webgl.textureCacheMode; } set textureCacheMode(t2) { r.env.webgl.textureCacheMode = t2; } get pack() { return r.env.webgl.pack; } set pack(t2) { r.env.webgl.pack = t2; } get async() { return r.env.webgl.async; } set async(t2) { r.env.webgl.async = t2; } initialize() { try { return this.glContext = (0, a.createWebGLContext)(this.contextId), "number" != typeof this.matmulMaxBatchSize && (this.matmulMaxBatchSize = 16), "string" != typeof this.textureCacheMode && (this.textureCacheMode = "full"), "boolean" != typeof this.pack && (this.pack = false), "boolean" != typeof this.async && (this.async = false), i.Logger.setWithEnv(r.env), i.Logger.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), true; } catch (t2) { return i.Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${t2}`), false; } } createSessionHandler(t2) { return new o.WebGLSessionHandler(this, t2); } dispose() { this.glContext.dispose(); } }; }, 5107: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.CoordsGlslLib = void 0; const r = n(2517), i = n(8520), o = n(5060), a = n(7859), s = n(9390); class u extends i.GlslLib { constructor(t2) { super(t2); } getFunctions() { return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet()); } getCustomTypes() { return {}; } offsetToCoords() { return { offsetToCoords: new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ") }; } coordsToOffset() { return { coordsToOffset: new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ") }; } getOutputSamplingSnippet() { const t2 = this.context.outputTextureLayout; return t2.isPacked ? this.getPackedOutputSamplingSnippet(t2) : this.getUnpackedOutputSamplingSnippet(t2); } getPackedOutputSamplingSnippet(t2) { const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords"; switch (e2.length) { case 0: r2[a2] = this.getOutputScalarCoords(); break; case 1: r2[a2] = this.getOutputPacked1DCoords(e2, n2); break; case 2: r2[a2] = this.getOutputPacked2DCoords(e2, n2); break; case 3: r2[a2] = this.getOutputPacked3DCoords(e2, n2); break; default: r2[a2] = this.getOutputPackedNDCoords(e2, n2); } const s2 = ` void setOutput(vec4 val) { ${(0, o.getGlsl)(this.context.glContext.version).output} = val; } `; return r2.floatTextureSetRGBA = new i.GlslLibRoutine(s2), r2; } getUnpackedOutputSamplingSnippet(t2) { const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords"; switch (e2.length) { case 0: r2[a2] = this.getOutputScalarCoords(); break; case 1: r2[a2] = this.getOutputUnpacked1DCoords(e2, n2); break; case 2: r2[a2] = this.getOutputUnpacked2DCoords(e2, n2); break; case 3: r2[a2] = this.getOutputUnpacked3DCoords(e2, n2); break; case 4: r2[a2] = this.getOutputUnpacked4DCoords(e2, n2); break; case 5: r2[a2] = this.getOutputUnpacked5DCoords(e2, n2); break; case 6: r2[a2] = this.getOutputUnpacked6DCoords(e2, n2); break; default: throw new Error(`Unsupported output dimensionality: ${e2.length}`); } const s2 = ` void setOutput(float val) { ${(0, o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); } `; return r2.floatTextureSetR = new i.GlslLibRoutine(s2), r2; } getOutputScalarCoords() { return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n "); } getOutputPacked1DCoords(t2, e2) { const n2 = e2; let r2 = ""; return 1 === n2[0] ? (r2 = ` int getOutputCoords() { return 2 * int(TexCoords.y * ${n2[1]}.0); } `, new i.GlslLibRoutine(r2)) : 1 === n2[1] ? (r2 = ` int getOutputCoords() { return 2 * int(TexCoords.x * ${n2[0]}.0); } `, new i.GlslLibRoutine(r2)) : (r2 = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n2[0]}, ${n2[1]})); return 2 * (resTexRC.y * ${n2[0]} + resTexRC.x); } `, new i.GlslLibRoutine(r2)); } getOutputPacked2DCoords(t2, e2) { let n2 = ""; if (r.ArrayUtil.arraysEqual(t2, e2)) return n2 = ` ivec2 getOutputCoords() { return 2 * ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); } `, new i.GlslLibRoutine(n2); const o2 = e2, a2 = Math.ceil(t2[1] / 2); return n2 = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${o2[0]}, ${o2[1]})); int index = resTexRC.y * ${o2[0]} + resTexRC.x; // reverse r and c order for packed texture int r = imod(index, ${a2}) * 2; int c = 2 * (index / ${a2}); return ivec2(r, c); } `, new i.GlslLibRoutine(n2); } getOutputPacked3DCoords(t2, e2) { const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[2] / 2), o2 = r2 * Math.ceil(t2[1] / 2), a2 = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n2[0]}, ${n2[1]})); int index = resTexRC.y * ${n2[0]} + resTexRC.x; int b = index / ${o2}; index -= b * ${o2}; // reverse r and c order for packed texture int r = imod(index, ${r2}) * 2; int c = 2 * (index / ${r2}); return ivec3(b, r, c); } `; return new i.GlslLibRoutine(a2); } getOutputPackedNDCoords(t2, e2) { const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[t2.length - 1] / 2), o2 = r2 * Math.ceil(t2[t2.length - 2] / 2); let a2 = o2, s2 = "", u2 = "b, r, c"; for (let e3 = 2; e3 < t2.length - 1; e3++) a2 *= t2[t2.length - e3 - 1], s2 = ` int b${e3} = index / ${a2}; index -= b${e3} * ${a2}; ` + s2, u2 = `b${e3}, ` + u2; const c = ` ivec${t2.length} getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n2[0]}, ${n2[1]})); int index = resTexRC.y * ${n2[0]} + resTexRC.x; ${s2} int b = index / ${o2}; index -= b * ${o2}; // reverse r and c order for packed texture int r = imod(index, ${r2}) * 2; int c = 2 * (index / ${r2}); return ivec${t2.length}(${u2}); } `; return new i.GlslLibRoutine(c); } getOutputUnpacked1DCoords(t2, e2) { const n2 = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); return resTexRC.y * ${e2[0]} + resTexRC.x; } `; return new i.GlslLibRoutine(n2); } getOutputUnpacked2DCoords(t2, e2) { const n2 = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); int index = resTexRC.y * ${e2[0]} + resTexRC.x; int r = index / ${t2[1]}; int c = index - r * ${t2[1]}; return ivec2(r, c); } `; return new i.GlslLibRoutine(n2); } getOutputUnpacked3DCoords(t2, e2) { let n2 = ""; const r2 = t2.length; let o2 = null; r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1]; const a2 = ["r", "c", "d"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join(""); return n2 = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); int index = resTexRC.y * ${e2[0]} + resTexRC.x; ${s2} return ivec3(r, c, d); } `, new i.GlslLibRoutine(n2); } getOutputUnpacked4DCoords(t2, e2) { let n2 = ""; const r2 = t2.length; let o2 = null; r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1]; const a2 = ["r", "c", "d", "d2"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join(""); return n2 = ` ivec4 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); int index = resTexRC.y * ${e2[0]} + resTexRC.x; ${s2} return ivec4(r, c, d, d2); } `, new i.GlslLibRoutine(n2); } getOutputUnpacked5DCoords(t2, e2) { let n2 = ""; const r2 = t2.length; let o2 = null; r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1]; const a2 = ["r", "c", "d", "d2", "d3"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join(""); return n2 = ` ivec5 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); int index = resTexRC.y * ${e2[0]} + resTexRC.x; ${s2} return ivec5(r, c, d, d2, d3); } `, new i.GlslLibRoutine(n2); } getOutputUnpacked6DCoords(t2, e2) { let n2 = ""; const r2 = t2.length; let o2 = null; r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1]; for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1]; const a2 = ["r", "c", "d", "d2", "d3", "d4"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join(""); return n2 = ` ivec6 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]})); int index = resTexRC.y * ${e2[0]} + resTexRC.x; ${s2} return ivec6(r, c, d, d2, d3, d4); } `, new i.GlslLibRoutine(n2); } getCommonUtilFuncs() { const t2 = {}; let e2 = "uvFromFlat"; t2[e2] = new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "), e2 = "packedUVfrom1D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "packedUVfrom2D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "packedUVfrom3D", t2[e2] = new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "), e2 = "sampleTexture"; const n2 = (0, o.getGlsl)(this.context.glContext.version); return t2[e2] = new i.GlslLibRoutine(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${n2.texture2D}(textureSampler, uv).r; }`), t2; } getInputsSamplingSnippets() { const t2 = {}, e2 = this.context.outputTextureLayout; return this.context.programInfo.inputNames.forEach(((n2, r2) => { const i2 = this.context.inputTextureLayouts[r2], o2 = (0, s.generateShaderFuncNameFromInputSamplerName)(n2); i2.isPacked ? t2[o2] = this.getPackedSamplerFromInput(o2, n2, i2) : t2[o2] = this.getUnpackedSamplerFromInput(o2, n2, i2); const a2 = (0, s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n2); i2.unpackedShape.length <= e2.unpackedShape.length && (i2.isPacked ? t2[a2] = this.getPackedSamplerAtOutputCoords(a2, i2, e2, n2) : t2[a2] = this.getUnpackedSamplerAtOutputCoords(a2, i2, e2, n2)); })), t2; } getPackedSamplerAtOutputCoords(t2, e2, n2, o2) { const a2 = e2.unpackedShape, u2 = n2.unpackedShape, c = o2, l = (0, s.generateShaderFuncNameFromInputSamplerName)(c), p = a2.length, f = u2.length, d = r.BroadcastUtil.getBroadcastDims(a2, u2), h = (0, s.getCoordsDataType)(f), g = f - p; let b; const m2 = (0, s.getGlChannels)(); b = 0 === p ? "" : f < 2 && d.length >= 1 ? "coords = 0;" : d.map(((t3) => `coords.${m2[t3 + g]} = 0;`)).join("\n"); let y = ""; y = f < 2 && p > 0 ? "coords" : a2.map(((t3, e3) => `coords.${m2[e3 + g]}`)).join(", "); let _ = "return outputValue;"; const v = 1 === r.ShapeUtil.size(a2), w = 1 === r.ShapeUtil.size(u2); if (1 !== p || v || w) { if (v && !w) _ = 1 === f ? "\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n " : "\n return vec4(outputValue.x);\n "; else if (d.length) { const t3 = p - 2, e3 = p - 1; d.indexOf(t3) > -1 && d.indexOf(e3) > -1 ? _ = "return vec4(outputValue.x);" : d.indexOf(t3) > -1 ? _ = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf(e3) > -1 && (_ = "return vec4(outputValue.xx, outputValue.zz);"); } } else _ = "\n return vec4(outputValue.xy, outputValue.xy);\n "; const x2 = ` vec4 ${t2}() { ${h} coords = getOutputCoords(); int lastDim = coords.${m2[f - 1]}; coords.${m2[f - 1]} = coords.${m2[f - 2]}; coords.${m2[f - 2]} = lastDim; ${b} vec4 outputValue = ${l}(${y}); ${_} } `; return new i.GlslLibRoutine(x2, ["coordinates.getOutputCoords"]); } getUnpackedSamplerAtOutputCoords(t2, e2, n2, o2) { const a2 = [n2.width, n2.height], u2 = [e2.width, e2.height], c = e2.unpackedShape.length, l = n2.unpackedShape.length, p = e2.unpackedShape, f = n2.unpackedShape, d = (0, s.generateShaderFuncNameFromInputSamplerName)(o2); if (c === l && r.ArrayUtil.arraysEqual(u2, a2)) { const e3 = ` float ${t2}() { return sampleTexture(${o2}, TexCoords); } `; return new i.GlslLibRoutine(e3, ["coordinates.sampleTexture"]); } const h = (0, s.getCoordsDataType)(l), g = r.BroadcastUtil.getBroadcastDims(p, f), b = l - c; let m2; const y = (0, s.getGlChannels)(); m2 = 0 === c ? "" : l < 2 && g.length >= 1 ? "coords = 0;" : g.map(((t3) => `coords.${y[t3 + b]} = 0;`)).join("\n"); let _ = ""; _ = l < 2 && c > 0 ? "coords" : e2.unpackedShape.map(((t3, e3) => `coords.${y[e3 + b]}`)).join(", "); const v = ` float ${t2}() { ${h} coords = getOutputCoords(); ${m2} return ${d}(${_}); } `; return new i.GlslLibRoutine(v, ["coordinates.getOutputCoords"]); } getPackedSamplerFromInput(t2, e2, n2) { switch (n2.unpackedShape.length) { case 0: return this.getPackedSamplerScalar(t2, e2); case 1: return this.getPackedSampler1D(t2, e2, n2); case 2: return this.getPackedSampler2D(t2, e2, n2); case 3: return this.getPackedSampler3D(t2, e2, n2); default: return this.getPackedSamplerND(t2, e2, n2); } } getUnpackedSamplerFromInput(t2, e2, n2) { const r2 = n2.unpackedShape; switch (r2.length) { case 0: return this.getUnpackedSamplerScalar(t2, e2, n2); case 1: return this.getUnpackedSampler1D(t2, e2, n2); case 2: return this.getUnpackedSampler2D(t2, e2, n2); case 3: return this.getUnpackedSampler3D(t2, e2, n2); case 4: return this.getUnpackedSampler4D(t2, e2, n2); case 5: return this.getUnpackedSampler5D(t2, e2, n2); case 6: return this.getUnpackedSampler6D(t2, e2, n2); default: throw new Error(`Unsupported dimension ${r2.length}-D`); } } getPackedSamplerScalar(t2, e2) { const n2 = ` vec4 ${t2}() { return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${e2}, halfCR); } `; return new i.GlslLibRoutine(n2); } getPackedSampler1D(t2, e2, n2) { const r2 = [n2.width, n2.height], a2 = [r2[1], r2[0]], s2 = (0, o.getGlsl)(this.context.glContext.version), u2 = `vec4 ${t2}(int index) { vec2 uv = packedUVfrom1D( ${a2[0]}, ${a2[1]}, index); return ${s2.texture2D}(${e2}, uv); }`; return new i.GlslLibRoutine(u2, ["coordinates.packedUVfrom1D"]); } getPackedSampler2D(t2, e2, n2) { const a2 = n2.unpackedShape, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = s2[0], l = s2[1]; if (null != s2 && r.ArrayUtil.arraysEqual(a2, s2)) { const n3 = `vec4 ${t2}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0); return ${u2.texture2D}(${e2}, uv); }`; return new i.GlslLibRoutine(n3); } const p = s2, f = Math.ceil(a2[1] / 2), d = `vec4 ${t2}(int row, int col) { vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col); return ${u2.texture2D}(${e2}, uv); }`; return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom2D"]); } getPackedSampler3D(t2, e2, n2) { const r2 = n2.unpackedShape, a2 = [n2.width, n2.height], u2 = [a2[0], a2[1]], c = (0, o.getGlsl)(this.context.glContext.version); if (1 === r2[0]) { const o2 = r2.slice(1), a3 = [1, 2], u3 = (0, s.squeezeInputShape)(r2, o2), c2 = ["b", "row", "col"], l2 = JSON.parse(JSON.stringify(n2)); l2.unpackedShape = u3; const p2 = this.getPackedSamplerFromInput(t2, e2, l2), f2 = `${p2.routineBody} vec4 ${t2}(int b, int row, int col) { return ${t2}(${(0, s.getSqueezedParams)(c2, a3)}); } `; return new i.GlslLibRoutine(f2, p2.dependencies); } const l = u2[0], p = u2[1], f = Math.ceil(r2[2] / 2), d = `vec4 ${t2}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${p}, ${l}, ${f * Math.ceil(r2[1] / 2)}, ${f}, b, row, col); return ${c.texture2D}(${e2}, uv);}`; return new i.GlslLibRoutine(d, ["coordinates.packedUVfrom3D"]); } getPackedSamplerND(t2, e2, n2) { const r2 = n2.unpackedShape, a2 = r2.length, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = [s2[0], s2[1]], l = c[1], p = c[0], f = Math.ceil(r2[a2 - 1] / 2); let d = f * Math.ceil(r2[a2 - 2] / 2), h = "int b, int row, int col", g = `b * ${d} + (row / 2) * ${f} + (col / 2)`; for (let t3 = 2; t3 < a2 - 1; t3++) h = `int b${t3}, ` + h, d *= r2[a2 - t3 - 1], g = `b${t3} * ${d} + ` + g; const b = `vec4 ${t2}(${h}) { int index = ${g}; int texR = index / ${p}; int texC = index - texR * ${p}; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${l}); return ${u2.texture2D}(${e2}, uv); }`; return new i.GlslLibRoutine(b); } getUnpackedSamplerScalar(t2, e2, n2) { const [r2, o2] = [n2.width, n2.height]; if (1 === r2 && 1 === o2) { const n3 = ` float ${t2}() { return sampleTexture(${e2}, halfCR); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); } const a2 = ` float ${t2}() { int offset_${e2} = coordsToOffset(TexCoords, ${r2}, ${o2}); vec2 uv = uvFromFlat(${r2}, ${o2}, offset_${e2}); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler1D(t2, e2, n2) { const r2 = n2.width, o2 = n2.height; if (1 === o2 && 1 === r2) { const n3 = ` float ${t2}(int index) { return sampleTexture(${e2}, halfCR); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); } if (1 === o2) { const n3 = ` float ${t2}(int index) { vec2 uv = vec2((float(index) + 0.5) / ${r2}.0, 0.5); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); } if (1 === r2) { const n3 = ` float ${t2}(int index) { vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o2}.0); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); } const a2 = ` float ${t2}(int index) { vec2 uv = uvFromFlat(${r2}, ${o2}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler2D(t2, e2, n2) { const o2 = n2.unpackedShape, u2 = [n2.height, n2.width]; if (null != u2 && r.ArrayUtil.arraysEqual(o2, u2)) { const n3 = ` float ${t2}(int row, int col) { vec2 uv = (vec2(row, col) + halfCR) / vec2(${u2[1]}.0, ${u2[0]}.0); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture"]); } const { newShape: c, keptDims: l } = (0, a.squeezeShape)(o2), p = c; if (p.length < o2.length) { const r2 = (0, s.squeezeInputShape)(o2, p), a2 = JSON.parse(JSON.stringify(n2)); a2.unpackedShape = r2; const u3 = ["col", "row"], c2 = ` ${this.getUnpackedSamplerFromInput(t2, e2, a2).routineBody} float ${t2}(int row, int col) { return ${t2}(${(0, s.getSqueezedParams)(u3, l)}); } `; return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture"]); } const f = u2[1], d = u2[0]; if (1 === d) { const n3 = ` float ${t2}(int row, int col) { int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d}); float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1)); vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } if (1 === f) { const n3 = ` float ${t2}(int row, int col) { int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d}); float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1)); vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } const h = ` float ${t2}(int row, int col) { int index = col * ${o2[1]} + row; vec2 uv = uvFromFlat(${f}, ${d}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler3D(t2, e2, n2) { const r2 = n2.unpackedShape, o2 = r2[1] * r2[2], u2 = r2[2], { newShape: c, keptDims: l } = (0, a.squeezeShape)(r2), p = c; if (p.length < r2.length) { const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["batch", "col", "row"], u3 = JSON.parse(JSON.stringify(n2)); u3.unpackedShape = o3; const c2 = this.getUnpackedSamplerFromInput(t2, e2, u3), f2 = l.reverse(), d = ` ${c2.routineBody} float ${t2}(int batch, int row, int col) { return ${t2}(${(0, s.getSqueezedParams)(a2, f2)}); } `; return new i.GlslLibRoutine(d, c2.dependencies); } const f = ` float ${t2}(int depth, int row, int col) { // Explicitly use integer operations as dot() only works on floats. int index = depth * ${o2} + col * ${u2} + row; vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(f, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler4D(t2, e2, n2) { const r2 = n2.unpackedShape, o2 = r2[3], a2 = r2[2] * o2, s2 = ` float ${t2}(int row, int col, int depth, int depth2) { int index = row * ${r2[1] * a2} + col * ${a2} + depth2 * ${o2} + depth; vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(s2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler5D(t2, e2, n2) { const r2 = n2.unpackedShape, o2 = r2[4], u2 = r2[3] * o2, c = r2[2] * u2, l = r2[1] * c, { newShape: p, keptDims: f } = (0, a.squeezeShape)(r2); if (p.length < r2.length) { const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["row", "col", "depth", "depth2", "depth3"], u3 = JSON.parse(JSON.stringify(n2)); u3.unpackedShape = o3; const c2 = ` ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody} float ${t2}(int row, int col, int depth, int depth2, int depth3) { return ${t2}(${(0, s.getSqueezedParams)(a2, f)}); } `; return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } const d = ` float ${t2}(int row, int col, int depth, int depth2, int depth3) { int index = row * ${l} + col * ${c} + depth * ${u2} + depth3 * ${o2} + depth2; vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(d, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } getUnpackedSampler6D(t2, e2, n2) { const r2 = n2.unpackedShape, o2 = r2[5], u2 = r2[4] * o2, c = r2[3] * u2, l = r2[2] * c, p = r2[1] * l, { newShape: f, keptDims: d } = (0, a.squeezeShape)(r2); if (f.length < r2.length) { const o3 = (0, s.squeezeInputShape)(r2, f), a2 = ["row", "col", "depth", "depth2", "depth3", "depth4"], u3 = JSON.parse(JSON.stringify(n2)); u3.unpackedShape = o3; const c2 = ` ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody} float ${t2}(int row, int col, int depth, int depth2, int depth3, int depth4) { return ${t2}(${(0, s.getSqueezedParams)(a2, d)}); } `; return new i.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } const h = ` float ${t2}(int row, int col, int depth, int depth2, int depth3, int depth4) { int index = row * ${p} + col * ${l} + depth * ${c} + depth2 * ${u2} + depth3 * ${o2} + depth4; vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index); return sampleTexture(${e2}, uv); } `; return new i.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } toVec() { const t2 = this.context.outputTextureLayout, e2 = t2.shape.length, n2 = t2.strides, r2 = t2.width, o2 = t2.height, a2 = []; for (let t3 = 0; t3 < e2 - 1; ++t3) a2.push(` c[${t3}] = offset / ${n2[t3]};`), a2.push(` offset -= c[${t3}] * ${n2[t3]};`); a2.push(` c[${e2 - 1}] = offset;`); const s2 = ` void toVec(vec2 texCoords, out int c[${e2}]) { int offset = coordsToOffset(texCoords, ${r2}, ${o2}); ${a2.join("")} } void toVec(int offset, out int c[${e2}]) { ${a2.join("")} } `; return { toVec: new i.GlslLibRoutine(s2, ["coordinates.coordsToOffset"]) }; } valueFrom() { const t2 = {}; return this.context.programInfo.inputNames.forEach(((e2, n2) => { const r2 = this.context.inputTextureLayouts[n2], o2 = (r2.unpackedShape.length > 0 ? r2.unpackedShape : r2.shape).length; let a2 = `_${e2}`; t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, false), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), a2 += "_T", t2[a2] = new i.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, true), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]); })), t2; } getValueFromSingle(t2, e2, n2, r2, i2) { let a2 = `_${t2}`; return i2 && (a2 += "_T"), ` float ${a2}(int m[${e2}]) { int offset = indicesToOffset${a2}(m); vec2 coords = offsetToCoords(offset, ${n2}, ${r2}); float value = getColorAsFloat(${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords)); return value; } `; } getPackedValueFrom(t2, e2, n2, r2, i2) { let a2 = `_${t2}_Pack`; return i2 && (a2 += "_T"), ` vec4 ${a2}(int m[${e2}]) { int offset = indicesToOffset_${t2}(m); vec2 coords = offsetToCoords(offset, ${n2}, ${r2}); return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords); } `; } } e.CoordsGlslLib = u; }, 8520: (t, e) => { "use strict"; var n; Object.defineProperty(e, "__esModule", { value: true }), e.TopologicalSortGlslRoutines = e.GlslLibRoutineNode = e.GlslLibRoutine = e.GlslLib = e.GlslContext = e.FunctionType = void 0, (n = e.FunctionType || (e.FunctionType = {}))[n.ValueBased = 0] = "ValueBased", n[n.Positional = 1] = "Positional", e.GlslContext = class { constructor(t2, e2, n2, r) { this.glContext = t2, this.programInfo = e2, this.inputTextureLayouts = n2, this.outputTextureLayout = r; } }, e.GlslLib = class { constructor(t2) { this.context = t2; } }, e.GlslLibRoutine = class { constructor(t2, e2) { this.routineBody = t2, this.dependencies = e2; } }, e.GlslLibRoutineNode = class { constructor(t2, e2, n2) { this.name = t2, this.dependencies = n2 || [], e2 && (this.routineBody = e2); } addDependency(t2) { t2 && this.dependencies.push(t2); } }, e.TopologicalSortGlslRoutines = class { static returnOrderedNodes(t2) { if (!t2 || 0 === t2.length) return []; if (1 === t2.length) return t2; const e2 = /* @__PURE__ */ new Set(), n2 = /* @__PURE__ */ new Set(), r = new Array(); return this.createOrderedNodes(t2, e2, n2, r), r; } static createOrderedNodes(t2, e2, n2, r) { for (let i = 0; i < t2.length; ++i) this.dfsTraverse(t2[i], e2, n2, r); } static dfsTraverse(t2, e2, n2, r) { if (!t2 || n2.has(t2.name)) return; if (e2.has(t2.name)) throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader."); e2.add(t2.name); const i = t2.dependencies; if (i && i.length > 0) for (let t3 = 0; t3 < i.length; ++t3) this.dfsTraverse(i[t3], e2, n2, r); r.push(t2), n2.add(t2.name), e2.delete(t2.name); } }; }, 7341: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.EncodingGlslLib = void 0; const r = n(8520); class i extends r.GlslLib { constructor(t2) { super(t2); } getFunctions() { return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32()); } getCustomTypes() { return {}; } encodeFloat32() { return { encode: new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ") }; } decodeFloat32() { return { decode: new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ") }; } encodeUint8() { const t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { encode: new r.GlslLibRoutine(` highp vec4 encode(highp float f) { highp float F = abs(f); highp float Sign = step(0.0,-f); highp float Exponent = floor(log2(F)); highp float Mantissa = (exp2(- Exponent) * F); Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); highp vec4 rgba; rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); ${t2} rgba = rgba / 255.0; // values need to be normalized to [0,1] return rgba; } `) }; } decodeUint8() { const t2 = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { decode: new r.GlslLibRoutine(` highp float decode(highp vec4 rgba) { rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] ${t2} highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); return Result; } `) }; } static isLittleEndian() { const t2 = new ArrayBuffer(4), e2 = new Uint32Array(t2), n2 = new Uint8Array(t2); if (e2[0] = 3735928559, 239 === n2[0]) return true; if (222 === n2[0]) return false; throw new Error("unknown endianness"); } } e.EncodingGlslLib = i; }, 9894: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.FragColorGlslLib = void 0; const r = n(8520), i = n(5060); class o extends r.GlslLib { constructor(t2) { super(t2); } getFunctions() { return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat()); } getCustomTypes() { return {}; } setFragColor() { const t2 = (0, i.getGlsl)(this.context.glContext.version); return { setFragColor: new r.GlslLibRoutine(` void setFragColor(float value) { ${t2.output} = encode(value); } `, ["encoding.encode"]) }; } getColorAsFloat() { return { getColorAsFloat: new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ", ["encoding.decode"]) }; } } e.FragColorGlslLib = o; }, 2848: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.replaceInlines = void 0; const n = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm; e.replaceInlines = function(t2) { const e2 = {}; let r; for (; null !== (r = n.exec(t2)); ) { const t3 = r[3].split(",").map(((t4) => { const e3 = t4.trim().split(" "); return e3 && 2 === e3.length ? { type: e3[0], name: e3[1] } : null; })).filter(((t4) => null !== t4)); e2[r[2]] = { params: t3, body: r[4] }; } for (const n2 in e2) { const i = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__", n2), o = new RegExp(i, "gm"); for (; null !== (r = o.exec(t2)); ) { const i2 = r[1], o2 = r[2], a = r[3].split(","), s = i2 ? `${i2} ${o2};` : ""; let u = e2[n2].body, c = ""; e2[n2].params.forEach(((t3, e3) => { t3 && (c += `${t3.type} ${t3.name} = ${a[e3]}; `); })), u = `${c} ${u}`, u = u.replace("return", `${o2} = `); const l = ` ${s} { ${u} } `; t2 = t2.replace(r[0], l); } } return t2.replace(n, ""); }; }, 8879: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.GlslPreprocessor = void 0; const r = n(8520), i = n(2848), o = n(5483), a = n(5060); e.GlslPreprocessor = class { constructor(t2, e2, n2, i2) { this.libs = {}, this.glslLibRoutineDependencyGraph = {}, this.context = new r.GlslContext(t2, e2, n2, i2), Object.keys(o.glslRegistry).forEach(((t3) => { const e3 = new o.glslRegistry[t3](this.context); this.libs[t3] = e3; })); const a2 = this.glslLibRoutineDependencyGraph; for (const t3 in this.libs) { const e3 = this.libs[t3].getFunctions(); for (const n3 in e3) { const i3 = t3 + "." + n3; let o2; a2[i3] ? (o2 = a2[i3], o2.routineBody = e3[n3].routineBody) : (o2 = new r.GlslLibRoutineNode(i3, e3[n3].routineBody), a2[i3] = o2); const s = e3[n3].dependencies; if (s) for (let t4 = 0; t4 < s.length; ++t4) if (a2[s[t4]]) o2.addDependency(a2[s[t4]]); else { const e4 = new r.GlslLibRoutineNode(s[t4]); a2[s[t4]] = e4, o2.addDependency(e4); } } } } preprocess() { const t2 = this.context.programInfo; let e2 = t2.shaderSource; return this.context.programInfo.hasMain || (e2 = `${e2} ${(0, a.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), e2 = (0, i.replaceInlines)(e2), `${(0, a.getFragShaderPreamble)(this.context.glContext.version)} ${this.getUniforms(t2.inputNames, t2.variables)} ${this.getImports(e2)} ${e2}`; } getImports(t2) { const e2 = this.selectGlslLibRoutinesToBeIncluded(t2); if (0 === e2.length) return ""; let n2 = ""; for (let t3 = 0; t3 < e2.length; ++t3) { if (!e2[t3].routineBody) throw new Error(`Missing body for the Glsl Library routine: ${e2[t3].name}`); n2 += e2[t3].routineBody + "\n"; } return n2; } selectGlslLibRoutinesToBeIncluded(t2) { const e2 = []; return Object.keys(this.glslLibRoutineDependencyGraph).forEach(((n2) => { const r2 = n2.split(".")[1]; -1 !== t2.indexOf(r2) && e2.push(this.glslLibRoutineDependencyGraph[n2]); })), r.TopologicalSortGlslRoutines.returnOrderedNodes(e2); } getUniforms(t2, e2) { const n2 = []; if (t2) for (const e3 of t2) n2.push(`uniform sampler2D ${e3};`); if (e2) for (const t3 of e2) n2.push(`uniform ${t3.type} ${t3.name}${t3.arrayLength ? `[${t3.arrayLength}]` : ""};`); return n2.join("\n"); } }; }, 5483: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.glslRegistry = void 0; const r = n(5107), i = n(7341), o = n(9894), a = n(2655), s = n(3891); e.glslRegistry = { encoding: i.EncodingGlslLib, fragcolor: o.FragColorGlslLib, vec: s.VecGlslLib, shapeUtils: a.ShapeUtilsGlslLib, coordinates: r.CoordsGlslLib }; }, 2655: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.ShapeUtilsGlslLib = void 0; const r = n(8520); class i extends r.GlslLib { constructor(t2) { super(t2); } getFunctions() { return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices()); } getCustomTypes() { return {}; } bcastIndex() { const t2 = this.context.outputTextureLayout.shape.length, e2 = {}; return this.context.programInfo.inputNames.forEach(((n2, i2) => { const o = this.context.inputTextureLayouts[i2].unpackedShape; if (o.length <= t2) { const i3 = o.length, a = t2 - i3, s = `bcastIndices_${n2}`; let u = ""; for (let t3 = 0; t3 < i3; ++t3) u += ` realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) ); `; const c = ` void ${s} (int bcastedIndices[${t2}], out int realIndices[${i3}]) { ${u} } `; e2[s] = new r.GlslLibRoutine(c); } })), e2; } bcastMatmulIndex() { const t2 = this.context.outputTextureLayout.shape.length, e2 = {}; return this.context.programInfo.inputNames.forEach(((n2, i2) => { const o = this.context.inputTextureLayouts[i2].shape; if (!(o.length < 2 || o.length > t2)) { const i3 = o.length, a = t2 - i3, s = `bcastMatmulIndices_${n2}`; let u = ""; for (let t3 = 0; t3 < i3 - 2; ++t3) u += ` realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) ); `; const c = ` void ${s}(int bcastedIndices[${t2}], out int realIndices[${i3}]) { ${u} realIndices[${i3 - 1}] = bcastedIndices[${t2 - 1}]; realIndices[${i3 - 2}] = bcastedIndices[${t2 - 2}]; } `; e2[s] = new r.GlslLibRoutine(c); } })), e2; } indicesToOffset() { const t2 = {}; return this.context.programInfo.inputNames.forEach(((e2, n2) => { const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length; let u = `indicesToOffset_${e2}`; t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a)), u = `indicesToOffset_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.indexToOffsetSingle(u, s, a.slice().reverse())); })), t2; } static indexToOffsetSingle(t2, e2, n2) { let r2 = ""; for (let t3 = e2 - 1; t3 >= 0; --t3) r2 += ` offset += indices[${t3}] * ${n2[t3]}; `; return ` int ${t2}(int indices[${e2}]) { int offset = 0; ${r2} return offset; } `; } offsetToIndices() { const t2 = {}; return this.context.programInfo.inputNames.forEach(((e2, n2) => { const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length; let u = `offsetToIndices_${e2}`; t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a)), u = `offsetToIndices_${e2}_T`, t2[u] = new r.GlslLibRoutine(i.offsetToIndicesSingle(u, s, a.slice().reverse())); })), t2; } static offsetToIndicesSingle(t2, e2, n2) { const r2 = []; for (let t3 = 0; t3 < e2 - 1; ++t3) r2.push(` indices[${t3}] = offset / ${n2[t3]};`), r2.push(` offset -= indices[${t3}] * ${n2[t3]};`); return r2.push(` indices[${e2 - 1}] = offset;`), ` void ${t2}(int offset, out int indices[${e2}]) { ${r2.join("")} } `; } incrementIndices() { const t2 = {}; return this.context.programInfo.inputNames.forEach(((e2, n2) => { const i2 = this.context.inputTextureLayouts[n2].shape, o = i2.length, a = `incrementIndices_${e2}`; let s = ""; for (let t3 = 0; t3 < o; ++t3) s += ` shape[${t3}] = ${i2[t3]};`; const u = ` void ${a}(int axis, out int indices[${o}]) { int shape[${o}]; ${s}; for(int i = ${o} -1 ; i >= 0; --i) { if(i > axis) continue; indices[i] += 1; if(indices[i] < shape[i]) { break; } indices[i] = 0; } } `; t2[a] = new r.GlslLibRoutine(u); })), t2; } } e.ShapeUtilsGlslLib = i; }, 5060: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.getDefaultFragShaderMain = e.getFragShaderPreamble = e.getVertexShaderSource = e.getGlsl = void 0; const n = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, r = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" }; function i(t2) { return 1 === t2 ? n : r; } e.getGlsl = i, e.getVertexShaderSource = function(t2) { const e2 = i(t2); return `${e2.version} precision highp float; ${e2.attribute} vec3 position; ${e2.attribute} vec2 textureCoord; ${e2.varyingVertex} vec2 TexCoords; void main() { gl_Position = vec4(position, 1.0); TexCoords = textureCoord; }`; }, e.getFragShaderPreamble = function(t2) { const e2 = i(t2); return `${e2.version} precision highp float; precision highp int; precision highp sampler2D; ${e2.varyingFrag} vec2 TexCoords; ${e2.outputDeclaration} const vec2 halfCR = vec2(0.5, 0.5); // Custom vector types to handle higher dimenalities. struct ivec5 { int x; int y; int z; int w; int u; }; struct ivec6 { int x; int y; int z; int w; int u; int v; }; int imod(int x, int y) { return x - y * (x / y); } `; }, e.getDefaultFragShaderMain = function(t2, e2) { return ` void main() { int indices[${e2}]; toVec(TexCoords, indices); vec4 result = vec4(process(indices)); ${i(t2).output} = result; } `; }; }, 3891: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.VecGlslLib = void 0; const r = n(8520); class i extends r.GlslLib { constructor(t2) { super(t2); } getCustomTypes() { return {}; } getFunctions() { return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem()); } binaryVecFunctions() { const t2 = this.context.outputTextureLayout.shape.length, e2 = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, n2 = {}; for (const i2 in e2) { const o = `${i2}Vec`; let a = ""; for (let n3 = 0; n3 < t2; ++n3) a += ` dest[${n3}] ${e2[i2]} src[${n3}]; `; const s = ` void ${o}(int src[${t2}], out int dest[${t2}]) { ${a} } `; n2[o] = new r.GlslLibRoutine(s); } return n2; } copyVec() { const t2 = this.context.outputTextureLayout.shape.length; let e2 = ""; for (let n3 = 0; n3 < t2; ++n3) e2 += ` dest[${n3}] = src[${n3}]; `; const n2 = ` void copyVec(int src[${t2}], out int dest[${t2}]) { ${e2} } `; return { copyVec: new r.GlslLibRoutine(n2) }; } setVecItem() { const t2 = this.context.outputTextureLayout.shape.length; let e2 = ` if(index < 0) index =${t2} + index; if (index == 0) m[0] = value; `; for (let n3 = 1; n3 < t2 - 1; ++n3) e2 += ` else if (index == ${n3}) m[${n3}] = value; `; e2 += ` else m[${t2 - 1}] = value; `; const n2 = ` void setVecItem(out int m[${t2}], int index, int value) { ${e2} } `; return { setVecItem: new r.GlslLibRoutine(n2) }; } getVecItem() { const t2 = this.context.outputTextureLayout.shape.length; let e2 = ` if(index < 0) index = ${t2} + index; if (index == 0) return m[0]; `; for (let n3 = 1; n3 < t2 - 1; ++n3) e2 += ` else if (index == ${n3}) return m[${n3}]; `; e2 += ` else return m[${t2 - 1}]; `; const n2 = ` int getVecItem(int m[${t2}], int index) { ${e2} } `; return { getVecItem: new r.GlslLibRoutine(n2) }; } } e.VecGlslLib = i; }, 8316: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.WebGLInferenceHandler = void 0; const r = n(6231), i = n(9162), o = n(2517), a = n(2403), s = n(7019), u = n(8710), c = n(5611), l = n(4057), p = n(2039); e.WebGLInferenceHandler = class { constructor(t2) { this.session = t2, this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } calculateTextureWidthAndHeight(t2, e2) { return (0, l.calculateTextureWidthAndHeight)(this.session.layoutStrategy, t2, e2); } executeProgram(t2, e2) { if (e2.length < t2.inputNames.length) throw new Error(`Input size mustn't be less than ${t2.inputNames.length}.`); if (t2.inputNames.length !== t2.inputTypes.length) throw new Error("input names size does not match input types"); const n2 = []; for (let r3 = 0; r3 < t2.inputNames.length; ++r3) n2[r3] = this.getOrCreateTextureData(e2[r3], t2.inputTypes[r3]); const r2 = ((t3, e3) => { const n3 = e3.map(((t4) => `${t4.unpackedShape.join(",")};${t4.width}x${t4.height}`)).join("_"); let r3 = t3.name; return t3.cacheHint && (r3 += "[" + t3.cacheHint + "]"), r3 += ":" + n3, r3; })(t2, n2); let i2 = this.session.programManager.getArtifact(r2); const o2 = i2 ? i2.programInfo : "function" == typeof t2.get ? t2.get() : t2, a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2.output.dims, o2.output.textureType), s2 = this.createTextureData(a2, o2.output.type); return i2 || (i2 = this.session.programManager.build(o2, n2, s2), this.session.programManager.setArtifact(r2, i2)), this.runProgram(i2, n2, s2), s2; } run(t2, e2) { return this.executeProgram(t2, e2).tensor; } runProgram(t2, e2, n2) { for (let n3 = 0; n3 < e2.length; ++n3) if (!!e2[n3].isPacked != (t2.programInfo.inputTypes[n3] === p.TextureType.packed)) throw new Error(`input[${n3}] property packed inconsistent`); if (!!n2.isPacked != (t2.programInfo.output.textureType === p.TextureType.packed)) throw new Error("output property packed inconsistent"); this.session.programManager.run(t2, e2, n2); } getOrCreateTextureData(t2, e2) { let n2 = this.getTextureData(t2.dataId, e2 === p.TextureType.packed); if (!n2 && (n2 = this.getTextureData(t2.dataId, e2 !== p.TextureType.packed), n2)) return e2 === p.TextureType.packed ? this.pack(n2) : this.unpack(n2); if (!n2) { const r2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, t2.dims, e2); if (e2 === p.TextureType.packedLastDimension) { const n3 = 1, r3 = 4, i2 = t2.dims; if (4 === i2.length) { const o2 = [i2[0], Math.ceil(i2[1] * i2[2] * i2[3] / r3)], a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2, e2); let s2 = t2.numberData; if (i2[1] * i2[2] * i2[3] % r3 != 0) { const e3 = i2[0], o3 = i2[1] * i2[2] * i2[3], a3 = Math.ceil(o3 * n3 / r3) * r3; s2 = new Float32Array(e3 * a3); for (let r4 = 0; r4 < e3; ++r4) { const e4 = r4 * o3, i3 = r4 * a3 + r4 % n3 * o3; s2.set(t2.numberData.subarray(e4, e4 + o3), i3); } } return this.createTextureData(a2, t2.type, s2, t2, 1); } } if (e2 === p.TextureType.packed) { const e3 = (0, l.createTextureLayoutFromShape)(this.session.layoutStrategy, t2.dims, 1, [], { reverseWH: true }), r3 = this.createTextureData(e3, t2.type, t2.numberData, t2, 1); n2 = this.pack(r3); } else n2 = this.createTextureData(r2, t2.type, t2.numberData, t2, 1); } return n2; } createTextureDataFromLayoutBindTensor(t2, e2, n2, r2) { return this.createTextureData(t2, e2, n2, r2, 1); } createTextureData(t2, e2, n2, i2, o2) { r.Logger.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(t2)}]`); const a2 = this.session.textureManager.createTextureFromLayout(e2, t2, n2, o2); return this.createTextureDataFromTexture(t2, e2, a2, i2); } reshapeUnpacked(t2, e2) { const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked), r2 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2 }; return this.createTextureDataFromTexture(r2, t2.type, n2.texture).tensor; } reshapePacked(t2, e2) { const n2 = this.getOrCreateTextureData(t2, p.TextureType.packed); if ((0, s.isReshapeCheap)(t2.dims, e2)) { const r3 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2, isPacked: true }; return this.createTextureDataFromTexture(r3, t2.type, n2.texture).tensor; } const r2 = (0, s.processDims3D)(t2.dims), i2 = (0, s.processDims3D)(e2), a2 = this.reshapePacked(t2, r2), u2 = this.run((0, s.createPackedReshape3DProgramInfoLoader)(this, a2, i2), [a2]); return this.reshapePacked(u2, e2); } cast(t2, e2) { const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked); return this.createTextureDataFromTexture(n2, e2, n2.texture).tensor; } createTextureDataFromTexture(t2, e2, n2, r2, o2) { const a2 = Object.assign(Object.assign({}, t2), { tensor: r2 || new i.Tensor(t2.unpackedShape, e2, ((t3) => this.readTexture(a2)), (async (t3) => this.readTextureAsync(a2)), void 0, o2), texture: n2 }); return this.setTextureData(a2.tensor.dataId, a2, t2.isPacked), a2; } getTextureData(t2, e2 = false) { return this.session.isInitializer(t2) ? this.session.getTextureData(t2, e2) : e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2); } setTextureData(t2, e2, n2 = false) { this.session.isInitializer(t2) ? this.session.setTextureData(t2, e2, n2) : (n2 ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(t2, e2); } isTextureLayoutCached(t2, e2 = false) { return !!this.getTextureData(t2.dataId, e2); } dispose() { this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((t2) => this.session.textureManager.releaseTexture(t2))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((t2) => this.session.textureManager.releaseTexture(t2))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } readTexture(t2) { return t2.isPacked ? this.readTexture(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2)); } async readTextureAsync(t2) { return t2.isPacked ? this.readTextureAsync(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2)); } pack(t2) { return this.executeProgram((0, a.createPackProgramInfoLoader)(this, t2.tensor), [t2.tensor]); } unpack(t2) { return this.executeProgram((0, c.createUnpackProgramInfoLoader)(this, t2.tensor), [t2.tensor]); } }; }, 1640: function(t, e, n) { "use strict"; var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2); var i2 = Object.getOwnPropertyDescriptor(e2, n2); i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { return e2[n2]; } }), Object.defineProperty(t2, r2, i2); } : function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); } : function(t2, e2) { t2.default = e2; }), o = this && this.__importStar || function(t2) { if (t2 && t2.__esModule) return t2; var e2 = {}; if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); return i(e2, t2), e2; }; Object.defineProperty(e, "__esModule", { value: true }), e.WEBGL_OP_RESOLVE_RULES = void 0; const a = n(2898), s = o(n(7839)), u = n(4196), c = n(2069), l = n(8138), p = n(9663), f = n(5193), d = n(7992), h = n(1253), g = n(4776), b = n(6572), m2 = n(3346), y = n(5623), _ = n(2870), v = n(2143), w = n(4939), x2 = n(718), T3 = n(2268), S = n(8117), O2 = n(2278), A2 = n(5524), E2 = n(5975), I2 = n(3933), P2 = n(6558), D3 = n(5723), $2 = n(3738), k4 = o(n(4909)), C = n(8428), F2 = n(9793); e.WEBGL_OP_RESOLVE_RULES = [["Abs", "", "6+", k4.abs], ["Acos", "", "7+", k4.acos], ["Add", "", "7+", s.add], ["And", "", "7+", s.and], ["Asin", "", "7+", k4.asin], ["Atan", "", "7+", k4.atan], ["AveragePool", "", "7+", v.averagePool, v.parseAveragePoolAttributes], ["BatchNormalization", "", "7+", a.batchNormalization, a.parseBatchNormalizationAttributes], ["Cast", "", "6+", u.cast, u.parseCastAttributes], ["Ceil", "", "6+", k4.ceil], ["Clip", "", "6-10", k4.clip, k4.parseClipAttributes], ["Clip", "", "11+", k4.clipV11], ["Concat", "", "4+", c.concat, c.parseConcatAttributes], ["Conv", "", "1+", l.conv, l.parseConvAttributes], ["ConvTranspose", "", "1+", p.convTranspose, p.parseConvTransposeAttributes], ["Cos", "", "7+", k4.cos], ["Div", "", "7+", s.div], ["Dropout", "", "7+", k4.identity], ["DepthToSpace", "", "1+", f.depthToSpace, f.parseDepthToSpaceAttributes], ["Equal", "", "7+", s.equal], ["Elu", "", "6+", k4.elu, k4.parseEluAttributes], ["Exp", "", "6+", k4.exp], ["Flatten", "", "1+", d.flatten, d.parseFlattenAttributes], ["Floor", "", "6+", k4.floor], ["FusedConv", "com.microsoft", "1+", l.conv, l.parseConvAttributes], ["Gather", "", "1+", h.gather, h.parseGatherAttributes], ["Gemm", "", "7-10", g.gemm, g.parseGemmAttributesV7], ["Gemm", "", "11+", g.gemm, g.parseGemmAttributesV11], ["GlobalAveragePool", "", "1+", v.globalAveragePool, v.parseGlobalAveragePoolAttributes], ["GlobalMaxPool", "", "1+", v.globalMaxPool], ["Greater", "", "7+", s.greater], ["Identity", "", "1+", k4.identity], ["ImageScaler", "", "1+", b.imageScaler, b.parseImageScalerAttributes], ["InstanceNormalization", "", "6+", m2.instanceNormalization, m2.parseInstanceNormalizationAttributes], ["LeakyRelu", "", "6+", k4.leakyRelu, k4.parseLeakyReluAttributes], ["Less", "", "7+", s.less], ["Log", "", "6+", k4.log], ["MatMul", "", "1+", y.matMul, y.parseMatMulAttributes], ["MaxPool", "", "1+", v.maxPool, v.parseMaxPoolAttributes], ["Mul", "", "7+", s.mul], ["Neg", "", "6+", k4.neg], ["Not", "", "1+", k4.not], ["Or", "", "7+", s.or], ["Pad", "", "2-10", _.padV2, _.parsePadAttributesV2], ["Pad", "", "11+", _.padV11, _.parsePadAttributesV11], ["Pow", "", "7+", s.pow], ["PRelu", "", "7+", s.pRelu], ["ReduceLogSum", "", "1+", w.reduceLogSum, w.parseReduceAttributes], ["ReduceMax", "", "1+", w.reduceMax, w.parseReduceAttributes], ["ReduceMean", "", "1+", w.reduceMean, w.parseReduceAttributes], ["ReduceMin", "", "1+", w.reduceMin, w.parseReduceAttributes], ["ReduceProd", "", "1+", w.reduceProd, w.parseReduceAttributes], ["ReduceSum", "", "1-12", w.reduceSum, w.parseReduceAttributes], ["ReduceSumSquare", "", "1+", w.reduceLogSumSquare, w.parseReduceAttributes], ["Relu", "", "6+", k4.relu], ["Reshape", "", "5+", x2.reshape], ["Resize", "", "10", T3.resize, T3.parseResizeAttributesV10], ["Resize", "", "11+", T3.resize, T3.parseResizeAttributesV11], ["Shape", "", "1+", S.shape], ["Sigmoid", "", "6+", k4.sigmoid], ["Sin", "", "7+", k4.sin], ["Slice", "", "10+", O2.sliceV10], ["Slice", "", "1-9", O2.slice, O2.parseSliceAttributes], ["Softmax", "", "1-12", A2.softmax, A2.parseSoftmaxAttributes], ["Softmax", "", "13+", A2.softmaxV13, A2.parseSoftmaxAttributesV13], ["Split", "", "2-12", E2.split, E2.parseSplitAttributes], ["Sqrt", "", "6+", k4.sqrt], ["Squeeze", "", "1-12", I2.squeeze, I2.parseSqueezeAttributes], ["Squeeze", "", "13+", I2.squeezeV13], ["Sub", "", "7+", s.sub], ["Sum", "", "6+", P2.sum], ["Tan", "", "7+", k4.tan], ["Tanh", "", "6+", k4.tanh], ["Tile", "", "6+", D3.tile], ["Transpose", "", "1+", $2.transpose, $2.parseTransposeAttributes], ["Upsample", "", "7-8", F2.upsample, F2.parseUpsampleAttributesV7], ["Upsample", "", "9", F2.upsample, F2.parseUpsampleAttributesV9], ["Unsqueeze", "", "1-12", C.unsqueeze, C.parseUnsqueezeAttributes], ["Unsqueeze", "", "13+", C.unsqueezeV13], ["Xor", "", "7+", s.xor]]; }, 2898: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseBatchNormalizationAttributes = e.batchNormalization = void 0; const r = n(246), i = n(5060), o = n(2039), a = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] }; e.batchNormalization = (t2, e2, n2) => (u(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2, n2) }), e2)]), e.parseBatchNormalizationAttributes = (t2) => { const e2 = t2.attributes.getFloat("epsilon", 1e-5), n2 = t2.attributes.getFloat("momentum", 0.9), i2 = t2.attributes.getInt("spatial", 1); return (0, r.createAttributeWithCacheKey)({ epsilon: e2, momentum: n2, spatial: i2 }); }; const s = (t2, e2, n2) => { const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), s2 = e2[0].dims.length, [u2, c] = t2.calculateTextureWidthAndHeight(e2[1].dims, o.TextureType.unpacked), l = ` float process(int[${s2}] indices) { vec2 position = offsetToCoords(indices[1], ${u2}, ${c}); float scale = getColorAsFloat(${r2.texture2D}(Scale, position)); float mean = getColorAsFloat(${r2.texture2D}(Mean, position)); float variance = getColorAsFloat(${r2.texture2D}(Variance, position)); float b = getColorAsFloat(${r2.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n2.epsilon})) ) + b; }`; return Object.assign(Object.assign({}, a), { output: { dims: e2[0].dims, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: l }); }, u = (t2) => { if (!t2 || 5 !== t2.length) throw new Error("BatchNormalization requires 5 inputs."); const e2 = t2[0], n2 = t2[1], r2 = t2[2], i2 = t2[3], o2 = t2[4]; if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length || 1 !== i2.dims.length || 1 !== o2.dims.length) throw new Error("invalid input shape."); if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1] || i2.dims[0] !== e2.dims[1] || o2.dims[0] !== e2.dims[1]) throw new Error("invalid input shape."); if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type || "float32" !== i2.type && "float64" !== i2.type || "float32" !== o2.type && "float64" !== o2.type) throw new Error("invalid input tensor types."); }; }, 7839: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.xor = e.sub = e.pRelu = e.pow = e.or = e.mul = e.less = e.greater = e.equal = e.div = e.and = e.add = e.glslPRelu = e.glslPow = e.glslXor = e.glslOr = e.glslAnd = e.glslLess = e.glslGreater = e.glslEqual = e.glslSub = e.glslMul = e.glslDiv = e.glslAdd = void 0; const r = n(2517), i = n(8520), o = n(5060), a = n(2039); function s() { const t2 = "add_"; return { body: ` float ${t2}(float a, float b) { return a + b; } vec4 ${t2}(vec4 v1, vec4 v2) { return v1 + v2; } `, name: t2, type: i.FunctionType.ValueBased }; } function u() { const t2 = "div_"; return { body: ` float ${t2}(float a, float b) { return a / b; } vec4 ${t2}(vec4 v1, vec4 v2) { return v1 / v2; } `, name: t2, type: i.FunctionType.ValueBased }; } function c() { const t2 = "mul_"; return { body: ` float ${t2}(float a, float b) { return a * b; } vec4 ${t2}(vec4 v1, vec4 v2) { return v1 * v2; } `, name: t2, type: i.FunctionType.ValueBased }; } function l() { const t2 = "sub_"; return { body: ` float ${t2}(float a, float b) { return a - b; } vec4 ${t2}(vec4 v1, vec4 v2) { return v1 - v2; } `, name: t2, type: i.FunctionType.ValueBased }; } function p() { const t2 = "equal_"; return { body: ` float ${t2}(float a, float b) { return float(a == b); } vec4 ${t2}(vec4 v1, vec4 v2) { return vec4(equal(v1, v2)); } `, name: t2, type: i.FunctionType.ValueBased }; } function f() { const t2 = "greater_"; return { body: ` float ${t2}(float a, float b) { return float(a > b); } vec4 ${t2}(vec4 v1, vec4 v2) { return vec4( v1.r > v2.r , v1.g > v2.g, v1.b > v2.b, v1.a > v2.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } function d() { const t2 = "less_"; return { body: ` float ${t2}(float a, float b) { return float(a < b); } vec4 ${t2}(vec4 v1, vec4 v2) { return vec4( v1.r < v2.r , v1.g < v2.g, v1.b < v2.b, v1.a < v2.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } function h() { const t2 = "and_"; return { body: ` float ${t2}(float a, float b) { return float( bool(a) && bool(b) ); } vec4 ${t2}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r && b2.r , b1.g && b2.g, b1.b && b2.b, b1.a && b2.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } function g() { const t2 = "or_"; return { body: ` float ${t2}(float a, float b) { return float( bool(a) || bool(b) ); } vec4 ${t2}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r || b2.r , b1.g || b2.g, b1.b || b2.b, b1.a || b2.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } function b() { const t2 = "xor_"; return { body: ` float ${t2}(float a, float b) { return float( bool(a) ^^ bool(b) ); } vec4 ${t2}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r ^^ b2.r , b1.g ^^ b2.g, b1.b ^^ b2.b, b1.a ^^ b2.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } function m2() { return (function(t2) { const e2 = `${t2}_`; return { body: ` float ${e2}(float a, float b) { return ${t2}(a, b); } vec4 ${e2}(vec4 v1, vec4 v2) { return ${t2}(v1, v2); } `, name: e2, type: i.FunctionType.ValueBased }; })("pow"); } function y() { const t2 = "prelu_"; return { body: ` float ${t2}(float a, float b) { return a < 0.0 ? a * b: a; } vec4 ${t2}(vec4 v1, vec4 v2) { return vec4( v1.r < 0.0 ? v1.r * v2.r: v1.r, v1.g < 0.0 ? v1.g * v2.g: v1.g, v1.b < 0.0 ? v1.b * v2.b: v1.b, v1.a < 0.0 ? v1.a * v2.a: v1.a ); } `, name: t2, type: i.FunctionType.ValueBased }; } e.glslAdd = s, e.glslDiv = u, e.glslMul = c, e.glslSub = l, e.glslEqual = p, e.glslGreater = f, e.glslLess = d, e.glslAnd = h, e.glslOr = g, e.glslXor = b, e.glslPow = m2, e.glslPRelu = y; const _ = (t2, e2, n2, r2 = e2[0].type, i2) => { const o2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked; return { name: n2.name, inputNames: ["A", "B"], inputTypes: [o2, o2], cacheHint: i2, get: () => v(t2, e2, n2, r2) }; }, v = (t2, e2, n2, i2 = e2[0].type) => { const s2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked, u2 = !r.ShapeUtil.areEqual(e2[0].dims, e2[1].dims); let c2 = e2[0].dims; const l2 = t2.session.pack; if (u2) { const a2 = r.BroadcastUtil.calcShape(e2[0].dims, e2[1].dims, false); if (!a2) throw new Error("Can't perform binary op on the given tensors"); c2 = a2; const u3 = c2.length, p3 = 0 !== e2[0].dims.length ? e2[0].dims.length : 1, f3 = 0 !== e2[1].dims.length ? e2[1].dims.length : 1, d2 = 0 !== e2[0].dims.length ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", h2 = 0 !== e2[1].dims.length ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", g2 = (0, o.getGlsl)(t2.session.backend.glContext.version), b2 = l2 ? ` ${n2.body} void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = ${n2.name}(a, b); ${g2.output} = result; }` : ` ${n2.body} float process(int indices[${u3}]) { int aindices[${p3}]; int bindices[${f3}]; ${d2} ${h2} return ${n2.name}(_A(aindices), _B(bindices)); }`; return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: c2, type: i2, textureType: s2 }, shaderSource: b2, hasMain: l2 }; } const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = ` ${n2.body} void main() { vec4 v1 = ${p2.texture2D}(A, TexCoords); vec4 v2 = ${p2.texture2D}(B, TexCoords); vec4 result = ${n2.name}(v1, v2); ${p2.output} = result; } `; return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: e2[0].dims, type: i2, textureType: s2 }, shaderSource: f2, hasMain: true }; }; e.add = (t2, e2) => [t2.run(_(t2, e2, s()), e2)], e.and = (t2, e2) => [t2.run(_(t2, e2, h(), "bool"), e2)], e.div = (t2, e2) => [t2.run(_(t2, e2, u()), e2)], e.equal = (t2, e2) => [t2.run(_(t2, e2, p(), "bool"), e2)], e.greater = (t2, e2) => [t2.run(_(t2, e2, f(), "bool"), e2)], e.less = (t2, e2) => [t2.run(_(t2, e2, d(), "bool"), e2)], e.mul = (t2, e2) => [t2.run(_(t2, e2, c()), e2)], e.or = (t2, e2) => [t2.run(_(t2, e2, g(), "bool"), e2)], e.pow = (t2, e2) => [t2.run(_(t2, e2, m2()), e2)], e.pRelu = (t2, e2) => [t2.run(_(t2, e2, y()), e2)], e.sub = (t2, e2) => [t2.run(_(t2, e2, l()), e2)], e.xor = (t2, e2) => [t2.run(_(t2, e2, b(), "bool"), e2)]; }, 4196: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseCastAttributes = e.cast = void 0; const r = n(2517); e.cast = (t2, e2, n2) => (i(e2), [t2.cast(e2[0], n2)]), e.parseCastAttributes = (t2) => r.ProtoUtil.tensorDataTypeFromProto(t2.attributes.getInt("to")); const i = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Cast requires 1 input."); if ("string" === t2[0].type) throw new Error("Invalid input type."); }; }, 1163: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createPackedConcatProgramInfoLoader = void 0; const r = n(5060), i = n(2039), o = n(9390), a = n(2827); e.createPackedConcatProgramInfoLoader = (t2, e2, n2) => { const u = (c = e2.length, l = n2.cacheKey, { name: "Concat (packed)", inputNames: Array.from({ length: c }, ((t3, e3) => `X${e3}`)), inputTypes: Array(c).fill(i.TextureType.packed), cacheHint: l }); var c, l; return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => { const c2 = n3[0].dims.slice(); if (u2 >= c2.length || u2 < -1 * c2.length) throw new Error("axis specified for concat doesn't match input dimensionality"); u2 < 0 && (u2 = c2.length + u2); const l2 = c2.slice(0); for (let t4 = 1; t4 < n3.length; t4++) { const e4 = n3[t4].dims.slice(); for (let t5 = 0; t5 < c2.length; t5++) if (t5 === u2) l2[u2] += e4[t5]; else if (c2[t5] !== e4[t5]) throw new Error("non concat dimensions must match"); } const p = l2.length, f = (0, a.getChannels)("coords", p), d = (0, o.getCoordsDataType)(p), h = (0, a.unpackFromChannel)(), g = n3.map(((t4) => t4.dims)), b = (0, o.getGlChannels)(p), m2 = new Array(g.length - 1); m2[0] = g[0][u2]; for (let t4 = 1; t4 < m2.length; t4++) m2[t4] = m2[t4 - 1] + g[t4][u2]; const y = b[u2], _ = b.slice(-2), v = b.join(); let w = `if (${y} < ${m2[0]}) { return getChannel( getX0(${v}), vec2(${_.join()})); }`; for (let t4 = 1; t4 < m2.length; t4++) { const e4 = m2[t4 - 1]; w += ` if (${y} < ${m2[t4]} && ${y} >= ${m2[t4 - 1]}) { return getChannel( getX${t4}(${s(b, y, e4)}), vec2(${s(_, y, e4)})); }`; } const x2 = m2.length, T3 = m2[m2.length - 1]; w += ` return getChannel( getX${x2}(${s(b, y, T3)}), vec2(${s(_, y, T3)}));`; const S = (0, r.getGlsl)(t3.session.backend.glContext.version), O2 = ` ${h} float getValue(${b.map(((t4) => "int " + t4))}) { ${w} } void main() { ${d} coords = getOutputCoords(); int lastDim = coords.${b[p - 1]}; coords.${b[p - 1]} = coords.${b[p - 2]}; coords.${b[p - 2]} = lastDim; vec4 result = vec4(getValue(${f}), 0., 0., 0.); ${f[p - 1]} = ${f[p - 1]} + 1; if (${f[p - 1]} < ${l2[p - 1]}) { result.g = getValue(${f}); } ${f[p - 2]} = ${f[p - 2]} + 1; if (${f[p - 2]} < ${l2[p - 2]}) { result.a = getValue(${f}); } ${f[p - 1]} = ${f[p - 1]} - 1; if (${f[p - 2]} < ${l2[p - 2]} && ${f[p - 1]} < ${l2[p - 1]}) { result.b = getValue(${f}); } ${S.output} = result; } `; return Object.assign(Object.assign({}, e3), { output: { dims: l2, type: n3[0].type, textureType: i.TextureType.packed }, shaderSource: O2, hasMain: true }); })(t2, u, e2, n2.axis) }); }; const s = (t2, e2, n2) => { const r2 = t2.indexOf(e2); return t2.map(((t3, e3) => e3 === r2 ? `${t3} - ${n2}` : t3)).join(); }; }, 2069: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseConcatAttributes = e.concat = void 0; const r = n(246), i = n(2039), o = n(1163); e.concat = (t2, e2, n2) => (p(e2), t2.session.pack && e2[0].dims.length > 1 ? [t2.run((0, o.createPackedConcatProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(a(t2, e2, n2), e2)]); const a = (t2, e2, n2) => { const r2 = (o2 = e2.length, a2 = n2.cacheKey, { name: "Concat", inputNames: Array.from({ length: o2 }, ((t3, e3) => `X${e3}`)), inputTypes: Array(o2).fill(i.TextureType.unpacked), cacheHint: a2 }); var o2, a2; return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { const o3 = n3[0].dims.slice(); if (r3 >= o3.length || r3 < -1 * o3.length) throw new Error("axis specified for concat doesn't match input dimensionality"); r3 < 0 && (r3 = o3.length + r3); const a3 = o3.slice(0); for (let t4 = 1; t4 < n3.length; t4++) { const e4 = n3[t4].dims.slice(); for (let t5 = 0; t5 < o3.length; t5++) if (t5 === r3) a3[r3] += e4[t5]; else if (o3[t5] !== e4[t5]) throw new Error("non concat dimensions must match"); } const p2 = a3.length, f = new Array(n3.length); let d = 0; for (let t4 = 0; t4 < f.length; ++t4) d += n3[t4].dims[r3], f[t4] = d; let h = ""; h = n3.length < 5 ? s(f) : u(f); const g = ` ${c(n3.length, p2)} ${l(f)} ${h} float process(int indices[${p2}]) { int textureIndex = getTextureWhereDataResides (indices[${r3}]); if(textureIndex != 0) { indices[${r3}] = indices[${r3}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1))); } return fetchDataFromCorrectTexture(textureIndex, indices); }`; return Object.assign(Object.assign({}, e3), { output: { dims: a3, type: n3[0].type, textureType: i.TextureType.unpacked }, shaderSource: g }); })(0, r2, e2, n2.axis) }); }, s = (t2) => `int getTextureWhereDataResides(int index) { ${t2.map(((t3, e2) => `if(index<${t3}) {return ${e2};} `)).join("")} }`, u = (t2) => s(t2), c = (t2, e2) => { const n2 = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e2}]) {`]; for (let e3 = 0; e3 < t2; ++e3) 0 === e3 ? n2.push(` if (textureIndex == ${e3}) { return _X${e3}(indices); }`) : e3 === t2 - 1 ? n2.push(` else { return _X${e3}(indices); }`) : n2.push(` else if (textureIndex == ${e3}) { return _X${e3}(indices); }`); return n2.push(" }"), n2.join("\n"); }, l = (t2) => { const e2 = ["int getSizeInConcatAxisValueFromIndex(int index) {"]; for (let n2 = 0; n2 < t2.length; ++n2) 0 === n2 ? e2.push(` if (index == ${n2}) { return ${t2[n2]}; }`) : n2 === t2.length - 1 ? e2.push(` else { return ${t2[n2]}; }`) : e2.push(` else if (index == ${n2}) { return ${t2[n2]}; }`); return e2.push(" }"), e2.join("\n"); }; e.parseConcatAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis") }); const p = (t2) => { if (!t2 || t2.length < 1) throw new Error("too few inputs"); const e2 = t2[0].type, n2 = t2[0].dims.length; if ("string" === e2) throw new Error("string tensor is not supported yet"); for (const r2 of t2) { if (r2.type !== e2) throw new Error("input tensors should be one type"); if (r2.dims.length !== n2) throw new Error("input tensors should have the same shape"); } }; }, 4770: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackedGroupedConvProgramInfoLoader = void 0; const r = n(6231), i = n(5060), o = n(2039), a = n(8138), s = n(2823); e.createUnpackedGroupedConvProgramInfoLoader = (t2, e2, n2) => { const u = (c = e2.length > 2, l = n2.cacheKey, { name: "GroupedConv", inputNames: c ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: c ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: l }); var c, l; return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => { const c2 = e3.length > 2 ? "value += getBias(output_channel);" : "", l2 = e3[0].dims.slice(), p = e3[1].dims.slice(), f = p[0] / u2.group; r.Logger.verbose("GroupedConv", `autpPad:${u2.autoPad}, dilations:${u2.dilations}, group:${u2.group}, kernelShape:${u2.kernelShape}, pads:${u2.pads}, strides:${u2.strides}`); const d = (0, a.calculateOutputShape)(l2, p, u2.dilations, u2.pads, u2.strides), h = (0, i.getGlsl)(t3.session.backend.glContext.version), { activationFunction: g, applyActivation: b } = (0, s.getActivationSnippet)(u2), m2 = ` const ivec2 strides = ivec2(${u2.strides[0]}, ${u2.strides[1]}); const ivec2 pads = ivec2(${u2.pads[0]}, ${u2.pads[1]}); ${g} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 xRCCorner = coords.zw * strides - pads; int group_id = output_channel / ${f}; float value = 0.0; for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) { int input_channel = group_id * ${p[1]} + wInChannel; for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) { int xHeight = xRCCorner.x + wHeight * ${u2.dilations[0]}; if (xHeight < 0 || xHeight >= ${l2[2]}) { continue; } for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) { int xWidth = xRCCorner.y + wWidth * ${u2.dilations[1]}; if (xWidth < 0 || xWidth >= ${l2[3]}) { continue; } float xVal = getX(batch, input_channel, xWidth, xHeight); float wVal = getW(output_channel, wInChannel, wWidth, wHeight); value += xVal*wVal; } } } ${c2} ${b} ${h.output} = vec4(value, .0, .0, .0); } `; return Object.assign(Object.assign({}, n3), { output: { dims: d, type: e3[0].type, textureType: o.TextureType.unpacked }, shaderSource: m2, hasMain: true }); })(t2, e2, u, n2) }); }; }, 1386: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.conv2DPacked = e.conv2DPackedPointwise = void 0; const r = n(8138), i = n(8555), o = n(708); e.conv2DPackedPointwise = (t2, e2, n2) => { const i2 = e2[0].dims, a = e2[1].dims, s = (0, r.calculateOutputShape)(i2, a, n2.dilations, n2.pads, n2.strides), u = t2.reshapePacked(e2[0], [i2[1], i2[2] * i2[3]]), c = t2.reshapePacked(e2[1], [a[0], a[1]]), l = e2.length > 2 ? [c, u, e2[2]] : [c, u], p = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, l, n2), l); return t2.reshapePacked(p, s); }, e.conv2DPacked = (t2, e2, n2) => { const a = e2[0].dims, s = e2[1].dims, u = (0, r.calculateOutputShape)(a, s, n2.dilations, n2.pads, n2.strides), c = t2.run((0, i.createPackedIm2ColProgramInfoLoader)(t2, e2[0], e2[1], u, n2), [e2[0]]), l = t2.reshapePacked(e2[1], [s[0], s[1] * s[2] * s[3]]), p = 3 === e2.length ? [l, c, e2[2]] : [l, c], f = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, p, n2), p); return t2.reshapePacked(f, u); }; }, 9663: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseConvTransposeAttributes = e.convTranspose = void 0; const r = n(246), i = n(5060), o = n(2039), a = n(2823), s = (t2, e2, n2, r2, i2, o2) => (t2 - 1) * e2 + n2 + (r2 - 1) * i2 + 1 - o2, u = (t2, e2, n2, r2, i2) => { const o2 = Math.floor(t2 / 2); "SAME_UPPER" === e2 ? (n2[r2] = o2, n2[i2] = t2 - o2) : "SAME_LOWER" === e2 && (n2[r2] = t2 - o2, n2[i2] = o2); }; e.convTranspose = (t2, e2, n2) => (f(e2, n2), c(t2, e2, n2)); const c = (t2, e2, n2) => { const r2 = p(n2, e2); return [l(t2, e2, r2)]; }, l = (t2, e2, n2) => t2.run(((t3, e3, n3) => { const r2 = (s2 = e3.length > 2, u2 = n3.cacheKey, { name: "ConvTranspose", inputNames: s2 ? ["X", "W", "B"] : ["X", "W"], inputTypes: s2 ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: u2 }); var s2, u2; return Object.assign(Object.assign({}, r2), { get: () => ((t4, e4, n4, r3) => { const s3 = e4.length > 2 ? "getB(output_channel)" : "0.0", u3 = e4[0].dims, c2 = e4[1].dims, l2 = c2[1], p2 = c2[0] / r3.group, f2 = [e4[0].dims[0], e4[1].dims[1] * r3.group, ...r3.outputShape], d = (0, i.getGlsl)(t4.session.backend.glContext.version), { activationFunction: h, applyActivation: g } = (0, a.getActivationSnippet)(r3), b = ` const ivec2 strides = ivec2(${r3.strides[0]}, ${r3.strides[1]}); const ivec2 pads = ivec2(${r3.pads[0]}, ${r3.pads[1]}); ${h} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 loc = coords.zw + pads; int group_id = output_channel / ${l2}; int wOutChannel = output_channel - group_id * ${l2}; float value = ${s3}; for (int inChannelOffset = 0; inChannelOffset < ${p2}; inChannelOffset++) { int input_channel = group_id * ${p2} + inChannelOffset; for (int wWOff = 0; wWOff < ${c2[2]}; wWOff++) { for (int wHOff = 0; wHOff < ${c2[3]}; wHOff++) { ivec2 wOff = ivec2(wWOff * ${r3.dilations[0]}, wHOff * ${r3.dilations[1]}); ivec2 wLoc = loc - wOff; ivec2 wLocIn = wLoc / strides; if ( wLocIn * strides == wLoc && wLocIn.x >= 0 && wLocIn.x < ${u3[2]} && wLocIn.y >= 0 && wLocIn.y < ${u3[3]} ) { float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); value += xVal * wVal; } } } } ${g} ${d.output} = vec4(value, .0, .0, .0); } `; return Object.assign(Object.assign({}, n4), { output: { dims: f2, type: e4[0].type, textureType: o.TextureType.unpacked }, shaderSource: b, hasMain: true }); })(t3, e3, r2, n3) }); })(t2, e2, n2), e2), p = (t2, e2) => { const n2 = t2.kernelShape.slice(); if (0 === t2.kernelShape.length) for (let t3 = 2; t3 < e2[1].dims.length; ++t3) n2.push(e2[1].dims[t3]); const r2 = t2.pads.slice(), i2 = t2.outputShape.slice(); ((t3, e3, n3, r3, i3, o3, a2, c2) => { const l2 = t3.length - 2, p2 = 0 === c2.length; for (let f2 = 0; f2 < l2; ++f2) { const d = p2 ? t3[f2 + 2] * o3[f2] : c2[f2], h = s(t3[f2 + 2], o3[f2], i3[f2], e3[f2], n3[f2], d); u(h, r3, i3, f2, f2 + l2), p2 && c2.push(o3[f2] * (t3[f2 + 2] - 1) + a2[f2] + (e3[f2] - 1) * n3[f2] + 1 - i3[f2] - i3[f2 + l2]); } })(e2[0].dims, n2, t2.dilations, t2.autoPad, r2, t2.strides, t2.outputPadding, i2); const o2 = Object.assign({}, t2); return Object.assign(o2, { kernelShape: n2, pads: r2, outputShape: i2, cacheKey: t2.cacheKey }), o2; }; e.parseConvTransposeAttributes = (t2) => { const e2 = t2.attributes, n2 = (0, a.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), s2 = e2.getInt("group", 1), u2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("output_padding", [0, 0]), l2 = e2.getInts("output_shape", []), p2 = e2.getInts("pads", [0, 0, 0, 0]), f2 = e2.getInts("strides", [1, 1]); return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: s2, kernelShape: u2, outputPadding: c2, outputShape: l2, pads: p2, strides: f2 }, n2)); }; const f = (t2, e2) => { if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Conv requires 2 or 3 inputs"); if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) throw new Error("currently only support 2-dimensional conv"); if (t2[0].dims[1] !== t2[1].dims[0]) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); const n2 = t2[1].dims[1] * e2.group; if (3 === t2.length && (1 !== t2[2].dims.length || t2[2].dims[0] !== n2)) throw new Error("invalid bias"); const r2 = t2[0].dims.length - 2; if (e2.dilations.length !== r2) throw new Error(`dilations should be ${r2}D`); if (e2.strides.length !== r2) throw new Error(`strides should be ${r2}D`); if (e2.pads.length !== 2 * r2) throw new Error(`pads should be ${2 * r2}D`); if (e2.outputPadding.length !== r2) throw new Error(`output_padding should be ${r2}D`); if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) throw new Error("invalid kernel shape"); if (0 !== e2.outputShape.length && e2.outputShape.length !== t2[0].dims.length - 2) throw new Error("invalid output shape"); if ("float32" !== t2[0].type || "float32" !== t2[1].type) throw new Error("ConvTranspose input(X,W) should be float tensor"); if (3 === t2.length && "float32" !== t2[2].type) throw new Error("ConvTranspose input(bias) should be float tensor"); }; }, 8138: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseConvAttributes = e.conv = e.calculateOutputShape = void 0; const r = n(246), i = n(2517), o = n(4770), a = n(1386), s = n(9828), u = n(2823), c = n(3248), l = n(5623); e.calculateOutputShape = (t2, e2, n2, r2, i2) => { const o2 = t2[0], a2 = t2.slice(2), s2 = a2.length, u2 = e2[0], c2 = e2.slice(2).map(((t3, e3) => t3 + (t3 - 1) * (n2[e3] - 1))), l2 = a2.map(((t3, e3) => t3 + r2[e3] + r2[e3 + s2])).map(((t3, e3) => Math.floor((t3 - c2[e3] + i2[e3]) / i2[e3]))); return [o2, u2].concat(...l2); }, e.conv = (t2, e2, n2) => (g(e2, n2), p(t2, e2, n2)); const p = (t2, e2, n2) => { const r2 = h(n2, e2), i2 = t2.session.pack, s2 = 1 === r2.kernelShape[0] && 1 === r2.kernelShape[1]; return r2.group > 1 ? [t2.run((0, o.createUnpackedGroupedConvProgramInfoLoader)(t2, e2, r2), e2)] : s2 && i2 ? [f(t2, e2, r2)] : i2 && 4 === e2[0].dims.length && 1 === e2[0].dims[0] && !s2 ? [(0, a.conv2DPacked)(t2, e2, r2)] : [d(t2, e2, r2)]; }, f = (t2, n2, r2) => { const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), s2 = t2.reshapeUnpacked(n2[0], [i2[1], i2[2] * i2[3]]), u2 = t2.reshapeUnpacked(n2[1], [o2[0], o2[1]]), c2 = n2.length > 2 ? [u2, s2, n2[2]] : [u2, s2], p2 = t2.run((0, l.createMatmulProgramInfoLoader)(c2, r2), c2); return t2.reshapeUnpacked(p2, a2); }, d = (t2, n2, r2) => { const i2 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i2, o2, r2.dilations, r2.pads, r2.strides), u2 = t2.run((0, c.createIm2ColProgramInfoLoader)(t2, n2[0], n2[1], a2, r2), [n2[0]]), l2 = 3 === n2.length ? [u2, n2[1], n2[2]] : [u2, n2[1]]; return t2.run((0, s.createDotProductProgramInfoLoader)(t2, n2, a2, r2), l2); }, h = (t2, e2) => { const n2 = t2.kernelShape.slice(); if (0 === t2.kernelShape.length) for (let t3 = 2; t3 < e2[1].dims.length; ++t3) n2.push(e2[1].dims[t3]); const r2 = t2.pads.slice(); i.PoolConvUtil.adjustPadsBasedOnAutoPad(e2[0].dims, t2.strides, t2.dilations, n2, r2, t2.autoPad); const o2 = Object.assign({}, t2); return Object.assign(o2, { kernelShape: n2, pads: r2, cacheKey: t2.cacheKey }), o2; }; e.parseConvAttributes = (t2) => { const e2 = t2.attributes, n2 = (0, u.parseInternalActivationAttributes)(e2), i2 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), a2 = e2.getInt("group", 1), s2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("pads", [0, 0, 0, 0]), l2 = e2.getInts("strides", [1, 1]); return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i2, dilations: o2, group: a2, kernelShape: s2, pads: c2, strides: l2 }, n2)); }; const g = (t2, e2) => { if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Conv requires 2 or 3 inputs"); if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) throw new Error("currently only support 2-dimensional conv"); if (t2[0].dims[1] !== t2[1].dims[1] * e2.group) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); if (3 === t2.length && (1 !== t2[2].dims.length || t2[1].dims[0] !== t2[2].dims[0])) throw new Error("invalid bias"); const n2 = t2[0].dims.length - 2; if (e2.dilations.length !== n2) throw new Error(`dilations should be ${n2}D`); if (e2.strides.length !== n2) throw new Error(`strides should be ${n2}D`); if (e2.pads.length !== 2 * n2) throw new Error(`pads should be ${2 * n2}D`); if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) throw new Error("invalid kernel shape"); if ("float32" !== t2[0].type || "float32" !== t2[1].type) throw new Error("Conv input(X,W) should be float tensor"); if (3 === t2.length && "float32" !== t2[2].type) throw new Error("Conv input(bias) should be float tensor"); }; }, 5193: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseDepthToSpaceAttributes = e.depthToSpace = void 0; const r = n(3738); e.depthToSpace = (t2, e2, n2) => { i(e2); const o = n2.blocksize, a = o * o, s = "DCR" === n2.mode ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], u = "DCR" === n2.mode ? [e2[0].dims[0], o, o, e2[0].dims[1] / a, e2[0].dims[2], e2[0].dims[3]] : [e2[0].dims[0], e2[0].dims[1] / a, o, o, e2[0].dims[2], e2[0].dims[3]], c = t2.reshapeUnpacked(e2[0], u), l = { perm: s, cacheKey: `${s}` }, [p] = (0, r.transpose)(t2, [c], l), f = [e2[0].dims[0], e2[0].dims[1] / a, e2[0].dims[2] * o, e2[0].dims[3] * o]; return [t2.reshapeUnpacked(p, f)]; }, e.parseDepthToSpaceAttributes = (t2) => { const e2 = t2.attributes.getInt("blocksize"); if (e2 < 1) throw new Error(`blocksize must be >= 1, but got : ${e2} for DepthToSpace`); const n2 = t2.attributes.getString("mode", "DCR"); if ("DCR" !== n2 && "CRD" !== n2) throw new Error(`unrecognized mode: ${n2} for DepthToSpace`); return { mode: n2, blocksize: e2 }; }; const i = (t2) => { if (1 !== t2.length) throw new Error(`DepthToSpace expect 1 inputs, but got ${t2.length}`); if ("string" === t2[0].type || 4 !== t2[0].dims.length) throw new TypeError("DepthToSpace input should be a 4-D numeric tensor"); }; }, 9828: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createDotProductProgramInfoLoader = void 0; const r = n(2517), i = n(5060), o = n(2039), a = n(2823), s = n(3248); e.createDotProductProgramInfoLoader = (t2, e2, n2, u) => { const c = ((t3, e3) => ({ name: "ConvDotProduct", inputNames: t3 ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: t3 ? [o.TextureType.unpacked, o.TextureType.packedLastDimension, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.packedLastDimension], cacheKey: e3.activationCacheKey }))(e2.length > 2, u); return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, u2, c2) => { const l = n3[0].dims, p = n3[1].dims, f = [p[0], Math.ceil(l[1] * p[2] * p[3] / 4)], d = (0, s.calculateIm2ColDims)(l, p, u2), [h, g] = t3.calculateTextureWidthAndHeight(f, o.TextureType.packedLastDimension), b = r.ShapeUtil.computeStrides(d), [m2, y] = t3.calculateTextureWidthAndHeight(d, o.TextureType.packedLastDimension), _ = u2.length, v = n3.length < 3 ? "0.0" : "_B(b)", w = Math.ceil(l[1] * p[2] * p[3] / 4), { activationFunction: x2, applyActivation: T3 } = (0, a.getActivationSnippet)(c2), S = (0, i.getGlsl)(t3.session.backend.glContext.version), O2 = ` ${x2} float process(int indices[${_}]) { int b[1]; b[0] = indices[1]; int im2col[4]; im2col[0] = indices[0]; im2col[1] = indices[2]; im2col[2] = indices[3]; int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]}; int kernelOffset = indices[1] * ${f[1]}; float value = ${v}; for (int i = 0; i < ${w}; ++i) { vec2 im2colCoords = offsetToCoords(im2colOffset, ${m2}, ${y}); vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g}); value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords)); ++im2colOffset; ++kernelOffset; } ${T3} return value; }`; return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: o.TextureType.unpacked }, shaderSource: O2 }); })(t2, c, e2, n2, u) }); }; }, 7992: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseFlattenAttributes = e.flatten = void 0; const r = n(2517); e.flatten = (t2, e2, n2) => { i(e2, n2); const o = r.ShapeUtil.flattenShape(e2[0].dims, n2); return [t2.reshapeUnpacked(e2[0], o)]; }, e.parseFlattenAttributes = (t2) => t2.attributes.getInt("axis", 1); const i = (t2, e2) => { if (!t2 || 1 !== t2.length) throw new Error("Flatten requires 1 input."); const n2 = t2[0].dims.length; if (0 === n2) throw new Error("scalar tensor is not supported."); if (e2 < -n2 || e2 > n2) throw new Error("Invalid axis"); if ("string" === t2[0].type) throw new Error("string tensor is not supported."); }; }, 2823: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseInternalActivationAttributes = e.getActivationSnippet = void 0; const r = n(2517), i = n(4909); e.getActivationSnippet = function(t2) { let e2; switch (t2.activation) { case "Relu": e2 = (0, i.glslRelu)(); break; case "Sigmoid": e2 = (0, i.glslSigmoid)(); break; case "Clip": e2 = (0, i.glslClip)(t2.clipMin, t2.clipMax); break; default: return { activationFunction: "", applyActivation: "" }; } const n2 = e2.name; return { activationFunction: e2.body, applyActivation: `value = ${n2}_(value);` }; }, e.parseInternalActivationAttributes = (t2) => { const e2 = t2.getString("activation", ""); if ("Clip" === e2) { const [n2, i2] = t2.getFloats("activation_params", [r.MIN_CLIP, r.MAX_CLIP]); return { activation: e2, clipMax: i2, clipMin: n2, activationCacheKey: `${e2}:${n2},${i2}` }; } return { activation: e2, activationCacheKey: e2 }; }; }, 1253: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseGatherAttributes = e.gather = void 0; const r = n(246), i = n(782), o = n(2517), a = n(2039); e.gather = (t2, e2, n2) => (c(e2, n2.axis), [t2.run(u(t2, e2, n2), e2)]), e.parseGatherAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 0) }); const s = { name: "Gather", inputNames: ["A", "B"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, u = (t2, e2, n2) => { const r2 = Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey }); return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { const i2 = n3[0].dims.slice(), s2 = n3[1].dims.slice(), u2 = new Array(i2.length + s2.length - 1); r3 = o.ShapeUtil.normalizeAxis(r3, i2.length); const c2 = []; for (let t4 = 0; t4 < u2.length; t4++) t4 < r3 ? (u2[t4] = i2[t4], c2.push(`inputIdx[${t4}] = outputIdx[${t4}];`)) : t4 < r3 + s2.length ? (u2[t4] = s2[t4 - r3], c2.push(`indexDataIdx[${t4 - r3}] = outputIdx[${t4}];`)) : (u2[t4] = i2[t4 - s2.length + 1], c2.push(`inputIdx[${t4 - s2.length + 1}] = outputIdx[${t4}];`)); const l = ` float process(int outputIdx[${u2.length || 1}]) { int inputIdx[${i2.length}]; int indexDataIdx[${s2.length || 1}]; indexDataIdx[0] = 0; ${c2.join("\n ")} int idx = int(_B(indexDataIdx)); inputIdx[${r3}] = idx < 0 ? idx + ${i2[r3]} : idx; return _A(inputIdx); }`; return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: a.TextureType.unpacked }, shaderSource: l }); })(0, r2, e2, n2.axis) }); }, c = (t2, e2) => { if (!t2 || 2 !== t2.length) throw new Error("Gather requires 2 inputs."); const n2 = t2[0].dims.length; if (n2 < 1) throw new Error("Invalid input shape."); if (e2 < -n2 || e2 > n2 - 1) throw new Error("Invalid axis."); if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invaid input type."); if ("int32" !== t2[1].type && "int16" !== t2[1].type) throw new Error("Invaid input type."); }; }, 4776: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseGemmAttributesV11 = e.parseGemmAttributesV7 = e.gemm = void 0; const r = n(246), i = n(2517), o = n(2039); e.gemm = (t2, e2, n2) => (c(e2, n2), [t2.run(s(e2, n2), e2)]); const a = (t2, e2) => { const n2 = 0 !== t2.attributes.getInt("transA", 0), i2 = 0 !== t2.attributes.getInt("transB", 0), o2 = t2.attributes.getFloat("alpha", 1), a2 = t2.attributes.getFloat("beta", 1); return (0, r.createAttributeWithCacheKey)({ transA: n2, transB: i2, alpha: o2, beta: a2, isOptionalC: e2 }); }; e.parseGemmAttributesV7 = (t2) => a(t2, false), e.parseGemmAttributesV11 = (t2) => a(t2, true); const s = (t2, e2) => { const n2 = { name: "Gemm", inputNames: 3 === t2.length ? ["A", "B", "C"] : ["A", "B"], inputTypes: 3 === t2.length ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], key: e2.cacheKey }; return Object.assign(Object.assign({}, n2), { get: () => u(n2, t2, e2) }); }, u = (t2, e2, n2) => { const r2 = e2[0].dims.slice(), a2 = e2[1].dims.slice(), [s2, u2] = i.GemmUtil.getShapeOfGemmResult(r2, n2.transA, a2, n2.transB, 3 === e2.length ? e2[2].dims : void 0), c2 = [s2, u2]; if (!c2) throw new Error("Can't use gemm on the given tensors"); let l = r2[r2.length - 1], p = ""; n2.transA && (l = r2[0]), n2.transA && n2.transB ? p = "value += _A_T(a) * _B_T(b);" : n2.transA && !n2.transB ? p = "value += _A_T(a) * _B(b);" : !n2.transA && n2.transB ? p = "value += _A(a) * _B_T(b);" : n2.transA || n2.transB || (p = "value += _A(a) * _B(b);"); const f = c2.length, d = ` float process(int indices[${f}]) { int a[${f}]; int b[${f}]; ${3 === e2.length ? `int c[${e2[2].dims.length}];` : ""} copyVec(indices, a); copyVec(indices, b); ${3 === e2.length ? "bcastIndices_C(indices, c);" : ""} float value = 0.0; for (int k=0; k<${l}; ++k) { a[${f - 1}] = k; b[${f - 2}] = k; ${p} } value = value * alpha; ${3 === e2.length ? "value += beta * _C(c);" : ""} return value; }`; return Object.assign(Object.assign({}, t2), { output: { dims: c2, type: e2[0].type, textureType: o.TextureType.unpacked }, variables: [{ name: "alpha", type: "float", data: n2.alpha }, { name: "beta", type: "float", data: n2.beta }], shaderSource: d }); }, c = (t2, e2) => { if (!t2) throw new Error("Input is missing"); if (e2.isOptionalC && (t2.length < 2 || t2.length > 3)) throw new Error("Invaid input shape."); if (!e2.isOptionalC && 3 !== t2.length) throw new Error("Gemm requires 3 inputs"); if (3 === t2.length && 1 !== t2[2].dims.length && 2 !== t2[2].dims.length) throw new Error("Invalid input shape of C"); if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type || 3 === t2.length && "float32" !== t2[2].type && "float64" !== t2[2].type) throw new Error("Invalid input type."); if (t2[0].type !== t2[1].type || 3 === t2.length && t2[0].type !== t2[2].type) throw new Error("Input types are mismatched"); }; }, 8555: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createPackedIm2ColProgramInfoLoader = void 0; const r = n(5060), i = n(2039), o = n(2827); e.createPackedIm2ColProgramInfoLoader = (t2, e2, n2, a, s) => { const u = (c = s.cacheKey, { name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [i.TextureType.packed], cacheHint: c }); var c; return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, a2, s2, u2) => { const c2 = n3.dims, l = a2.dims, p = s2.length, f = [l[1] * l[2] * l[3], s2[2] * s2[3]], d = l[2] * l[3], h = (0, o.unpackFromChannel)(), g = (0, r.getGlsl)(t3.session.backend.glContext.version); let b = ""; for (let t4 = 0; t4 <= 1; t4++) for (let e4 = 0; e4 <= 1; e4++) b += ` blockIndex = rc.x + ${e4}; pos = rc.y + ${t4}; if(blockIndex < ${f[1]} && pos < ${f[0]}) { offsetY = int(blockIndex / (${s2[p - 1]})) * ${u2.strides[0]} - ${u2.pads[0]}; d0 = offsetY + ${u2.dilations[0]} * (imod(pos, ${d}) / ${l[2]}); if(d0 < ${c2[2]} && d0 >= 0) { offsetX = imod(blockIndex, ${s2[p - 1]}) * ${u2.strides[1]} - ${u2.pads[1]}; d1 = offsetX + ${u2.dilations[1]} * imod(imod(pos, ${d}), ${l[2]}); if(d1 < ${c2[3]} && d1 >= 0) { ch = int(float(pos)/ ${d}.); innerDims = vec2(d0, d1); result[${2 * t4 + e4}] = getChannel( getA(0, ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } `; const m2 = ` ${h} void main() { ivec2 rc = getOutputCoords(); vec4 result = vec4(0.0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${b} ${g.output} = result; } `; return Object.assign(Object.assign({}, e3), { output: { dims: f, type: n3.type, textureType: i.TextureType.packed }, shaderSource: m2, hasMain: true }); })(t2, u, e2, n2, a, s) }); }; }, 3248: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.calculateIm2ColDims = e.createIm2ColProgramInfoLoader = void 0; const r = n(2039); e.createIm2ColProgramInfoLoader = (t2, n2, i, o, a) => { const s = (u = a.cacheKey, { name: "Im2Col", inputNames: ["X"], inputTypes: [r.TextureType.unpacked], cacheHint: u }); var u; return Object.assign(Object.assign({}, s), { get: () => ((t3, n3, i2, o2, a2, s2) => { const u2 = i2.dims, c = o2.dims, l = a2.length, p = (0, e.calculateIm2ColDims)(u2, c, a2, 4), f = ` const int XC = ${u2[1]}; const int XH = ${u2[2]}; const int XW = ${u2[3]}; const int KH = ${s2.kernelShape[0]}; const int KW = ${s2.kernelShape[1]}; const int dilationH = ${s2.dilations[0]}; const int dilationW = ${s2.dilations[1]}; const int strideH = ${s2.strides[0]}; const int strideW = ${s2.strides[1]}; const int padH = ${s2.pads[0]}; const int padW = ${s2.pads[1]}; const int KHKW = KH*KW; const int XCKHKW = XC * KHKW; const int outputChannels = 4; vec4 process(int indices[${l}]) { int b = indices[0]; // batch size int oh = indices[1] * strideH - padH; //output height int ow = indices[2] * strideW - padW; //output width int p = indices[3] * outputChannels; //patch vec4 value = vec4(0.0); for(int i=0; i < outputChannels; ++i) { if(p < XCKHKW) { int patchC = p / KHKW; int patchH = (p - patchC*KHKW) / KW; int patchW = (p - patchC*KHKW) - patchH * KW; int xh2 = oh + patchH * dilationH; int xw2 = ow + patchW * dilationW; int x[${u2.length}]; x[0] = b; x[1] = patchC; x[2] = xh2; x[3] = xw2; if(xh2 >= 0 && xh2 < XH && xw2 >= 0 && xw2 < XW) { value[i] = _X(x); } } ++p; } return value; } `; return Object.assign(Object.assign({}, n3), { output: { dims: p, type: i2.type, textureType: r.TextureType.packedLastDimension }, shaderSource: f }); })(0, s, n2, i, o, a) }); }, e.calculateIm2ColDims = (t2, e2, n2, r2 = 4) => [n2[0], n2[2], n2[3], Math.ceil(t2[1] * e2[2] * e2[3] / r2)]; }, 6572: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseImageScalerAttributes = e.imageScaler = void 0; const r = n(246), i = n(2039); e.imageScaler = (t2, e2, n2) => (u(e2), [t2.run(a(t2, e2, n2), e2)]), e.parseImageScalerAttributes = (t2) => { const e2 = t2.attributes.getFloat("scale"), n2 = t2.attributes.getFloats("bias"); return (0, r.createAttributeWithCacheKey)({ scale: e2, bias: n2 }); }; const o = { name: "ImageScaler", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2, e2, n2) => { const r2 = Object.assign(Object.assign({}, o), { cacheHint: n2.cacheKey }); return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => { const o2 = n3[0].dims.slice(), a2 = o2.length, u2 = ` ${s(r3.bias.length)} float process(int indices[${a2}]) { return _X(indices) * scale + getBias(bias, indices[1]); }`; return Object.assign(Object.assign({}, e3), { output: { dims: o2, type: n3[0].type, textureType: i.TextureType.unpacked }, variables: [{ name: "bias", type: "float", arrayLength: r3.bias.length, data: r3.bias }, { name: "scale", type: "float", data: r3.scale }], shaderSource: u2 }); })(0, r2, e2, n2) }); }, s = (t2) => { const e2 = [`float getBias(float bias[${t2}], int channel) {`]; for (let n2 = 0; n2 < t2; ++n2) 0 === n2 ? e2.push(` if (channel == ${n2}) { return bias[${n2}]; }`) : n2 === t2 - 1 ? e2.push(` else { return bias[${n2}]; }`) : e2.push(` else if (channel == ${n2}) { return bias[${n2}]; }`); return e2.push(" }"), e2.join("\n"); }, u = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("ImageScaler requires 1 input."); if (4 !== t2[0].dims.length) throw new Error("Invalid input shape."); if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type."); }; }, 3346: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseInstanceNormalizationAttributes = e.instanceNormalization = void 0; const r = n(5060), i = n(2039); e.instanceNormalization = (t2, e2, n2) => { c(e2); const r2 = t2.run(a(e2[0]), e2); return [t2.run(u(t2, e2[0], n2, r2.dims), [e2[0], r2, e2[1], e2[2]])]; }, e.parseInstanceNormalizationAttributes = (t2) => t2.attributes.getFloat("epsilon", 1e-5); const o = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [i.TextureType.unpacked] }, a = (t2) => Object.assign(Object.assign({}, o), { get: () => ((t3, e2) => { const n2 = e2.dims.slice(), r2 = n2[1], o2 = n2[2] * n2[3], a2 = [n2[0], r2], s2 = ` vec4 process(int[2] indices) { vec4 v = vec4(0.0); int a[4]; a[0] = indices[0]; a[1] = indices[1]; float temp = 0.0; for(int a2=0; a2<${n2[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${n2[3]}; a3++) { a[3] = a3; float x = _X(a); temp += x; } } float mean = temp / float(${o2}); temp = 0.0; for(int a2=0; a2<${n2[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${n2[3]}; a3++) { a[3] = a3; float x = _X(a); temp += (x - mean) * (x - mean); } } v.r = mean; v.g = temp / float(${o2}); return v; }`; return Object.assign(Object.assign({}, t3), { output: { dims: a2, type: e2.type, textureType: i.TextureType.packedLastDimension }, shaderSource: s2 }); })(o, t2) }), s = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [i.TextureType.unpacked, i.TextureType.packedLastDimension, i.TextureType.unpacked, i.TextureType.unpacked] }, u = (t2, e2, n2, o2) => { const a2 = Object.assign(Object.assign({}, s), { cacheHint: `${n2}` }); return Object.assign(Object.assign({}, a2), { get: () => ((t3, e3, n3, o3, a3) => { const s2 = (0, r.getGlsl)(t3.session.backend.glContext.version), [u2, c2] = t3.calculateTextureWidthAndHeight(a3, i.TextureType.packedLastDimension), [l, p] = [u2 / 4, c2], f = ` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); vec2 coords = offsetToCoords(offset, ${l}, ${p}); return ${s2.texture2D}(MeanAndVariance, coords); } float process(int[4] indices) { int mv[2]; mv[0] = indices[0]; mv[1] = indices[1]; vec4 mean_and_variance = get_MeanAndVariance(mv); float mean = mean_and_variance.r; float variance = mean_and_variance.g; int sb[1]; sb[0] = indices[1]; float scale = _Scale(sb); float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; }`; return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i.TextureType.unpacked }, variables: [{ name: "epsilon", type: "float", data: o3 }], shaderSource: f }); })(t2, a2, e2, n2, o2) }); }, c = (t2) => { if (!t2 || 3 !== t2.length) throw new Error("InstanceNormalization requires 3 inputs."); const e2 = t2[0], n2 = t2[1], r2 = t2[2]; if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length) throw new Error("Invalid input shape."); if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1]) throw new Error("Input shapes are mismatched."); if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type) throw new Error("Invalid input type."); if (4 !== t2[0].dims.length) throw new Error("Only support 4-D input shape."); }; }, 708: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createPackedMatmulProgramInfoLoader = void 0; const r = n(2517), i = n(5060), o = n(2039), a = n(9390), s = n(2823), u = n(5623); e.createPackedMatmulProgramInfoLoader = (t2, e2, n2) => { const c = (l = e2.length > 2, p = n2.activationCacheKey, { name: "MatMul (packed)", inputNames: l ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: l ? [o.TextureType.packed, o.TextureType.packed, o.TextureType.packed] : [o.TextureType.packed, o.TextureType.packed], cacheHint: p }); var l, p; return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, c2) => { const l2 = n3.length > 2, p2 = l2 ? "value += getBiasForMatmul();" : "", f = n3[0].dims, d = n3[1].dims, h = r.BroadcastUtil.calcShape(f, d, true), g = !r.ShapeUtil.areEqual(n3[0].dims, n3[1].dims); if (!h) throw new Error("Can't use matmul on the given tensors"); const b = f[f.length - 1], m2 = Math.ceil(b / 2), y = f.length, _ = d.length, v = (0, i.getGlsl)(t3.session.backend.glContext.version), w = (0, a.getCoordsDataType)(h.length), x2 = h.length, T3 = (0, a.getGlChannels)(), { activationFunction: S, applyActivation: O2 } = (0, s.getActivationSnippet)(c2), A2 = l2 ? `${(0, u.getBiasForMatmul)(w, T3, n3[2].dims, h, true)}` : "", E2 = g ? `${(function(t4, e4, n4, i2) { let o2 = [], a2 = []; const s2 = n4[0].dims, u2 = n4[1].dims, c3 = s2.length, l3 = u2.length, p3 = i2.length, f2 = p3 - c3, d2 = p3 - l3; o2 = s2.map(((t5, n5) => `coords.${e4[n5 + f2]}`)), o2[c3 - 1] = "i*2", o2.join(", "), a2 = u2.map(((t5, n5) => `coords.${e4[n5 + d2]}`)), a2[l3 - 2] = "i*2", a2.join(", "); const h2 = r.BroadcastUtil.getBroadcastDims(s2, i2), g2 = r.BroadcastUtil.getBroadcastDims(u2, i2), b2 = h2.map(((t5) => `coords.${e4[t5 + f2]} = 0;`)).join("\n"), m3 = g2.map(((t5) => `coords.${e4[t5 + d2]} = 0;`)).join("\n"), y2 = `int lastDim = coords.${e4[p3 - 1]}; coords.${e4[p3 - 1]} = coords.${e4[p3 - 2]}; coords.${e4[p3 - 2]} = lastDim;`; return ` vec4 getAAtOutCoordsMatmul(int i) { ${t4} coords = getOutputCoords(); ${y2} ${b2} vec4 outputValue = getA(${o2}); return outputValue; } vec4 getBAtOutCoordsMatmul(int i) { ${t4} coords = getOutputCoords(); ${y2} ${m3} vec4 outputValue = getB(${a2}); return outputValue; }`; })(w, T3, n3, h)}` : "", I2 = g ? "getAAtOutCoordsMatmul(i)" : `getA(${(function(t4, e4) { let n4 = ""; for (let r2 = 0; r2 < e4 - 2; r2++) n4 += `rc.${t4[r2]}, `; return n4 += `rc.${t4[e4 - 2]}, i*2`, n4; })(T3, y)})`, P2 = g ? "getBAtOutCoordsMatmul(i)" : `getB(${(function(t4, e4) { let n4 = ""; for (let r2 = 0; r2 < e4 - 2; r2++) n4 += `rc.${t4[r2]}, `; return n4 += `i*2, rc.${t4[e4 - 1]}`, n4; })(T3, _)})`, D3 = ` ${E2} ${A2} ${S} void main() { ${g ? "" : `${w} rc = getOutputCoords(); int lastDim = rc.${T3[x2 - 1]}; rc.${T3[x2 - 1]} = rc.${T3[x2 - 2]}; rc.${T3[x2 - 2]} = lastDim; `} vec4 value = vec4(0); for (int i = 0; i < ${m2}; i++) { vec4 a = ${I2}; vec4 b = ${P2}; value += (a.rrbb * b.rgrg); value += (a.ggaa * b.baba); } ${p2} ${O2} ${v.output} = value; }`; return Object.assign(Object.assign({}, e3), { output: { dims: h, type: n3[0].type, textureType: o.TextureType.packed }, shaderSource: D3, hasMain: true }); })(t2, c, e2, n2) }); }; }, 5623: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.getBiasForMatmul = e.createMatmulProgramInfoLoader = e.parseMatMulAttributes = e.matMul = void 0; const r = n(2517), i = n(2039), o = n(9390), a = n(2823), s = n(708); function u(t2, e2) { const n2 = (s2 = t2.length > 2, u2 = e2.activationCacheKey, { name: "MatMul", inputNames: s2 ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: s2 ? [i.TextureType.unpacked, i.TextureType.unpacked, i.TextureType.unpacked] : [i.TextureType.unpacked, i.TextureType.unpacked], cacheHint: u2 }); var s2, u2; return Object.assign(Object.assign({}, n2), { get: () => (function(t3, e3, n3) { const s3 = e3[0].dims, u3 = e3[1].dims, c2 = r.BroadcastUtil.calcShape(s3, u3, true); if (!c2) throw new Error("Can't use matmul on the given tensors"); const p = (0, o.getCoordsDataType)(c2.length), f = (0, o.getGlChannels)(), { activationFunction: d, applyActivation: h } = (0, a.getActivationSnippet)(n3), g = e3.length > 2, b = g ? "value += getBiasForMatmul();" : "", m2 = g ? `${l(p, f, e3[2].dims, c2, false)}` : "", y = c2.length, _ = s3.length, v = u3.length, w = ` ${d} ${m2} float process(int indices[${y}]) { int a[${_}]; int b[${v}]; bcastMatmulIndices_A(indices, a); bcastMatmulIndices_B(indices, b); float value; for (int k=0; k<${s3[s3.length - 1]}; ++k) { a[${_ - 1}] = k; b[${v - 2}] = k; value += _A(a) * _B(b); } ${b} ${h} return value; }`; return Object.assign(Object.assign({}, t3), { output: { dims: c2, type: e3[0].type, textureType: i.TextureType.unpacked }, shaderSource: w }); })(n2, t2, e2) }); } e.matMul = (t2, e2, n2) => (c(e2), t2.session.pack ? [t2.run((0, s.createPackedMatmulProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(u(e2, n2), e2)]), e.parseMatMulAttributes = (t2) => (0, a.parseInternalActivationAttributes)(t2.attributes), e.createMatmulProgramInfoLoader = u; const c = (t2) => { if (!t2 || 2 !== t2.length) throw new Error("MatMul requires 2 inputs."); if (t2[0].dims[t2[0].dims.length - 1] !== t2[1].dims[t2[1].dims.length - 2]) throw new Error("shared dimension does not match."); if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type) throw new Error("inputs should be float type"); if (t2[0].type !== t2[1].type) throw new Error("inputs types should match"); }; function l(t2, e2, n2, i2, o2) { let a2 = ""; const s2 = n2.length, u2 = i2.length, c2 = u2 - s2; a2 = u2 < 2 && s2 > 0 ? "coords" : n2.map(((t3, n3) => `coords.${e2[n3 + c2]}`)).join(", "); const l2 = r.BroadcastUtil.getBroadcastDims(n2, i2).map(((t3) => `coords.${e2[t3 + c2]} = 0;`)).join("\n"); let p = "vec4(outputValue.xx, outputValue.yy)"; return 1 === r.ShapeUtil.size(n2) && (p = "vec4(outputValue.x)"), o2 ? ` vec4 getBiasForMatmul() { ${t2} coords = getOutputCoords(); ${l2} vec4 outputValue = getBias(${a2}); return ${p}; }` : ` float getBiasForMatmul() { ${t2} coords = getOutputCoords(); ${l2} return getBias(coords.x); }`; } e.getBiasForMatmul = l; }, 2403: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createPackProgramInfoLoader = void 0; const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = { name: "pack", inputNames: ["A"], inputTypes: [i.TextureType.unpackedReversed] }; e.createPackProgramInfoLoader = (t2, e2) => Object.assign(Object.assign({}, s), { get: () => ((t3, e3) => { const n2 = (0, r.getGlsl)(t3.session.backend.glContext.version), u = e3.dims, c = u.length, l = e3.dims.length, p = (0, o.getCoordsDataType)(l), f = (0, a.getChannels)("rc", l), d = (h = l, g = f, b = u[u.length - 2], m2 = u[u.length - 1], 0 === h || 1 === h ? "" : ` int r = ${g[h - 2]}; int c = ${g[h - 1]}; int rp1 = ${g[h - 2]} + 1; int cp1 = ${g[h - 1]} + 1; bool rEdge = rp1 >= ${m2}; bool cEdge = cp1 >= ${b}; `); var h, g, b, m2; let y; y = 0 === c ? [1, 1] : 1 === c ? [u[0], 1] : [u[l - 1], u[l - 2]]; const _ = (function(t4, e4, n3) { if (0 === t4) return "false"; if (1 === t4) return `rc > ${e4[0]}`; let r2 = ""; for (let i2 = t4 - 2; i2 < t4; i2++) r2 += `${n3[i2]} >= ${e4[i2 - t4 + 2]}`, i2 < t4 - 1 && (r2 += "||"); return r2; })(l, y, f), v = (function(t4, e4) { const n3 = t4.length; if (0 === n3) return "getA(), 0, 0, 0"; if (1 === n3) return `getA(rc), rc + 1 >= ${t4[0]} ? 0. : getA(rc + 1), 0, 0`; let r2 = ""; if (n3 > 2) for (let t5 = 0; t5 < n3 - 2; ++t5) r2 += `${e4[t5]},`; return `getA(${r2}r, c), rEdge ? 0. : getA(${r2}rp1, c), cEdge ? 0. : getA(${r2}r, cp1), rEdge || cEdge ? 0. : getA(${r2}rp1, cp1)`; })(u, f), w = ` void main() { ${p} rc = getOutputCoords(); if(${_}) { ${n2.output} = vec4(0); } else { ${d} ${n2.output} = vec4(${v}); } } `; return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e3.dims, type: e3.type, textureType: i.TextureType.packed }, shaderSource: w }); })(t2, e2) }); }, 2827: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.unpackFromChannel = e.getChannels = e.getVecChannels = void 0; const r = n(9390); function i(t2, e2) { return (0, r.getGlChannels)(e2).map(((e3) => `${t2}.${e3}`)); } e.getVecChannels = i, e.getChannels = function(t2, e2) { return 1 === e2 ? [t2] : i(t2, e2); }, e.unpackFromChannel = function() { return "\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "; }; }, 2870: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parsePadAttributesV11 = e.padV11 = e.parsePadAttributesV2 = e.padV2 = void 0; const r = n(246), i = n(2517), o = n(5060), a = n(2039), s = { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; e.padV2 = (t2, e2, n2) => (l(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => c(t2, e2[0], n2) }), e2)]), e.parsePadAttributesV2 = (t2) => { const e2 = t2.attributes.getString("mode", "constant"), n2 = t2.attributes.getFloat("value", 0), i2 = t2.attributes.getInts("pads"); return (0, r.createAttributeWithCacheKey)({ mode: e2, value: n2, pads: i2 }); }, e.padV11 = (t2, n2, r2) => { p(n2); const i2 = u(t2, n2, r2); return (0, e.padV2)(t2, [n2[0]], i2); }, e.parsePadAttributesV11 = (t2) => t2.attributes.getString("mode", "constant"); const u = (t2, e2, n2) => { if (!t2.session.isInitializer(e2[1].dataId) || e2.length >= 3 && !t2.session.isInitializer(e2[2].dataId)) throw new Error("dynamic pad attributes are not allowed"); const i2 = Array.from(e2[1].integerData), o2 = e2.length >= 3 ? e2[2].floatData[0] : 0; return (0, r.createAttributeWithCacheKey)({ mode: n2, pads: i2, value: o2 }); }, c = (t2, e2, n2) => { const r2 = i.ShapeUtil.padShape(e2.dims.slice(), n2.pads), o2 = r2.length, s2 = ` ${f(t2, e2, n2)} float process(int[${o2}] indices) { return padA(indices); }`; return { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked], output: { dims: r2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: s2 }; }, l = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Pad requires 1 input"); if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type."); }, p = (t2) => { if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Pad requires 2 or 3 inputs"); if ("int32" !== t2[1].type) throw new Error("Invalid input type."); if (t2.length >= 3 && "string" === t2[2].type) throw new Error("Invalid input type."); }, f = (t2, e2, n2) => { const r2 = (0, o.getGlsl)(t2.session.backend.glContext.version), [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = i.ShapeUtil.computeStrides(e2.dims); switch (n2.mode) { case "constant": return d(r2, e2.dims, c2, s2, u2, n2.pads, n2.value); case "reflect": return h(r2, e2.dims, c2, s2, u2, n2.pads); case "edge": return g(r2, e2.dims, c2, s2, u2, n2.pads); default: throw new Error("Invalid mode"); } }, d = (t2, e2, n2, r2, i2, o2, a2) => { const s2 = e2.length; let u2 = ""; for (let t3 = s2 - 1; t3 >= 0; --t3) u2 += ` k = m[${t3}] - ${o2[t3]}; if (k < 0) return constant; if (k >= ${e2[t3]}) return constant; offset += k * ${n2[t3]}; `; return ` float padA(int m[${s2}]) { const float constant = float(${a2}); int offset = 0; int k = 0; ${u2} vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); float value = getColorAsFloat(${t2.texture2D}(A, coords)); return value; } `; }, h = (t2, e2, n2, r2, i2, o2) => { const a2 = e2.length; let s2 = ""; for (let t3 = a2 - 1; t3 >= 0; --t3) s2 += ` k = m[${t3}] - ${o2[t3]}; if (k < 0) { k = -k; } { const int _2n_1 = ${2 * (e2[t3] - 1)}; k = int( mod( float(k), float(_2n_1) ) ) ; if(k >= ${e2[t3]}) { k = _2n_1 - k; } } offset += k * ${n2[t3]}; `; return ` float padA(int m[${a2}]) { int offset = 0; int k = 0; ${s2} vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); float value = getColorAsFloat(${t2.texture2D}(A, coords)); return value; } `; }, g = (t2, e2, n2, r2, i2, o2) => { const a2 = e2.length; let s2 = ""; for (let t3 = a2 - 1; t3 >= 0; --t3) s2 += ` k = m[${t3}] - ${o2[t3]}; if (k < 0) k = 0; if (k >= ${e2[t3]}) k = ${e2[t3] - 1}; offset += k * ${n2[t3]}; `; return ` float padA(int m[${a2}]) { int offset = 0; int k = 0; ${s2} vec2 coords = offsetToCoords(offset, ${r2}, ${i2}); float value = getColorAsFloat(${t2.texture2D}(A, coords)); return value; } `; }; }, 2143: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.globalMaxPool = e.parseMaxPoolAttributes = e.maxPool = e.parseGlobalAveragePoolAttributes = e.globalAveragePool = e.parseAveragePoolAttributes = e.averagePool = void 0; const r = n(246), i = n(2517), o = n(2039); e.averagePool = (t2, e2, n2) => { p(e2); const r2 = { name: "AveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey }; return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, false, n2) }), e2)]; }, e.parseAveragePoolAttributes = (t2) => { const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = 0 !== t2.attributes.getInt("count_include_pad", 0), o2 = t2.attributes.getInts("kernel_shape"), a2 = t2.attributes.getInts("strides", []), s2 = t2.attributes.getInts("pads", []); if (0 !== n2) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: i2, kernelShape: o2, strides: a2, pads: s2 }); }; const a = (t2, e2, n2, r2) => { const [a2, s2] = u(t2, r2, n2), c2 = i.ShapeUtil.size(a2.kernelShape); let l2 = ""; a2.countIncludePad ? l2 += `value /= float(${c2});` : l2 += `value /= float(${c2} - pad);`; const p2 = ` ${f(t2[0].dims, a2, "value += _X(x);", l2, "0.0")} `; return Object.assign(Object.assign({}, e2), { output: { dims: s2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: p2 }); }; e.globalAveragePool = (t2, e2, n2) => { p(e2); const r2 = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: `${n2.countIncludePad}` }; return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, true, n2) }), e2)]; }, e.parseGlobalAveragePoolAttributes = (t2) => { const e2 = 0 !== t2.attributes.getInt("count_include_pad", 0); return (0, r.createAttributeWithCacheKey)({ autoPad: "", ceilMode: 0, countIncludePad: e2, kernelShape: [], strides: [], pads: [] }); }, e.maxPool = (t2, e2, n2) => { p(e2); const r2 = { name: "MaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey }; return [t2.run(Object.assign(Object.assign({}, r2), { get: () => s(e2, r2, false, n2) }), e2)]; }, e.parseMaxPoolAttributes = (t2) => { const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i2 = t2.attributes.getInts("kernel_shape"), o2 = t2.attributes.getInts("strides", []), a2 = t2.attributes.getInts("pads", []), s2 = t2.attributes.getInt("storage_order", 0), u2 = t2.attributes.getInts("dilations", []); if (0 !== s2) throw new Error("column major storage order is not yet supported for MaxPool"); if (0 !== n2) throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: false, kernelShape: i2, strides: o2, pads: a2, storageOrder: s2, dilations: u2 }); }; const s = (t2, e2, n2, r2) => { const [i2, a2] = u(t2, r2, n2), s2 = ` ${f(t2[0].dims, i2, "\n value = max(_X(x), value);\n ", "", "-1e5")} `; return Object.assign(Object.assign({}, e2), { output: { dims: a2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: s2 }); }, u = (t2, e2, n2) => { const r2 = t2[0].dims.slice(), o2 = Object.hasOwnProperty.call(e2, "dilations"), a2 = e2.kernelShape.slice(), s2 = e2.strides.slice(), u2 = o2 ? e2.dilations.slice() : [], c2 = e2.pads.slice(); i.PoolConvUtil.adjustPoolAttributes(n2, r2, a2, s2, u2, c2); const l2 = i.PoolConvUtil.computePoolOutputShape(n2, r2, s2, u2, a2, c2, e2.autoPad), p2 = Object.assign({}, e2); return o2 ? Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, dilations: u2, cacheKey: e2.cacheKey }) : Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, cacheKey: e2.cacheKey }), [p2, l2]; }, c = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, l = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] }; e.globalMaxPool = (t2, e2) => (p(e2), [t2.run(Object.assign(Object.assign({}, l), { get: () => s(e2, l, true, c) }), e2)]); const p = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Pool ops requires 1 input."); if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type."); }, f = (t2, e2, n2, r2, o2) => { const a2 = t2.length; if (e2.kernelShape.length <= 2) { const i2 = e2.kernelShape[e2.kernelShape.length - 1], s2 = e2.strides[e2.strides.length - 1], u2 = e2.pads[e2.pads.length / 2 - 1], c2 = e2.pads[e2.pads.length - 1], l2 = t2[a2 - 1]; let p2 = "", f2 = "", d2 = ""; if (p2 = u2 + c2 !== 0 ? ` for (int i = 0; i < ${i2}; i++) { x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i; if (x[${a2} - 1] < 0 || x[${a2} - 1] >= ${l2}) { pad++; continue; } ${n2} }` : ` for (int i = 0; i < ${i2}; i++) { x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i; ${n2} }`, 2 === e2.kernelShape.length) { const n3 = e2.kernelShape[e2.kernelShape.length - 2], r3 = e2.strides[e2.strides.length - 2], o3 = e2.pads[e2.pads.length / 2 - 2], s3 = e2.pads[e2.pads.length - 2], u3 = t2[a2 - 2]; f2 = o3 + s3 !== 0 ? ` for (int j = 0; j < ${n3}; j++) { x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j; if (x[${a2} - 2] < 0 || x[${a2} - 2] >= ${u3}) { pad+= ${i2}; continue; } ` : ` for (int j = 0; j < ${n3}; j++) { x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j; `, d2 = "\n }\n "; } return ` float process(int indices[${a2}]) { int x[${a2}]; copyVec(indices, x); float value = ${o2}; int pad = 0; ${f2} ${p2} ${d2} ${r2} return value; } `; } { const s2 = i.ShapeUtil.size(e2.kernelShape), u2 = i.ShapeUtil.computeStrides(e2.kernelShape), c2 = u2.length, l2 = e2.pads.length, p2 = h(c2), f2 = d(t2, "inputDims"), g = d(e2.pads, "pads"), b = d(u2, "kernelStrides"), m2 = d(e2.strides, "strides"); let y = ""; return y = e2.pads.reduce(((t3, e3) => t3 + e3)) ? ` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; break; } } if (!isPad) { ${n2} }` : ` } ${n2} `, ` ${p2} float process(int indices[${a2}]) { int x[${a2}]; copyVec(indices, x); int offset[${c2}]; int pads[${l2}]; int inputDims[${a2}]; int kernelStrides[${c2}]; int strides[${c2}]; ${g} ${f2} ${m2} ${b} float value = ${o2}; int pad = 0; bool isPad = false; for (int i = 0; i < ${s2}; i++) { offsetToIndices(i, kernelStrides, offset); isPad = false; for (int j = ${a2} - ${c2}; j < ${a2}; j++) { x[j] = indices[j] * strides[j - ${a2} + ${c2}] + offset[j - ${a2} + ${c2}] - pads[j - 2]; ${y} } ${r2} return value; } `; } }, d = (t2, e2) => { let n2 = ""; for (let r2 = 0; r2 < t2.length; r2++) n2 += ` ${e2}[${r2}] = ${t2[r2]}; `; return n2; }, h = (t2) => ` void offsetToIndices(int offset, int[${t2}] strides, out int[${t2}] indices) { if (${t2} == 0) { return; } for (int i = 0; i < ${t2} - 1; ++i) { indices[i] = offset / strides[i]; offset -= indices[i] * strides[i]; } indices[${t2} - 1] = offset; }`; }, 4939: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.reduceLogSumSquare = e.reduceLogSum = e.reduceProd = e.reduceMin = e.reduceMax = e.reduceMean = e.reduceSum = e.parseReduceAttributes = void 0; const r = n(246), i = n(782), o = n(2517), a = n(2039), s = (t2, e2, n2, r2, i2) => { c(e2); const o2 = { name: r2, inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; return [t2.run(Object.assign(Object.assign({}, o2), { cacheHint: n2.cacheKey, get: () => u(t2, e2, n2, r2, i2, o2) }), e2)]; }; e.parseReduceAttributes = (t2) => { const e2 = t2.attributes.getInts("axes", []), n2 = 1 === t2.attributes.getInt("keepdims", 1); return (0, r.createAttributeWithCacheKey)({ axes: e2, keepDims: n2 }); }; const u = (t2, e2, n2, r2, i2, s2) => { const u2 = [], c2 = e2[0].dims.length || 1, l = [], p = o.ShapeUtil.normalizeAxes(n2.axes, e2[0].dims.length), f = i2(e2, p); let d = f[1]; for (let t3 = 0; t3 < e2[0].dims.length; t3++) p.indexOf(t3) >= 0 || 0 === p.length ? (n2.keepDims && u2.push(1), d = ` for(int j${t3} = 0; j${t3} < ${e2[0].dims[t3]}; j${t3}++) { inputIdx[${t3}] = j${t3}; ${d} }`) : (l.push(`inputIdx[${t3}] = outputIdx[${u2.length}];`), u2.push(e2[0].dims[t3])); const h = ` float process(int outputIdx[${u2.length || 1}]) { float value; // final result int inputIdx[${c2}]; // addressing input data ${l.join("\n")} ${f[0]} // init ops for reduce max/min ${d} ${f[2]} // final computation for reduce mean return value; }`; return Object.assign(Object.assign({}, s2), { output: { dims: u2, type: e2[0].type, textureType: a.TextureType.unpacked }, shaderSource: h }); }, c = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Reduce op requires 1 input."); if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type."); }; e.reduceSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceSum", (() => ["value = 0.0;", "value += _A(inputIdx);", ""])), e.reduceMean = (t2, e2, n2) => s(t2, e2, n2, "ReduceMean", ((t3, e3) => { let n3 = 1; for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && (n3 *= t3[0].dims[r2]); return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${n3}.;`]; })), e.reduceMax = (t2, e2, n2) => s(t2, e2, n2, "ReduceMax", ((t3, e3) => { const n3 = []; for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`); return [`${n3.join("\n")} value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""]; })), e.reduceMin = (t2, e2, n2) => s(t2, e2, n2, "ReduceMin", ((t3, e3) => { const n3 = []; for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`); return [`${n3.join("\n")} value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""]; })), e.reduceProd = (t2, e2, n2) => s(t2, e2, n2, "ReduceProd", (() => ["value = 1.0;", "value *= _A(inputIdx);", ""])), e.reduceLogSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSum", (() => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"])), e.reduceLogSumSquare = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSumSquare", (() => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""])); }, 7019: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.isReshapeCheap = e.processDims3D = e.createPackedReshape3DProgramInfoLoader = void 0; const r = n(2517), i = n(5060), o = n(2039), a = n(2827); e.createPackedReshape3DProgramInfoLoader = (t2, e2, n2) => { const s = ((t3) => ({ name: "Reshape (packed)", inputTypes: [o.TextureType.packed], inputNames: ["A"], cacheHint: `${t3}` }))(n2); return Object.assign(Object.assign({}, s), { get: () => ((t3, e3, n3, s2) => { const u = e3.dims, c = s2; let l = ""; for (let t4 = 0; t4 < 4; t4++) { let e4 = ""; switch (t4) { case 0: e4 = "outputCoords = rc;"; break; case 1: e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);"; break; case 2: e4 = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);"; break; case 3: e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);"; break; default: throw new Error(); } l += ` ${e4} ${t4 > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""} int flattenedIndex = getFlattenedIndex(outputCoords); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); result[${t4}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); ${t4 > 0 ? "}" : ""} `; } const p = (0, i.getGlsl)(t3.session.backend.glContext.version), f = ` ${(function(t4) { const e4 = r.ShapeUtil.computeStrides(t4), n4 = ["b", "r", "c"], i2 = "index"; return ` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${e4.map(((t5, r2) => `int ${n4[r2]} = ${i2} / ${t5}; ${r2 === e4.length - 1 ? `int ${n4[r2 + 1]} = ${i2} - ${n4[r2]} * ${t5}` : `index -= ${n4[r2]} * ${t5}`};`)).join("")} return ivec3(b, r, c); } `; })(u)} ${(function(t4) { const e4 = r.ShapeUtil.computeStrides(t4); return ` int getFlattenedIndex(ivec3 coords) { // reverse y, z order return coords.x * ${e4[0]} + coords.z * ${e4[1]} + coords.y; } `; })(c)} ${(0, a.unpackFromChannel)()} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.0); ivec3 outputCoords; int rows = ${c[2]}; int cols = ${c[1]}; ${l} ${p.output} = result; } `; return Object.assign(Object.assign({}, n3), { output: { dims: c, type: e3.type, textureType: o.TextureType.packed }, shaderSource: f, hasMain: true }); })(t2, e2, s, n2) }); }, e.processDims3D = function(t2) { if (0 === t2.length) return [1, 1, 1]; let e2 = 1; for (let n2 = 0; n2 < t2.length - 2; ++n2) e2 *= t2[n2]; return [e2, t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]]; }, e.isReshapeCheap = function(t2, e2) { let n2 = false; return n2 = 0 === t2.length || 0 === e2.length || (t2.length < 2 || e2.length < 2 ? t2[t2.length - 1] === e2[e2.length - 1] : t2[t2.length - 1] === e2[e2.length - 1] && t2[t2.length - 2] === e2[e2.length - 2]), n2; }; }, 718: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.reshape = void 0; const r = n(2517); e.reshape = (t2, e2) => { const n2 = r.ShapeUtil.calculateReshapedDims(e2[0].dims, e2[1].integerData); return t2.session.pack ? [t2.reshapePacked(e2[0], n2)] : [t2.reshapeUnpacked(e2[0], n2)]; }; }, 2268: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseResizeAttributesV11 = e.parseResizeAttributesV10 = e.resize = void 0; const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = n(9793), u = { name: "Resize", inputNames: ["A"], inputTypes: [i.TextureType.packed] }; e.resize = (t2, e2, n2) => ((0, s.validateInputs)(e2, n2), [t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => c(t2, e2, n2) }), e2)]), e.parseResizeAttributesV10 = (t2) => (0, s.parseUpsampleAttributes)(t2, 10), e.parseResizeAttributesV11 = (t2) => (0, s.parseUpsampleAttributes)(t2, 11); const c = (t2, e2, n2) => { const s2 = (0, r.getGlsl)(t2.session.backend.glContext.version), [c2, p2] = l(e2, n2); if (c2.every(((t3) => 1 === t3)) && "tf_crop_and_resize" !== n2.coordinateTransformMode) return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: `void main() { vec4 v = ${s2.texture2D}(X, TexCoords); ${s2.output} = v; }` }); const f2 = p2.length; if (f2 < 2) throw new Error(`output dimension should be at least 2, but got ${f2}`); const d = p2[f2 - 2], h = p2[f2 - 1], g = e2[0].dims; if (f2 !== g.length) throw new Error(`output dimension should match input ${g.length}, but got ${f2}`); const b = g[f2 - 2], m2 = g[f2 - 1], y = c2[f2 - 2], _ = c2[f2 - 1]; let v = ""; if ("linear" !== n2.mode) throw new Error(`resize (packed) does not support mode: '${n2.mode}'`); switch (n2.coordinateTransformMode) { case "asymmetric": v = "\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n "; break; case "half_pixel": v = "\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n "; break; case "pytorch_half_pixel": v = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 fcoords = vec4(coords); return vec4( ${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, ${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, ${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, ${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 ); } `; break; case "align_corners": v = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0, ${d}.0 - 1.0); vec4 original = vec4(${m2}.0 - 1.0, ${b}.0 - 1.0, ${m2}.0 - 1.0, ${b}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `; break; default: throw new Error(`resize (packed) does not support coordinateTransformMode: '${n2.coordinateTransformMode}'`); } const w = (0, o.getCoordsDataType)(f2), x2 = ` const vec2 inputWH = vec2(${b}.0, ${m2}.0); const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_})); ${(0, a.unpackFromChannel)()} ${v} float getAValue(int x10, int r, int c, int d) { return getChannel(getA(x10, r, c, d), vec2(c, d)); } void main() { ${w} rc = getOutputCoords(); int batch = rc[0]; int depth = rc[1]; // retrieve the 4 coordinates that is used in the 4 packed output values. ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); // calculate the source index in fraction vec4 sourceFrac = getSourceFracIndex(coords); // get the lower and upper bound of the 4 values that will be packed into one texel. ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); bool hasNextRow = rc.w < ${d - 1}; bool hasNextCol = rc.z < ${h - 1}; // pack x00, x01, x10, x11's top-left corner into one vec4 structure vec4 topLeft = vec4( getAValue(batch, depth, x00.x, x00.y), hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); // pack x00, x01, x10, x11's top-right corner into one vec4 structure vec4 topRight = vec4( getAValue(batch, depth, x00.x, x00.w), hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure vec4 bottomLeft = vec4( getAValue(batch, depth, x00.z, x00.y), hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure vec4 bottomRight = vec4( getAValue(batch, depth, x00.z, x00.w), hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); // calculate the interpolation fraction on u and v direction vec4 frac = vec4(sourceFrac) - floor(sourceFrac); vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); vec4 top = mix(topLeft, topRight, clampFrac.ywyw); vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); vec4 newValue = mix(top, bottom, clampFrac.xxzz); ${s2.output} = vec4(newValue); } `; return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i.TextureType.packed }, hasMain: true, shaderSource: x2 }); }, l = (t2, e2) => { const n2 = t2[0].dims; let r2, i2 = e2.scales; if (0 === i2.length) { const o3 = t2[e2.scalesInputIdx]; if (o3 && 0 !== o3.size) { if (t2[e2.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); i2 = p(o3, e2.mode, e2.isResize); } else { const o4 = t2[e2.sizesInputIdx]; if (!o4 || 0 === o4.size) throw new Error("Either scales or sizes MUST be provided as input."); r2 = Array.from(o4.integerData), i2 = f(r2, n2, e2.mode, e2.isResize); } } else if (t2[e2.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); const o2 = r2 || n2.map(((t3, e3) => Math.floor(t3 * i2[e3]))); return [i2, o2]; }, p = (t2, e2, n2) => { const r2 = Array.from(t2.floatData); return (0, s.scalesValidation)(r2, e2, n2), r2; }, f = (t2, e2, n2, r2) => { const i2 = e2.length, o2 = new Array(i2); for (let n3 = 0, r3 = i2; n3 < r3; n3++) if (0 === e2[n3]) { if (0 !== t2[n3]) throw new Error("Input dim is zero but required output dim is non-zero."); o2[n3] = 1; } else o2[n3] = t2[n3] / e2[n3]; return (0, s.scalesValidation)(o2, n2, r2), o2; }; }, 8117: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.shape = void 0; const r = n(9162); e.shape = (t2, e2) => (i(e2), [new r.Tensor([e2[0].dims.length], "int32", void 0, void 0, new Int32Array(e2[0].dims))]); const i = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Shape requires 1 input."); }; }, 2278: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.sliceV10 = e.parseSliceAttributes = e.slice = void 0; const r = n(246), i = n(782), o = n(2517), a = n(2039), s = { name: "Slice", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }; e.slice = (t2, e2, n2) => (c(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), e2)]), e.parseSliceAttributes = (t2) => { const e2 = t2.attributes.getInts("starts"), n2 = t2.attributes.getInts("ends"), i2 = t2.attributes.getInts("axes", []); return (0, r.createAttributeWithCacheKey)({ starts: e2, ends: n2, axes: i2 }); }; const u = (t2, e2, n2) => { const r2 = 0 === n2.axes.length ? e2.dims.slice(0).map(((t3, e3) => e3)) : n2.axes, i2 = o.ShapeUtil.normalizeAxes(r2, e2.dims.length), u2 = n2.starts.map(((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]]))), c2 = n2.ends.map(((t3, n3) => t3 > e2.dims[i2[n3]] - 1 ? e2.dims[i2[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i2[n3]]))), l2 = e2.dims.slice(), p2 = []; for (let t3 = 0; t3 < i2.length; t3++) l2[i2[t3]] = c2[t3] - u2[t3], u2[t3] > 0 && p2.push(`outputIdx[${i2[t3]}] += ${u2[t3]};`); const f = ` float process(int outputIdx[${l2.length}]) { ${p2.join("\n ")} return _A(outputIdx); }`; return Object.assign(Object.assign({}, s), { output: { dims: l2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f }); }, c = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Slice requires 1 input."); if (-1 === i.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type."); }; e.sliceV10 = (t2, e2) => { p(e2); const n2 = l(t2, e2); return [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), [e2[0]])]; }; const l = (t2, e2) => { if (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId) || e2.length >= 4 && !t2.session.isInitializer(e2[3].dataId) || e2.length >= 5 && !t2.session.isInitializer(e2[4].dataId)) throw new Error("dynamic slice attributes are not allowed"); if (e2.length >= 5 && e2[4].integerData.some(((t3) => 1 !== t3))) throw new Error("currently non-1 steps is not supported for Slice"); const n2 = Array.from(e2[1].integerData), r2 = Array.from(e2[2].integerData), i2 = e2.length >= 4 ? Array.from(e2[3].integerData) : []; return { starts: n2, ends: r2, axes: i2, cacheKey: `${i2};${n2};${r2}` }; }, p = (t2) => { if (!t2 || t2.length < 3 || t2.length > 5) throw new Error("Invalid input number."); if ("int32" !== t2[1].type || 1 !== t2[1].dims.length) throw new Error("Invalid input type."); if ("int32" !== t2[2].type || 1 !== t2[2].dims.length) throw new Error("Invalid input type."); if (t2.length >= 4 && ("int32" !== t2[3].type || 1 !== t2[3].dims.length)) throw new Error("Invalid input type."); if (t2.length >= 5 && ("int32" !== t2[4].type || 1 !== t2[4].dims.length)) throw new Error("Invalid input type."); }; }, 5524: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.softmaxV13 = e.parseSoftmaxAttributesV13 = e.parseSoftmaxAttributes = e.softmax = void 0; const r = n(246), i = n(2517), o = n(5060), a = n(2039), s = n(3738), u = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }, c = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, l = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked, a.TextureType.unpacked] }; e.softmax = (t2, e2, n2) => { g(e2); const r2 = e2[0].dims.slice(), o2 = i.ShapeUtil.normalizeAxis(n2.axis, r2.length), a2 = i.ShapeUtil.sizeToDimension(r2, o2), s2 = i.ShapeUtil.sizeFromDimension(r2, o2); return p(t2, e2, n2, a2, s2); }, e.parseSoftmaxAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 1) }), e.parseSoftmaxAttributesV13 = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", -1) }), e.softmaxV13 = (t2, e2, n2) => { g(e2); const o2 = e2[0].dims.slice(), a2 = i.ShapeUtil.normalizeAxis(n2.axis, o2.length), u2 = o2.length, c2 = a2 !== u2 - 1, l2 = []; let f2, d2 = [], h2 = []; c2 && (d2 = Array.from({ length: u2 }).map(((t3, e3) => e3)), d2[a2] = u2 - 1, d2[u2 - 1] = a2, d2.map(((t3) => l2.push(o2[t3]))), f2 = (0, r.createAttributeWithCacheKey)({ perm: d2 }), h2 = (0, s.transpose)(t2, e2, f2)); const b = c2 ? i.ShapeUtil.sizeToDimension(l2, u2 - 1) : i.ShapeUtil.sizeToDimension(o2, u2 - 1), m2 = c2 ? i.ShapeUtil.sizeFromDimension(l2, u2 - 1) : i.ShapeUtil.sizeFromDimension(o2, u2 - 1), y = p(t2, c2 ? h2 : e2, n2, b, m2); return c2 ? (0, s.transpose)(t2, y, f2) : y; }; const p = (t2, e2, n2, r2, i2) => { const o2 = f(t2, e2[0], r2, i2, [r2]), a2 = t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => o2 }), e2), s2 = d(t2, e2[0], r2, i2, o2.output.dims, [r2]), p2 = t2.run(Object.assign(Object.assign({}, c), { cacheHint: n2.cacheKey, get: () => s2 }), [e2[0], a2]), g2 = h(t2, e2[0], r2, i2, o2.output.dims, s2.output.dims); return [t2.run(Object.assign(Object.assign({}, l), { cacheHint: n2.cacheKey, get: () => g2 }), [e2[0], a2, p2])]; }, f = (t2, e2, n2, r2, i2) => { const [s2, c2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), l2 = i2.length; if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (1 !== i2.length) throw new Error("Dimensionality of the output should be 1"); if (i2[0] !== n2) throw new Error("Shape of the output should be equal to logical row count"); const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = ` float process(int[${l2}] indices) { int logical_row_start_offset = indices[0] * ${r2}; float max = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s2}, ${c2} ))); for(int i=1; i<${r2}; ++i) { float current = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${s2}, ${c2}))); if(current > max) max = current; } return max; }`; return Object.assign(Object.assign({}, u), { output: { dims: i2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 }); }, d = (t2, e2, n2, r2, i2, s2) => { const [u2, l2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), p2 = s2.length; if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (1 !== s2.length) throw new Error("Dimensionality of the output should be 1"); if (s2[0] !== n2) throw new Error("Shape of the output should be equal to logical row count"); if (1 !== i2.length) throw new Error("Dimensionality of the intermediate results should be 1"); if (i2[0] !== n2) throw new Error("Shape of the intermediate results should be equal to logical row count"); const f2 = ` float process(int[${p2}] indices) { int logical_row_start_offset = indices[0] * ${r2}; float norm_factor = 0.0; float max = _Max(indices); for(int i=0; i<${r2}; ++i) { norm_factor += exp(getColorAsFloat(${(0, o.getGlsl)(t2.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${u2}, ${l2}))) - max); } return norm_factor; }`; return Object.assign(Object.assign({}, c), { output: { dims: s2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 }); }, h = (t2, e2, n2, r2, i2, o2) => { const [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = e2.dims.length; if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (1 !== i2.length || 1 !== o2.length) throw new Error("Dimensionality of the intermediate results should be 1"); if (i2[0] !== n2 || o2[0] !== n2) throw new Error("Shape of the intermediate results should be equal to logical row count"); const p2 = ` float process(int[${c2}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) int offset = coordsToOffset(TexCoords, ${s2}, ${u2}); //determine the logical row for this index int logical_row_index[1]; logical_row_index[0] = offset / ${r2}; float norm_factor = _Norm(logical_row_index); // avoid possible division by 0 // if norm_facor is 0, all elements are zero // if so, return 0 if(norm_factor == 0.0) return 0.0; return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; }`; return Object.assign(Object.assign({}, l), { output: { dims: e2.dims, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: p2 }); }, g = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Softmax requires 1 input."); if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type"); }; }, 5975: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseSplitAttributes = e.split = void 0; const r = n(246), i = n(2517), o = n(2039), a = { name: "Split", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] }; e.split = (t2, e2, n2) => { c(e2); const r2 = i.ShapeUtil.normalizeAxis(n2.axis, e2[0].dims.length), o2 = s(t2, e2, r2, n2), l = []; for (let i2 = 0; i2 < o2; ++i2) l.push(t2.run(Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey};${i2}`, get: () => u(t2, e2[0], n2, r2, i2) }), e2)); return l; }, e.parseSplitAttributes = (t2) => { const e2 = t2.attributes.getInt("axis", 0), n2 = t2.attributes.getInts("split", []), i2 = t2.outputs.length; return (0, r.createAttributeWithCacheKey)({ axis: e2, split: n2, numOutputs: i2 }); }; const s = (t2, e2, n2, r2) => { const [, o2] = i.SplitUtil.splitShape(e2[0].dims, n2, r2.split, r2.numOutputs); return o2.length; }, u = (t2, e2, n2, r2, s2) => { const [u2, c2] = i.SplitUtil.splitShape(e2.dims, r2, n2.split, n2.numOutputs), l = c2[s2], p = u2[s2], f = ` float process(int indices[${p.length}]) { indices[${r2}] += ${l}; return _A(indices); } `; return Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey}:${s2}`, output: { dims: p, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: f }); }, c = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Split requires one input."); if ("int8" !== t2[0].type && "uint8" !== t2[0].type && "int16" !== t2[0].type && "uint16" !== t2[0].type && "int32" !== t2[0].type && "uint32" !== t2[0].type && "float32" !== t2[0].type && "float64" !== t2[0].type && "bool" !== t2[0].type) throw new Error("Invalid input type."); }; }, 3933: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseSqueezeAttributes = e.squeezeV13 = e.squeeze = void 0; const r = n(2517); e.squeeze = (t2, e2, n2) => { i(e2); const o2 = r.ShapeUtil.squeezeShape(e2[0].dims, n2); return [t2.reshapeUnpacked(e2[0], o2)]; }, e.squeezeV13 = (t2, n2) => (o(n2), (0, e.squeeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseSqueezeAttributes = (t2) => t2.attributes.getInts("axes"); const i = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Squeeze requires 1 input."); if ("string" === t2[0].type) throw new Error("invalid input tensor types."); }, o = (t2) => { if (!t2 || 2 !== t2.length) throw new Error("Squeeze requires 2 inputs."); if ("int32" !== t2[1].type) throw new Error("Invalid input type."); }; }, 6558: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.sum = void 0; const r = n(5060), i = n(2039); e.sum = (t2, e2) => { a(e2); const n2 = { name: "Sum", inputNames: e2.map(((t3, e3) => `X${e3}`)), inputTypes: new Array(e2.length).fill(i.TextureType.unpacked) }; return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)]; }; const o = (t2, e2, n2) => { const o2 = (0, r.getGlsl)(t2.session.backend.glContext.version), a2 = e2[0].dims.slice(), s = ` void main() { vec4 result = ${e2.map(((t3, e3) => `${o2.texture2D}(X${e3},TexCoords)`)).join(" + ")}; ${o2.output} = result; } `; return Object.assign(Object.assign({}, n2), { output: { dims: a2, type: e2[0].type, textureType: i.TextureType.unpacked }, hasMain: true, shaderSource: s }); }, a = (t2) => { if (!t2 || 0 === t2.length) throw new Error("Sum requires inputs."); const e2 = t2[0].dims.length; for (let n2 = 1; n2 < t2.length; n2++) { if (e2 !== t2[n2].dims.length) throw new Error("Input shapes are mismatched."); for (let r2 = 0; r2 < e2; r2++) if (t2[0].dims[r2] !== t2[n2].dims[r2]) throw new Error("Input shapes are not matched."); } if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type."); for (let e3 = 1; e3 < t2.length; e3++) if (t2[0].type !== t2[e3].type) throw new Error("Input types are not matched."); }; }, 5723: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.tile = void 0; const r = n(782), i = n(2039); e.tile = (t2, e2) => { a(e2); const n2 = { name: "Tile", inputNames: ["A"], inputTypes: [i.TextureType.unpacked] }; return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)]; }; const o = (t2, e2, n2) => { const r2 = e2[0].dims.slice(), o2 = new Array(r2.length), a2 = []; for (let t3 = 0; t3 < r2.length; t3++) o2[t3] = r2[t3] * e2[1].numberData[t3], a2.push(`inputIdx[${t3}] = int(mod(float(outputIdx[${t3}]), ${r2[t3]}.));`); const s = o2.length, u = ` float process(int outputIdx[${s}]) { int inputIdx[${s}]; ${a2.join("\n")} return _A(inputIdx); } `; return Object.assign(Object.assign({}, n2), { output: { dims: o2, type: e2[0].type, textureType: i.TextureType.unpacked }, shaderSource: u }); }, a = (t2) => { if (!t2 || 2 !== t2.length) throw new Error("Tile requires 2 input."); if (1 !== t2[1].dims.length) throw new Error("The second input shape must 1 dimension."); if (t2[1].dims[0] !== t2[0].dims.length) throw new Error("Invalid input shape."); if (-1 === r.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type."); if ("int32" !== t2[1].type && "int16" !== t2[1].type) throw new Error("Invalid repeat type."); }; }, 3738: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseTransposeAttributes = e.transpose = void 0; const r = n(246), i = n(2517), o = n(2039), a = { name: "Transpose", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] }; e.transpose = (t2, e2, n2) => (p(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2[0], n2.perm) }), e2)]), e.parseTransposeAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ perm: t2.attributes.getInts("perm", []) }); const s = (t2, e2, n2) => { const r2 = e2.dims; n2 = u(r2, n2); const i2 = c(r2, n2), s2 = r2.length, p2 = ` ${l("perm", n2, s2)} float process(int indices[${s2}]) { int a[${s2}]; perm(a, indices); return _A(a); }`; return Object.assign(Object.assign({}, a), { output: { dims: i2, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: p2 }); }, u = (t2, e2) => (e2 && e2.length !== t2.length && (e2 = [...t2.keys()].reverse()), e2), c = (t2, e2) => (e2 = u(t2, e2), i.ShapeUtil.sortBasedOnPerm(t2, e2)), l = (t2, e2, n2) => { const r2 = []; r2.push(`void ${t2}(out int a[${n2}], int src[${n2}]) {`); for (let t3 = 0; t3 < n2; ++t3) r2.push(` a[${e2[t3]}]=src[${t3}];`); return r2.push(" }"), r2.join("\n"); }, p = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Transpose requires 1 input."); if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("input should be float tensor"); }; }, 8710: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.encodeAsUint8 = void 0; const r = n(5060), i = n(2039); e.encodeAsUint8 = (t2, e2) => { const n2 = e2.shape, o = (0, r.getGlsl)(t2.session.backend.glContext.version), a = ` const float FLOAT_MAX = 1.70141184e38; const float FLOAT_MIN = 1.17549435e-38; bool isNaN(float val) { return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; } highp vec4 encodeAsUint8(highp float v) { if (isNaN(v)) { return vec4(255, 255, 255, 255); } highp float av = abs(v); if(av < FLOAT_MIN) { return vec4(0.0, 0.0, 0.0, 0.0); } else if(v > FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; } else if(v < -FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; } highp vec4 c = vec4(0,0,0,0); highp float e = floor(log2(av)); highp float m = exp2(fract(log2(av))) - 1.0; c[2] = floor(128.0 * m); m -= c[2] / 128.0; c[1] = floor(32768.0 * m); m -= c[1] / 32768.0; c[0] = floor(8388608.0 * m); highp float ebias = e + 127.0; c[3] = floor(ebias / 2.0); ebias -= c[3] * 2.0; c[2] += floor(ebias) * 128.0; c[3] += 128.0 * step(0.0, -v); return c / 255.0; } void main() { float value = ${o.texture2D}(X,TexCoords).r; ${o.output} = encodeAsUint8(value); }`, s = { name: "Uint8Encode", inputTypes: [i.TextureType.unpacked], inputNames: ["X"], output: { dims: n2, type: e2.tensor.type, textureType: i.TextureType.downloadUint8AsFloat }, shaderSource: a, hasMain: true }; return t2.executeProgram(s, [e2.tensor]); }; }, 4909: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.tanh = e.tan = e.sqrt = e.sin = e.sigmoid = e.relu = e.not = e.neg = e.log = e.parseLeakyReluAttributes = e.leakyRelu = e.identity = e.floor = e.exp = e.parseEluAttributes = e.elu = e.cos = e.ceil = e.clipV11 = e.parseClipAttributes = e.clip = e.atan = e.asin = e.acos = e.abs = e.glslTanh = e.glslTan = e.glslSqrt = e.glslSigmoid = e.glslRelu = e.glslSin = e.glslNot = e.glslNeg = e.glslLog = e.glslLeakyRelu = e.glslIdentity = e.glslClip = e.glslFloor = e.glslExp = e.glslElu = e.glslCos = e.glslCeil = e.glslAtan = e.glslAsin = e.glslAcos = e.glslAbs = void 0; const r = n(246), i = n(2517), o = n(8520), a = n(5060), s = n(2039); function u() { return P2("abs"); } function c() { return P2("acos"); } function l() { return P2("asin"); } function p() { return P2("atan"); } function f() { return P2("ceil"); } function d() { return P2("cos"); } function h(t2) { const e2 = "elu"; return { body: ` const float alpha = float(${t2}); float ${e2}_(float a) { return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; } vec4 ${e2}_(vec4 v) { return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w)); } `, name: e2, type: o.FunctionType.ValueBased }; } function g() { return P2("exp"); } function b() { return P2("floor"); } function m2(t2, e2) { const n2 = "clip"; return { body: ` const float min = float(${t2}); const float max = float(${e2}); float ${n2}_(float a) { return clamp(a, min, max); } vec4 ${n2}_(vec4 v) { return clamp(v, min, max); } `, name: n2, type: o.FunctionType.ValueBased }; } function y() { const t2 = "indentity"; return { body: ` float ${t2}_(float a) { return a; } vec4 ${t2}_(vec4 v) { return v; } `, name: t2, type: o.FunctionType.ValueBased }; } function _(t2) { const e2 = "leakyRelu"; return { body: ` const float alpha = float(${t2}); float ${e2}_(float a) { return a < 0.0 ? a * alpha : a; } vec4 ${e2}_(vec4 v) { return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w)); } `, name: e2, type: o.FunctionType.ValueBased }; } function v() { return P2("log"); } function w() { const t2 = "neg"; return { body: ` float ${t2}_(float a) { return -a; } vec4 ${t2}_(vec4 v) { return -v; } `, name: t2, type: o.FunctionType.ValueBased }; } function x2() { const t2 = "not"; return { body: ` float ${t2}_(float a) { return float( ! bool(a) ); } bool ${t2}_(bool a) { return !a; } vec4 ${t2}_(vec4 v) { return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); } bvec4 ${t2}_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } `, name: t2, type: o.FunctionType.ValueBased }; } function T3() { return P2("sin"); } function S() { const t2 = "relu"; return { body: ` float ${t2}_(float a) { return max( a, 0.0 ); } vec4 ${t2}_(vec4 v) { return max( v, 0.0 ); } `, name: t2, type: o.FunctionType.ValueBased }; } function O2() { const t2 = "sigmoid"; return { body: ` float ${t2}_(float a) { return 1.0 / (1.0 + exp(-a)); } vec4 ${t2}_(vec4 v) { return 1.0 / (1.0 + exp(-v)); } `, name: t2, type: o.FunctionType.ValueBased }; } function A2() { return P2("sqrt"); } function E2() { return P2("tan"); } function I2() { const t2 = "tanh"; return { body: ` float ${t2}_(float a) { a = clamp(a, -10., 10.); a = exp(2.*a); return (a - 1.) / (a + 1.); } vec4 ${t2}_(vec4 v) { v = clamp(v, -10., 10.); v = exp(2.*v); return (v - 1.) / (v + 1.); } `, name: t2, type: o.FunctionType.ValueBased }; } function P2(t2) { return { body: ` float ${t2}_(float a) { return ${t2}(a); } vec4 ${t2}_(vec4 v) { return ${t2}(v); } `, name: t2, type: o.FunctionType.ValueBased }; } e.glslAbs = u, e.glslAcos = c, e.glslAsin = l, e.glslAtan = p, e.glslCeil = f, e.glslCos = d, e.glslElu = h, e.glslExp = g, e.glslFloor = b, e.glslClip = m2, e.glslIdentity = y, e.glslLeakyRelu = _, e.glslLog = v, e.glslNeg = w, e.glslNot = x2, e.glslSin = T3, e.glslRelu = S, e.glslSigmoid = O2, e.glslSqrt = A2, e.glslTan = E2, e.glslTanh = I2; const D3 = (t2, e2, n2, r2) => { const i2 = t2.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o2 = { name: n2.name, inputTypes: [i2], inputNames: ["A"], cacheHint: r2 }; return Object.assign(Object.assign({}, o2), { get: () => ((t3, e3, n3, r3) => { const i3 = t3.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o3 = (0, a.getGlsl)(t3.session.backend.glContext.version); return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i3 }, shaderSource: ` ${r3.body} void main() { vec4 v = ${o3.texture2D}(A, TexCoords); v = ${r3.name}_(v); ${o3.output} = v; } `, hasMain: true }); })(t2, o2, e2, n2) }); }; e.abs = (t2, e2) => [t2.run(D3(t2, e2[0], u()), e2)], e.acos = (t2, e2) => [t2.run(D3(t2, e2[0], c()), e2)], e.asin = (t2, e2) => [t2.run(D3(t2, e2[0], l()), e2)], e.atan = (t2, e2) => [t2.run(D3(t2, e2[0], p()), e2)], e.clip = (t2, e2, n2) => [t2.run(D3(t2, e2[0], m2(n2.min, n2.max), n2.cacheKey), e2)], e.parseClipAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ min: t2.attributes.getFloat("min", i.MIN_CLIP), max: t2.attributes.getFloat("max", i.MAX_CLIP) }), e.clipV11 = (t2, n2) => { const r2 = $2(t2, n2); return (0, e.clip)(t2, [n2[0]], r2); }; const $2 = (t2, e2) => { if (e2.length >= 3 && (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId))) throw new Error("dynamic clip attributes are not allowed"); const n2 = e2.length >= 3 ? e2[1].numberData[0] : i.MIN_CLIP, o2 = e2.length >= 3 ? e2[2].numberData[0] : i.MAX_CLIP; return (0, r.createAttributeWithCacheKey)({ min: n2, max: o2 }); }; e.ceil = (t2, e2) => [t2.run(D3(t2, e2[0], f()), e2)], e.cos = (t2, e2) => [t2.run(D3(t2, e2[0], d()), e2)], e.elu = (t2, e2, n2) => [t2.run(D3(t2, e2[0], h(n2.alpha), n2.cacheKey), e2)], e.parseEluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 1) }), e.exp = (t2, e2) => [t2.run(D3(t2, e2[0], g()), e2)], e.floor = (t2, e2) => [t2.run(D3(t2, e2[0], b()), e2)], e.identity = (t2, e2) => [t2.run(D3(t2, e2[0], y()), e2)], e.leakyRelu = (t2, e2, n2) => [t2.run(D3(t2, e2[0], _(n2.alpha), n2.cacheKey), e2)], e.parseLeakyReluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 0.01) }), e.log = (t2, e2) => [t2.run(D3(t2, e2[0], v()), e2)], e.neg = (t2, e2) => [t2.run(D3(t2, e2[0], w()), e2)], e.not = (t2, e2) => [t2.run(D3(t2, e2[0], x2()), e2)], e.relu = (t2, e2) => [t2.run(D3(t2, e2[0], S()), e2)], e.sigmoid = (t2, e2) => [t2.run(D3(t2, e2[0], O2()), e2)], e.sin = (t2, e2) => [t2.run(D3(t2, e2[0], T3()), e2)], e.sqrt = (t2, e2) => [t2.run(D3(t2, e2[0], A2()), e2)], e.tan = (t2, e2) => [t2.run(D3(t2, e2[0], E2()), e2)], e.tanh = (t2, e2) => [t2.run(D3(t2, e2[0], I2()), e2)]; }, 5611: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackProgramInfoLoader = e.createUnpackProgramInfo = void 0; const r = n(5060), i = n(2039), o = n(9390), a = n(2827), s = { name: "unpack", inputNames: ["A"], inputTypes: [i.TextureType.packed] }; e.createUnpackProgramInfo = (t2, e2) => { const n2 = e2.dims.length, u = (0, a.getChannels)("rc", n2), c = u.slice(-2), l = (0, o.getCoordsDataType)(n2), p = (0, a.unpackFromChannel)(), f = 0 === e2.dims.length ? "" : (function(t3, e3) { if (1 === t3) return "rc"; let n3 = ""; for (let r2 = 0; r2 < t3; r2++) n3 += e3[r2], r2 < t3 - 1 && (n3 += ","); return n3; })(n2, u), d = n2 <= 1 ? "rc" : `vec2(${c.join(",")})`, h = ` ${p} void main() { ${l} rc = getOutputCoords(); // Sample the texture with the coords to get the rgba channel value. vec4 packedInput = getA(${f}); ${(0, r.getGlsl)(t2.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0); } `; return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e2.dims, type: e2.type, textureType: i.TextureType.unpacked }, shaderSource: h }); }, e.createUnpackProgramInfoLoader = (t2, n2) => Object.assign(Object.assign({}, s), { get: () => (0, e.createUnpackProgramInfo)(t2, n2) }); }, 8428: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.parseUnsqueezeAttributes = e.unsqueezeV13 = e.unsqueeze = void 0; const r = n(2517); e.unsqueeze = (t2, e2, n2) => { i(e2); const o2 = r.ShapeUtil.unsqueezeShape(e2[0].dims, n2); return [t2.reshapeUnpacked(e2[0], o2)]; }, e.unsqueezeV13 = (t2, n2) => (o(n2), (0, e.unsqueeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseUnsqueezeAttributes = (t2) => t2.attributes.getInts("axes"); const i = (t2) => { if (!t2 || 1 !== t2.length) throw new Error("Unsqueeze requires 1 input."); if ("string" === t2[0].type) throw new Error("invalid input tensor types."); }, o = (t2) => { if (!t2 || 2 !== t2.length) throw new Error("Unsqueeze requires 2 inputs."); if ("int32" !== t2[1].type) throw new Error("Invalid input type."); }; }, 9793: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.scalesValidation = e.validateInputs = e.parseUpsampleAttributes = e.parseUpsampleAttributesV9 = e.parseUpsampleAttributesV7 = e.upsample = void 0; const r = n(246), i = n(5060), o = n(2039), a = { name: "Upsample", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] }; e.upsample = (t2, n2, r2) => ((0, e.validateInputs)(n2, r2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: r2.cacheKey, get: () => s(t2, n2, r2) }), n2)]), e.parseUpsampleAttributesV7 = (t2) => (0, e.parseUpsampleAttributes)(t2, 7), e.parseUpsampleAttributesV9 = (t2) => (0, e.parseUpsampleAttributes)(t2, 9), e.parseUpsampleAttributes = (t2, n2) => { const i2 = n2 >= 10, o2 = t2.attributes.getString("mode", "nearest"); if ("nearest" !== o2 && "linear" !== o2 && (n2 < 11 || "cubic" !== o2)) throw new Error(`unrecognized mode: ${o2}`); let a2 = []; n2 < 9 && (a2 = t2.attributes.getFloats("scales"), (0, e.scalesValidation)(a2, o2, i2)); const s2 = t2.attributes.getFloat("extrapolation_value", 0), u = n2 > 10 ? t2.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric"; if (-1 === ["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(u)) throw new Error(`coordinate_transform_mode '${u}' is not supported`); const c = "tf_crop_and_resize" === u, l = c, p = "nearest" === o2 && n2 >= 11 ? t2.attributes.getString("nearest_mode", "round_prefer_floor") : ""; if (-1 === ["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(p)) throw new Error(`nearest_mode '${p}' is not supported`); const f = t2.attributes.getFloat("cubic_coeff_a", -0.75), d = 0 !== t2.attributes.getInt("exclude_outside", 0); if (d && "cubic" !== o2) throw new Error("exclude_outside can be set to 1 only when mode is CUBIC."); const h = n2 < 11 || "nearest" === o2 && "asymmetric" === u && "floor" === p; let g = 0, b = 0, m2 = 0; return n2 > 10 ? t2.inputs.length > 2 ? (g = 1, b = 2, m2 = 3) : (b = 1, m2 = 2) : 9 === n2 && (b = 1), (0, r.createAttributeWithCacheKey)({ opset: n2, isResize: i2, mode: o2, scales: a2, extrapolationValue: s2, coordinateTransformMode: u, useExtrapolation: l, needRoiInput: c, nearestMode: p, cubicCoefficientA: f, excludeOutside: d, useNearest2xOptimization: h, roiInputIdx: g, scalesInputIdx: b, sizesInputIdx: m2 }); }; const s = (t2, e2, n2) => { const r2 = (0, i.getGlsl)(t2.session.backend.glContext.version), [s2, u] = t2.calculateTextureWidthAndHeight(e2[0].dims, o.TextureType.unpacked), c = e2[0].dims.map(((t3, e3) => Math.floor(t3 * n2.scales[e3]))), [l, p] = t2.calculateTextureWidthAndHeight(c, o.TextureType.unpacked), f = c.length, d = new Array(f), h = new Array(f); let g = ` int output_pitches[${f}]; int input_pitches[${f}]; `; for (let t3 = f - 1; t3 >= 0; t3--) d[t3] = t3 === f - 1 ? 1 : d[t3 + 1] * c[t3 + 1], h[t3] = t3 === f - 1 ? 1 : h[t3 + 1] * e2[0].dims[t3 + 1], g += ` output_pitches[${t3}] = ${d[t3]}; input_pitches[${t3}] = ${h[t3]}; `; const b = ` float getInputFloat(int index) { vec2 coords = offsetToCoords(index, ${s2}, ${u}); float value = getColorAsFloat(${r2.texture2D}(X, coords)); return value; } `, m2 = "nearest" === n2.mode ? ` ${b} float process(int indices[${f}]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${l}, ${p}); ${g} int d, m; for (int dim = 0; dim < ${f}; ++dim) { d = output_index / output_pitches[dim]; m = output_index - d * output_pitches[dim]; output_index = m; if (scales[dim] != 1 && d > 0) { int d2 = d / scales[dim]; m = d - d2 * scales[dim]; d = d2; } input_index += input_pitches[dim] * d; } return getInputFloat(input_index); }` : 4 === f ? ` ${b} float process(int indices[4]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${l}, ${p}); ${g} int m; int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m / output_pitches[1]; m = m - index_of_dim1 * output_pitches[1]; index_of_dim2 = m / output_pitches[2]; m = m - index_of_dim2 * output_pitches[2]; index_of_dim3 = m; int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; index_of_input_dim2 = index_of_dim2 / scales[2]; y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; index_of_input_dim3 = index_of_dim3 / scales[3]; x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; input_index = index_of_dim0 * input_pitches[0] + index_of_dim1 * input_pitches[1] + index_of_input_dim2 * input_pitches[2] + index_of_input_dim3; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim2 = false; if (index_of_input_dim2 == (${e2[0].dims[2]} - 1)) { // It's the end in dimension 2 x01 = x00; end_of_dim2 = true; } else { x01 = getInputFloat(input_index + input_pitches[2]); } if (index_of_input_dim3 == (input_pitches[2] - 1)) { // It's the end in dimension 3 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); }` : ` ${b} float process(int indices[2]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${l}, ${p}); ${g} int m; int index_of_dim0, index_of_dim1; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m; int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; index_of_input_dim0 = index_of_dim0 / scales[0]; y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; index_of_input_dim1 = index_of_dim1 / scales[1]; x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim0 = false; if (index_of_input_dim0 == (${e2[0].dims[0]} - 1)) { // It's the end in dimension 0 x01 = x00; end_of_dim0 = true; } else { x01 = getInputFloat(input_index + input_pitches[0]); } if (index_of_input_dim1 == (input_pitches[0] - 1)) { // It's the end in dimension 1 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); }`; return Object.assign(Object.assign({}, a), { output: { dims: c, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: m2, variables: [{ name: "scales", type: "int", arrayLength: n2.scales.length, data: n2.scales.map(((t3) => Math.ceil(t3))) }] }); }; e.validateInputs = (t2, e2) => { if (!t2 || e2.opset < 9 && 1 !== t2.length || e2.opset >= 9 && e2.opset < 11 && 2 !== t2.length || e2.opset >= 11 && t2.length < 2) throw new Error("invalid inputs."); if (e2.scales.length > 0 && t2[0].dims.length !== e2.scales.length) throw new Error("Invalid input shape."); if ("string" === t2[0].type) throw new Error("Invalid input tensor types."); }, e.scalesValidation = (t2, e2, n2) => { if (n2) { for (const e3 of t2) if (e3 <= 0) throw new Error("Scale value should be greater than 0."); } else for (const e3 of t2) if (e3 < 1) throw new Error("Scale value should be greater than or equal to 1."); if (!("linear" !== e2 && "cubic" !== e2 || 2 === t2.length || 4 === t2.length && 1 === t2[0] && 1 === t2[1])) throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n2 ? "Resize" : "Upsample"} opeartor.`); }; }, 1958: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.ProgramManager = void 0; const r = n(1670), i = n(6231), o = n(8879), a = n(5060); e.ProgramManager = class { constructor(t2, e2, n2) { this.profiler = t2, this.glContext = e2, this.textureLayoutStrategy = n2, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; } getArtifact(t2) { return this.repo.get(t2); } setArtifact(t2, e2) { this.repo.set(t2, e2); } run(t2, e2, n2) { var r2; this.profiler.event("op", `ProgramManager.run ${null !== (r2 = t2.programInfo.name) && void 0 !== r2 ? r2 : "unknown kernel"}`, (() => { var r3; const o2 = this.glContext.gl, a2 = t2.program; o2.useProgram(a2); try { this.bindOutput(n2), this.attributesBound || this.bindAttributes(t2.attribLocations), this.bindUniforms(t2.uniformLocations, null !== (r3 = t2.programInfo.variables) && void 0 !== r3 ? r3 : [], e2); } catch (e3) { throw i.Logger.error("ProgramManager", t2.programInfo.shaderSource), e3; } this.profiler.event("backend", "GlContext.draw()", (() => { this.glContext.draw(); })); }), this.glContext); } dispose() { this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach(((t2) => this.glContext.deleteProgram(t2.program))); } build(t2, e2, n2) { return this.profiler.event("backend", "ProgramManager.build", (() => { const r2 = new o.GlslPreprocessor(this.glContext, t2, e2, n2), i2 = r2.preprocess(), a2 = this.compile(i2); return { programInfo: t2, program: a2, uniformLocations: this.getUniformLocations(a2, r2.context.programInfo.inputNames, r2.context.programInfo.variables), attribLocations: this.getAttribLocations(a2) }; })); } compile(t2) { if (!this.vertexShader) { i.Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time"); const t3 = (0, a.getVertexShaderSource)(this.glContext.version); this.vertexShader = this.glContext.compileShader(t3, this.glContext.gl.VERTEX_SHADER); } r.env.debug && i.Logger.verbose("ProrgramManager", `FragShader: ${t2} `); const e2 = this.glContext.compileShader(t2, this.glContext.gl.FRAGMENT_SHADER), n2 = this.glContext.createProgram(this.vertexShader, e2); return this.glContext.deleteShader(e2), n2; } bindOutput(t2) { const e2 = t2.width, n2 = t2.height; i.Logger.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${e2}/${n2}, shape=${t2.shape}, type=${t2.tensor.type}`), this.glContext.attachFramebuffer(t2.texture, e2, n2); } bindAttributes(t2) { const e2 = t2.position, n2 = t2.textureCoord; this.glContext.setVertexAttributes(e2, n2), this.attributesBound = true; } bindUniforms(t2, e2, n2) { var r2; const i2 = this.glContext.gl; let o2 = 0; for (const { name: a2, type: s, location: u, arrayLength: c } of t2) { const t3 = null === (r2 = e2.find(((t4) => t4.name === a2))) || void 0 === r2 ? void 0 : r2.data; if ("sampler2D" !== s && !t3) throw new Error(`variable '${a2}' does not have data defined in program info`); switch (s) { case "sampler2D": this.bindTexture(n2[o2], u, o2), o2++; break; case "float": c ? i2.uniform1fv(u, t3) : i2.uniform1f(u, t3); break; case "int": c ? i2.uniform1iv(u, t3) : i2.uniform1i(u, t3); break; default: throw new Error(`Uniform not implemented: ${s}`); } } } bindTexture(t2, e2, n2) { this.glContext.bindTextureToUniform(t2.texture, n2, e2); } getAttribLocations(t2) { return { position: this.getAttribLocation(t2, "position"), textureCoord: this.getAttribLocation(t2, "textureCoord") }; } getUniformLocations(t2, e2, n2) { const r2 = []; if (e2) for (const n3 of e2) r2.push({ name: n3, type: "sampler2D", location: this.getUniformLocation(t2, n3) }); if (n2) for (const e3 of n2) r2.push(Object.assign(Object.assign({}, e3), { location: this.getUniformLocation(t2, e3.name) })); return r2; } getUniformLocation(t2, e2) { const n2 = this.glContext.gl.getUniformLocation(t2, e2); if (null === n2) throw new Error(`Uniform ${e2} not found.`); return n2; } getAttribLocation(t2, e2) { return this.glContext.gl.getAttribLocation(t2, e2); } }; }, 6416: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.WebGLSessionHandler = void 0; const r = n(6231), i = n(1047), o = n(8316), a = n(1640), s = n(1958), u = n(7859), c = n(5702); e.WebGLSessionHandler = class { constructor(t2, e2) { this.backend = t2, this.context = e2, this.layoutStrategy = new u.PreferLogicalStrategy(t2.glContext.maxTextureSize), this.programManager = new s.ProgramManager(this.context.profiler, t2.glContext, this.layoutStrategy), this.textureManager = new c.TextureManager(t2.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: "full" === t2.textureCacheMode }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = t2.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map(); } createInferenceHandler() { return new o.WebGLInferenceHandler(this); } onGraphInitialized(t2) { const e2 = t2.getValues().filter(((t3) => -1 === t3.from && t3.tensor)).map(((t3) => t3.tensor.dataId)); this.initializers = new Set(e2); } isInitializer(t2) { return !!this.initializers && this.initializers.has(t2); } addInitializer(t2) { this.initializers.add(t2); } getTextureData(t2, e2) { return e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2); } setTextureData(t2, e2, n2 = false) { r.Logger.verbose("WebGLSessionHandler", "Storing Texture data in cache"), n2 ? this.packedTextureDataCache.set(t2, e2) : this.unpackedTextureDataCache.set(t2, e2); } dispose() { this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((t2) => this.textureManager.releaseTexture(t2, true))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((t2) => this.textureManager.releaseTexture(t2, true))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } resolve(t2, e2, n2) { const r2 = (0, i.resolveOperator)(t2, e2, a.WEBGL_OP_RESOLVE_RULES); return { impl: r2.opImpl, context: r2.opInit ? r2.opInit(t2, n2) : t2 }; } }; }, 7769: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.Uint8DataEncoder = e.RGBAFloatDataEncoder = e.RedFloat32DataEncoder = void 0; const r = n(6231); e.RedFloat32DataEncoder = class { constructor(t2, e2 = 1) { if (1 === e2) this.internalFormat = t2.R32F, this.format = t2.RED, this.textureType = t2.FLOAT, this.channelSize = e2; else { if (4 !== e2) throw new Error(`Invalid number of channels: ${e2}`); this.internalFormat = t2.RGBA32F, this.format = t2.RGBA, this.textureType = t2.FLOAT, this.channelSize = e2; } } encode(t2, e2) { let n2, i; return t2.constructor !== Float32Array && (r.Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array"), i = new Float32Array(t2)), e2 * this.channelSize > t2.length ? (r.Logger.warning("Encoder", "Source data too small. Allocating larger array"), i = t2, n2 = this.allocate(e2 * this.channelSize), i.forEach(((t3, e3) => n2[e3] = t3))) : (i = t2, n2 = i), n2; } allocate(t2) { return new Float32Array(4 * t2); } decode(t2, e2) { return 1 === this.channelSize ? t2.filter(((t3, e3) => e3 % 4 == 0)).subarray(0, e2) : t2.subarray(0, e2); } }, e.RGBAFloatDataEncoder = class { constructor(t2, e2 = 1, n2) { if (1 !== e2 && 4 !== e2) throw new Error(`Invalid number of channels: ${e2}`); this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.channelSize = e2, this.textureType = n2 || t2.FLOAT; } encode(t2, e2) { let n2 = t2; return 1 === this.channelSize && (r.Logger.verbose("Encoder", "Exploding into a larger array"), n2 = this.allocate(e2), t2.forEach(((t3, e3) => n2[4 * e3] = t3))), n2; } allocate(t2) { return new Float32Array(4 * t2); } decode(t2, e2) { return 1 === this.channelSize ? t2.filter(((t3, e3) => e3 % 4 == 0)).subarray(0, e2) : t2.subarray(0, e2); } }, e.Uint8DataEncoder = class { constructor(t2, e2 = 1) { if (this.channelSize = 4, 1 === e2) this.internalFormat = t2.ALPHA, this.format = t2.ALPHA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2; else { if (4 !== e2) throw new Error(`Invalid number of channels: ${e2}`); this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2; } } encode(t2, e2) { return new Uint8Array(t2.buffer, t2.byteOffset, t2.byteLength); } allocate(t2) { return new Uint8Array(t2 * this.channelSize); } decode(t2, e2) { if (t2 instanceof Uint8Array) return t2.subarray(0, e2); throw new Error(`Invalid array type: ${t2.constructor}`); } }; }, 7859: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.getBatchDim = e.sizeToSquarishShape = e.getRowsCols = e.sizeFromShape = e.isInt = e.parseAxisParam = e.squeezeShape = e.PreferLogicalStrategy = e.AlwaysKeepOriginalSizeStrategy = void 0; const r = n(6231), i = n(2517); function o(t2, e2) { const n2 = [], r2 = [], i2 = null != e2 && Array.isArray(e2) && 0 === e2.length, o2 = null == e2 || i2 ? null : a(e2, t2).sort(); let s2 = 0; for (let e3 = 0; e3 < t2.length; ++e3) { if (null != o2) { if (o2[s2] === e3 && 1 !== t2[e3]) throw new Error(`Can't squeeze axis ${e3} since its dim '${t2[e3]}' is not 1`); (null == o2[s2] || o2[s2] > e3) && 1 === t2[e3] && (n2.push(t2[e3]), r2.push(e3)), o2[s2] <= e3 && s2++; } 1 !== t2[e3] && (n2.push(t2[e3]), r2.push(e3)); } return { newShape: n2, keptDims: r2 }; } function a(t2, e2) { const n2 = e2.length; return t2 = null == t2 ? e2.map(((t3, e3) => e3)) : [].concat(t2), (0, i.assert)(t2.every(((t3) => t3 >= -n2 && t3 < n2)), (() => `All values in axis param must be in range [-${n2}, ${n2}) but got axis ${t2}`)), (0, i.assert)(t2.every(s), (() => `All values in axis param must be integers but got axis ${t2}`)), t2.map(((t3) => t3 < 0 ? n2 + t3 : t3)); } function s(t2) { return t2 % 1 == 0; } function u(t2) { if (0 === t2.length) return 1; let e2 = t2[0]; for (let n2 = 1; n2 < t2.length; n2++) e2 *= t2[n2]; return e2; } function c(t2) { const e2 = Math.ceil(Math.sqrt(t2)); return [e2, Math.ceil(t2 / e2)]; } e.AlwaysKeepOriginalSizeStrategy = class { constructor(t2) { this.maxTextureSize = t2; } computeTextureWH(t2, e2) { if (0 === t2.length) return [1, 1]; const n2 = this.maxTextureSize; if (e2 && void 0 !== e2.breakAxis) { const i3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce(((t3, e3) => t3 * e3)), o3 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce(((t3, e3) => t3 * e3)); if (!(i3 > n2 || o3 > n2)) return [i3, o3]; r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`); } const i2 = t2.reduce(((t3, e3) => t3 * e3)); let o2 = Math.floor(Math.sqrt(i2)); for (; o2 < n2 && o2 < i2 && i2 % o2 != 0; o2++) ; if (o2 >= n2 || i2 % o2 != 0) throw new Error(`The given dimensions are outside this GPU's boundaries: ${t2}`); return [o2, i2 / o2]; } }, e.PreferLogicalStrategy = class { constructor(t2) { this.maxTextureSize = t2; } computeTextureWH(t2, e2) { const n2 = this.computeTexture(t2, e2); return e2 && e2.isPacked && (n2[0] /= 2, n2[1] /= 2), e2 && e2.reverseWH ? [n2[1], n2[0]] : n2; } computeTexture(t2, e2) { const n2 = e2 && e2.isPacked; if (0 === t2.length) return n2 ? [2, 2] : [1, 1]; let i2 = this.maxTextureSize; if (e2 && void 0 !== e2.breakAxis) { const n3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce(((t3, e3) => t3 * e3)), o2 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce(((t3, e3) => t3 * e3)); if (!(n3 > i2 || o2 > i2)) return [n3, o2]; r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`); } let a2 = t2.slice(0); if (n2 && (i2 *= 2, a2 = a2.map(((t3, e3) => e3 >= a2.length - 2 ? a2[e3] % 2 == 0 ? a2[e3] : a2[e3] + 1 : a2[e3])), 1 === a2.length && (a2 = [2, a2[0]])), 2 !== a2.length) { const t3 = o(a2); a2 = t3.newShape; } const s2 = u(a2); return a2.length <= 1 && s2 <= i2 ? [1, s2] : 2 === a2.length && a2[0] <= i2 && a2[1] <= i2 ? a2 : 3 === a2.length && a2[0] * a2[1] <= i2 && a2[2] <= i2 ? [a2[0] * a2[1], a2[2]] : 3 === a2.length && a2[0] <= i2 && a2[1] * a2[2] <= i2 ? [a2[0], a2[1] * a2[2]] : 4 === a2.length && a2[0] * a2[1] * a2[2] <= i2 && a2[3] <= i2 ? [a2[0] * a2[1] * a2[2], a2[3]] : 4 === a2.length && a2[0] <= i2 && a2[1] * a2[2] * a2[3] <= i2 ? [a2[0], a2[1] * a2[2] * a2[3]] : n2 ? c(s2 / 4).map(((t3) => 2 * t3)) : c(s2); } }, e.squeezeShape = o, e.parseAxisParam = a, e.isInt = s, e.sizeFromShape = u, e.getRowsCols = function(t2) { if (0 === t2.length) throw Error("Cannot get rows and columns of an empty shape array."); return [t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]]; }, e.sizeToSquarishShape = c, e.getBatchDim = function(t2, e2 = 2) { return u(t2.slice(0, t2.length - e2)); }; }, 4057: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createTextureLayoutFromShape = e.calculateTextureWidthAndHeight = e.createTextureLayoutFromTextureType = void 0; const r = n(2517), i = n(2039); e.createTextureLayoutFromTextureType = (t2, n2, r2) => { const o = r2 === i.TextureType.unpacked || r2 === i.TextureType.unpackedReversed ? 1 : 4, a = r2 === i.TextureType.packed, s = r2 === i.TextureType.unpackedReversed || r2 === i.TextureType.packed, u = r2 === i.TextureType.packedLastDimension ? n2.length - 1 : void 0, c = r2 === i.TextureType.packedLastDimension ? n2.map(((t3, e2) => e2 === n2.length - 1 ? 4 * t3 : t3)) : void 0; return (0, e.createTextureLayoutFromShape)(t2, n2, o, c, { isPacked: a, reverseWH: s, breakAxis: u }); }, e.calculateTextureWidthAndHeight = (t2, n2, r2) => { const i2 = (0, e.createTextureLayoutFromTextureType)(t2, n2, r2); return [i2.width, i2.height]; }, e.createTextureLayoutFromShape = (t2, e2, n2 = 1, i2, o) => { const a = !(!o || !o.isPacked), [s, u] = t2.computeTextureWH(a && i2 || e2, o), c = e2.length; let l = e2.slice(0); if (0 === c && (l = [1]), 1 === n2) i2 = e2; else if (a) { if (4 !== n2) throw new Error("a packed texture must be 4-channel"); i2 = e2, c > 0 && (l[c - 1] = Math.ceil(l[c - 1] / 2)), c > 1 && (l[c - 2] = Math.ceil(l[c - 2] / 2)); } else if (!i2) throw new Error("Unpacked shape is needed when using channels > 1"); return { width: s, height: u, channels: n2, isPacked: a, shape: l, strides: r.ShapeUtil.computeStrides(l), unpackedShape: i2, reversedWH: o && o.reverseWH }; }; }, 5702: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.TextureManager = void 0; const r = n(6231); e.TextureManager = class { constructor(t2, e2, n2, r2) { this.glContext = t2, this.layoutStrategy = e2, this.profiler = n2, this.config = r2, this.pendingRead = /* @__PURE__ */ new Map(), r2.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map()); } createTextureFromLayout(t2, e2, n2, i) { const o = this.toEncoderType(t2), a = this.glContext.getEncoder(o, e2.channels || 1, i); if (e2.isPacked && 1 === i) throw new Error("not implemented"); const s = e2.width, u = e2.height; let c, l; if (this.config.reuseTextures) { c = `${s}x${u}_${a.format}_${a.internalFormat}_${a.textureType}`, l = this.inUseTextures.get(c), l || (l = [], this.inUseTextures.set(c, l)); const e3 = this.idleTextures.get(c); if (e3 && e3.length > 0) { const r2 = e3.pop(); return l.push(r2), 1 === i && this.glContext.updateTexture(r2, s, u, a, this.toTextureData(t2, n2)), r2; } } r.Logger.verbose("TextureManager", `Creating new texture of size ${e2.width}x${e2.height}`); const p = this.glContext.allocateTexture(s, u, a, this.toTextureData(t2, n2)); return this.config.reuseTextures && (l.push(p), this.textureLookup.set(p, c)), p; } readTexture(t2, e2, n2) { return n2 || (n2 = 1), this.profiler.event("backend", "TextureManager.readTexture", (() => { const r2 = t2.shape.reduce(((t3, e3) => t3 * e3)) * n2, i = this.glContext.readTexture(t2.texture, t2.width, t2.height, r2, this.toEncoderType(e2), n2); return this.toTensorData(e2, i); })); } async readTextureAsync(t2, e2, n2) { const r2 = t2.tensor.dataId; if (n2 || (n2 = 1), this.pendingRead.has(r2)) { const t3 = this.pendingRead.get(r2); return new Promise(((e3) => null == t3 ? void 0 : t3.push(e3))); } return this.profiler.event("backend", "TextureManager.readTextureAsync", (async () => { this.pendingRead.set(r2, []); const i = t2.shape.reduce(((t3, e3) => t3 * e3)) * n2; await this.glContext.createAndWaitForFence(); const o = this.glContext.readTexture(t2.texture, t2.width, t2.height, i, this.toEncoderType(e2), n2), a = this.toTensorData(e2, o), s = this.pendingRead.get(r2); return this.pendingRead.delete(r2), null == s || s.forEach(((t3) => t3(a))), a; })); } readUint8TextureAsFloat(t2) { return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", (() => { const e2 = t2.shape.reduce(((t3, e3) => t3 * e3)), n2 = this.glContext.readTexture(t2.texture, t2.width, t2.height, 4 * e2, "byte", 4); return new Float32Array(n2.buffer, n2.byteOffset, e2); })); } releaseTexture(t2, e2) { let n2; if (this.config.reuseTextures && (n2 = this.textureLookup.get(t2.texture), n2)) { e2 && this.textureLookup.delete(n2); const r2 = this.inUseTextures.get(n2); if (r2) { const e3 = r2.indexOf(t2.texture); if (-1 !== e3) { r2.splice(e3, 1); let i = this.idleTextures.get(n2); i || (i = [], this.idleTextures.set(n2, i)), i.push(t2.texture); } } } n2 && !e2 || (r.Logger.verbose("TextureManager", `Deleting texture of size ${t2.width}x${t2.height}`), this.glContext.deleteTexture(t2.texture)); } toTensorData(t2, e2) { switch (t2) { case "int16": return e2 instanceof Int16Array ? e2 : Int16Array.from(e2); case "int32": return e2 instanceof Int32Array ? e2 : Int32Array.from(e2); case "int8": return e2 instanceof Int8Array ? e2 : Int8Array.from(e2); case "uint16": return e2 instanceof Uint16Array ? e2 : Uint16Array.from(e2); case "uint32": return e2 instanceof Uint32Array ? e2 : Uint32Array.from(e2); case "uint8": case "bool": return e2 instanceof Uint8Array ? e2 : Uint8Array.from(e2); case "float32": return e2 instanceof Float32Array ? e2 : Float32Array.from(e2); case "float64": return e2 instanceof Float64Array ? e2 : Float64Array.from(e2); default: throw new Error(`TensorData type ${t2} is not supported`); } } toTextureData(t2, e2) { if (e2) return e2 instanceof Float32Array ? e2 : new Float32Array(e2); } toEncoderType(t2) { return "float"; } clearActiveTextures() { this.glContext.clearActiveTextures(); } }; }, 2039: (t, e) => { "use strict"; var n; Object.defineProperty(e, "__esModule", { value: true }), e.TextureType = void 0, (n = e.TextureType || (e.TextureType = {}))[n.unpacked = 0] = "unpacked", n[n.unpackedReversed = 1] = "unpackedReversed", n[n.packed = 2] = "packed", n[n.downloadUint8AsFloat = 3] = "downloadUint8AsFloat", n[n.packedLastDimension = 4] = "packedLastDimension"; }, 9390: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.getGlChannels = e.getCoordsDataType = e.getSqueezedParams = e.squeezeInputShape = e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = e.generateShaderFuncNameFromInputSamplerName = e.repeatedTry = e.getPackedShape = void 0; const r = n(2517); e.getPackedShape = function(t2) { const e2 = t2.length; return t2.slice(0, e2 - 1).concat(t2[e2 - 1] / 4); }, e.repeatedTry = async function(t2, e2 = ((t3) => 0), n2) { return new Promise(((r2, i) => { let o = 0; const a = () => { if (t2()) return void r2(); o++; const s = e2(o); null != n2 && o >= n2 ? i() : setTimeout(a, s); }; a(); })); }, e.generateShaderFuncNameFromInputSamplerName = function(t2) { return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, (() => "empty string found for sampler name")), "get" + t2.charAt(0).toUpperCase() + t2.slice(1); }, e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = function(t2) { return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, (() => "empty string found for sampler name")), "get" + t2.charAt(0).toUpperCase() + t2.slice(1) + "AtOutCoords"; }, e.squeezeInputShape = function(t2, e2) { let n2 = JSON.parse(JSON.stringify(t2)); return n2 = e2, n2; }, e.getSqueezedParams = function(t2, e2) { return e2.map(((e3) => t2[e3])).join(", "); }, e.getCoordsDataType = function(t2) { if (t2 <= 1) return "int"; if (2 === t2) return "ivec2"; if (3 === t2) return "ivec3"; if (4 === t2) return "ivec4"; if (5 === t2) return "ivec5"; if (6 === t2) return "ivec6"; throw Error(`GPU for rank ${t2} is not yet supported`); }, e.getGlChannels = function(t2 = 6) { return ["x", "y", "z", "w", "u", "v"].slice(0, t2); }; }, 7305: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.createNewWebGLContext = e.createWebGLContext = void 0; const r = n(6231), i = n(1713), o = {}; function a(t2) { const e2 = (function() { if ("undefined" == typeof document) { if ("undefined" == typeof OffscreenCanvas) throw new TypeError("failed to create canvas: OffscreenCanvas is not supported"); return new OffscreenCanvas(1, 1); } const t3 = document.createElement("canvas"); return t3.width = 1, t3.height = 1, t3; })(); let n2; const o2 = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false }; if ((!t2 || "webgl2" === t2) && (n2 = e2.getContext("webgl2", o2), n2)) try { return new i.WebGLContext(n2, 2); } catch (t3) { r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${t3}`); } if ((!t2 || "webgl" === t2) && (n2 = e2.getContext("webgl", o2) || e2.getContext("experimental-webgl", o2), n2)) try { return new i.WebGLContext(n2, 1); } catch (t3) { r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t3}`); } throw new Error("WebGL is not supported"); } e.createWebGLContext = function t2(e2) { let n2; e2 && "webgl2" !== e2 || !("webgl2" in o) ? e2 && "webgl" !== e2 || !("webgl" in o) || (n2 = o.webgl) : n2 = o.webgl2, n2 = n2 || a(e2), e2 = e2 || 1 === n2.version ? "webgl" : "webgl2"; const r2 = n2.gl; return o[e2] = n2, r2.isContextLost() ? (delete o[e2], t2(e2)) : (r2.disable(r2.DEPTH_TEST), r2.disable(r2.STENCIL_TEST), r2.disable(r2.BLEND), r2.disable(r2.DITHER), r2.disable(r2.POLYGON_OFFSET_FILL), r2.disable(r2.SAMPLE_COVERAGE), r2.enable(r2.SCISSOR_TEST), r2.enable(r2.CULL_FACE), r2.cullFace(r2.BACK), n2); }, e.createNewWebGLContext = a; }, 1713: function(t, e, n) { "use strict"; var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2); var i2 = Object.getOwnPropertyDescriptor(e2, n2); i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { return e2[n2]; } }), Object.defineProperty(t2, r2, i2); } : function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); } : function(t2, e2) { t2.default = e2; }), o = this && this.__importStar || function(t2) { if (t2 && t2.__esModule) return t2; var e2 = {}; if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); return i(e2, t2), e2; }; Object.defineProperty(e, "__esModule", { value: true }), e.WebGLContext = e.linearSearchLastTrue = void 0; const a = n(1670), s = o(n(7769)), u = n(9390); function c(t2) { let e2 = 0; for (; e2 < t2.length && t2[e2](); ++e2) ; return e2 - 1; } e.linearSearchLastTrue = c, e.WebGLContext = class { constructor(t2, e2) { this.frameBufferBound = false, this.itemsToPoll = [], this.gl = t2, this.version = e2, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters(); } allocateTexture(t2, e2, n2, r2) { const i2 = this.gl, o2 = i2.createTexture(); i2.bindTexture(i2.TEXTURE_2D, o2), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MIN_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_MAG_FILTER, i2.NEAREST), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_S, i2.CLAMP_TO_EDGE), i2.texParameteri(i2.TEXTURE_2D, i2.TEXTURE_WRAP_T, i2.CLAMP_TO_EDGE); const a2 = r2 ? n2.encode(r2, t2 * e2) : null; return i2.texImage2D(i2.TEXTURE_2D, 0, n2.internalFormat, t2, e2, 0, n2.format, n2.textureType, a2), this.checkError(), o2; } updateTexture(t2, e2, n2, r2, i2) { const o2 = this.gl; o2.bindTexture(o2.TEXTURE_2D, t2); const a2 = r2.encode(i2, e2 * n2); o2.texSubImage2D(o2.TEXTURE_2D, 0, 0, 0, e2, n2, r2.format, r2.textureType, a2), this.checkError(); } attachFramebuffer(t2, e2, n2) { const r2 = this.gl; r2.bindTexture(r2.TEXTURE_2D, t2), r2.bindFramebuffer(r2.FRAMEBUFFER, this.framebuffer), r2.framebufferTexture2D(r2.FRAMEBUFFER, r2.COLOR_ATTACHMENT0, r2.TEXTURE_2D, t2, 0), this.checkError(), r2.viewport(0, 0, e2, n2), r2.scissor(0, 0, e2, n2); } readTexture(t2, e2, n2, r2, i2, o2) { const a2 = this.gl; o2 || (o2 = 1), this.frameBufferBound || this.attachFramebuffer(t2, e2, n2); const s2 = this.getEncoder(i2, o2), u2 = s2.allocate(e2 * n2); return a2.bindTexture(a2.TEXTURE_2D, t2), a2.framebufferTexture2D(a2.FRAMEBUFFER, a2.COLOR_ATTACHMENT0, a2.TEXTURE_2D, t2, 0), a2.readPixels(0, 0, e2, n2, a2.RGBA, s2.textureType, u2), this.checkError(), s2.decode(u2, r2); } isFramebufferReady() { return true; } getActiveTexture() { const t2 = this.gl; return "TEXTURE" + (t2.getParameter(this.gl.ACTIVE_TEXTURE) - t2.TEXTURE0); } getTextureBinding() { return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); } getFramebufferBinding() { return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); } setVertexAttributes(t2, e2) { const n2 = this.gl; n2.vertexAttribPointer(t2, 3, n2.FLOAT, false, 20, 0), n2.enableVertexAttribArray(t2), -1 !== e2 && (n2.vertexAttribPointer(e2, 2, n2.FLOAT, false, 20, 12), n2.enableVertexAttribArray(e2)), this.checkError(); } createProgram(t2, e2) { const n2 = this.gl, r2 = n2.createProgram(); return n2.attachShader(r2, t2), n2.attachShader(r2, e2), n2.linkProgram(r2), r2; } compileShader(t2, e2) { const n2 = this.gl, r2 = n2.createShader(e2); if (!r2) throw new Error(`createShader() returned null with type ${e2}`); if (n2.shaderSource(r2, t2), n2.compileShader(r2), false === n2.getShaderParameter(r2, n2.COMPILE_STATUS)) throw new Error(`Failed to compile shader: ${n2.getShaderInfoLog(r2)} Shader source: ${t2}`); return r2; } deleteShader(t2) { this.gl.deleteShader(t2); } bindTextureToUniform(t2, e2, n2) { const r2 = this.gl; r2.activeTexture(r2.TEXTURE0 + e2), this.checkError(), r2.bindTexture(r2.TEXTURE_2D, t2), this.checkError(), r2.uniform1i(n2, e2), this.checkError(); } draw() { this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError(); } checkError() { if (a.env.debug) { const t2 = this.gl, e2 = t2.getError(); let n2 = ""; switch (e2) { case t2.NO_ERROR: return; case t2.INVALID_ENUM: n2 = "INVALID_ENUM"; break; case t2.INVALID_VALUE: n2 = "INVALID_VALUE"; break; case t2.INVALID_OPERATION: n2 = "INVALID_OPERATION"; break; case t2.INVALID_FRAMEBUFFER_OPERATION: n2 = "INVALID_FRAMEBUFFER_OPERATION"; break; case t2.OUT_OF_MEMORY: n2 = "OUT_OF_MEMORY"; break; case t2.CONTEXT_LOST_WEBGL: n2 = "CONTEXT_LOST_WEBGL"; break; default: n2 = `Unknown WebGL Error: ${e2.toString(16)}`; } throw new Error(n2); } } deleteTexture(t2) { this.gl.deleteTexture(t2); } deleteProgram(t2) { this.gl.deleteProgram(t2); } getEncoder(t2, e2, n2 = 0) { if (2 === this.version) return new s.RedFloat32DataEncoder(this.gl, e2); switch (t2) { case "float": return 1 === n2 || this.isRenderFloat32Supported ? new s.RGBAFloatDataEncoder(this.gl, e2) : new s.RGBAFloatDataEncoder(this.gl, e2, this.textureHalfFloatExtension.HALF_FLOAT_OES); case "int": throw new Error("not implemented"); case "byte": return new s.Uint8DataEncoder(this.gl, e2); default: throw new Error(`Invalid dataType: ${t2}`); } } clearActiveTextures() { const t2 = this.gl; for (let e2 = 0; e2 < this.maxTextureImageUnits; ++e2) t2.activeTexture(t2.TEXTURE0 + e2), t2.bindTexture(t2.TEXTURE_2D, null); } dispose() { if (this.disposed) return; const t2 = this.gl; t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(this.framebuffer), t2.bindBuffer(t2.ARRAY_BUFFER, null), t2.deleteBuffer(this.vertexbuffer), t2.bindBuffer(t2.ELEMENT_ARRAY_BUFFER, null), t2.finish(), this.disposed = true; } createDefaultGeometry() { return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]); } createVertexbuffer() { const t2 = this.gl, e2 = t2.createBuffer(); if (!e2) throw new Error("createBuffer() returned null"); const n2 = this.createDefaultGeometry(); return t2.bindBuffer(t2.ARRAY_BUFFER, e2), t2.bufferData(t2.ARRAY_BUFFER, n2, t2.STATIC_DRAW), this.checkError(), e2; } createFramebuffer() { const t2 = this.gl.createFramebuffer(); if (!t2) throw new Error("createFramebuffer returned null"); return t2; } queryVitalParameters() { const t2 = this.gl; if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), 1 === this.version && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) throw new Error("both float32 and float16 TextureType are not supported"); this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = t2.getParameter(t2.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = t2.getParameter(t2.MAX_TEXTURE_IMAGE_UNITS), this.version; } getExtensions() { 2 === this.version ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float")); } checkFloatTextureAttachableToFrameBuffer() { const t2 = this.gl, e2 = t2.createTexture(); t2.bindTexture(t2.TEXTURE_2D, e2); const n2 = 2 === this.version ? t2.RGBA32F : t2.RGBA; t2.texImage2D(t2.TEXTURE_2D, 0, n2, 1, 1, 0, t2.RGBA, t2.FLOAT, null); const r2 = t2.createFramebuffer(); t2.bindFramebuffer(t2.FRAMEBUFFER, r2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0); const i2 = t2.checkFramebufferStatus(t2.FRAMEBUFFER) === t2.FRAMEBUFFER_COMPLETE; return t2.bindTexture(t2.TEXTURE_2D, null), t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteTexture(e2), t2.deleteFramebuffer(r2), i2; } checkRenderFloat32() { if (2 === this.version) { if (!this.colorBufferFloatExtension) return false; } else if (!this.textureFloatExtension) return false; return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Download() { if (2 === this.version) { if (!this.colorBufferFloatExtension) return false; } else { if (!this.textureFloatExtension) return false; if (!this.gl.getExtension("WEBGL_color_buffer_float")) return false; } return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Blend() { const t2 = this.gl; let e2, n2, r2, i2, o2; try { e2 = t2.createTexture(), n2 = t2.createFramebuffer(), t2.bindTexture(t2.TEXTURE_2D, e2); const a2 = 2 === this.version ? t2.RGBA32F : t2.RGBA; return t2.texImage2D(t2.TEXTURE_2D, 0, a2, 1, 1, 0, t2.RGBA, t2.FLOAT, null), t2.bindFramebuffer(t2.FRAMEBUFFER, n2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0), t2.enable(t2.BLEND), r2 = t2.createShader(t2.VERTEX_SHADER), !!r2 && (t2.shaderSource(r2, "void main(){}"), t2.compileShader(r2), i2 = t2.createShader(t2.FRAGMENT_SHADER), !!i2 && (t2.shaderSource(i2, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), t2.compileShader(i2), o2 = t2.createProgram(), !!o2 && (t2.attachShader(o2, r2), t2.attachShader(o2, i2), t2.linkProgram(o2), t2.useProgram(o2), t2.drawArrays(t2.POINTS, 0, 1), t2.getError() === t2.NO_ERROR))); } finally { t2.disable(t2.BLEND), o2 && t2.deleteProgram(o2), r2 && t2.deleteShader(r2), i2 && t2.deleteShader(i2), n2 && (t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(n2)), e2 && (t2.bindTexture(t2.TEXTURE_2D, null), t2.deleteTexture(e2)); } } beginTimer() { if (2 === this.version && this.disjointTimerQueryWebgl2Extension) { const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension, n2 = t2.createQuery(); return t2.beginQuery(e2.TIME_ELAPSED_EXT, n2), n2; } throw new Error("WebGL1 profiling currently not supported."); } endTimer() { if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported"); { const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension; t2.endQuery(e2.TIME_ELAPSED_EXT); } } isTimerResultAvailable(t2) { let e2 = false, n2 = false; if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported"); { const r2 = this.gl, i2 = this.disjointTimerQueryWebgl2Extension; e2 = r2.getQueryParameter(t2, r2.QUERY_RESULT_AVAILABLE), n2 = r2.getParameter(i2.GPU_DISJOINT_EXT); } return e2 && !n2; } getTimerResult(t2) { let e2 = 0; if (2 !== this.version) throw new Error("WebGL1 profiling currently not supported"); { const n2 = this.gl; e2 = n2.getQueryParameter(t2, n2.QUERY_RESULT), n2.deleteQuery(t2); } return e2 / 1e6; } async waitForQueryAndGetTime(t2) { return await (0, u.repeatedTry)((() => this.isTimerResultAvailable(t2))), this.getTimerResult(t2); } async createAndWaitForFence() { const t2 = this.createFence(this.gl); return this.pollFence(t2); } createFence(t2) { let e2; const n2 = t2, r2 = n2.fenceSync(n2.SYNC_GPU_COMMANDS_COMPLETE, 0); return t2.flush(), e2 = null === r2 ? () => true : () => { const t3 = n2.clientWaitSync(r2, 0, 0); return t3 === n2.ALREADY_SIGNALED || t3 === n2.CONDITION_SATISFIED; }, { query: r2, isFencePassed: e2 }; } async pollFence(t2) { return new Promise(((e2) => { this.addItemToPoll((() => t2.isFencePassed()), (() => e2())); })); } pollItems() { const t2 = c(this.itemsToPoll.map(((t3) => t3.isDoneFn))); for (let e2 = 0; e2 <= t2; ++e2) { const { resolveFn: t3 } = this.itemsToPoll[e2]; t3(); } this.itemsToPoll = this.itemsToPoll.slice(t2 + 1); } async addItemToPoll(t2, e2) { this.itemsToPoll.push({ isDoneFn: t2, resolveFn: e2 }), this.itemsToPoll.length > 1 || await (0, u.repeatedTry)((() => (this.pollItems(), 0 === this.itemsToPoll.length))); } }; }, 1036: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.ExecutionPlan = void 0; const r = n(6231); class i { constructor(t2, e2) { this.op = t2, this.node = e2; } } e.ExecutionPlan = class { constructor(t2, e2, n2) { this.graph = t2, this.profiler = n2, this.initialize(e2); } initialize(t2) { this.profiler.event("session", "ExecutionPlan.initialize", (() => { const e2 = this.graph.getNodes(); if (e2.length !== t2.length) throw new Error("The size of nodes and OPs do not match."); this._ops = t2.map(((t3, n2) => new i(t3, e2[n2]))), this.reset(), this._starter = [], this._ops.forEach(((t3, e3) => { let n2 = true; for (const e4 of t3.node.inputs) if (!this._values[e4] && -1 === this.graph.getInputIndices().indexOf(e4)) { n2 = false; break; } n2 && this._starter.push(e3); })); })); } reset() { this._values = this.graph.getValues().map(((t2) => t2.tensor)); } async execute(t2, e2) { return this.profiler.event("session", "ExecutionPlan.execute", (async () => { this.reset(); const n2 = t2.createInferenceHandler(), i2 = this.graph.getInputIndices(); if (e2.length !== i2.length) throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e2.length} expected: ${i2.length}`); e2.forEach(((t3, e3) => { const n3 = i2[e3]; this._values[n3] = t3; })); const o = this._starter.slice(0), a = this.graph.getValues(), s = this.graph.getNodes(); let u = 0; for (; u < o.length; ) { const t3 = o[u++], e3 = this._ops[t3], i3 = e3.node.inputs.map(((t4) => this._values[t4])); if (-1 !== i3.indexOf(void 0)) throw new Error(`unresolved input detected: op: ${e3.node}`); const c2 = i3; r.Logger.verbose("ExecPlan", `Runing op:${e3.node.name} (${c2.map(((t4, n3) => `'${e3.node.inputs[n3]}': ${t4.type}[${t4.dims.join(",")}]`)).join(", ")})`); const l = await this.profiler.event("node", e3.node.name, (async () => e3.op.impl(n2, c2, e3.op.context))); if (l.length !== e3.node.outputs.length) throw new Error("the size of output does not match model definition."); l.forEach(((t4, n3) => { const r2 = e3.node.outputs[n3]; if (this._values[r2]) throw new Error(`output [${r2}] already has value: op:${e3.node.name}`); this._values[r2] = t4; })); const p = /* @__PURE__ */ new Set(); l.forEach(((t4, n3) => { const r2 = e3.node.outputs[n3]; for (const t5 of a[r2].to) { const e4 = s[t5]; let n4 = true; for (const t6 of e4.inputs) if (!this._values[t6]) { n4 = false; break; } n4 && p.add(t5); } })), o.push(...p); } const c = []; for (let t3 = 0; t3 < this.graph.getOutputIndices().length; t3++) { const e3 = this.graph.getOutputIndices()[t3], n3 = this._values[e3]; if (void 0 === n3) throw new Error(`required output [${e3}] does not have value`); 0 === e3 ? await n3.getData() : n3.data, c.push(n3); } return r.Logger.verbose("ExecPlan", "disposing of inferenceHandler"), n2.dispose(), c; })); } }; }, 7070: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.Graph = void 0; const r = n(1446), i = n(7778), o = n(9395), a = n(9162), s = n(2517); var u = o.onnxruntime.experimental.fbs; e.Graph = { from: (t2, e2) => new p(t2, e2) }; class c { constructor(t2) { this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, t2 && (this.type = s.ProtoUtil.tensorValueTypeFromProto(t2.type.tensorType)); } get from() { return this._from; } get to() { return this._to; } } class l { constructor(t2, e2) { t2 instanceof r.onnx.NodeProto ? (this.name = t2.name, this.opType = t2.opType, this.attributes = new i.Attribute(t2.attribute)) : t2 instanceof u.Node && (this.name = null != e2 ? e2 : t2.name(), this.opType = t2.opType(), this.attributes = new i.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t2))), this.inputs = [], this.outputs = [], this.executeNode = true; } } class p { constructor(t2, e2) { if (!t2) throw new TypeError("graph is empty"); this.buildGraph(t2), this.transformGraph(e2), this.checkIsAcyclic(); } getInputIndices() { return this._allInputIndices; } getInputNames() { return this._allInputNames; } getOutputIndices() { return this._allOutputIndices; } getOutputNames() { return this._allOutputNames; } getValues() { return this._allData; } getNodes() { return this._nodes; } buildGraph(t2) { if (t2 instanceof r.onnx.GraphProto) this.buildGraphFromOnnxFormat(t2); else { if (!(t2 instanceof u.Graph)) throw new TypeError("Graph type is not supported."); this.buildGraphFromOrtFormat(t2); } } buildGraphFromOnnxFormat(t2) { const e2 = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; const n2 = /* @__PURE__ */ new Map(); if (!t2.input) throw new Error("missing information in graph: input"); const r2 = []; for (const n3 of t2.input) { if (e2.has(n3.name)) throw new Error(`duplicated input name: ${n3.name}`); const t3 = this._allData.push(new c(n3)) - 1; e2.set(n3.name, t3), r2.push(n3.name); } if (!t2.initializer) throw new Error("missing information in graph: initializer"); for (const n3 of t2.initializer) { let t3 = e2.get(n3.name); if (void 0 === t3) { const r3 = new c(); r3.type = { shape: { dims: s.ProtoUtil.tensorDimsFromProto(n3.dims) }, tensorType: s.ProtoUtil.tensorDataTypeFromProto(n3.dataType) }, t3 = this._allData.push(r3) - 1, e2.set(n3.name, t3); } this._allData[t3]._from = -1, this._allData[t3].tensor = a.Tensor.fromProto(n3); } for (let t3 = 0; t3 < this._allData.length; t3++) this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(r2[t3])); if (!t2.output) throw new Error("missing information in graph: output"); for (const n3 of t2.output) { if (e2.has(n3.name)) throw new Error(`duplicated output name: ${n3.name}`); const t3 = this._allData.push(new c(n3)) - 1; e2.set(n3.name, t3), this._allOutputIndices.push(t3), this._allOutputNames.push(n3.name); } if (!t2.node) throw new Error("missing information in graph: node"); for (const e3 of t2.node) { if (!e3.name) for (let t4 = 0; ; t4++) { const r3 = `unnamed_${e3.opType}_${t4}`; if (!n2.has(r3)) { e3.name = r3; break; } } if (n2.has(e3.name)) throw new Error(`duplicated node name: ${e3.name}`); const t3 = this._nodes.push(new l(e3)) - 1; n2.set(e3.name, t3); } for (let n3 = 0; n3 < this._nodes.length; n3++) { const r3 = this._nodes[n3], i2 = t2.node[n3]; if (!i2.output) throw new Error(`missing output for node: ${i2.name}`); for (const t3 of i2.output) { let o2 = e2.get(t3); if (void 0 === o2 && (o2 = this._allData.push(new c()) - 1, e2.set(t3, o2)), r3.outputs.push(o2), void 0 !== this._allData[o2]._from) throw new Error(`multiple nodes output to one data value: ${o2}`); if (this._allData[o2]._from = n3, "Constant" === i2.opType) { if (!i2.attribute || 1 !== i2.attribute.length || !i2.attribute[0].t) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (!i2.output || 1 !== i2.output.length) throw new Error("missing output or incorrect number of outputs for this Constant operator"); r3.outputs.pop(), r3.executeNode = false, this._allData[o2]._from = -1, this._allData[o2].tensor = a.Tensor.fromProto(i2.attribute[0].t); } } } for (let n3 = 0; n3 < this._nodes.length; n3++) { const r3 = this._nodes[n3], i2 = t2.node[n3]; if (!i2.input) throw new Error(`missing input for node: ${i2.name}`); for (const t3 of i2.input) { const o2 = e2.get(t3); if (void 0 === o2) { if ("" === t3 && 3 === i2.input.length && "Resize" === i2.opType) continue; throw new Error(`unrecognized input '${t3}' for node: ${i2.name}`); } r3.inputs.push(o2), this._allData[o2]._to.push(n3); } } return true; } buildGraphFromOrtFormat(t2) { var e2, n2, r2; const i2 = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; const o2 = /* @__PURE__ */ new Map(), p2 = []; for (let o3 = 0; o3 < t2.inputsLength(); o3++) { const a2 = t2.inputs(o3); if (i2.has(a2)) throw new Error(`duplicated input name: ${a2}`); for (let o4 = 0; o4 < t2.nodeArgsLength(); o4++) if ((null === (e2 = t2.nodeArgs(o4)) || void 0 === e2 ? void 0 : e2.name()) === a2) { const e3 = new c(); if ((null === (r2 = null === (n2 = t2.nodeArgs(o4)) || void 0 === n2 ? void 0 : n2.type()) || void 0 === r2 ? void 0 : r2.valueType()) !== u.TypeInfoValue.tensor_type) throw new Error("Unexpected value type for the nodeArg."); const l2 = t2.nodeArgs(o4).type().value(new u.TensorTypeAndShape()), f = s.ProtoUtil.tensorDataTypeFromProto(l2.elemType()), d = l2.shape(), h = []; for (let t3 = 0; t3 < d.dimLength(); t3++) h.push(s.LongUtil.longToNumber(d.dim(t3).value().dimValue())); e3.type = { shape: { dims: h }, tensorType: f }; const g = this._allData.push(e3) - 1; i2.set(a2, g), p2.push(a2); } } for (let e3 = 0; e3 < t2.initializersLength(); e3++) { const n3 = t2.initializers(e3); let r3 = i2.get(n3.name()); if (void 0 === r3) { const t3 = new c(), e4 = s.ProtoUtil.tensorDimsFromORTFormat(n3), o3 = s.ProtoUtil.tensorDataTypeFromProto(n3.dataType()); t3.type = { shape: { dims: e4 }, tensorType: o3 }, r3 = this._allData.push(t3) - 1, i2.set(n3.name(), r3); } this._allData[r3]._from = -1, this._allData[r3].tensor = a.Tensor.fromOrtTensor(n3); } for (let t3 = 0; t3 < this._allData.length; t3++) this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(p2[t3])); for (let e3 = 0; e3 < t2.outputsLength(); e3++) { const n3 = t2.outputs(e3); if (i2.has(n3)) throw new Error(`duplicated output name: ${n3}`); const r3 = this._allData.push(new c()) - 1; i2.set(n3, r3), this._allOutputIndices.push(r3), this._allOutputNames.push(n3); } if (!t2.nodes) throw new Error("missing information in graph: node"); for (let e3 = 0; e3 < t2.nodesLength(); e3++) { const n3 = t2.nodes(e3); let r3 = n3.name(); if (!r3) for (let t3 = 0; r3 = `unnamed_${n3.opType()}_${t3}`, o2.has(r3); t3++) ; if (o2.has(r3)) throw new Error(`duplicated node name: ${r3}`); const i3 = this._nodes.push(new l(n3, r3)) - 1; o2.set(r3, i3); } for (let e3 = 0; e3 < this._nodes.length; e3++) { const n3 = this._nodes[e3], r3 = t2.nodes(e3); if (null == r3) throw new Error(`No node exists at index ${e3}`); if (0 === (null == r3 ? void 0 : r3.outputsLength())) throw new Error(`missing output for node: ${r3.name}`); for (let t3 = 0; t3 < (null == r3 ? void 0 : r3.outputsLength()); t3++) { const o3 = null == r3 ? void 0 : r3.outputs(t3); let s2 = i2.get(o3); if (void 0 === s2 && (s2 = this._allData.push(new c()) - 1, i2.set(o3, s2)), n3.outputs.push(s2), void 0 !== this._allData[s2]._from) throw new Error(`multiple nodes output to one data value: ${s2}`); if (this._allData[s2]._from = e3, "Constant" === r3.opType()) { if (1 !== r3.attributesLength() || !r3.attributes(0).t()) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (1 !== r3.outputsLength()) throw new Error("missing output or incorrect number of outputs for this Constant operator"); n3.outputs.pop(), n3.executeNode = false, this._allData[s2]._from = -1, this._allData[s2].tensor = a.Tensor.fromOrtTensor(r3.attributes(0).t()); } } } for (let e3 = 0; e3 < this._nodes.length; e3++) { const n3 = this._nodes[e3], r3 = t2.nodes(e3); if (0 === r3.inputsLength()) throw new Error(`missing input for node: ${r3.name}`); for (let t3 = 0; t3 < r3.inputsLength(); t3++) { const o3 = r3.inputs(t3), a2 = i2.get(o3); if (void 0 === a2) throw new Error(`unrecognized input '${o3}' for node: ${r3.name()}`); n3.inputs.push(a2), this._allData[a2]._to.push(e3); } } } checkIsAcyclic() { const t2 = /* @__PURE__ */ new Set(); this._allInputIndices.forEach(((e3) => { this._allData[e3]._to.forEach(((e4) => { t2.add(e4); })); })); const e2 = Array.from(t2), n2 = new Array(this._nodes.length).fill("white"); for (; e2.length > 0; ) { const t3 = e2.pop(); "gray" === n2[t3] ? n2[t3] = "black" : (e2.push(t3), n2[t3] = "gray", this._nodes[t3].outputs.forEach(((r2) => { const i2 = this._allData[r2]; if (void 0 !== i2.tensor) throw new Error("node outputs should not be initialized"); if (i2._from !== t3) throw new Error("from property of the Value object doesn't match index of Node being processed"); i2._to.forEach(((t4) => { if ("gray" === n2[t4]) throw new Error("model graph is cyclic"); "white" === n2[t4] && e2.push(t4); })); }))); } } transformGraph(t2) { this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), t2 && t2.transformGraph(this), this.finalizeGraph(); } finalizeGraph() { let t2 = 0; for (let e2 = 0; e2 < this._nodes.length; e2++) this._nodes[e2].executeNode ? t2 > 0 && (this._nodes[e2].inputs.forEach(((n2) => { const r2 = this._allData[n2]._to.indexOf(e2 + t2); -1 !== r2 && (this._allData[n2]._to[r2] = e2); })), this._nodes[e2].outputs.forEach(((n2) => { this._allData[n2]._from && this._allData[n2]._from === e2 + t2 && (this._allData[n2]._from = e2); }))) : (t2++, this._nodes[e2].outputs.forEach(((t3) => { this._allData[t3]._from = -2; })), this._nodes.splice(e2, 1), e2--); t2 = 0; for (let e2 = 0; e2 < this._allData.length; e2++) if (-2 !== this._allData[e2].from || -1 !== this._allOutputIndices.indexOf(e2 + t2)) { if (t2 > 0) { let n2 = -1; void 0 !== this._allData[e2].from && -1 !== this._allData[e2].from ? (n2 = this._nodes[this._allData[e2].from].outputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[this._allData[e2].from].outputs[n2] = e2)) : (n2 = this._allInputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allInputIndices[n2] = e2)), this._allData[e2].to.forEach(((r2) => { n2 = this._nodes[r2].inputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[r2].inputs[n2] = e2); })), 0 === this._allData[e2].to.length && (n2 = this._allOutputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allOutputIndices[n2] = e2)); } } else t2++, this._allData.splice(e2, 1), e2--; } deleteNode(t2) { const e2 = this._nodes[t2]; if (e2.outputs.length > 1) { for (let t3 = 1; t3 < e2.outputs.length; t3++) if (this._allData[e2.outputs[t3]].to.length > 0) throw new Error("Node deletion with more than one output connected to other nodes is not supported. "); } e2.executeNode = false; const n2 = e2.inputs[0], r2 = e2.outputs[0], i2 = this._allData[r2].to, o2 = this._allData[n2].to.indexOf(t2); if (-1 === o2) throw new Error("The Value object doesn't have the current Node in it's 'to' property "); this._allData[n2].to.splice(o2, 1), this._allData[r2]._to = []; const a2 = this._allOutputIndices.indexOf(r2); if (-1 !== a2 && (this._allOutputIndices[a2] = n2), i2 && i2.length > 0) for (const t3 of i2) { const e3 = this._nodes[t3].inputs.indexOf(r2); if (-1 === e3) throw new Error("The Node object doesn't have the output Value in it's 'inputs' property "); this._nodes[t3].inputs[e3] = n2, this._allData[n2].to.push(t3); } } removeAllDropoutNodes() { let t2 = 0; for (const e2 of this._nodes) { if ("Dropout" === e2.opType) { if (1 !== e2.inputs.length) throw new Error("Dropout nodes should only contain one input. "); if (1 !== e2.outputs.length && 2 !== e2.outputs.length) throw new Error("Dropout nodes should contain either 1 or 2 output(s)"); if (2 === e2.outputs.length && 0 !== this._allData[e2.outputs[1]]._to.length) throw new Error("Dropout nodes's second output should not be referenced by other nodes"); this.deleteNode(t2); } t2++; } } removeAllIdentityNodes() { let t2 = 0; for (const e2 of this._nodes) "Identity" === e2.opType && this.deleteNode(t2), t2++; } isActivation(t2) { switch (t2.opType) { case "Relu": case "Sigmoid": case "Clip": return true; default: return false; } } fuseConvActivationNodes() { for (const t2 of this._nodes) if ("Conv" === t2.opType) { const e2 = this._allData[t2.outputs[0]]._to; if (1 === e2.length && this.isActivation(this._nodes[e2[0]])) { const n2 = this._nodes[e2[0]]; if ("Clip" === n2.opType) if (1 === n2.inputs.length) try { t2.attributes.set("activation_params", "floats", [n2.attributes.getFloat("min"), n2.attributes.getFloat("max")]); } catch (e3) { t2.attributes.set("activation_params", "floats", [s.MIN_CLIP, s.MAX_CLIP]); } else { if (!(n2.inputs.length >= 3 && void 0 !== this._allData[n2.inputs[1]].tensor && void 0 !== this._allData[n2.inputs[2]].tensor)) continue; t2.attributes.set("activation_params", "floats", [this._allData[n2.inputs[1]].tensor.floatData[0], this._allData[n2.inputs[2]].tensor.floatData[0]]); } t2.attributes.set("activation", "string", n2.opType), this.deleteNode(e2[0]); } } } } }, 6231: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.now = e.Profiler = e.Logger = void 0; const n = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, r = { none: new class { log(t2, e2, n2) { } }(), console: new class { log(t2, e2, n2) { console.log(`${this.color(t2)} ${n2 ? "\x1B[35m" + n2 + "\x1B[0m " : ""}${e2}`); } color(t2) { switch (t2) { case "verbose": return "\x1B[34;40mv\x1B[0m"; case "info": return "\x1B[32mi\x1B[0m"; case "warning": return "\x1B[30;43mw\x1B[0m"; case "error": return "\x1B[31;40me\x1B[0m"; case "fatal": return "\x1B[101mf\x1B[0m"; default: throw new Error(`unsupported severity: ${t2}`); } } }() }, i = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false }; let o = { "": i }; function a(t2, e2, n2, r2) { if (void 0 === e2) return i2 = t2, { verbose: a.verbose.bind(null, i2), info: a.info.bind(null, i2), warning: a.warning.bind(null, i2), error: a.error.bind(null, i2), fatal: a.fatal.bind(null, i2) }; if (void 0 === n2) s(t2, e2); else if ("number" == typeof n2 && void 0 === r2) s(t2, e2); else if ("string" == typeof n2 && void 0 === r2) s(t2, n2, 0, e2); else { if ("string" != typeof n2 || "number" != typeof r2) throw new TypeError("input is valid"); s(t2, n2, 0, e2); } var i2; } function s(t2, e2, i2, a2) { const s2 = o[a2 || ""] || o[""]; n[t2] < n[s2.minimalSeverity] || (s2.logDateTime && (e2 = `${(/* @__PURE__ */ new Date()).toISOString()}|${e2}`), s2.logSourceLocation, r[s2.provider].log(t2, e2, a2)); } !(function(t2) { function e2(t3) { o = {}, n2("", t3 || {}); } function n2(t3, n3) { if ("*" === t3) e2(n3); else { const e3 = o[t3] || i; o[t3] = { provider: n3.provider || e3.provider, minimalSeverity: n3.minimalSeverity || e3.minimalSeverity, logDateTime: void 0 === n3.logDateTime ? e3.logDateTime : n3.logDateTime, logSourceLocation: void 0 === n3.logSourceLocation ? e3.logSourceLocation : n3.logSourceLocation }; } } t2.verbose = function(e3, n3) { t2("verbose", e3, n3); }, t2.info = function(e3, n3) { t2("info", e3, n3); }, t2.warning = function(e3, n3) { t2("warning", e3, n3); }, t2.error = function(e3, n3) { t2("error", e3, n3); }, t2.fatal = function(e3, n3) { t2("fatal", e3, n3); }, t2.reset = e2, t2.set = n2, t2.setWithEnv = function(t3) { const e3 = {}; t3.logLevel && (e3.minimalSeverity = t3.logLevel), n2("", e3); }; })(a || (a = {})), e.Logger = a; class u { constructor(t2, e2, n2, r2, i2, o2) { this.category = t2, this.name = e2, this.startTime = n2, this.endCallback = r2, this.timer = i2, this.ctx = o2; } end() { return this.endCallback(this); } async checkTimer() { if (void 0 === this.ctx || void 0 === this.timer) throw new Error("No webgl timer found"); return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer); } } class c { constructor(t2, e2, n2, r2) { this.category = t2, this.name = e2, this.startTime = n2, this.endTime = r2; } } e.Profiler = class { static create(t2) { return void 0 === t2 ? new this() : new this(t2.maxNumberEvents, t2.flushBatchSize, t2.flushIntervalInMilliseconds); } constructor(t2, e2, n2) { this._started = false, this._flushPointer = 0, this._started = false, this._maxNumberEvents = void 0 === t2 ? 1e4 : t2, this._flushBatchSize = void 0 === e2 ? 10 : e2, this._flushIntervalInMilliseconds = void 0 === n2 ? 5e3 : n2; } start() { this._started = true, this._timingEvents = [], this._flushTime = (0, e.now)(), this._flushPointer = 0; } stop() { for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); } event(t2, e2, n2, r2) { const i2 = this._started ? this.begin(t2, e2, r2) : void 0; let o2 = false; const a2 = n2(); if (a2 && "function" == typeof a2.then) return o2 = true, new Promise(((t3, e3) => { a2.then((async (e4) => { i2 && await i2.end(), t3(e4); }), (async (t4) => { i2 && await i2.end(), e3(t4); })); })); if (!o2 && i2) { const t3 = i2.end(); if (t3 && "function" == typeof t3.then) return new Promise(((e3, n3) => { t3.then((() => { e3(a2); }), ((t4) => { n3(t4); })); })); } return a2; } begin(t2, n2, r2) { if (!this._started) throw new Error("profiler is not started yet"); if (void 0 === r2) { const r3 = (0, e.now)(); return this.flush(r3), new u(t2, n2, r3, ((t3) => this.endSync(t3))); } { const e2 = r2.beginTimer(); return new u(t2, n2, 0, (async (t3) => this.end(t3)), e2, r2); } } async end(t2) { const e2 = await t2.checkTimer(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, e2)), this.flush(e2)); } endSync(t2) { const n2 = (0, e.now)(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, n2)), this.flush(n2)); } logOneEvent(t2) { e.Logger.verbose(`Profiler.${t2.category}`, `${(t2.endTime - t2.startTime).toFixed(2)}ms on event '${t2.name}' at ${t2.endTime.toFixed(2)}`); } flush(t2) { if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || t2 - this._flushTime >= this._flushIntervalInMilliseconds) { for (const t3 = this._flushPointer; this._flushPointer < t3 + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); this._flushTime = (0, e.now)(); } } get started() { return this._started; } }, e.now = "undefined" != typeof performance && performance.now ? () => performance.now() : Date.now; }, 2644: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.Model = void 0; const r = n(5686), i = n(1446), o = n(7070), a = n(9395), s = n(2517); var u = a.onnxruntime.experimental.fbs; e.Model = class { constructor() { } load(t2, e2, n2) { if (!n2) try { return void this.loadFromOnnxFormat(t2, e2); } catch (t3) { if (void 0 !== n2) throw t3; } this.loadFromOrtFormat(t2, e2); } loadFromOnnxFormat(t2, e2) { const n2 = i.onnx.ModelProto.decode(t2); if (s.LongUtil.longToNumber(n2.irVersion) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = n2.opsetImport.map(((t3) => ({ domain: t3.domain, version: s.LongUtil.longToNumber(t3.version) }))), this._graph = o.Graph.from(n2.graph, e2); } loadFromOrtFormat(t2, e2) { const n2 = new r.flatbuffers.ByteBuffer(t2), i2 = u.InferenceSession.getRootAsInferenceSession(n2).model(); if (s.LongUtil.longToNumber(i2.irVersion()) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = []; for (let t3 = 0; t3 < i2.opsetImportLength(); t3++) { const e3 = i2.opsetImport(t3); this._opsets.push({ domain: null == e3 ? void 0 : e3.domain(), version: s.LongUtil.longToNumber(e3.version()) }); } this._graph = o.Graph.from(i2.graph(), e2); } get graph() { return this._graph; } get opsets() { return this._opsets; } }; }, 782: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.FLOAT_TYPES = e.INT_TYPES = e.NUMBER_TYPES = void 0, e.NUMBER_TYPES = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"], e.INT_TYPES = ["int32", "int16", "int8", "uint16", "uint32", "uint8"], e.FLOAT_TYPES = ["float32", "float64"]; }, 1047: (t, e) => { "use strict"; function n(t2, e2) { if (e2.endsWith("+")) { const n2 = Number.parseInt(e2.substring(0, e2.length - 1), 10); return !isNaN(n2) && n2 <= t2; } if (2 === e2.split("-").length) { const n2 = e2.split("-"), r = Number.parseInt(n2[0], 10), i = Number.parseInt(n2[1], 10); return !isNaN(r) && !isNaN(i) && r <= t2 && t2 <= i; } return Number.parseInt(e2, 10) === t2; } Object.defineProperty(e, "__esModule", { value: true }), e.resolveOperator = void 0, e.resolveOperator = function(t2, e2, r) { for (const i of r) { const r2 = i[0], o = i[1], a = i[2], s = i[3], u = i[4]; if (t2.opType === r2) { for (const t3 of e2) if ((t3.domain === o || "ai.onnx" === t3.domain && "" === o) && n(t3.version, a)) return { opImpl: s, opInit: u }; } } throw new TypeError(`cannot resolve operator '${t2.opType}' with opsets: ${e2.map(((t3) => `${t3.domain || "ai.onnx"} v${t3.version}`)).join(", ")}`); }; }, 9395: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.onnxruntime = void 0; const r = n(5686); var i, o; i = e.onnxruntime || (e.onnxruntime = {}), (function(t2) { let e2; !(function(t3) { t3[t3.UNDEFINED = 0] = "UNDEFINED", t3[t3.FLOAT = 1] = "FLOAT", t3[t3.INT = 2] = "INT", t3[t3.STRING = 3] = "STRING", t3[t3.TENSOR = 4] = "TENSOR", t3[t3.GRAPH = 5] = "GRAPH", t3[t3.FLOATS = 6] = "FLOATS", t3[t3.INTS = 7] = "INTS", t3[t3.STRINGS = 8] = "STRINGS", t3[t3.TENSORS = 9] = "TENSORS", t3[t3.GRAPHS = 10] = "GRAPHS", t3[t3.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", t3[t3.SPARSE_TENSORS = 12] = "SPARSE_TENSORS"; })(e2 = t2.AttributeType || (t2.AttributeType = {})); })((o = i.experimental || (i.experimental = {})).fbs || (o.fbs = {})), (function(t2) { !(function(t3) { !(function(t4) { let e2; !(function(t5) { t5[t5.UNKNOWN = 0] = "UNKNOWN", t5[t5.VALUE = 1] = "VALUE", t5[t5.PARAM = 2] = "PARAM"; })(e2 = t4.DimensionValueType || (t4.DimensionValueType = {})); })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { !(function(t4) { let e2; !(function(t5) { t5[t5.UNDEFINED = 0] = "UNDEFINED", t5[t5.FLOAT = 1] = "FLOAT", t5[t5.UINT8 = 2] = "UINT8", t5[t5.INT8 = 3] = "INT8", t5[t5.UINT16 = 4] = "UINT16", t5[t5.INT16 = 5] = "INT16", t5[t5.INT32 = 6] = "INT32", t5[t5.INT64 = 7] = "INT64", t5[t5.STRING = 8] = "STRING", t5[t5.BOOL = 9] = "BOOL", t5[t5.FLOAT16 = 10] = "FLOAT16", t5[t5.DOUBLE = 11] = "DOUBLE", t5[t5.UINT32 = 12] = "UINT32", t5[t5.UINT64 = 13] = "UINT64", t5[t5.COMPLEX64 = 14] = "COMPLEX64", t5[t5.COMPLEX128 = 15] = "COMPLEX128", t5[t5.BFLOAT16 = 16] = "BFLOAT16"; })(e2 = t4.TensorDataType || (t4.TensorDataType = {})); })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { !(function(t4) { let e2; !(function(t5) { t5[t5.Primitive = 0] = "Primitive", t5[t5.Fused = 1] = "Fused"; })(e2 = t4.NodeType || (t4.NodeType = {})); })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { !(function(t4) { let e2; !(function(t5) { t5[t5.NONE = 0] = "NONE", t5[t5.tensor_type = 1] = "tensor_type", t5[t5.sequence_type = 2] = "sequence_type", t5[t5.map_type = 3] = "map_type"; })(e2 = t4.TypeInfoValue || (t4.TypeInfoValue = {})); })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsShape(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsShape(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } dim(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 4); return r2 ? (n3 || new t2.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } dimLength() { let t3 = this.bb.__offset(this.bb_pos, 4); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startShape(t3) { t3.startObject(1); } static addDim(t3, e4) { t3.addFieldOffset(0, e4, 0); } static createDimVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startDimVector(t3, e4) { t3.startVector(4, e4, 4); } static endShape(t3) { return t3.endObject(); } static createShape(t3, e4) { return n2.startShape(t3), n2.addDim(t3, e4), n2.endShape(t3); } } e3.Shape = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsDimension(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsDimension(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } value(e4) { let n3 = this.bb.__offset(this.bb_pos, 4); return n3 ? (e4 || new t2.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } denotation(t3) { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } static startDimension(t3) { t3.startObject(2); } static addValue(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addDenotation(t3, e4) { t3.addFieldOffset(1, e4, 0); } static endDimension(t3) { return t3.endObject(); } static createDimension(t3, e4, r2) { return n2.startDimension(t3), n2.addValue(t3, e4), n2.addDenotation(t3, r2), n2.endDimension(t3); } } e3.Dimension = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsDimensionValue(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsDimensionValue(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } dimType() { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.readInt8(this.bb_pos + e4) : t2.experimental.fbs.DimensionValueType.UNKNOWN; } dimValue() { let t3 = this.bb.__offset(this.bb_pos, 6); return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); } dimParam(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } static startDimensionValue(t3) { t3.startObject(3); } static addDimType(e4, n3) { e4.addFieldInt8(0, n3, t2.experimental.fbs.DimensionValueType.UNKNOWN); } static addDimValue(t3, e4) { t3.addFieldInt64(1, e4, t3.createLong(0, 0)); } static addDimParam(t3, e4) { t3.addFieldOffset(2, e4, 0); } static endDimensionValue(t3) { return t3.endObject(); } static createDimensionValue(t3, e4, r2, i2) { return n2.startDimensionValue(t3), n2.addDimType(t3, e4), n2.addDimValue(t3, r2), n2.addDimParam(t3, i2), n2.endDimensionValue(t3); } } e3.DimensionValue = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsTensorTypeAndShape(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsTensorTypeAndShape(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } elemType() { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; } shape(e4) { let n3 = this.bb.__offset(this.bb_pos, 6); return n3 ? (e4 || new t2.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startTensorTypeAndShape(t3) { t3.startObject(2); } static addElemType(e4, n3) { e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); } static addShape(t3, e4) { t3.addFieldOffset(1, e4, 0); } static endTensorTypeAndShape(t3) { return t3.endObject(); } static createTensorTypeAndShape(t3, e4, r2) { return n2.startTensorTypeAndShape(t3), n2.addElemType(t3, e4), n2.addShape(t3, r2), n2.endTensorTypeAndShape(t3); } } e3.TensorTypeAndShape = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsMapType(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsMapType(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } keyType() { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; } valueType(e4) { let n3 = this.bb.__offset(this.bb_pos, 6); return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startMapType(t3) { t3.startObject(2); } static addKeyType(e4, n3) { e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); } static addValueType(t3, e4) { t3.addFieldOffset(1, e4, 0); } static endMapType(t3) { return t3.endObject(); } static createMapType(t3, e4, r2) { return n2.startMapType(t3), n2.addKeyType(t3, e4), n2.addValueType(t3, r2), n2.endMapType(t3); } } e3.MapType = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsSequenceType(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsSequenceType(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } elemType(e4) { let n3 = this.bb.__offset(this.bb_pos, 4); return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startSequenceType(t3) { t3.startObject(1); } static addElemType(t3, e4) { t3.addFieldOffset(0, e4, 0); } static endSequenceType(t3) { return t3.endObject(); } static createSequenceType(t3, e4) { return n2.startSequenceType(t3), n2.addElemType(t3, e4), n2.endSequenceType(t3); } } e3.SequenceType = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { (t3.fbs || (t3.fbs = {})).EdgeEnd = class { constructor() { this.bb = null, this.bb_pos = 0; } __init(t4, e2) { return this.bb_pos = t4, this.bb = e2, this; } nodeIndex() { return this.bb.readUint32(this.bb_pos); } srcArgIndex() { return this.bb.readInt32(this.bb_pos + 4); } dstArgIndex() { return this.bb.readInt32(this.bb_pos + 8); } static createEdgeEnd(t4, e2, n2, r2) { return t4.prep(4, 12), t4.writeInt32(r2), t4.writeInt32(n2), t4.writeInt32(e2), t4.offset(); } }; })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsNodeEdge(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsNodeEdge(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } nodeIndex() { let t3 = this.bb.__offset(this.bb_pos, 4); return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; } inputEdges(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 6); return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null; } inputEdgesLength() { let t3 = this.bb.__offset(this.bb_pos, 6); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } outputEdges(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 8); return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null; } outputEdgesLength() { let t3 = this.bb.__offset(this.bb_pos, 8); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startNodeEdge(t3) { t3.startObject(3); } static addNodeIndex(t3, e4) { t3.addFieldInt32(0, e4, 0); } static addInputEdges(t3, e4) { t3.addFieldOffset(1, e4, 0); } static startInputEdgesVector(t3, e4) { t3.startVector(12, e4, 4); } static addOutputEdges(t3, e4) { t3.addFieldOffset(2, e4, 0); } static startOutputEdgesVector(t3, e4) { t3.startVector(12, e4, 4); } static endNodeEdge(t3) { return t3.endObject(); } static createNodeEdge(t3, e4, r2, i2) { return n2.startNodeEdge(t3), n2.addNodeIndex(t3, e4), n2.addInputEdges(t3, r2), n2.addOutputEdges(t3, i2), n2.endNodeEdge(t3); } } e3.NodeEdge = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsNode(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsNode(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } name(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } docString(t3) { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } domain(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } sinceVersion() { let t3 = this.bb.__offset(this.bb_pos, 10); return t3 ? this.bb.readInt32(this.bb_pos + t3) : 0; } index() { let t3 = this.bb.__offset(this.bb_pos, 12); return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; } opType(t3) { let e4 = this.bb.__offset(this.bb_pos, 14); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } type() { let e4 = this.bb.__offset(this.bb_pos, 16); return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.NodeType.Primitive; } executionProviderType(t3) { let e4 = this.bb.__offset(this.bb_pos, 18); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } inputs(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 20); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } inputsLength() { let t3 = this.bb.__offset(this.bb_pos, 20); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } outputs(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 22); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } outputsLength() { let t3 = this.bb.__offset(this.bb_pos, 22); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } attributes(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 24); return r2 ? (n3 || new t2.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } attributesLength() { let t3 = this.bb.__offset(this.bb_pos, 24); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } inputArgCounts(t3) { let e4 = this.bb.__offset(this.bb_pos, 26); return e4 ? this.bb.readInt32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0; } inputArgCountsLength() { let t3 = this.bb.__offset(this.bb_pos, 26); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } inputArgCountsArray() { let t3 = this.bb.__offset(this.bb_pos, 26); return t3 ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; } implicitInputs(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 28); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } implicitInputsLength() { let t3 = this.bb.__offset(this.bb_pos, 28); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startNode(t3) { t3.startObject(13); } static addName(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addDocString(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addDomain(t3, e4) { t3.addFieldOffset(2, e4, 0); } static addSinceVersion(t3, e4) { t3.addFieldInt32(3, e4, 0); } static addIndex(t3, e4) { t3.addFieldInt32(4, e4, 0); } static addOpType(t3, e4) { t3.addFieldOffset(5, e4, 0); } static addType(e4, n3) { e4.addFieldInt32(6, n3, t2.experimental.fbs.NodeType.Primitive); } static addExecutionProviderType(t3, e4) { t3.addFieldOffset(7, e4, 0); } static addInputs(t3, e4) { t3.addFieldOffset(8, e4, 0); } static createInputsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startInputsVector(t3, e4) { t3.startVector(4, e4, 4); } static addOutputs(t3, e4) { t3.addFieldOffset(9, e4, 0); } static createOutputsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startOutputsVector(t3, e4) { t3.startVector(4, e4, 4); } static addAttributes(t3, e4) { t3.addFieldOffset(10, e4, 0); } static createAttributesVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startAttributesVector(t3, e4) { t3.startVector(4, e4, 4); } static addInputArgCounts(t3, e4) { t3.addFieldOffset(11, e4, 0); } static createInputArgCountsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt32(e4[n3]); return t3.endVector(); } static startInputArgCountsVector(t3, e4) { t3.startVector(4, e4, 4); } static addImplicitInputs(t3, e4) { t3.addFieldOffset(12, e4, 0); } static createImplicitInputsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startImplicitInputsVector(t3, e4) { t3.startVector(4, e4, 4); } static endNode(t3) { return t3.endObject(); } static createNode(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) { return n2.startNode(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDomain(t3, i2), n2.addSinceVersion(t3, o2), n2.addIndex(t3, a), n2.addOpType(t3, s), n2.addType(t3, u), n2.addExecutionProviderType(t3, c), n2.addInputs(t3, l), n2.addOutputs(t3, p), n2.addAttributes(t3, f), n2.addInputArgCounts(t3, d), n2.addImplicitInputs(t3, h), n2.endNode(t3); } } e3.Node = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsValueInfo(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsValueInfo(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } name(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } docString(t3) { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } type(e4) { let n3 = this.bb.__offset(this.bb_pos, 8); return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startValueInfo(t3) { t3.startObject(3); } static addName(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addDocString(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addType(t3, e4) { t3.addFieldOffset(2, e4, 0); } static endValueInfo(t3) { return t3.endObject(); } static createValueInfo(t3, e4, r2, i2) { return n2.startValueInfo(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.endValueInfo(t3); } } e3.ValueInfo = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsTypeInfo(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsTypeInfo(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } denotation(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } valueType() { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.readUint8(this.bb_pos + e4) : t2.experimental.fbs.TypeInfoValue.NONE; } value(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.__union(t3, this.bb_pos + e4) : null; } static startTypeInfo(t3) { t3.startObject(3); } static addDenotation(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addValueType(e4, n3) { e4.addFieldInt8(1, n3, t2.experimental.fbs.TypeInfoValue.NONE); } static addValue(t3, e4) { t3.addFieldOffset(2, e4, 0); } static endTypeInfo(t3) { return t3.endObject(); } static createTypeInfo(t3, e4, r2, i2) { return n2.startTypeInfo(t3), n2.addDenotation(t3, e4), n2.addValueType(t3, r2), n2.addValue(t3, i2), n2.endTypeInfo(t3); } } e3.TypeInfo = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { !(function(t4) { class e2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t5, e3) { return this.bb_pos = t5, this.bb = e3, this; } static getRootAsOperatorSetId(t5, n2) { return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); } static getSizePrefixedRootAsOperatorSetId(t5, n2) { return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); } domain(t5) { let e3 = this.bb.__offset(this.bb_pos, 4); return e3 ? this.bb.__string(this.bb_pos + e3, t5) : null; } version() { let t5 = this.bb.__offset(this.bb_pos, 6); return t5 ? this.bb.readInt64(this.bb_pos + t5) : this.bb.createLong(0, 0); } static startOperatorSetId(t5) { t5.startObject(2); } static addDomain(t5, e3) { t5.addFieldOffset(0, e3, 0); } static addVersion(t5, e3) { t5.addFieldInt64(1, e3, t5.createLong(0, 0)); } static endOperatorSetId(t5) { return t5.endObject(); } static createOperatorSetId(t5, n2, r2) { return e2.startOperatorSetId(t5), e2.addDomain(t5, n2), e2.addVersion(t5, r2), e2.endOperatorSetId(t5); } } t4.OperatorSetId = e2; })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsTensor(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsTensor(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } name(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } docString(t3) { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } dims(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); } dimsLength() { let t3 = this.bb.__offset(this.bb_pos, 8); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } dataType() { let e4 = this.bb.__offset(this.bb_pos, 10); return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED; } rawData(t3) { let e4 = this.bb.__offset(this.bb_pos, 12); return e4 ? this.bb.readUint8(this.bb.__vector(this.bb_pos + e4) + t3) : 0; } rawDataLength() { let t3 = this.bb.__offset(this.bb_pos, 12); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } rawDataArray() { let t3 = this.bb.__offset(this.bb_pos, 12); return t3 ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; } stringData(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 14); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } stringDataLength() { let t3 = this.bb.__offset(this.bb_pos, 14); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startTensor(t3) { t3.startObject(6); } static addName(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addDocString(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addDims(t3, e4) { t3.addFieldOffset(2, e4, 0); } static createDimsVector(t3, e4) { t3.startVector(8, e4.length, 8); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]); return t3.endVector(); } static startDimsVector(t3, e4) { t3.startVector(8, e4, 8); } static addDataType(e4, n3) { e4.addFieldInt32(3, n3, t2.experimental.fbs.TensorDataType.UNDEFINED); } static addRawData(t3, e4) { t3.addFieldOffset(4, e4, 0); } static createRawDataVector(t3, e4) { t3.startVector(1, e4.length, 1); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt8(e4[n3]); return t3.endVector(); } static startRawDataVector(t3, e4) { t3.startVector(1, e4, 1); } static addStringData(t3, e4) { t3.addFieldOffset(5, e4, 0); } static createStringDataVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startStringDataVector(t3, e4) { t3.startVector(4, e4, 4); } static endTensor(t3) { return t3.endObject(); } static createTensor(t3, e4, r2, i2, o2, a, s) { return n2.startTensor(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDims(t3, i2), n2.addDataType(t3, o2), n2.addRawData(t3, a), n2.addStringData(t3, s), n2.endTensor(t3); } } e3.Tensor = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsSparseTensor(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsSparseTensor(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } values(e4) { let n3 = this.bb.__offset(this.bb_pos, 4); return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } indices(e4) { let n3 = this.bb.__offset(this.bb_pos, 6); return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } dims(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); } dimsLength() { let t3 = this.bb.__offset(this.bb_pos, 8); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startSparseTensor(t3) { t3.startObject(3); } static addValues(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addIndices(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addDims(t3, e4) { t3.addFieldOffset(2, e4, 0); } static createDimsVector(t3, e4) { t3.startVector(8, e4.length, 8); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]); return t3.endVector(); } static startDimsVector(t3, e4) { t3.startVector(8, e4, 8); } static endSparseTensor(t3) { return t3.endObject(); } static createSparseTensor(t3, e4, r2, i2) { return n2.startSparseTensor(t3), n2.addValues(t3, e4), n2.addIndices(t3, r2), n2.addDims(t3, i2), n2.endSparseTensor(t3); } } e3.SparseTensor = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsAttribute(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsAttribute(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } name(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } docString(t3) { let e4 = this.bb.__offset(this.bb_pos, 6); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } type() { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.AttributeType.UNDEFINED; } f() { let t3 = this.bb.__offset(this.bb_pos, 10); return t3 ? this.bb.readFloat32(this.bb_pos + t3) : 0; } i() { let t3 = this.bb.__offset(this.bb_pos, 12); return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); } s(t3) { let e4 = this.bb.__offset(this.bb_pos, 14); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } t(e4) { let n3 = this.bb.__offset(this.bb_pos, 16); return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } g(e4) { let n3 = this.bb.__offset(this.bb_pos, 18); return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } floats(t3) { let e4 = this.bb.__offset(this.bb_pos, 20); return e4 ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0; } floatsLength() { let t3 = this.bb.__offset(this.bb_pos, 20); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } floatsArray() { let t3 = this.bb.__offset(this.bb_pos, 20); return t3 ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null; } ints(t3) { let e4 = this.bb.__offset(this.bb_pos, 22); return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0); } intsLength() { let t3 = this.bb.__offset(this.bb_pos, 22); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } strings(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 24); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } stringsLength() { let t3 = this.bb.__offset(this.bb_pos, 24); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } tensors(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 26); return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } tensorsLength() { let t3 = this.bb.__offset(this.bb_pos, 26); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } graphs(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 28); return r2 ? (n3 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } graphsLength() { let t3 = this.bb.__offset(this.bb_pos, 28); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startAttribute(t3) { t3.startObject(13); } static addName(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addDocString(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addType(e4, n3) { e4.addFieldInt32(2, n3, t2.experimental.fbs.AttributeType.UNDEFINED); } static addF(t3, e4) { t3.addFieldFloat32(3, e4, 0); } static addI(t3, e4) { t3.addFieldInt64(4, e4, t3.createLong(0, 0)); } static addS(t3, e4) { t3.addFieldOffset(5, e4, 0); } static addT(t3, e4) { t3.addFieldOffset(6, e4, 0); } static addG(t3, e4) { t3.addFieldOffset(7, e4, 0); } static addFloats(t3, e4) { t3.addFieldOffset(8, e4, 0); } static createFloatsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addFloat32(e4[n3]); return t3.endVector(); } static startFloatsVector(t3, e4) { t3.startVector(4, e4, 4); } static addInts(t3, e4) { t3.addFieldOffset(9, e4, 0); } static createIntsVector(t3, e4) { t3.startVector(8, e4.length, 8); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]); return t3.endVector(); } static startIntsVector(t3, e4) { t3.startVector(8, e4, 8); } static addStrings(t3, e4) { t3.addFieldOffset(10, e4, 0); } static createStringsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startStringsVector(t3, e4) { t3.startVector(4, e4, 4); } static addTensors(t3, e4) { t3.addFieldOffset(11, e4, 0); } static createTensorsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startTensorsVector(t3, e4) { t3.startVector(4, e4, 4); } static addGraphs(t3, e4) { t3.addFieldOffset(12, e4, 0); } static createGraphsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startGraphsVector(t3, e4) { t3.startVector(4, e4, 4); } static endAttribute(t3) { return t3.endObject(); } static createAttribute(t3, e4, r2, i2, o2, a, s, u, c, l, p, f, d, h) { return n2.startAttribute(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i2), n2.addF(t3, o2), n2.addI(t3, a), n2.addS(t3, s), n2.addT(t3, u), n2.addG(t3, c), n2.addFloats(t3, l), n2.addInts(t3, p), n2.addStrings(t3, f), n2.addTensors(t3, d), n2.addGraphs(t3, h), n2.endAttribute(t3); } } e3.Attribute = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsGraph(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsGraph(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } initializers(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 4); return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } initializersLength() { let t3 = this.bb.__offset(this.bb_pos, 4); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } nodeArgs(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 6); return r2 ? (n3 || new t2.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } nodeArgsLength() { let t3 = this.bb.__offset(this.bb_pos, 6); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } nodes(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 8); return r2 ? (n3 || new t2.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } nodesLength() { let t3 = this.bb.__offset(this.bb_pos, 8); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } maxNodeIndex() { let t3 = this.bb.__offset(this.bb_pos, 10); return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0; } nodeEdges(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 12); return r2 ? (n3 || new t2.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } nodeEdgesLength() { let t3 = this.bb.__offset(this.bb_pos, 12); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } inputs(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 14); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } inputsLength() { let t3 = this.bb.__offset(this.bb_pos, 14); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } outputs(t3, e4) { let n3 = this.bb.__offset(this.bb_pos, 16); return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null; } outputsLength() { let t3 = this.bb.__offset(this.bb_pos, 16); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } sparseInitializers(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 18); return r2 ? (n3 || new t2.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } sparseInitializersLength() { let t3 = this.bb.__offset(this.bb_pos, 18); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startGraph(t3) { t3.startObject(8); } static addInitializers(t3, e4) { t3.addFieldOffset(0, e4, 0); } static createInitializersVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startInitializersVector(t3, e4) { t3.startVector(4, e4, 4); } static addNodeArgs(t3, e4) { t3.addFieldOffset(1, e4, 0); } static createNodeArgsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startNodeArgsVector(t3, e4) { t3.startVector(4, e4, 4); } static addNodes(t3, e4) { t3.addFieldOffset(2, e4, 0); } static createNodesVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startNodesVector(t3, e4) { t3.startVector(4, e4, 4); } static addMaxNodeIndex(t3, e4) { t3.addFieldInt32(3, e4, 0); } static addNodeEdges(t3, e4) { t3.addFieldOffset(4, e4, 0); } static createNodeEdgesVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startNodeEdgesVector(t3, e4) { t3.startVector(4, e4, 4); } static addInputs(t3, e4) { t3.addFieldOffset(5, e4, 0); } static createInputsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startInputsVector(t3, e4) { t3.startVector(4, e4, 4); } static addOutputs(t3, e4) { t3.addFieldOffset(6, e4, 0); } static createOutputsVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startOutputsVector(t3, e4) { t3.startVector(4, e4, 4); } static addSparseInitializers(t3, e4) { t3.addFieldOffset(7, e4, 0); } static createSparseInitializersVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startSparseInitializersVector(t3, e4) { t3.startVector(4, e4, 4); } static endGraph(t3) { return t3.endObject(); } static createGraph(t3, e4, r2, i2, o2, a, s, u, c) { return n2.startGraph(t3), n2.addInitializers(t3, e4), n2.addNodeArgs(t3, r2), n2.addNodes(t3, i2), n2.addMaxNodeIndex(t3, o2), n2.addNodeEdges(t3, a), n2.addInputs(t3, s), n2.addOutputs(t3, u), n2.addSparseInitializers(t3, c), n2.endGraph(t3); } } e3.Graph = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsModel(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsModel(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } irVersion() { let t3 = this.bb.__offset(this.bb_pos, 4); return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); } opsetImport(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 6); return r2 ? (n3 || new t2.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } opsetImportLength() { let t3 = this.bb.__offset(this.bb_pos, 6); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } producerName(t3) { let e4 = this.bb.__offset(this.bb_pos, 8); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } producerVersion(t3) { let e4 = this.bb.__offset(this.bb_pos, 10); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } domain(t3) { let e4 = this.bb.__offset(this.bb_pos, 12); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } modelVersion() { let t3 = this.bb.__offset(this.bb_pos, 14); return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0); } docString(t3) { let e4 = this.bb.__offset(this.bb_pos, 16); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } graph(e4) { let n3 = this.bb.__offset(this.bb_pos, 18); return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } graphDocString(t3) { let e4 = this.bb.__offset(this.bb_pos, 20); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } static startModel(t3) { t3.startObject(9); } static addIrVersion(t3, e4) { t3.addFieldInt64(0, e4, t3.createLong(0, 0)); } static addOpsetImport(t3, e4) { t3.addFieldOffset(1, e4, 0); } static createOpsetImportVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startOpsetImportVector(t3, e4) { t3.startVector(4, e4, 4); } static addProducerName(t3, e4) { t3.addFieldOffset(2, e4, 0); } static addProducerVersion(t3, e4) { t3.addFieldOffset(3, e4, 0); } static addDomain(t3, e4) { t3.addFieldOffset(4, e4, 0); } static addModelVersion(t3, e4) { t3.addFieldInt64(5, e4, t3.createLong(0, 0)); } static addDocString(t3, e4) { t3.addFieldOffset(6, e4, 0); } static addGraph(t3, e4) { t3.addFieldOffset(7, e4, 0); } static addGraphDocString(t3, e4) { t3.addFieldOffset(8, e4, 0); } static endModel(t3) { return t3.endObject(); } static createModel(t3, e4, r2, i2, o2, a, s, u, c, l) { return n2.startModel(t3), n2.addIrVersion(t3, e4), n2.addOpsetImport(t3, r2), n2.addProducerName(t3, i2), n2.addProducerVersion(t3, o2), n2.addDomain(t3, a), n2.addModelVersion(t3, s), n2.addDocString(t3, u), n2.addGraph(t3, c), n2.addGraphDocString(t3, l), n2.endModel(t3); } } e3.Model = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(t3) { !(function(t4) { class e2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t5, e3) { return this.bb_pos = t5, this.bb = e3, this; } static getRootAsKernelCreateInfos(t5, n2) { return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); } static getSizePrefixedRootAsKernelCreateInfos(t5, n2) { return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5); } nodeIndices(t5) { let e3 = this.bb.__offset(this.bb_pos, 4); return e3 ? this.bb.readUint32(this.bb.__vector(this.bb_pos + e3) + 4 * t5) : 0; } nodeIndicesLength() { let t5 = this.bb.__offset(this.bb_pos, 4); return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0; } nodeIndicesArray() { let t5 = this.bb.__offset(this.bb_pos, 4); return t5 ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t5), this.bb.__vector_len(this.bb_pos + t5)) : null; } kernelDefHashes(t5) { let e3 = this.bb.__offset(this.bb_pos, 6); return e3 ? this.bb.readUint64(this.bb.__vector(this.bb_pos + e3) + 8 * t5) : this.bb.createLong(0, 0); } kernelDefHashesLength() { let t5 = this.bb.__offset(this.bb_pos, 6); return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0; } static startKernelCreateInfos(t5) { t5.startObject(2); } static addNodeIndices(t5, e3) { t5.addFieldOffset(0, e3, 0); } static createNodeIndicesVector(t5, e3) { t5.startVector(4, e3.length, 4); for (let n2 = e3.length - 1; n2 >= 0; n2--) t5.addInt32(e3[n2]); return t5.endVector(); } static startNodeIndicesVector(t5, e3) { t5.startVector(4, e3, 4); } static addKernelDefHashes(t5, e3) { t5.addFieldOffset(1, e3, 0); } static createKernelDefHashesVector(t5, e3) { t5.startVector(8, e3.length, 8); for (let n2 = e3.length - 1; n2 >= 0; n2--) t5.addInt64(e3[n2]); return t5.endVector(); } static startKernelDefHashesVector(t5, e3) { t5.startVector(8, e3, 8); } static endKernelCreateInfos(t5) { return t5.endObject(); } static createKernelCreateInfos(t5, n2, r2) { return e2.startKernelCreateInfos(t5), e2.addNodeIndices(t5, n2), e2.addKernelDefHashes(t5, r2), e2.endKernelCreateInfos(t5); } } t4.KernelCreateInfos = e2; })(t3.fbs || (t3.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsSubGraphSessionState(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsSubGraphSessionState(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } graphId(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } sessionState(e4) { let n3 = this.bb.__offset(this.bb_pos, 6); return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startSubGraphSessionState(t3) { t3.startObject(2); } static addGraphId(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addSessionState(t3, e4) { t3.addFieldOffset(1, e4, 0); } static endSubGraphSessionState(t3) { let e4 = t3.endObject(); return t3.requiredField(e4, 4), e4; } static createSubGraphSessionState(t3, e4, r2) { return n2.startSubGraphSessionState(t3), n2.addGraphId(t3, e4), n2.addSessionState(t3, r2), n2.endSubGraphSessionState(t3); } } e3.SubGraphSessionState = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsSessionState(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsSessionState(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } kernels(e4) { let n3 = this.bb.__offset(this.bb_pos, 4); return n3 ? (e4 || new t2.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } subGraphSessionStates(e4, n3) { let r2 = this.bb.__offset(this.bb_pos, 6); return r2 ? (n3 || new t2.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null; } subGraphSessionStatesLength() { let t3 = this.bb.__offset(this.bb_pos, 6); return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0; } static startSessionState(t3) { t3.startObject(2); } static addKernels(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addSubGraphSessionStates(t3, e4) { t3.addFieldOffset(1, e4, 0); } static createSubGraphSessionStatesVector(t3, e4) { t3.startVector(4, e4.length, 4); for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]); return t3.endVector(); } static startSubGraphSessionStatesVector(t3, e4) { t3.startVector(4, e4, 4); } static endSessionState(t3) { return t3.endObject(); } static createSessionState(t3, e4, r2) { return n2.startSessionState(t3), n2.addKernels(t3, e4), n2.addSubGraphSessionStates(t3, r2), n2.endSessionState(t3); } } e3.SessionState = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) { !(function(e2) { !(function(e3) { class n2 { constructor() { this.bb = null, this.bb_pos = 0; } __init(t3, e4) { return this.bb_pos = t3, this.bb = e4, this; } static getRootAsInferenceSession(t3, e4) { return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static getSizePrefixedRootAsInferenceSession(t3, e4) { return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3); } static bufferHasIdentifier(t3) { return t3.__has_identifier("ORTM"); } ortVersion(t3) { let e4 = this.bb.__offset(this.bb_pos, 4); return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null; } model(e4) { let n3 = this.bb.__offset(this.bb_pos, 6); return n3 ? (e4 || new t2.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } sessionState(e4) { let n3 = this.bb.__offset(this.bb_pos, 8); return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null; } static startInferenceSession(t3) { t3.startObject(3); } static addOrtVersion(t3, e4) { t3.addFieldOffset(0, e4, 0); } static addModel(t3, e4) { t3.addFieldOffset(1, e4, 0); } static addSessionState(t3, e4) { t3.addFieldOffset(2, e4, 0); } static endInferenceSession(t3) { return t3.endObject(); } static finishInferenceSessionBuffer(t3, e4) { t3.finish(e4, "ORTM"); } static finishSizePrefixedInferenceSessionBuffer(t3, e4) { t3.finish(e4, "ORTM", true); } static createInferenceSession(t3, e4, r2, i2) { return n2.startInferenceSession(t3), n2.addOrtVersion(t3, e4), n2.addModel(t3, r2), n2.addSessionState(t3, i2), n2.endInferenceSession(t3); } } e3.InferenceSession = n2; })(e2.fbs || (e2.fbs = {})); })(t2.experimental || (t2.experimental = {})); })(e.onnxruntime || (e.onnxruntime = {})); }, 7448: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.OnnxjsSessionHandler = void 0; const r = n(1670), i = n(9162); e.OnnxjsSessionHandler = class { constructor(t2) { this.session = t2, this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames; } async dispose() { } async run(t2, e2, n2) { const o = /* @__PURE__ */ new Map(); for (const e3 in t2) if (Object.hasOwnProperty.call(t2, e3)) { const n3 = t2[e3]; o.set(e3, new i.Tensor(n3.dims, n3.type, void 0, void 0, n3.data)); } const a = await this.session.run(o), s = {}; return a.forEach(((t3, e3) => { s[e3] = new r.Tensor(t3.type, t3.data, t3.dims); })), s; } startProfiling() { this.session.startProfiling(); } endProfiling() { this.session.endProfiling(); } }; }, 6919: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.Session = void 0; const r = n(7067), i = n(1296), o = n(7091), a = n(1036), s = n(6231), u = n(2644); e.Session = class { constructor(t2 = {}) { this._initialized = false, this.backendHint = t2.backendHint, this.profiler = s.Profiler.create(t2.profiler), this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] }; } get inputNames() { return this._model.graph.getInputNames(); } get outputNames() { return this._model.graph.getOutputNames(); } startProfiling() { this.profiler.start(); } endProfiling() { this.profiler.stop(); } async loadModel(t2, e2, n2) { await this.profiler.event("session", "Session.loadModel", (async () => { const a2 = await (0, o.resolveBackend)(this.backendHint); if (this.sessionHandler = a2.createSessionHandler(this.context), this._model = new u.Model(), "string" == typeof t2) { const e3 = t2.endsWith(".ort"); if ("undefined" == typeof fetch) { const n3 = await (0, i.promisify)(r.readFile)(t2); this.initialize(n3, e3); } else { const n3 = await fetch(t2), r2 = await n3.arrayBuffer(); this.initialize(new Uint8Array(r2), e3); } } else if (ArrayBuffer.isView(t2)) this.initialize(t2); else { const r2 = new Uint8Array(t2, e2 || 0, n2 || t2.byteLength); this.initialize(r2); } })); } initialize(t2, e2) { if (this._initialized) throw new Error("already initialized"); this.profiler.event("session", "Session.initialize", (() => { const n2 = this.sessionHandler.transformGraph ? this.sessionHandler : void 0; this._model.load(t2, n2, e2), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new a.ExecutionPlan(this._model.graph, this._ops, this.profiler); })), this._initialized = true; } async run(t2) { if (!this._initialized) throw new Error("session not initialized yet"); return this.profiler.event("session", "Session.run", (async () => { const e2 = this.normalizeAndValidateInputs(t2), n2 = await this._executionPlan.execute(this.sessionHandler, e2); return this.createOutput(n2); })); } normalizeAndValidateInputs(t2) { const e2 = this._model.graph.getInputNames(); if (Array.isArray(t2)) { if (t2.length !== e2.length) throw new Error(`incorrect input array length: expected ${e2.length} but got ${t2.length}`); } else { if (t2.size !== e2.length) throw new Error(`incorrect input map size: expected ${e2.length} but got ${t2.size}`); const n2 = new Array(t2.size); let r2 = 0; for (let i2 = 0; i2 < e2.length; ++i2) { const o2 = t2.get(e2[i2]); if (!o2) throw new Error(`missing input tensor for: '${name}'`); n2[r2++] = o2; } t2 = n2; } if (this.context.graphInputTypes && 0 !== this.context.graphInputTypes.length && this.context.graphInputDims && 0 !== this.context.graphInputDims.length) this.validateInputTensorDims(this.context.graphInputDims, t2, false); else { const e3 = this._model.graph.getInputIndices(), n2 = this._model.graph.getValues(), r2 = new Array(e3.length); for (let i2 = 0; i2 < e3.length; ++i2) { const o2 = n2[e3[i2]]; r2[i2] = o2.type.shape.dims, this.context.graphInputTypes.push(o2.type.tensorType), this.context.graphInputDims.push(t2[i2].dims); } this.validateInputTensorDims(r2, t2, true); } return this.validateInputTensorTypes(this.context.graphInputTypes, t2), t2; } validateInputTensorTypes(t2, e2) { for (let n2 = 0; n2 < e2.length; n2++) { const r2 = t2[n2], i2 = e2[n2].type; if (r2 !== i2) throw new Error(`input tensor[${n2}] check failed: expected type '${r2}' but got ${i2}`); } } validateInputTensorDims(t2, e2, n2) { for (let r2 = 0; r2 < e2.length; r2++) { const i2 = t2[r2], o2 = e2[r2].dims; if (!this.compareTensorDims(i2, o2, n2)) throw new Error(`input tensor[${r2}] check failed: expected shape '[${i2.join(",")}]' but got [${o2.join(",")}]`); } } compareTensorDims(t2, e2, n2) { if (t2.length !== e2.length) return false; for (let r2 = 0; r2 < t2.length; ++r2) if (t2[r2] !== e2[r2] && (!n2 || 0 !== t2[r2])) return false; return true; } createOutput(t2) { const e2 = this._model.graph.getOutputNames(); if (t2.length !== e2.length) throw new Error("expected number of outputs do not match number of generated outputs"); const n2 = /* @__PURE__ */ new Map(); for (let r2 = 0; r2 < e2.length; ++r2) n2.set(e2[r2], t2[r2]); return n2; } initializeOps(t2) { const e2 = t2.getNodes(); this._ops = new Array(e2.length); for (let n2 = 0; n2 < e2.length; n2++) this._ops[n2] = this.sessionHandler.resolve(e2[n2], this._model.opsets, t2); } }; }, 9162: function(t, e, n) { "use strict"; var r = this && this.__importDefault || function(t2) { return t2 && t2.__esModule ? t2 : { default: t2 }; }; Object.defineProperty(e, "__esModule", { value: true }), e.Tensor = void 0; const i = n(3442), o = r(n(3720)), a = n(1446), s = n(9395), u = n(2517); var c = s.onnxruntime.experimental.fbs; class l { get data() { if (void 0 === this.cache) { const t2 = this.dataProvider(this.dataId); if (t2.length !== this.size) throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor."); this.cache = t2; } return this.cache; } get stringData() { if ("string" !== this.type) throw new TypeError("data type is not string"); return this.data; } get integerData() { switch (this.type) { case "uint8": case "int8": case "uint16": case "int16": case "int32": case "uint32": case "bool": return this.data; default: throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)"); } } get floatData() { switch (this.type) { case "float32": case "float64": return this.data; default: throw new TypeError("data type is not float (float32, float64)"); } } get numberData() { if ("string" !== this.type) return this.data; throw new TypeError("type cannot be non-number (string)"); } get(t2) { return this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)]; } set(t2, e2) { this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)] = e2; } async getData() { return void 0 === this.cache && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache; } get strides() { return this._strides || (this._strides = u.ShapeUtil.computeStrides(this.dims)), this._strides; } constructor(t2, e2, n2, r2, o2, a2 = i.Guid.create()) { this.dims = t2, this.type = e2, this.dataProvider = n2, this.asyncDataProvider = r2, this.cache = o2, this.dataId = a2, this.size = u.ShapeUtil.validateDimsAndCalcSize(t2); const s2 = this.size, c2 = void 0 === n2 && void 0 === r2 && void 0 === o2; if (void 0 !== o2 && o2.length !== s2) throw new RangeError("Input dims doesn't match data length."); if ("string" === e2) { if (!(void 0 === o2 || Array.isArray(o2) && o2.every(((t3) => "string" == typeof t3)))) throw new TypeError("cache should be a string array"); c2 && (this.cache = new Array(s2)); } else { if (void 0 !== o2) { const t3 = f(e2); if (!(o2 instanceof t3)) throw new TypeError(`cache should be type ${t3.name}`); } if (c2) { const t3 = new ArrayBuffer(s2 * (function(t4) { switch (t4) { case "bool": case "int8": case "uint8": return 1; case "int16": case "uint16": return 2; case "int32": case "uint32": case "float32": return 4; case "float64": return 8; default: throw new Error(`cannot calculate sizeof() on type ${t4}`); } })(e2)); this.cache = (function(t4, e3) { return new (f(e3))(t4); })(t3, e2); } } } static fromProto(t2) { if (!t2) throw new Error("cannot construct Value from an empty tensor"); const e2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType), n2 = u.ProtoUtil.tensorDimsFromProto(t2.dims), r2 = new l(n2, e2); if ("string" === e2) t2.stringData.forEach(((t3, e3) => { r2.data[e3] = (0, u.decodeUtf8String)(t3); })); else if (t2.rawData && "number" == typeof t2.rawData.byteLength && t2.rawData.byteLength > 0) { const e3 = r2.data, n3 = new DataView(t2.rawData.buffer, t2.rawData.byteOffset, t2.rawData.byteLength), i2 = p(t2.dataType), o2 = t2.rawData.byteLength / i2; if (t2.rawData.byteLength % i2 != 0) throw new Error("invalid buffer length"); if (e3.length !== o2) throw new Error("buffer length mismatch"); for (let r3 = 0; r3 < o2; r3++) { const o3 = h(n3, t2.dataType, r3 * i2); e3[r3] = o3; } } else { let e3; switch (t2.dataType) { case a.onnx.TensorProto.DataType.FLOAT: e3 = t2.floatData; break; case a.onnx.TensorProto.DataType.INT32: case a.onnx.TensorProto.DataType.INT16: case a.onnx.TensorProto.DataType.UINT16: case a.onnx.TensorProto.DataType.INT8: case a.onnx.TensorProto.DataType.UINT8: case a.onnx.TensorProto.DataType.BOOL: e3 = t2.int32Data; break; case a.onnx.TensorProto.DataType.INT64: e3 = t2.int64Data; break; case a.onnx.TensorProto.DataType.DOUBLE: e3 = t2.doubleData; break; case a.onnx.TensorProto.DataType.UINT32: case a.onnx.TensorProto.DataType.UINT64: e3 = t2.uint64Data; break; default: throw new Error("unspecific error"); } if (null == e3) throw new Error("failed to populate data from a tensorproto value"); const n3 = r2.data; if (n3.length !== e3.length) throw new Error("array length mismatch"); for (let r3 = 0; r3 < e3.length; r3++) { const i2 = e3[r3]; o.default.isLong(i2) ? n3[r3] = d(i2, t2.dataType) : n3[r3] = i2; } } return r2; } static fromData(t2, e2, n2) { return new l(e2, n2, void 0, void 0, t2); } static fromOrtTensor(t2) { if (!t2) throw new Error("cannot construct Value from an empty tensor"); const e2 = u.ProtoUtil.tensorDimsFromORTFormat(t2), n2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType()), r2 = new l(e2, n2); if ("string" === n2) for (let e3 = 0; e3 < t2.stringDataLength(); e3++) r2.data[e3] = t2.stringData(e3); else if (t2.rawDataArray() && "number" == typeof t2.rawDataLength() && t2.rawDataLength() > 0) { const e3 = r2.data, n3 = new DataView(t2.rawDataArray().buffer, t2.rawDataArray().byteOffset, t2.rawDataLength()), i2 = p(t2.dataType()), o2 = t2.rawDataLength() / i2; if (t2.rawDataLength() % i2 != 0) throw new Error("invalid buffer length"); if (e3.length !== o2) throw new Error("buffer length mismatch"); for (let r3 = 0; r3 < o2; r3++) { const o3 = h(n3, t2.dataType(), r3 * i2); e3[r3] = o3; } } return r2; } } function p(t2) { switch (t2) { case a.onnx.TensorProto.DataType.UINT8: case a.onnx.TensorProto.DataType.INT8: case a.onnx.TensorProto.DataType.BOOL: return 1; case a.onnx.TensorProto.DataType.UINT16: case a.onnx.TensorProto.DataType.INT16: return 2; case a.onnx.TensorProto.DataType.FLOAT: case a.onnx.TensorProto.DataType.INT32: case a.onnx.TensorProto.DataType.UINT32: return 4; case a.onnx.TensorProto.DataType.INT64: case a.onnx.TensorProto.DataType.DOUBLE: case a.onnx.TensorProto.DataType.UINT64: return 8; default: throw new Error(`cannot calculate sizeof() on type ${a.onnx.TensorProto.DataType[t2]}`); } } function f(t2) { switch (t2) { case "bool": case "uint8": return Uint8Array; case "int8": return Int8Array; case "int16": return Int16Array; case "uint16": return Uint16Array; case "int32": return Int32Array; case "uint32": return Uint32Array; case "float32": return Float32Array; case "float64": return Float64Array; default: throw new Error("unspecified error"); } } function d(t2, e2) { if (e2 === a.onnx.TensorProto.DataType.INT64 || e2 === c.TensorDataType.INT64) { if (t2.greaterThanOrEqual(2147483648) || t2.lessThan(-2147483648)) throw new TypeError("int64 is not supported"); } else { if (e2 !== a.onnx.TensorProto.DataType.UINT32 && e2 !== c.TensorDataType.UINT32 && e2 !== a.onnx.TensorProto.DataType.UINT64 && e2 !== c.TensorDataType.UINT64) throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[e2]}`); if (t2.greaterThanOrEqual(4294967296) || t2.lessThan(0)) throw new TypeError("uint64 is not supported"); } return t2.toNumber(); } function h(t2, e2, n2) { switch (e2) { case a.onnx.TensorProto.DataType.BOOL: case a.onnx.TensorProto.DataType.UINT8: return t2.getUint8(n2); case a.onnx.TensorProto.DataType.INT8: return t2.getInt8(n2); case a.onnx.TensorProto.DataType.UINT16: return t2.getUint16(n2, true); case a.onnx.TensorProto.DataType.INT16: return t2.getInt16(n2, true); case a.onnx.TensorProto.DataType.FLOAT: return t2.getFloat32(n2, true); case a.onnx.TensorProto.DataType.INT32: return t2.getInt32(n2, true); case a.onnx.TensorProto.DataType.UINT32: return t2.getUint32(n2, true); case a.onnx.TensorProto.DataType.INT64: return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), false), e2); case a.onnx.TensorProto.DataType.DOUBLE: return t2.getFloat64(n2, true); case a.onnx.TensorProto.DataType.UINT64: return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), true), e2); default: throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[e2]}`); } } e.Tensor = l; }, 2517: function(t, e, n) { "use strict"; var r = this && this.__importDefault || function(t2) { return t2 && t2.__esModule ? t2 : { default: t2 }; }; Object.defineProperty(e, "__esModule", { value: true }), e.decodeUtf8String = e.MAX_CLIP = e.MIN_CLIP = e.PoolConvUtil = e.ReduceUtil = e.SplitUtil = e.MathUtil = e.ShapeUtil = e.LongUtil = e.ProtoUtil = e.GemmUtil = e.arrayCopyHelper = e.BroadcastUtil = e.MatMulUtil = e.ArrayUtil = e.assert = e.checkInputsShape = void 0; const i = n(5686), o = r(n(3720)), a = n(1446), s = n(9162); e.checkInputsShape = function(t2, ...e2) { if (!t2 || t2.length !== e2.length) return false; for (let n2 = 0; n2 < t2.length; n2++) if (!t2[n2].dims || t2[n2].dims.length !== e2[n2]) return false; return true; }, e.assert = function(t2, e2) { if (!t2) throw new Error("string" == typeof e2 ? e2 : e2()); }, e.ArrayUtil = class { static arraysEqual(t2, e2) { if (t2.length !== e2.length) return false; for (let n2 = 0; n2 < t2.length; n2++) if (t2[n2] !== e2[n2]) return false; return true; } }; class u { static preprocessInputShapes(t2, e2) { return [1 === t2.length ? [1, t2[0]] : t2, 1 === e2.length ? [e2[0], 1] : e2]; } static postprocessOutputShape(t2, e2, n2) { 1 === e2 && t2.splice(t2.length - 2, 1), 1 === n2 && t2.pop(); } static calcMatMulShape(t2, e2) { return t2[1] !== e2[0] ? void 0 : [t2[0], e2[1]]; } } e.MatMulUtil = u; class c { static calcShape(t2, e2, n2 = false) { const r2 = t2.length, i2 = e2.length; if (0 === r2) return e2; if (0 === i2) return t2; const o2 = Math.max(t2.length, e2.length), a2 = new Array(o2); if (n2) { if (r2 < 2 || i2 < 2) return; const n3 = u.calcMatMulShape([t2[r2 - 2], t2[r2 - 1]], [e2[i2 - 2], e2[i2 - 1]]); if (void 0 === n3) return; [a2[o2 - 2], a2[o2 - 1]] = n3; } for (let s2 = n2 ? 3 : 1; s2 <= o2; s2++) { const n3 = r2 - s2 < 0 ? 1 : t2[r2 - s2], u2 = i2 - s2 < 0 ? 1 : e2[i2 - s2]; if (n3 !== u2 && n3 > 1 && u2 > 1) return; a2[o2 - s2] = Math.max(n3, u2); } return a2; } static index(t2, e2) { const n2 = new Array(e2.length); return c.fillIndex(t2, e2, n2), n2; } static fillIndex(t2, e2, n2) { const r2 = t2.length - e2.length; for (let i2 = 0; i2 < e2.length; i2++) n2[i2] = t2[r2 + i2] % e2[i2]; } static calc(t2, e2, n2, r2, i2) { const o2 = c.calcShape(t2.dims, e2.dims); if (o2) { if (r2 && !f.areEqual(o2, t2.dims)) return; const a2 = f.size(o2), u2 = r2 ? t2 : new s.Tensor(o2, i2 || t2.type); if (0 === o2.length) u2.set([], n2(t2.get([]), e2.get([]))); else { const r3 = new Array(o2.length), i3 = new Array(t2.dims.length), s2 = new Array(e2.dims.length); let l2, p2 = 0, f2 = 0, d2 = false, h2 = false; 0 === t2.dims.length && (p2 = t2.get([]), d2 = true), 0 === e2.dims.length && (f2 = e2.get([]), h2 = true); for (let g2 = 0; g2 < a2; g2++) { l2 = g2; for (let t3 = o2.length - 1; t3 >= 0; t3--) r3[t3] = l2 % o2[t3], l2 = Math.floor(l2 / o2[t3]); d2 || (c.fillIndex(r3, t2.dims, i3), p2 = t2.get(i3)), h2 || (c.fillIndex(r3, e2.dims, s2), f2 = e2.get(s2)), u2.set(r3, n2(p2, f2)); } } return u2; } } static isValidBroadcast(t2, e2) { const n2 = t2.length, r2 = e2.length; if (n2 > r2) return false; for (let i2 = 1; i2 <= n2; i2++) if (1 !== t2[n2 - i2] && t2[n2 - i2] !== e2[r2 - i2]) return false; return true; } static getBroadcastDims(t2, e2) { const n2 = t2.length, r2 = []; for (let i2 = 0; i2 < n2; i2++) { const o2 = n2 - 1 - i2, a2 = t2[o2] || 1; (e2[e2.length - 1 - i2] || 1) > 1 && 1 === a2 && r2.unshift(o2); } return r2; } } e.BroadcastUtil = c, e.arrayCopyHelper = function(t2, e2, n2, r2, i2) { if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds"); if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds"); if (r2 + i2 > e2.length) throw new Error("source indices to be copied are outside bounds"); if (n2 + i2 > t2.length) throw new Error("target array is too small to hold result"); for (let o2 = 0; o2 < i2; o2++) t2[n2 + o2] = e2[r2 + o2]; }, e.GemmUtil = class { static getShapeOfGemmResult(t2, e2, n2, r2, i2) { if (2 !== t2.length || 2 !== n2.length) throw new Error("shape need to be of size 2"); let o2, a2, s2; e2 ? (o2 = t2[1], a2 = t2[0]) : (o2 = t2[0], a2 = t2[1]); let u2 = -1; if (r2 ? (s2 = n2[0], u2 = 1) : (s2 = n2[1], u2 = 0), n2[u2] !== a2) throw new Error("dimension mismatch"); if (o2 <= 0 || s2 <= 0 || a2 <= 0) throw new Error("invalid shape specified"); if (i2 && !c.isValidBroadcast(i2, [o2, s2])) throw new Error("gemm: invalid bias shape for broadcast"); return [o2, s2, a2]; } }; class l { static tensorDataTypeFromProto(t2) { switch (t2) { case a.onnx.TensorProto.DataType.INT8: return "int8"; case a.onnx.TensorProto.DataType.UINT8: return "uint8"; case a.onnx.TensorProto.DataType.BOOL: return "bool"; case a.onnx.TensorProto.DataType.INT16: return "int16"; case a.onnx.TensorProto.DataType.UINT16: return "uint16"; case a.onnx.TensorProto.DataType.INT32: return "int32"; case a.onnx.TensorProto.DataType.UINT32: return "uint32"; case a.onnx.TensorProto.DataType.FLOAT: return "float32"; case a.onnx.TensorProto.DataType.DOUBLE: return "float64"; case a.onnx.TensorProto.DataType.STRING: return "string"; case a.onnx.TensorProto.DataType.INT64: return "int32"; case a.onnx.TensorProto.DataType.UINT64: return "uint32"; default: throw new Error(`unsupported data type: ${a.onnx.TensorProto.DataType[t2]}`); } } static tensorDataTypeStringToEnum(t2) { switch (t2) { case "int8": return a.onnx.TensorProto.DataType.INT8; case "uint8": return a.onnx.TensorProto.DataType.UINT8; case "bool": return a.onnx.TensorProto.DataType.BOOL; case "int16": return a.onnx.TensorProto.DataType.INT16; case "uint16": return a.onnx.TensorProto.DataType.UINT16; case "int32": return a.onnx.TensorProto.DataType.INT32; case "uint32": return a.onnx.TensorProto.DataType.UINT32; case "float32": return a.onnx.TensorProto.DataType.FLOAT; case "float64": return a.onnx.TensorProto.DataType.DOUBLE; case "string": return a.onnx.TensorProto.DataType.STRING; case "int64": return a.onnx.TensorProto.DataType.INT64; case "uint64": return a.onnx.TensorProto.DataType.UINT64; default: throw new Error(`unsupported data type: ${t2}`); } } static tensorDimsFromProto(t2) { return t2.map(((t3) => o.default.isLong(t3) ? t3.toNumber() : t3)); } static tensorValueTypeFromProto(t2) { return { tensorType: l.tensorDataTypeFromProto(t2.elemType), shape: { dims: l.tensorDimsFromProto(t2.shape.dim.map(((t3) => t3.dimValue))) } }; } static tensorDimsFromORTFormat(t2) { const e2 = []; for (let n2 = 0; n2 < t2.dimsLength(); n2++) e2.push(p.longToNumber(t2.dims(n2))); return e2; } static tensorAttributesFromORTFormat(t2) { const e2 = []; for (let n2 = 0; n2 < t2.attributesLength(); n2++) e2.push(t2.attributes(n2)); return e2; } } e.ProtoUtil = l; class p { static longToNumber(t2, e2) { return o.default.isLong(t2) ? t2.toNumber() : t2 instanceof i.flatbuffers.Long ? o.default.fromValue({ low: t2.low, high: t2.high, unsigned: null != e2 && e2 }).toNumber() : t2; } static isLong(t2) { return o.default.isLong(t2) || t2 instanceof i.flatbuffers.Long; } } e.LongUtil = p; class f { static size(t2) { return f.getSizeFromDimensionRange(t2, 0, t2.length); } static sizeFromDimension(t2, e2) { if (e2 < 0 || e2 > t2.length) throw new Error(`invalid dimension of ${e2} for sizeFromDimension as Tensor has ${t2.length} dimensions.`); return f.getSizeFromDimensionRange(t2, e2, t2.length); } static sizeToDimension(t2, e2) { if (e2 < 0 || e2 > t2.length) throw new Error(`invalid dimension of ${e2} for sizeToDimension as Tensor has ${t2.length} dimensions.`); return f.getSizeFromDimensionRange(t2, 0, e2); } static getSizeFromDimensionRange(t2, e2, n2) { let r2 = 1; for (let i2 = e2; i2 < n2; i2++) { if (t2[i2] <= 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them."); r2 *= t2[i2]; } return r2; } static computeStrides(t2) { const e2 = t2.length; if (0 === e2) return []; if (1 === e2) return [1]; const n2 = new Array(e2); n2[e2 - 1] = 1, n2[e2 - 2] = t2[e2 - 1]; for (let r2 = e2 - 3; r2 >= 0; --r2) n2[r2] = n2[r2 + 1] * t2[r2 + 1]; return n2; } static transpose(t2) { return t2.slice().reverse(); } static indicesToOffset(t2, e2, n2) { void 0 === n2 && (n2 = t2.length); let r2 = 0; for (let i2 = 0; i2 < n2; ++i2) r2 += e2[i2] * t2[i2]; return r2; } static offsetToIndices(t2, e2) { const n2 = e2.length; if (0 === n2) return []; if (1 === n2) return [t2 * e2[0]]; const r2 = new Array(e2.length); for (let n3 = 0; n3 < r2.length - 1; ++n3) r2[n3] = Math.floor(t2 / e2[n3]), t2 -= r2[n3] * e2[n3]; return r2[r2.length - 1] = t2, r2; } static normalizeAxis(t2, e2) { if (t2 < -e2 && t2 >= e2) throw new Error("unsupported axis for this operation."); return t2 < 0 ? t2 + e2 : t2; } static normalizeAxes(t2, e2) { return t2.map(((t3) => this.normalizeAxis(t3, e2))); } static incrementIndex(t2, e2, n2) { if (0 === e2.length || 0 === t2.length) throw new Error("Index incrementing unsupported for scalar Tensor"); if (void 0 === n2) n2 = e2.length; else if (n2 <= 0 || n2 > e2.length) throw new Error("Incorrect axis to increment on"); for (let r2 = n2 - 1; r2 >= 0 && (t2[r2]++, !(t2[r2] < e2[r2])); --r2) t2[r2] = 0; } static calculateReshapedDims(t2, e2) { if (0 === e2.length) { if (0 === t2.length || 1 === f.size(t2)) return []; throw new Error("cannot reshape to a scalar Tensor"); } const n2 = e2.length, r2 = new Array(n2); let i2 = -1, o2 = 1; for (let a3 = 0; a3 < n2; a3++) { if (e2[a3] < -1) throw new Error("a dimension in shape hints cannot be less than -1"); if (-1 === e2[a3]) { if (-1 !== i2) throw new Error("at most one dimension in shape hints can be -1"); i2 = a3; } else { if (0 === e2[a3]) { if (a3 >= t2.length) throw new Error("the dimension with value zero exceeds the dimension size of the input tensor"); r2[a3] = t2[a3]; } else r2[a3] = e2[a3]; o2 *= r2[a3]; } } const a2 = f.size(t2); if (-1 !== i2) { if (a2 % o2 != 0) throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t2}] Output shape: [${e2}]`); r2[i2] = a2 / o2; } else if (o2 !== a2) throw new Error("reshapedDims and originalDims don't have matching sizes"); return r2; } static sortBasedOnPerm(t2, e2) { return e2 ? e2.map(((e3) => t2[e3])) : t2.slice().reverse(); } static padShape(t2, e2) { const n2 = t2.length; return t2.map(((t3, r2) => t3 + e2[r2] + e2[r2 + n2])); } static areEqual(t2, e2) { return t2.length === e2.length && t2.every(((t3, n2) => t3 === e2[n2])); } static validateDimsAndCalcSize(t2) { if (t2.length > 6) throw new TypeError("Only rank 0 to 6 is supported for tensor shape."); let e2 = 1; for (const n2 of t2) { if (!Number.isInteger(n2)) throw new TypeError(`Invalid shape: ${n2} is not an integer`); if (n2 < 0 || n2 > 2147483647) throw new TypeError(`Invalid shape: length ${n2} is not allowed`); e2 *= n2; } return e2; } static flattenShape(t2, e2) { e2 < 0 && (e2 += t2.length); const n2 = t2.reduce(((t3, e3) => t3 * e3), 1), r2 = t2.slice(e2).reduce(((t3, e3) => t3 * e3), 1); return [n2 / r2, r2]; } static squeezeShape(t2, e2) { const n2 = new Array(); e2 = f.normalizeAxes(e2, t2.length); for (let r2 = 0; r2 < t2.length; r2++) { const i2 = e2.indexOf(r2) >= 0; if (i2 && 1 !== t2[r2]) throw new Error("squeeze an axis of size different than 1"); (0 === e2.length && t2[r2] > 1 || e2.length > 0 && !i2) && n2.push(t2[r2]); } return n2; } static unsqueezeShape(t2, e2) { const n2 = new Array(t2.length + e2.length); n2.fill(0); for (let t3 = 0; t3 < e2.length; t3++) { const r3 = f.normalizeAxis(e2[t3], n2.length); if (r3 >= n2.length) throw new Error("'axes' has an out of range axis"); if (0 !== n2[r3]) throw new Error("'axes' has a duplicate axis"); n2[r3] = 1; } let r2 = 0; for (let e3 = 0; e3 < n2.length; e3++) 0 === n2[e3] && (n2[e3] = t2[r2++]); if (r2 !== t2.length) throw new Error("the unsqueezed dimension could not be established"); return n2; } } e.ShapeUtil = f, e.MathUtil = class { static sqr(t2, e2, n2, r2, i2) { if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds"); if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds"); if (r2 + i2 > e2.length) throw new Error("source indices to be copied are outside bounds"); if (n2 + i2 > t2.length) throw new Error("target array is too small to hold result"); for (let o2 = 0; o2 < i2; o2++) t2[n2 + o2] += Math.pow(e2[r2 + o2], 2); } static axpy(t2, e2, n2, r2, i2, o2) { if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds"); if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds"); if (r2 + i2 > e2.length) throw new Error("source indices to be copied are outside bounds"); if (n2 + i2 > t2.length) throw new Error("target array is too small to hold result"); for (let a2 = 0; a2 < i2; a2++) t2[n2 + a2] += o2 * e2[r2 + a2]; } static powx(t2, e2, n2, r2, i2, o2) { if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds"); if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds"); if (r2 + i2 > e2.length) throw new Error("source indices to be copied are outside bounds"); if (n2 + i2 > t2.length) throw new Error("target array is too small to hold result"); for (let a2 = 0; a2 < i2; a2++) t2[n2 + a2] = Math.pow(e2[r2 + a2], o2); } static mul(t2, e2, n2, r2, i2) { if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds"); if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds"); if (r2 + i2 > e2.length) throw new Error("source indices to be copied are outside bounds"); if (n2 + i2 > t2.length) throw new Error("target array is too small to hold result"); for (let o2 = 0; o2 < i2; o2++) t2[n2 + o2] = e2[r2 + o2] * t2[n2 + o2]; } }; class d { static splitShape(t2, e2, n2, r2) { if (0 === n2.length) { if (!r2) throw new Error("need to know number of outputs when the 'split' attribute is not specified"); d.determineSplit(t2[e2], r2, n2); } const i2 = [], o2 = [0]; for (let r3 = 0; r3 < n2.length; ++r3) { 0 !== r3 && o2.push(o2[r3 - 1] + n2[r3 - 1]); const a2 = t2.slice(); a2[e2] = n2[r3], i2.push(a2); } return [i2, o2]; } static determineSplit(t2, e2, n2) { if (t2 % e2 != 0) throw new Error("cannot split tensor to equal sized parts"); for (let r2 = 0; r2 < e2; ++r2) n2.push(t2 / e2); } } e.SplitUtil = d; class h { static calcReduce(t2, e2, n2, r2, i2) { const o2 = t2.dims.slice(0); 0 === e2.length && o2.forEach(((t3, n3) => e2.push(n3))); const a2 = h.calcReduceShape(o2, e2, true), u2 = f.size(a2), l2 = new s.Tensor(a2, t2.type), p2 = f.computeStrides(a2), d2 = f.computeStrides(o2), g2 = new Array(o2.length); for (let n3 = 0; n3 < u2; n3++) { const a3 = f.offsetToIndices(n3, p2); c.fillIndex(a3, o2, g2), l2.set(a3, h.calcReduceByAxis(t2.numberData, e2, o2, 0, f.indicesToOffset(g2, d2), r2, i2)); } return n2 ? l2 : new s.Tensor(h.calcReduceShape(o2, e2, n2), l2.type, void 0, void 0, l2.data, l2.dataId); } static calcReduceByAxis(t2, e2, n2, r2, i2, o2, a2) { let s2 = 0; if (r2 >= e2.length) return o2(t2[i2]); const u2 = e2[r2], c2 = u2 >= n2.length ? 1 : f.size(n2.slice(u2 + 1)); for (let l2 = 0; l2 < n2[u2]; l2++) s2 = 0 === l2 ? h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2) : a2(s2, h.calcReduceByAxis(t2, e2, n2, r2 + 1, i2, o2, a2)), i2 += c2; return s2; } static calcReduceShape(t2, e2, n2) { const r2 = t2.slice(); for (let t3 = 0; t3 < e2.length; t3++) r2[e2[t3]] = n2 ? 1 : 0; return r2.filter(((t3) => 0 !== t3)); } } e.ReduceUtil = h; class g { static adjustPoolAttributes(t2, e2, n2, r2, i2, o2) { if (!t2 && n2.length !== e2.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); if (t2) for (let t3 = 0; t3 < e2.length - 2; t3++) t3 >= n2.length ? n2.push(e2[t3 + 2]) : n2[t3] = e2[t3 + 2]; for (let t3 = 0; t3 < n2.length; t3++) if (t3 < r2.length) { if (r2[t3] < 0) throw new Error("strides should be greater than or equal to 1"); } else r2.push(1); for (let t3 = 0; t3 < n2.length; t3++) if (t3 < i2.length) { if (i2[t3] < 0) throw new Error("dilations should be greater than or equal to 1"); } else i2.push(1); for (let t3 = 0; t3 < 2 * n2.length; t3++) if (t3 < o2.length) { if (o2[t3] < 0) throw new Error("pad should be greater than or equal to 1"); } else o2.push(0); for (let t3 = 0; t3 < n2.length; t3++) { if (n2[t3] <= 0) throw new Error("kernel shapes need to be greater than 0"); if (o2[t3] >= n2[t3] || o2[t3 + n2.length] >= n2[t3]) throw new Error("pads should be smaller than kernel"); } } static adjustPadsBasedOnAutoPad(t2, e2, n2, r2, i2, o2) { if (o2) { if (i2.length !== 2 * (t2.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); if (e2.length !== t2.length - 2) throw new Error("length of strides should be the length of data dimensions"); if (r2.length !== t2.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions"); for (let a2 = 0; a2 < t2.length - 2; a2++) g.adjustPadAndReturnShape(t2[a2 + 2], e2[a2], n2[a2], r2[a2], i2, a2, a2 + t2.length - 2, o2); } } static computePoolOutputShape(t2, e2, n2, r2, i2, o2, a2) { if (e2.length <= 0) throw new Error("input shape must be of size greater than 0"); const s2 = [e2[0], e2[1]]; return g.computeShapeHelper(t2, e2, s2, n2, r2, i2, o2, a2), s2; } static computeConvOutputShape(t2, e2, n2, r2, i2, o2, a2) { if (t2.length <= 0 || e2.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); const s2 = [t2[0], e2[0]]; return g.computeShapeHelper(false, t2, s2, n2, r2, i2, o2, a2), s2; } static computeShapeHelper(t2, e2, n2, r2, i2, o2, a2, s2) { if (t2) for (let t3 = 0; t3 < e2.length - 2; t3++) n2.push(1); else for (let t3 = 0; t3 < e2.length - 2; t3++) n2.push(g.adjustPadAndReturnShape(e2[t3 + 2], r2[t3], i2[t3], o2[t3], a2, t3, t3 + e2.length - 2, s2)); } static adjustPadAndReturnShape(t2, e2, n2, r2, i2, o2, a2, s2) { const u2 = n2 * (r2 - 1) + 1; if (!s2 || "NOTSET" === s2) return Math.floor((t2 + i2[o2] + i2[a2] - u2) / e2 + 1); switch (s2) { case "VALID": return i2[o2] = 0, i2[a2] = 0, Math.floor((t2 - u2) / e2 + 1); case "SAME_LOWER": case "SAME_UPPER": if (1 !== n2) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); { const n3 = ((t2 + e2 - 1) / e2 - 1) * e2 + r2 - t2; return i2[o2] = "SAME_LOWER" === s2 ? Math.floor((n3 + 1) / 2) : Math.floor(n3 / 2), i2[a2] = n3 - i2[o2], Math.floor((t2 + n3 - r2) / e2 + 1); } default: throw new Error("Unsupported AutoPad type"); } } } e.PoolConvUtil = g, e.MIN_CLIP = -34028234663852886e22, e.MAX_CLIP = 34028234663852886e22, e.decodeUtf8String = function(t2) { return new TextDecoder().decode(t2); }; }, 7967: (t, e) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.iterateExtraOptions = void 0, e.iterateExtraOptions = (t2, n, r, i) => { if ("object" == typeof t2 && null !== t2) { if (r.has(t2)) throw new Error("Circular reference in options"); r.add(t2); } Object.entries(t2).forEach((([t3, o]) => { const a = n ? n + t3 : t3; if ("object" == typeof o) (0, e.iterateExtraOptions)(o, a + ".", r, i); else if ("string" == typeof o || "number" == typeof o) i(a, o.toString()); else { if ("boolean" != typeof o) throw new Error("Can't handle extra config type: " + typeof o); i(a, o ? "1" : "0"); } })); }; }, 2157: function(t, e, n) { "use strict"; var r, i = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2); var i2 = Object.getOwnPropertyDescriptor(e2, n2); i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { return e2[n2]; } }), Object.defineProperty(t2, r2, i2); } : function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; }), o = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); } : function(t2, e2) { t2.default = e2; }), a = this && this.__importStar || function(t2) { if (t2 && t2.__esModule) return t2; var e2 = {}; if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && i(e2, t2, n2); return o(e2, t2), e2; }; Object.defineProperty(e, "__esModule", { value: true }), e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = e.initWasm = void 0; const s = n(1670), u = a(n(349)), c = n(6361), l = () => !!s.env.wasm.proxy && "undefined" != typeof document; let p, f, d, h = false, g = false, b = false; const m2 = [], y = [], _ = [], v = [], w = [], x2 = [], T3 = () => { if (h || !g || b || !p) throw new Error("worker not ready"); }, S = (t2) => { switch (t2.data.type) { case "init-wasm": h = false, t2.data.err ? (b = true, f[1](t2.data.err)) : (g = true, f[0]()); break; case "init-ort": t2.data.err ? d[1](t2.data.err) : d[0](); break; case "create_allocate": t2.data.err ? m2.shift()[1](t2.data.err) : m2.shift()[0](t2.data.out); break; case "create_finalize": t2.data.err ? y.shift()[1](t2.data.err) : y.shift()[0](t2.data.out); break; case "create": t2.data.err ? _.shift()[1](t2.data.err) : _.shift()[0](t2.data.out); break; case "release": t2.data.err ? v.shift()[1](t2.data.err) : v.shift()[0](); break; case "run": t2.data.err ? w.shift()[1](t2.data.err) : w.shift()[0](t2.data.out); break; case "end-profiling": t2.data.err ? x2.shift()[1](t2.data.err) : x2.shift()[0](); } }, O2 = "undefined" != typeof document ? null === (r = null === document || void 0 === document ? void 0 : document.currentScript) || void 0 === r ? void 0 : r.src : void 0; e.initWasm = async () => { if (l()) { if (g) return; if (h) throw new Error("multiple calls to 'initWasm()' detected."); if (b) throw new Error("previous call to 'initWasm()' failed."); return h = true, void 0 === s.env.wasm.wasmPaths && O2 && 0 !== O2.indexOf("blob:") && (s.env.wasm.wasmPaths = O2.substr(0, +O2.lastIndexOf("/") + 1)), new Promise(((t2, e2) => { null == p || p.terminate(), p = n(9710).Z(), p.onmessage = S, f = [t2, e2]; const r2 = { type: "init-wasm", in: s.env.wasm }; p.postMessage(r2); })); } return (0, c.initializeWebAssembly)(s.env.wasm); }, e.initOrt = async (t2, e2) => { if (l()) return T3(), new Promise(((n2, r2) => { d = [n2, r2]; const i2 = { type: "init-ort", in: { numThreads: t2, loggingLevel: e2 } }; p.postMessage(i2); })); u.initOrt(t2, e2); }, e.createSessionAllocate = async (t2) => l() ? (T3(), new Promise(((e2, n2) => { m2.push([e2, n2]); const r2 = { type: "create_allocate", in: { model: t2 } }; p.postMessage(r2, [t2.buffer]); }))) : u.createSessionAllocate(t2), e.createSessionFinalize = async (t2, e2) => l() ? (T3(), new Promise(((n2, r2) => { y.push([n2, r2]); const i2 = { type: "create_finalize", in: { modeldata: t2, options: e2 } }; p.postMessage(i2); }))) : u.createSessionFinalize(t2, e2), e.createSession = async (t2, e2) => l() ? (T3(), new Promise(((n2, r2) => { _.push([n2, r2]); const i2 = { type: "create", in: { model: t2, options: e2 } }; p.postMessage(i2, [t2.buffer]); }))) : u.createSession(t2, e2), e.releaseSession = async (t2) => { if (l()) return T3(), new Promise(((e2, n2) => { v.push([e2, n2]); const r2 = { type: "release", in: t2 }; p.postMessage(r2); })); u.releaseSession(t2); }, e.run = async (t2, e2, n2, r2, i2) => l() ? (T3(), new Promise(((o2, a2) => { w.push([o2, a2]); const s2 = { type: "run", in: { sessionId: t2, inputIndices: e2, inputs: n2, outputIndices: r2, options: i2 } }; p.postMessage(s2, u.extractTransferableBuffers(n2)); }))) : u.run(t2, e2, n2, r2, i2), e.endProfiling = async (t2) => { if (l()) return T3(), new Promise(((e2, n2) => { x2.push([e2, n2]); const r2 = { type: "end-profiling", in: t2 }; p.postMessage(r2); })); u.endProfiling(t2); }; }, 586: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.setRunOptions = void 0; const r = n(7967), i = n(4983), o = n(6361); e.setRunOptions = (t2) => { const e2 = (0, o.getInstance)(); let n2 = 0; const a = [], s = t2 || {}; try { if (void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) s.logSeverityLevel = 2; else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`); if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) s.logVerbosityLevel = 0; else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`); void 0 === (null == t2 ? void 0 : t2.terminate) && (s.terminate = false); let o2 = 0; if (void 0 !== (null == t2 ? void 0 : t2.tag) && (o2 = (0, i.allocWasmString)(t2.tag, a)), n2 = e2._OrtCreateRunOptions(s.logSeverityLevel, s.logVerbosityLevel, !!s.terminate, o2), 0 === n2) throw new Error("Can't create run options"); return void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), ((t3, r2) => { const o3 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a); if (0 !== e2._OrtAddRunConfigEntry(n2, o3, s2)) throw new Error(`Can't set a run config entry: ${t3} - ${r2}`); })), [n2, a]; } catch (t3) { throw 0 !== n2 && e2._OrtReleaseRunOptions(n2), a.forEach(e2._free), t3; } }; }, 2306: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.OnnxruntimeWebAssemblySessionHandler = void 0; const r = n(2806), i = n(1670), o = n(2850), a = n(2157); let s; e.OnnxruntimeWebAssemblySessionHandler = class { async createSessionAllocate(t2) { const e2 = await fetch(t2), n2 = await e2.arrayBuffer(); return (0, a.createSessionAllocate)(new Uint8Array(n2)); } async loadModel(t2, e2) { if (s || (await (0, a.initOrt)(i.env.wasm.numThreads, ((t3) => { switch (t3) { case "verbose": return 0; case "info": return 1; case "warning": return 2; case "error": return 3; case "fatal": return 4; default: throw new Error(`unsupported logging level: ${t3}`); } })(i.env.logLevel)), s = true), "string" == typeof t2) if ("undefined" == typeof fetch) { const n2 = await (0, o.promisify)(r.readFile)(t2); [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(n2, e2); } else { const n2 = await this.createSessionAllocate(t2); [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSessionFinalize)(n2, e2); } else [this.sessionId, this.inputNames, this.outputNames] = await (0, a.createSession)(t2, e2); } async dispose() { return (0, a.releaseSession)(this.sessionId); } async run(t2, e2, n2) { const r2 = [], o2 = []; Object.entries(t2).forEach(((t3) => { const e3 = t3[0], n3 = t3[1], i2 = this.inputNames.indexOf(e3); if (-1 === i2) throw new Error(`invalid input '${e3}'`); r2.push(n3), o2.push(i2); })); const s2 = []; Object.entries(e2).forEach(((t3) => { const e3 = t3[0], n3 = this.outputNames.indexOf(e3); if (-1 === n3) throw new Error(`invalid output '${e3}'`); s2.push(n3); })); const u = await (0, a.run)(this.sessionId, o2, r2.map(((t3) => [t3.type, t3.dims, t3.data])), s2, n2), c = {}; for (let t3 = 0; t3 < u.length; t3++) c[this.outputNames[s2[t3]]] = new i.Tensor(u[t3][0], u[t3][2], u[t3][1]); return c; } startProfiling() { } endProfiling() { (0, a.endProfiling)(this.sessionId); } }; }, 4919: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.setSessionOptions = void 0; const r = n(7967), i = n(4983), o = n(6361); e.setSessionOptions = (t2) => { const e2 = (0, o.getInstance)(); let n2 = 0; const a = [], s = t2 || {}; ((t3) => { t3.extra || (t3.extra = {}), t3.extra.session || (t3.extra.session = {}); const e3 = t3.extra.session; e3.use_ort_model_bytes_directly || (e3.use_ort_model_bytes_directly = "1"); })(s); try { void 0 === (null == t2 ? void 0 : t2.graphOptimizationLevel) && (s.graphOptimizationLevel = "all"); const u = ((t3) => { switch (t3) { case "disabled": return 0; case "basic": return 1; case "extended": return 2; case "all": return 99; default: throw new Error(`unsupported graph optimization level: ${t3}`); } })(s.graphOptimizationLevel); void 0 === (null == t2 ? void 0 : t2.enableCpuMemArena) && (s.enableCpuMemArena = true), void 0 === (null == t2 ? void 0 : t2.enableMemPattern) && (s.enableMemPattern = true), void 0 === (null == t2 ? void 0 : t2.executionMode) && (s.executionMode = "sequential"); const c = ((t3) => { switch (t3) { case "sequential": return 0; case "parallel": return 1; default: throw new Error(`unsupported execution mode: ${t3}`); } })(s.executionMode); let l = 0; if (void 0 !== (null == t2 ? void 0 : t2.logId) && (l = (0, i.allocWasmString)(t2.logId, a)), void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) s.logSeverityLevel = 2; else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`); if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) s.logVerbosityLevel = 0; else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`); if (void 0 === (null == t2 ? void 0 : t2.enableProfiling) && (s.enableProfiling = false), n2 = e2._OrtCreateSessionOptions(u, !!s.enableCpuMemArena, !!s.enableMemPattern, c, !!s.enableProfiling, 0, l, s.logSeverityLevel, s.logVerbosityLevel), 0 === n2) throw new Error("Can't create session options"); return (null == t2 ? void 0 : t2.executionProviders) && ((t3, e3, n3) => { for (const r2 of e3) { let e4 = "string" == typeof r2 ? r2 : r2.name; switch (e4) { case "xnnpack": e4 = "XNNPACK"; break; case "wasm": case "cpu": continue; default: throw new Error(`not supported EP: ${e4}`); } const a2 = (0, i.allocWasmString)(e4, n3); if (0 !== (0, o.getInstance)()._OrtAppendExecutionProvider(t3, a2)) throw new Error(`Can't append execution provider: ${e4}`); } })(n2, t2.executionProviders, a), void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), ((t3, r2) => { const o2 = (0, i.allocWasmString)(t3, a), s2 = (0, i.allocWasmString)(r2, a); if (0 !== e2._OrtAddSessionConfigEntry(n2, o2, s2)) throw new Error(`Can't set a session config entry: ${t3} - ${r2}`); })), [n2, a]; } catch (t3) { throw 0 !== n2 && e2._OrtReleaseSessionOptions(n2), a.forEach(e2._free), t3; } }; }, 4983: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.allocWasmString = void 0; const r = n(6361); e.allocWasmString = (t2, e2) => { const n2 = (0, r.getInstance)(), i = n2.lengthBytesUTF8(t2) + 1, o = n2._malloc(i); return n2.stringToUTF8(t2, o, i), e2.push(o), o; }; }, 349: (t, e, n) => { "use strict"; Object.defineProperty(e, "__esModule", { value: true }), e.extractTransferableBuffers = e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = void 0; const r = n(586), i = n(4919), o = n(4983), a = n(6361); e.initOrt = (t2, e2) => { const n2 = (0, a.getInstance)()._OrtInit(t2, e2); if (0 !== n2) throw new Error(`Can't initialize onnxruntime. error code = ${n2}`); }; const s = /* @__PURE__ */ new Map(); e.createSessionAllocate = (t2) => { const e2 = (0, a.getInstance)(), n2 = e2._malloc(t2.byteLength); return e2.HEAPU8.set(t2, n2), [n2, t2.byteLength]; }, e.createSessionFinalize = (t2, e2) => { const n2 = (0, a.getInstance)(); let r2 = 0, o2 = 0, u2 = []; try { if ([o2, u2] = (0, i.setSessionOptions)(e2), r2 = n2._OrtCreateSession(t2[0], t2[1], o2), 0 === r2) throw new Error("Can't create a session"); } finally { n2._free(t2[0]), n2._OrtReleaseSessionOptions(o2), u2.forEach(n2._free); } const c2 = n2._OrtGetInputCount(r2), l2 = n2._OrtGetOutputCount(r2), p = [], f = [], d = [], h = []; for (let t3 = 0; t3 < c2; t3++) { const e3 = n2._OrtGetInputName(r2, t3); if (0 === e3) throw new Error("Can't get an input name"); f.push(e3), p.push(n2.UTF8ToString(e3)); } for (let t3 = 0; t3 < l2; t3++) { const e3 = n2._OrtGetOutputName(r2, t3); if (0 === e3) throw new Error("Can't get an output name"); h.push(e3), d.push(n2.UTF8ToString(e3)); } return s.set(r2, [r2, f, h]), [r2, p, d]; }, e.createSession = (t2, n2) => { const r2 = (0, e.createSessionAllocate)(t2); return (0, e.createSessionFinalize)(r2, n2); }, e.releaseSession = (t2) => { const e2 = (0, a.getInstance)(), n2 = s.get(t2); if (!n2) throw new Error("invalid session id"); const r2 = n2[0], i2 = n2[1], o2 = n2[2]; i2.forEach(e2._OrtFree), o2.forEach(e2._OrtFree), e2._OrtReleaseSession(r2), s.delete(t2); }; const u = (t2) => { switch (t2) { case "int8": return 3; case "uint8": return 2; case "bool": return 9; case "int16": return 5; case "uint16": return 4; case "int32": return 6; case "uint32": return 12; case "float32": return 1; case "float64": return 11; case "string": return 8; case "int64": return 7; case "uint64": return 13; default: throw new Error(`unsupported data type: ${t2}`); } }, c = (t2) => { switch (t2) { case 3: return "int8"; case 2: return "uint8"; case 9: return "bool"; case 5: return "int16"; case 4: return "uint16"; case 6: return "int32"; case 12: return "uint32"; case 1: return "float32"; case 11: return "float64"; case 8: return "string"; case 7: return "int64"; case 13: return "uint64"; default: throw new Error(`unsupported data type: ${t2}`); } }, l = (t2) => { switch (t2) { case "float32": return Float32Array; case "uint8": case "bool": return Uint8Array; case "int8": return Int8Array; case "uint16": return Uint16Array; case "int16": return Int16Array; case "int32": return Int32Array; case "float64": return Float64Array; case "uint32": return Uint32Array; case "int64": return BigInt64Array; case "uint64": return BigUint64Array; default: throw new Error(`unsupported type: ${t2}`); } }; e.run = (t2, e2, n2, i2, p) => { const f = (0, a.getInstance)(), d = s.get(t2); if (!d) throw new Error("invalid session id"); const h = d[0], g = d[1], b = d[2], m2 = e2.length, y = i2.length; let _ = 0, v = []; const w = [], x2 = []; try { [_, v] = (0, r.setRunOptions)(p); for (let t4 = 0; t4 < m2; t4++) { const e3 = n2[t4][0], r2 = n2[t4][1], i3 = n2[t4][2]; let a3, s3; if (Array.isArray(i3)) { s3 = 4 * i3.length, a3 = f._malloc(s3), x2.push(a3); let t5 = a3 / 4; for (let e4 = 0; e4 < i3.length; e4++) { if ("string" != typeof i3[e4]) throw new TypeError(`tensor data at index ${e4} is not a string`); f.HEAPU32[t5++] = (0, o.allocWasmString)(i3[e4], x2); } } else s3 = i3.byteLength, a3 = f._malloc(s3), x2.push(a3), f.HEAPU8.set(new Uint8Array(i3.buffer, i3.byteOffset, s3), a3); const c2 = f.stackSave(), l2 = f.stackAlloc(4 * r2.length); try { let t5 = l2 / 4; r2.forEach(((e4) => f.HEAP32[t5++] = e4)); const n3 = f._OrtCreateTensor(u(e3), a3, s3, l2, r2.length); if (0 === n3) throw new Error("Can't create a tensor"); w.push(n3); } finally { f.stackRestore(c2); } } const t3 = f.stackSave(), a2 = f.stackAlloc(4 * m2), s2 = f.stackAlloc(4 * m2), d2 = f.stackAlloc(4 * y), T3 = f.stackAlloc(4 * y); try { let n3 = a2 / 4, r2 = s2 / 4, o2 = d2 / 4, u2 = T3 / 4; for (let t4 = 0; t4 < m2; t4++) f.HEAPU32[n3++] = w[t4], f.HEAPU32[r2++] = g[e2[t4]]; for (let t4 = 0; t4 < y; t4++) f.HEAPU32[o2++] = 0, f.HEAPU32[u2++] = b[i2[t4]]; let p2 = f._OrtRun(h, s2, a2, m2, T3, y, d2, _); const v2 = []; if (0 === p2) for (let t4 = 0; t4 < y; t4++) { const e3 = f.HEAPU32[d2 / 4 + t4], n4 = f.stackSave(), r3 = f.stackAlloc(16); let i3, o3 = 0; try { if (p2 = f._OrtGetTensorData(e3, r3, r3 + 4, r3 + 8, r3 + 12), 0 !== p2) throw new Error(`Can't access output tensor data. error code = ${p2}`); let t5 = r3 / 4; const a3 = f.HEAPU32[t5++]; o3 = f.HEAPU32[t5++]; const s3 = f.HEAPU32[t5++], u3 = f.HEAPU32[t5++], d3 = []; for (let t6 = 0; t6 < u3; t6++) d3.push(f.HEAPU32[s3 / 4 + t6]); f._OrtFree(s3); const h2 = 0 === d3.length ? 1 : d3.reduce(((t6, e4) => t6 * e4)); if (i3 = c(a3), "string" === i3) { const t6 = []; let e4 = o3 / 4; for (let n5 = 0; n5 < h2; n5++) { const r4 = f.HEAPU32[e4++], i4 = n5 === h2 - 1 ? void 0 : f.HEAPU32[e4] - r4; t6.push(f.UTF8ToString(r4, i4)); } v2.push([i3, d3, t6]); } else { const t6 = new (l(i3))(h2); new Uint8Array(t6.buffer, t6.byteOffset, t6.byteLength).set(f.HEAPU8.subarray(o3, o3 + t6.byteLength)), v2.push([i3, d3, t6]); } } finally { f.stackRestore(n4), "string" === i3 && o3 && f._free(o3), f._OrtReleaseTensor(e3); } } if (0 === p2) return v2; throw new Error(`failed to call OrtRun(). error code = ${p2}.`); } finally { f.stackRestore(t3); } } finally { w.forEach(f._OrtReleaseTensor), x2.forEach(f._free), f._OrtReleaseRunOptions(_), v.forEach(f._free); } }, e.endProfiling = (t2) => { const e2 = (0, a.getInstance)(), n2 = s.get(t2); if (!n2) throw new Error("invalid session id"); const r2 = n2[0], i2 = e2._OrtEndProfiling(r2); if (0 === i2) throw new Error("Can't get an profile file name"); e2._OrtFree(i2); }, e.extractTransferableBuffers = (t2) => { const e2 = []; for (const n2 of t2) { const t3 = n2[2]; !Array.isArray(t3) && t3.buffer && e2.push(t3.buffer); } return e2; }; }, 6361: function(t, e, n) { "use strict"; var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2); var i2 = Object.getOwnPropertyDescriptor(e2, n2); i2 && !("get" in i2 ? !e2.__esModule : i2.writable || i2.configurable) || (i2 = { enumerable: true, get: function() { return e2[n2]; } }), Object.defineProperty(t2, r2, i2); } : function(t2, e2, n2, r2) { void 0 === r2 && (r2 = n2), t2[r2] = e2[n2]; }), i = this && this.__setModuleDefault || (Object.create ? function(t2, e2) { Object.defineProperty(t2, "default", { enumerable: true, value: e2 }); } : function(t2, e2) { t2.default = e2; }), o = this && this.__importStar || function(t2) { if (t2 && t2.__esModule) return t2; var e2 = {}; if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2); return i(e2, t2), e2; }, a = this && this.__importDefault || function(t2) { return t2 && t2.__esModule ? t2 : { default: t2 }; }; Object.defineProperty(e, "__esModule", { value: true }), e.dispose = e.getInstance = e.initializeWebAssembly = void 0; const s = o(n(6449)), u = a(n(932)), c = n(3474); let l, p = false, f = false, d = false; const h = (t2, e2) => e2 ? t2 ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-threaded.wasm" : t2 ? "ort-wasm-simd.wasm" : "ort-wasm.wasm"; e.initializeWebAssembly = async (t2) => { if (p) return Promise.resolve(); if (f) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); if (d) throw new Error("previous call to 'initializeWebAssembly()' failed."); f = true; const e2 = t2.initTimeout, r2 = t2.numThreads, i2 = t2.simd, o2 = r2 > 1 && (() => { try { return "undefined" != typeof SharedArrayBuffer && ("undefined" != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]))); } catch (t3) { return false; } })(), a2 = i2 && (() => { try { return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11])); } catch (t3) { return false; } })(), g = "string" == typeof t2.wasmPaths ? t2.wasmPaths : void 0, b = h(false, o2), m2 = h(a2, o2), y = "object" == typeof t2.wasmPaths ? t2.wasmPaths[m2] : void 0; let _ = false; const v = []; if (e2 > 0 && v.push(new Promise(((t3) => { setTimeout((() => { _ = true, t3(); }), e2); }))), v.push(new Promise(((t3, e3) => { const r3 = o2 ? c : u.default, i3 = { locateFile: (t4, e4) => o2 && t4.endsWith(".worker.js") && "undefined" != typeof Blob ? URL.createObjectURL(new Blob([n(4154)], { type: "text/javascript" })) : t4 === b ? null != y ? y : (null != g ? g : e4) + m2 : e4 + t4 }; if (o2) if ("undefined" == typeof Blob) i3.mainScriptUrlOrBlob = s.join("/", "ort-wasm-threaded.js"); else { const t4 = `var ortWasmThreaded=(function(){var _scriptDir;return ${r3.toString()}})();`; i3.mainScriptUrlOrBlob = new Blob([t4], { type: "text/javascript" }); } r3(i3).then(((e4) => { f = false, p = true, l = e4, t3(); }), ((t4) => { f = false, d = true, e3(t4); })); }))), await Promise.race(v), _) throw new Error(`WebAssembly backend initializing failed due to timeout: ${e2}ms`); }, e.getInstance = () => { if (p && l) return l; throw new Error("WebAssembly is not initialized yet."); }, e.dispose = () => { var t2; !p || f || d || (f = true, null === (t2 = l.PThread) || void 0 === t2 || t2.terminateAllThreads(), l = void 0, f = false, p = false, d = true); }; }, 9710: (t, e, n) => { "use strict"; n.d(e, { Z: () => o }); var r = n(477), i = n.n(r); function o() { return i()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n', "Worker", void 0, void 0); } }, 477: (t) => { "use strict"; t.exports = function(t2, e, n, r) { var i = self || window; try { try { var o; try { o = new i.Blob([t2]); } catch (e2) { (o = new (i.BlobBuilder || i.WebKitBlobBuilder || i.MozBlobBuilder || i.MSBlobBuilder)()).append(t2), o = o.getBlob(); } var a = i.URL || i.webkitURL, s = a.createObjectURL(o), u = new i[e](s, n); return a.revokeObjectURL(s), u; } catch (r2) { return new i[e]("data:application/javascript,".concat(encodeURIComponent(t2)), n); } } catch (t3) { if (!r) throw Error("Inline worker is not supported"); return new i[e](r, n); } }; }, 4154: (t) => { "use strict"; t.exports = '"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'; }, 1670: (t) => { "use strict"; t.exports = __WEBPACK_EXTERNAL_MODULE__1670__; }, 7067: () => { }, 1296: () => { }, 1384: () => { }, 3993: () => { }, 908: () => { }, 6953: () => { }, 9925: () => { }, 2806: () => { }, 6449: () => { }, 2850: () => { }, 5381: () => { }, 5686: (t, e, n) => { "use strict"; n.r(e), n.d(e, { flatbuffers: () => r }); var r = {}; r.Offset, r.Table, r.SIZEOF_SHORT = 2, r.SIZEOF_INT = 4, r.FILE_IDENTIFIER_LENGTH = 4, r.SIZE_PREFIX_LENGTH = 4, r.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }, r.int32 = new Int32Array(2), r.float32 = new Float32Array(r.int32.buffer), r.float64 = new Float64Array(r.int32.buffer), r.isLittleEndian = 1 === new Uint16Array(new Uint8Array([1, 0]).buffer)[0], r.Long = function(t2, e2) { this.low = 0 | t2, this.high = 0 | e2; }, r.Long.create = function(t2, e2) { return 0 == t2 && 0 == e2 ? r.Long.ZERO : new r.Long(t2, e2); }, r.Long.prototype.toFloat64 = function() { return (this.low >>> 0) + 4294967296 * this.high; }, r.Long.prototype.equals = function(t2) { return this.low == t2.low && this.high == t2.high; }, r.Long.ZERO = new r.Long(0, 0), r.Builder = function(t2) { if (t2) e2 = t2; else var e2 = 1024; this.bb = r.ByteBuffer.allocate(e2), this.space = e2, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }, r.Builder.prototype.clear = function() { this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }, r.Builder.prototype.forceDefaults = function(t2) { this.force_defaults = t2; }, r.Builder.prototype.dataBuffer = function() { return this.bb; }, r.Builder.prototype.asUint8Array = function() { return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); }, r.Builder.prototype.prep = function(t2, e2) { t2 > this.minalign && (this.minalign = t2); for (var n2 = 1 + ~(this.bb.capacity() - this.space + e2) & t2 - 1; this.space < n2 + t2 + e2; ) { var i = this.bb.capacity(); this.bb = r.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - i; } this.pad(n2); }, r.Builder.prototype.pad = function(t2) { for (var e2 = 0; e2 < t2; e2++) this.bb.writeInt8(--this.space, 0); }, r.Builder.prototype.writeInt8 = function(t2) { this.bb.writeInt8(this.space -= 1, t2); }, r.Builder.prototype.writeInt16 = function(t2) { this.bb.writeInt16(this.space -= 2, t2); }, r.Builder.prototype.writeInt32 = function(t2) { this.bb.writeInt32(this.space -= 4, t2); }, r.Builder.prototype.writeInt64 = function(t2) { this.bb.writeInt64(this.space -= 8, t2); }, r.Builder.prototype.writeFloat32 = function(t2) { this.bb.writeFloat32(this.space -= 4, t2); }, r.Builder.prototype.writeFloat64 = function(t2) { this.bb.writeFloat64(this.space -= 8, t2); }, r.Builder.prototype.addInt8 = function(t2) { this.prep(1, 0), this.writeInt8(t2); }, r.Builder.prototype.addInt16 = function(t2) { this.prep(2, 0), this.writeInt16(t2); }, r.Builder.prototype.addInt32 = function(t2) { this.prep(4, 0), this.writeInt32(t2); }, r.Builder.prototype.addInt64 = function(t2) { this.prep(8, 0), this.writeInt64(t2); }, r.Builder.prototype.addFloat32 = function(t2) { this.prep(4, 0), this.writeFloat32(t2); }, r.Builder.prototype.addFloat64 = function(t2) { this.prep(8, 0), this.writeFloat64(t2); }, r.Builder.prototype.addFieldInt8 = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addInt8(e2), this.slot(t2)); }, r.Builder.prototype.addFieldInt16 = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addInt16(e2), this.slot(t2)); }, r.Builder.prototype.addFieldInt32 = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addInt32(e2), this.slot(t2)); }, r.Builder.prototype.addFieldInt64 = function(t2, e2, n2) { !this.force_defaults && e2.equals(n2) || (this.addInt64(e2), this.slot(t2)); }, r.Builder.prototype.addFieldFloat32 = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addFloat32(e2), this.slot(t2)); }, r.Builder.prototype.addFieldFloat64 = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addFloat64(e2), this.slot(t2)); }, r.Builder.prototype.addFieldOffset = function(t2, e2, n2) { (this.force_defaults || e2 != n2) && (this.addOffset(e2), this.slot(t2)); }, r.Builder.prototype.addFieldStruct = function(t2, e2, n2) { e2 != n2 && (this.nested(e2), this.slot(t2)); }, r.Builder.prototype.nested = function(t2) { if (t2 != this.offset()) throw new Error("FlatBuffers: struct must be serialized inline."); }, r.Builder.prototype.notNested = function() { if (this.isNested) throw new Error("FlatBuffers: object serialization must not be nested."); }, r.Builder.prototype.slot = function(t2) { this.vtable[t2] = this.offset(); }, r.Builder.prototype.offset = function() { return this.bb.capacity() - this.space; }, r.Builder.growByteBuffer = function(t2) { var e2 = t2.capacity(); if (3221225472 & e2) throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); var n2 = e2 << 1, i = r.ByteBuffer.allocate(n2); return i.setPosition(n2 - e2), i.bytes().set(t2.bytes(), n2 - e2), i; }, r.Builder.prototype.addOffset = function(t2) { this.prep(r.SIZEOF_INT, 0), this.writeInt32(this.offset() - t2 + r.SIZEOF_INT); }, r.Builder.prototype.startObject = function(t2) { this.notNested(), null == this.vtable && (this.vtable = []), this.vtable_in_use = t2; for (var e2 = 0; e2 < t2; e2++) this.vtable[e2] = 0; this.isNested = true, this.object_start = this.offset(); }, r.Builder.prototype.endObject = function() { if (null == this.vtable || !this.isNested) throw new Error("FlatBuffers: endObject called without startObject"); this.addInt32(0); for (var t2 = this.offset(), e2 = this.vtable_in_use - 1; e2 >= 0 && 0 == this.vtable[e2]; e2--) ; for (var n2 = e2 + 1; e2 >= 0; e2--) this.addInt16(0 != this.vtable[e2] ? t2 - this.vtable[e2] : 0); this.addInt16(t2 - this.object_start); var i = (n2 + 2) * r.SIZEOF_SHORT; this.addInt16(i); var o = 0, a = this.space; t: for (e2 = 0; e2 < this.vtables.length; e2++) { var s = this.bb.capacity() - this.vtables[e2]; if (i == this.bb.readInt16(s)) { for (var u = r.SIZEOF_SHORT; u < i; u += r.SIZEOF_SHORT) if (this.bb.readInt16(a + u) != this.bb.readInt16(s + u)) continue t; o = this.vtables[e2]; break; } } return o ? (this.space = this.bb.capacity() - t2, this.bb.writeInt32(this.space, o - t2)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - t2, this.offset() - t2)), this.isNested = false, t2; }, r.Builder.prototype.finish = function(t2, e2, n2) { var i = n2 ? r.SIZE_PREFIX_LENGTH : 0; if (e2) { var o = e2; if (this.prep(this.minalign, r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH + i), o.length != r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH); for (var a = r.FILE_IDENTIFIER_LENGTH - 1; a >= 0; a--) this.writeInt8(o.charCodeAt(a)); } this.prep(this.minalign, r.SIZEOF_INT + i), this.addOffset(t2), i && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space); }, r.Builder.prototype.finishSizePrefixed = function(t2, e2) { this.finish(t2, e2, true); }, r.Builder.prototype.requiredField = function(t2, e2) { var n2 = this.bb.capacity() - t2, r2 = n2 - this.bb.readInt32(n2); if (0 == this.bb.readInt16(r2 + e2)) throw new Error("FlatBuffers: field " + e2 + " must be set"); }, r.Builder.prototype.startVector = function(t2, e2, n2) { this.notNested(), this.vector_num_elems = e2, this.prep(r.SIZEOF_INT, t2 * e2), this.prep(n2, t2 * e2); }, r.Builder.prototype.endVector = function() { return this.writeInt32(this.vector_num_elems), this.offset(); }, r.Builder.prototype.createString = function(t2) { if (t2 instanceof Uint8Array) var e2 = t2; else { e2 = []; for (var n2 = 0; n2 < t2.length; ) { var r2, i = t2.charCodeAt(n2++); (r2 = i < 55296 || i >= 56320 ? i : (i << 10) + t2.charCodeAt(n2++) + -56613888) < 128 ? e2.push(r2) : (r2 < 2048 ? e2.push(r2 >> 6 & 31 | 192) : (r2 < 65536 ? e2.push(r2 >> 12 & 15 | 224) : e2.push(r2 >> 18 & 7 | 240, r2 >> 12 & 63 | 128), e2.push(r2 >> 6 & 63 | 128)), e2.push(63 & r2 | 128)); } } this.addInt8(0), this.startVector(1, e2.length, 1), this.bb.setPosition(this.space -= e2.length), n2 = 0; for (var o = this.space, a = this.bb.bytes(); n2 < e2.length; n2++) a[o++] = e2[n2]; return this.endVector(); }, r.Builder.prototype.createLong = function(t2, e2) { return r.Long.create(t2, e2); }, r.ByteBuffer = function(t2) { this.bytes_ = t2, this.position_ = 0; }, r.ByteBuffer.allocate = function(t2) { return new r.ByteBuffer(new Uint8Array(t2)); }, r.ByteBuffer.prototype.clear = function() { this.position_ = 0; }, r.ByteBuffer.prototype.bytes = function() { return this.bytes_; }, r.ByteBuffer.prototype.position = function() { return this.position_; }, r.ByteBuffer.prototype.setPosition = function(t2) { this.position_ = t2; }, r.ByteBuffer.prototype.capacity = function() { return this.bytes_.length; }, r.ByteBuffer.prototype.readInt8 = function(t2) { return this.readUint8(t2) << 24 >> 24; }, r.ByteBuffer.prototype.readUint8 = function(t2) { return this.bytes_[t2]; }, r.ByteBuffer.prototype.readInt16 = function(t2) { return this.readUint16(t2) << 16 >> 16; }, r.ByteBuffer.prototype.readUint16 = function(t2) { return this.bytes_[t2] | this.bytes_[t2 + 1] << 8; }, r.ByteBuffer.prototype.readInt32 = function(t2) { return this.bytes_[t2] | this.bytes_[t2 + 1] << 8 | this.bytes_[t2 + 2] << 16 | this.bytes_[t2 + 3] << 24; }, r.ByteBuffer.prototype.readUint32 = function(t2) { return this.readInt32(t2) >>> 0; }, r.ByteBuffer.prototype.readInt64 = function(t2) { return new r.Long(this.readInt32(t2), this.readInt32(t2 + 4)); }, r.ByteBuffer.prototype.readUint64 = function(t2) { return new r.Long(this.readUint32(t2), this.readUint32(t2 + 4)); }, r.ByteBuffer.prototype.readFloat32 = function(t2) { return r.int32[0] = this.readInt32(t2), r.float32[0]; }, r.ByteBuffer.prototype.readFloat64 = function(t2) { return r.int32[r.isLittleEndian ? 0 : 1] = this.readInt32(t2), r.int32[r.isLittleEndian ? 1 : 0] = this.readInt32(t2 + 4), r.float64[0]; }, r.ByteBuffer.prototype.writeInt8 = function(t2, e2) { this.bytes_[t2] = e2; }, r.ByteBuffer.prototype.writeUint8 = function(t2, e2) { this.bytes_[t2] = e2; }, r.ByteBuffer.prototype.writeInt16 = function(t2, e2) { this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8; }, r.ByteBuffer.prototype.writeUint16 = function(t2, e2) { this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8; }, r.ByteBuffer.prototype.writeInt32 = function(t2, e2) { this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24; }, r.ByteBuffer.prototype.writeUint32 = function(t2, e2) { this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24; }, r.ByteBuffer.prototype.writeInt64 = function(t2, e2) { this.writeInt32(t2, e2.low), this.writeInt32(t2 + 4, e2.high); }, r.ByteBuffer.prototype.writeUint64 = function(t2, e2) { this.writeUint32(t2, e2.low), this.writeUint32(t2 + 4, e2.high); }, r.ByteBuffer.prototype.writeFloat32 = function(t2, e2) { r.float32[0] = e2, this.writeInt32(t2, r.int32[0]); }, r.ByteBuffer.prototype.writeFloat64 = function(t2, e2) { r.float64[0] = e2, this.writeInt32(t2, r.int32[r.isLittleEndian ? 0 : 1]), this.writeInt32(t2 + 4, r.int32[r.isLittleEndian ? 1 : 0]); }, r.ByteBuffer.prototype.getBufferIdentifier = function() { if (this.bytes_.length < this.position_ + r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier."); for (var t2 = "", e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) t2 += String.fromCharCode(this.readInt8(this.position_ + r.SIZEOF_INT + e2)); return t2; }, r.ByteBuffer.prototype.__offset = function(t2, e2) { var n2 = t2 - this.readInt32(t2); return e2 < this.readInt16(n2) ? this.readInt16(n2 + e2) : 0; }, r.ByteBuffer.prototype.__union = function(t2, e2) { return t2.bb_pos = e2 + this.readInt32(e2), t2.bb = this, t2; }, r.ByteBuffer.prototype.__string = function(t2, e2) { t2 += this.readInt32(t2); var n2 = this.readInt32(t2), i = "", o = 0; if (t2 += r.SIZEOF_INT, e2 === r.Encoding.UTF8_BYTES) return this.bytes_.subarray(t2, t2 + n2); for (; o < n2; ) { var a, s = this.readUint8(t2 + o++); if (s < 192) a = s; else { var u = this.readUint8(t2 + o++); if (s < 224) a = (31 & s) << 6 | 63 & u; else { var c = this.readUint8(t2 + o++); a = s < 240 ? (15 & s) << 12 | (63 & u) << 6 | 63 & c : (7 & s) << 18 | (63 & u) << 12 | (63 & c) << 6 | 63 & this.readUint8(t2 + o++); } } a < 65536 ? i += String.fromCharCode(a) : (a -= 65536, i += String.fromCharCode(55296 + (a >> 10), 56320 + (1023 & a))); } return i; }, r.ByteBuffer.prototype.__indirect = function(t2) { return t2 + this.readInt32(t2); }, r.ByteBuffer.prototype.__vector = function(t2) { return t2 + this.readInt32(t2) + r.SIZEOF_INT; }, r.ByteBuffer.prototype.__vector_len = function(t2) { return this.readInt32(t2 + this.readInt32(t2)); }, r.ByteBuffer.prototype.__has_identifier = function(t2) { if (t2.length != r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH); for (var e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) if (t2.charCodeAt(e2) != this.readInt8(this.position_ + r.SIZEOF_INT + e2)) return false; return true; }, r.ByteBuffer.prototype.createLong = function(t2, e2) { return r.Long.create(t2, e2); }; } }, __webpack_module_cache__ = {}; function __webpack_require__(t) { var e = __webpack_module_cache__[t]; if (void 0 !== e) return e.exports; var n = __webpack_module_cache__[t] = { exports: {} }; return __webpack_modules__[t].call(n.exports, n, n.exports, __webpack_require__), n.exports; } __webpack_require__.n = (t) => { var e = t && t.__esModule ? () => t.default : () => t; return __webpack_require__.d(e, { a: e }), e; }, __webpack_require__.d = (t, e) => { for (var n in e) __webpack_require__.o(e, n) && !__webpack_require__.o(t, n) && Object.defineProperty(t, n, { enumerable: true, get: e[n] }); }, __webpack_require__.g = (function() { if ("object" == typeof globalThis) return globalThis; try { return this || new Function("return this")(); } catch (t) { if ("object" == typeof window) return window; } })(), __webpack_require__.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), __webpack_require__.r = (t) => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: true }); }; var __webpack_exports__ = __webpack_require__(6018); return __webpack_exports__; })())); } }); // node_modules/@xenova/transformers/src/backends/onnx.js var ONNX_NODE, ONNX_WEB, ONNX, executionProviders; var init_onnx = __esm({ "node_modules/@xenova/transformers/src/backends/onnx.js"() { ONNX_NODE = __toESM(require_dist(), 1); ONNX_WEB = __toESM(require_ort_web_min(), 1); executionProviders = [ // 'webgpu', "wasm" ]; if (typeof process !== "undefined" && process?.release?.name === "node") { ONNX = ONNX_NODE.default ?? ONNX_NODE; executionProviders.unshift("cpu"); } else { ONNX = ONNX_WEB.default ?? ONNX_WEB; const isIOS = typeof navigator !== "undefined" && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent); if (isIOS) { ONNX.env.wasm.simd = false; } } } }); // node_modules/@xenova/transformers/src/env.js function isEmpty(obj) { return Object.keys(obj).length === 0; } var import_fs, import_path, import_url, onnx_env, VERSION, WEB_CACHE_AVAILABLE, FS_AVAILABLE, PATH_AVAILABLE, RUNNING_LOCALLY, __dirname, DEFAULT_CACHE_DIR, DEFAULT_LOCAL_MODEL_PATH, localModelPath, env; var init_env = __esm({ "node_modules/@xenova/transformers/src/env.js"() { import_fs = __toESM(require_fs(), 1); import_path = __toESM(require_path(), 1); import_url = __toESM(require_url(), 1); init_onnx(); ({ env: onnx_env } = ONNX); VERSION = "2.17.2"; WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self; FS_AVAILABLE = !isEmpty(import_fs.default); PATH_AVAILABLE = !isEmpty(import_path.default); RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE; __dirname = RUNNING_LOCALLY ? import_path.default.dirname(import_path.default.dirname(import_url.default.fileURLToPath(import.meta.url))) : "./"; DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/.cache/") : null; DEFAULT_LOCAL_MODEL_PATH = "/models/"; localModelPath = RUNNING_LOCALLY ? import_path.default.join(__dirname, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH; if (onnx_env?.wasm) { onnx_env.wasm.wasmPaths = RUNNING_LOCALLY ? import_path.default.join(__dirname, "/dist/") : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`; } env = { /////////////////// Backends settings /////////////////// backends: { // onnxruntime-web/onnxruntime-node onnx: onnx_env, // TensorFlow.js tfjs: {} }, __dirname, version: VERSION, /////////////////// Model settings /////////////////// allowRemoteModels: true, remoteHost: "https://huggingface.co/", remotePathTemplate: "{model}/resolve/{revision}/", allowLocalModels: true, localModelPath, useFS: FS_AVAILABLE, /////////////////// Cache settings /////////////////// useBrowserCache: WEB_CACHE_AVAILABLE, useFSCache: FS_AVAILABLE, cacheDir: DEFAULT_CACHE_DIR, useCustomCache: false, customCache: null ////////////////////////////////////////////////////// }; } }); // node_modules/@xenova/transformers/src/utils/hub.js function isValidUrl(string, protocols = null, validHosts = null) { let url2; try { url2 = new URL(string); } catch (_) { return false; } if (protocols && !protocols.includes(url2.protocol)) { return false; } if (validHosts && !validHosts.includes(url2.hostname)) { return false; } return true; } async function getFile(urlOrPath) { if (env.useFS && !isValidUrl(urlOrPath, ["http:", "https:", "blob:"])) { return new FileResponse(urlOrPath); } else if (typeof process !== "undefined" && process?.release?.name === "node") { const IS_CI = !!process.env?.TESTING_REMOTELY; const version = env.version; const headers = new Headers(); headers.set("User-Agent", `transformers.js/${version}; is_ci/${IS_CI};`); const isHFURL = isValidUrl(urlOrPath, ["http:", "https:"], ["huggingface.co", "hf.co"]); if (isHFURL) { const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; if (token) { headers.set("Authorization", `Bearer ${token}`); } } return fetch(urlOrPath, { headers }); } else { return fetch(urlOrPath); } } function handleError(status, remoteURL, fatal) { if (!fatal) { return null; } const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; throw Error(`${message}: "${remoteURL}".`); } async function tryCache(cache, ...names) { for (let name2 of names) { try { let result = await cache.match(name2); if (result) return result; } catch (e) { continue; } } return void 0; } async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) { if (!env.allowLocalModels) { if (options.local_files_only) { throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`)."); } else if (!env.allowRemoteModels) { throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`."); } } dispatchCallback(options.progress_callback, { status: "initiate", name: path_or_repo_id, file: filename }); let cache; if (!cache && env.useBrowserCache) { if (typeof caches === "undefined") { throw Error("Browser cache is not available in this environment."); } try { cache = await caches.open("transformers-cache"); } catch (e) { console.warn("An error occurred while opening the browser cache:", e); } } if (!cache && env.useFSCache) { cache = new FileCache(options.cache_dir ?? env.cacheDir); } if (!cache && env.useCustomCache) { if (!env.customCache) { throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined."); } if (!env.customCache.match || !env.customCache.put) { throw new Error( "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache" ); } cache = env.customCache; } const revision = options.revision ?? "main"; let requestURL = pathJoin(path_or_repo_id, filename); let localPath = pathJoin(env.localModelPath, requestURL); let remoteURL = pathJoin( env.remoteHost, env.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", encodeURIComponent(revision)), filename ); let fsCacheKey = revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename); let cacheKey; let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL; let toCacheResponse = false; let response; if (cache) { response = await tryCache(cache, localPath, proposedCacheKey); } const cacheHit = response !== void 0; if (response === void 0) { if (env.allowLocalModels) { const isURL = isValidUrl(requestURL, ["http:", "https:"]); if (!isURL) { try { response = await getFile(localPath); cacheKey = localPath; } catch (e) { console.warn(`Unable to load from local path "${localPath}": "${e}"`); } } else if (options.local_files_only) { throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); } else if (!env.allowRemoteModels) { throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`); } } if (response === void 0 || response.status === 404) { if (options.local_files_only || !env.allowRemoteModels) { if (fatal) { throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`); } else { return null; } } response = await getFile(remoteURL); if (response.status !== 200) { return handleError(response.status, remoteURL, fatal); } cacheKey = proposedCacheKey; } toCacheResponse = cache && typeof Response !== "undefined" && response instanceof Response && response.status === 200; } dispatchCallback(options.progress_callback, { status: "download", name: path_or_repo_id, file: filename }); const progressInfo = { status: "progress", name: path_or_repo_id, file: filename }; let buffer; if (!options.progress_callback) { buffer = new Uint8Array(await response.arrayBuffer()); } else if (cacheHit && typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) { buffer = new Uint8Array(await response.arrayBuffer()); dispatchCallback(options.progress_callback, { ...progressInfo, progress: 100, loaded: buffer.length, total: buffer.length }); } else { buffer = await readResponse(response, (data) => { dispatchCallback(options.progress_callback, { ...progressInfo, ...data }); }); } if ( // Only cache web responses // i.e., do not cache FileResponses (prevents duplication) toCacheResponse && cacheKey && // Check again whether request is in cache. If not, we add the response to the cache await cache.match(cacheKey) === void 0 ) { await cache.put(cacheKey, new Response(buffer, { headers: response.headers })).catch((err) => { console.warn(`Unable to add response to browser cache: ${err}.`); }); } dispatchCallback(options.progress_callback, { status: "done", name: path_or_repo_id, file: filename }); return buffer; } async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { let buffer = await getModelFile(modelPath, fileName, fatal, options); if (buffer === null) { return {}; } let decoder = new TextDecoder("utf-8"); let jsonData = decoder.decode(buffer); return JSON.parse(jsonData); } async function readResponse(response, progress_callback) { const contentLength = response.headers.get("Content-Length"); if (contentLength === null) { console.warn("Unable to determine content-length from response headers. Will expand buffer when needed."); } let total = parseInt(contentLength ?? "0"); let buffer = new Uint8Array(total); let loaded = 0; const reader = response.body.getReader(); async function read() { const { done, value } = await reader.read(); if (done) return; let newLoaded = loaded + value.length; if (newLoaded > total) { total = newLoaded; let newBuffer = new Uint8Array(total); newBuffer.set(buffer); buffer = newBuffer; } buffer.set(value, loaded); loaded = newLoaded; const progress = loaded / total * 100; progress_callback({ progress, loaded, total }); return read(); } await read(); return buffer; } function pathJoin(...parts) { parts = parts.map((part, index) => { if (index) { part = part.replace(new RegExp("^/"), ""); } if (index !== parts.length - 1) { part = part.replace(new RegExp("/$"), ""); } return part; }); return parts.join("/"); } var import_fs2, import_path2, FileResponse, ERROR_MAPPING, FileCache; var init_hub = __esm({ "node_modules/@xenova/transformers/src/utils/hub.js"() { import_fs2 = __toESM(require_fs(), 1); import_path2 = __toESM(require_path(), 1); init_env(); init_core(); FileResponse = class _FileResponse { /** * Mapping from file extensions to MIME types. */ _CONTENT_TYPE_MAP = { "txt": "text/plain", "html": "text/html", "css": "text/css", "js": "text/javascript", "json": "application/json", "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif" }; /** * Creates a new `FileResponse` object. * @param {string|URL} filePath */ constructor(filePath) { this.filePath = filePath; this.headers = new Headers(); this.exists = import_fs2.default.existsSync(filePath); if (this.exists) { this.status = 200; this.statusText = "OK"; let stats = import_fs2.default.statSync(filePath); this.headers.set("content-length", stats.size.toString()); this.updateContentType(); let self2 = this; this.body = new ReadableStream({ start(controller) { self2.arrayBuffer().then((buffer) => { controller.enqueue(new Uint8Array(buffer)); controller.close(); }); } }); } else { this.status = 404; this.statusText = "Not Found"; this.body = null; } } /** * Updates the 'content-type' header property of the response based on the extension of * the file specified by the filePath property of the current object. * @returns {void} */ updateContentType() { const extension = this.filePath.toString().split(".").pop().toLowerCase(); this.headers.set("content-type", this._CONTENT_TYPE_MAP[extension] ?? "application/octet-stream"); } /** * Clone the current FileResponse object. * @returns {FileResponse} A new FileResponse object with the same properties as the current object. */ clone() { let response = new _FileResponse(this.filePath); response.exists = this.exists; response.status = this.status; response.statusText = this.statusText; response.headers = new Headers(this.headers); return response; } /** * Reads the contents of the file specified by the filePath property and returns a Promise that * resolves with an ArrayBuffer containing the file's contents. * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. * @throws {Error} If the file cannot be read. */ async arrayBuffer() { const data = await import_fs2.default.promises.readFile(this.filePath); return data.buffer; } /** * Reads the contents of the file specified by the filePath property and returns a Promise that * resolves with a Blob containing the file's contents. * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. * @throws {Error} If the file cannot be read. */ async blob() { const data = await import_fs2.default.promises.readFile(this.filePath); return new Blob([data], { type: this.headers.get("content-type") }); } /** * Reads the contents of the file specified by the filePath property and returns a Promise that * resolves with a string containing the file's contents. * @returns {Promise} A Promise that resolves with a string containing the file's contents. * @throws {Error} If the file cannot be read. */ async text() { const data = await import_fs2.default.promises.readFile(this.filePath, "utf8"); return data; } /** * Reads the contents of the file specified by the filePath property and returns a Promise that * resolves with a parsed JavaScript object containing the file's contents. * * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. * @throws {Error} If the file cannot be read. */ async json() { return JSON.parse(await this.text()); } }; ERROR_MAPPING = { // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) 400: "Bad request error occurred while trying to load file", 401: "Unauthorized access to file", 403: "Forbidden access to file", 404: "Could not locate file", 408: "Request timeout error occurred while trying to load file", // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) 500: "Internal server error error occurred while trying to load file", 502: "Bad gateway error occurred while trying to load file", 503: "Service unavailable error occurred while trying to load file", 504: "Gateway timeout error occurred while trying to load file" }; FileCache = class { /** * Instantiate a `FileCache` object. * @param {string} path */ constructor(path3) { this.path = path3; } /** * Checks whether the given request is in the cache. * @param {string} request * @returns {Promise} */ async match(request) { let filePath = import_path2.default.join(this.path, request); let file = new FileResponse(filePath); if (file.exists) { return file; } else { return void 0; } } /** * Adds the given response to the cache. * @param {string} request * @param {Response|FileResponse} response * @returns {Promise} */ async put(request, response) { const buffer = Buffer.from(await response.arrayBuffer()); let outputPath = import_path2.default.join(this.path, request); try { await import_fs2.default.promises.mkdir(import_path2.default.dirname(outputPath), { recursive: true }); await import_fs2.default.promises.writeFile(outputPath, buffer); } catch (err) { console.warn("An error occurred while writing the file to cache:", err); } } // TODO add the rest? // addAll(requests: RequestInfo[]): Promise; // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; }; } }); // node_modules/@xenova/transformers/src/utils/maths.js function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = "bilinear", align_corners = false) { const x_scale = out_width / in_width; const y_scale = out_height / in_height; const out_img = new input.constructor(out_height * out_width * in_channels); const inStride = in_height * in_width; const outStride = out_height * out_width; for (let i = 0; i < out_height; ++i) { for (let j3 = 0; j3 < out_width; ++j3) { const outOffset = i * out_width + j3; const x2 = (j3 + 0.5) / x_scale - 0.5; const y = (i + 0.5) / y_scale - 0.5; let x1 = Math.floor(x2); let y1 = Math.floor(y); const x22 = Math.min(x1 + 1, in_width - 1); const y2 = Math.min(y1 + 1, in_height - 1); x1 = Math.max(x1, 0); y1 = Math.max(y1, 0); const s = x2 - x1; const t = y - y1; const w1 = (1 - s) * (1 - t); const w2 = s * (1 - t); const w3 = (1 - s) * t; const w4 = s * t; const yStride = y1 * in_width; const xStride = y2 * in_width; const idx1 = yStride + x1; const idx2 = yStride + x22; const idx3 = xStride + x1; const idx4 = xStride + x22; for (let k4 = 0; k4 < in_channels; ++k4) { const cOffset = k4 * inStride; out_img[k4 * outStride + outOffset] = w1 * input[cOffset + idx1] + w2 * input[cOffset + idx2] + w3 * input[cOffset + idx3] + w4 * input[cOffset + idx4]; } } } return out_img; } function permute_data(array, dims, axes) { const shape = new Array(axes.length); const stride = new Array(axes.length); for (let i = axes.length - 1, s = 1; i >= 0; --i) { stride[i] = s; shape[i] = dims[axes[i]]; s *= shape[i]; } const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); const permutedData = new array.constructor(array.length); for (let i = 0; i < array.length; ++i) { let newIndex = 0; for (let j3 = dims.length - 1, k4 = i; j3 >= 0; --j3) { newIndex += k4 % dims[j3] * invStride[j3]; k4 = Math.floor(k4 / dims[j3]); } permutedData[newIndex] = array[i]; } return [permutedData, shape]; } function softmax(arr) { const maxVal = max(arr)[0]; const exps = arr.map((x2) => Math.exp(x2 - maxVal)); const sumExps = exps.reduce((acc, val) => acc + val, 0); const softmaxArr = exps.map((x2) => x2 / sumExps); return ( /** @type {T} */ softmaxArr ); } function log_softmax(arr) { const softmaxArr = softmax(arr); const logSoftmaxArr = softmaxArr.map((x2) => Math.log(x2)); return ( /** @type {T} */ logSoftmaxArr ); } function getTopItems(items, top_k = 0) { items = Array.from(items).map((x2, i) => [i, x2]).sort((a, b) => b[1] - a[1]); if (top_k !== null && top_k > 0) { items = items.slice(0, top_k); } return items; } function min(arr) { if (arr.length === 0) throw Error("Array must not be empty"); let min2 = arr[0]; let indexOfMin = 0; for (let i = 1; i < arr.length; ++i) { if (arr[i] < min2) { min2 = arr[i]; indexOfMin = i; } } return [min2, indexOfMin]; } function max(arr) { if (arr.length === 0) throw Error("Array must not be empty"); let max2 = arr[0]; let indexOfMax = 0; for (let i = 1; i < arr.length; ++i) { if (arr[i] > max2) { max2 = arr[i]; indexOfMax = i; } } return [Number(max2), indexOfMax]; } function isPowerOfTwo(number) { return number > 0 && (number & number - 1) === 0; } function medianFilter(data, windowSize) { if (windowSize % 2 === 0 || windowSize <= 0) { throw new Error("Window size must be a positive odd number"); } const outputArray = new data.constructor(data.length); const buffer = new data.constructor(windowSize); const halfWindowSize = Math.floor(windowSize / 2); for (let i = 0; i < data.length; ++i) { let valuesIndex = 0; for (let j3 = -halfWindowSize; j3 <= halfWindowSize; ++j3) { let index = i + j3; if (index < 0) { index = Math.abs(index); } else if (index >= data.length) { index = 2 * (data.length - 1) - index; } buffer[valuesIndex++] = data[index]; } buffer.sort(); outputArray[i] = buffer[halfWindowSize]; } return outputArray; } function round(num, decimals) { const pow = Math.pow(10, decimals); return Math.round(num * pow) / pow; } function bankers_round(x2) { const r = Math.round(x2); const br4 = Math.abs(x2) % 1 === 0.5 ? r % 2 === 0 ? r : r - 1 : r; return br4; } var P2FFT, NP2FFT, FFT; var init_maths = __esm({ "node_modules/@xenova/transformers/src/utils/maths.js"() { P2FFT = class { /** * @param {number} size The size of the input array. Must be a power of two larger than 1. * @throws {Error} FFT size must be a power of two larger than 1. */ constructor(size) { this.size = size | 0; if (this.size <= 1 || !isPowerOfTwo(this.size)) throw new Error("FFT size must be a power of two larger than 1"); this._csize = size << 1; this.table = new Float64Array(this.size * 2); for (let i = 0; i < this.table.length; i += 2) { const angle = Math.PI * i / this.size; this.table[i] = Math.cos(angle); this.table[i + 1] = -Math.sin(angle); } let power = 0; for (let t = 1; this.size > t; t <<= 1) ++power; this._width = power % 2 === 0 ? power - 1 : power; this._bitrev = new Int32Array(1 << this._width); for (let j3 = 0; j3 < this._bitrev.length; ++j3) { this._bitrev[j3] = 0; for (let shift = 0; shift < this._width; shift += 2) { const revShift = this._width - shift - 2; this._bitrev[j3] |= (j3 >>> shift & 3) << revShift; } } } /** * Create a complex number array with size `2 * size` * * @returns {Float64Array} A complex number array with size `2 * size` */ createComplexArray() { return new Float64Array(this._csize); } /** * Converts a complex number representation stored in a Float64Array to an array of real numbers. * * @param {Float64Array} complex The complex number representation to be converted. * @param {number[]} [storage] An optional array to store the result in. * @returns {number[]} An array of real numbers representing the input complex number representation. */ fromComplexArray(complex, storage) { const res = storage || new Array(complex.length >>> 1); for (let i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i]; return res; } /** * Convert a real-valued input array to a complex-valued output array. * @param {Float64Array} input The real-valued input array. * @param {Float64Array} [storage] Optional buffer to store the output array. * @returns {Float64Array} The complex-valued output array. */ toComplexArray(input, storage) { const res = storage || this.createComplexArray(); for (let i = 0; i < res.length; i += 2) { res[i] = input[i >>> 1]; res[i + 1] = 0; } return res; } /** * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. * * @param {Float64Array} out The output buffer to store the result. * @param {Float64Array} data The input data to transform. * * @throws {Error} Input and output buffers must be different. * * @returns {void} */ transform(out, data) { if (out === data) throw new Error("Input and output buffers must be different"); this._transform4( out, data, 1 /* DONE */ ); } /** * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. * The input buffer must contain real values only, while the output buffer will contain complex values. The input and * output buffers must be different. * * @param {Float64Array} out The output buffer. * @param {Float64Array} data The input buffer containing real values. * * @throws {Error} If the input and output buffers are the same. */ realTransform(out, data) { if (out === data) throw new Error("Input and output buffers must be different"); this._realTransform4( out, data, 1 /* DONE */ ); } /** * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. * The `out` array must be a different buffer than the `data` array. The `out` array will contain the * result of the transformation. The `data` array will not be modified. * * @param {Float64Array} out The output buffer for the transformed data. * @param {Float64Array} data The input data to transform. * @throws {Error} If `out` and `data` refer to the same buffer. * @returns {void} */ inverseTransform(out, data) { if (out === data) throw new Error("Input and output buffers must be different"); this._transform4( out, data, -1 /* DONE */ ); for (let i = 0; i < out.length; ++i) out[i] /= this.size; } /** * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. * * @param {Float64Array} out The output buffer for the transformed data. * @param {Float64Array} data The input buffer of data to be transformed. * @param {number} inv A scaling factor to apply to the transform. * @returns {void} */ _transform4(out, data, inv) { const size = this._csize; const width = this._width; let step = 1 << width; let len = size / step << 1; let outOff; let t; const bitrev = this._bitrev; if (len === 4) { for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { const off = bitrev[t]; this._singleTransform2(data, out, outOff, off, step); } } else { for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { const off = bitrev[t]; this._singleTransform4(data, out, outOff, off, step, inv); } } const table = this.table; for (step >>= 2; step >= 2; step >>= 2) { len = size / step << 1; const quarterLen = len >>> 2; for (outOff = 0; outOff < size; outOff += len) { const limit = outOff + quarterLen - 1; for (let i = outOff, k4 = 0; i < limit; i += 2, k4 += step) { const A2 = i; const B3 = A2 + quarterLen; const C = B3 + quarterLen; const D3 = C + quarterLen; const Ar4 = out[A2]; const Ai3 = out[A2 + 1]; const Br4 = out[B3]; const Bi3 = out[B3 + 1]; const Cr4 = out[C]; const Ci3 = out[C + 1]; const Dr3 = out[D3]; const Di2 = out[D3 + 1]; const tableBr = table[k4]; const tableBi = inv * table[k4 + 1]; const MBr = Br4 * tableBr - Bi3 * tableBi; const MBi = Br4 * tableBi + Bi3 * tableBr; const tableCr = table[2 * k4]; const tableCi = inv * table[2 * k4 + 1]; const MCr = Cr4 * tableCr - Ci3 * tableCi; const MCi = Cr4 * tableCi + Ci3 * tableCr; const tableDr = table[3 * k4]; const tableDi = inv * table[3 * k4 + 1]; const MDr = Dr3 * tableDr - Di2 * tableDi; const MDi = Dr3 * tableDi + Di2 * tableDr; const T0r = Ar4 + MCr; const T0i = Ai3 + MCi; const T1r = Ar4 - MCr; const T1i = Ai3 - MCi; const T2r = MBr + MDr; const T2i = MBi + MDi; const T3r = inv * (MBr - MDr); const T3i = inv * (MBi - MDi); out[A2] = T0r + T2r; out[A2 + 1] = T0i + T2i; out[B3] = T1r + T3i; out[B3 + 1] = T1i - T3r; out[C] = T0r - T2r; out[C + 1] = T0i - T2i; out[D3] = T1r - T3i; out[D3 + 1] = T1i + T3r; } } } } /** * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. * * @param {Float64Array} data The input buffer of data to be transformed. * @param {Float64Array} out The output buffer for the transformed data. * @param {number} outOff The offset at which to write the output data. * @param {number} off The offset at which to begin reading the input data. * @param {number} step The step size for indexing the input data. * @returns {void} */ _singleTransform2(data, out, outOff, off, step) { const evenR = data[off]; const evenI = data[off + 1]; const oddR = data[off + step]; const oddI = data[off + step + 1]; out[outOff] = evenR + oddR; out[outOff + 1] = evenI + oddI; out[outOff + 2] = evenR - oddR; out[outOff + 3] = evenI - oddI; } /** * Performs radix-4 transformation on input data of length 8 * * @param {Float64Array} data Input data array of length 8 * @param {Float64Array} out Output data array of length 8 * @param {number} outOff Index of output array to start writing from * @param {number} off Index of input array to start reading from * @param {number} step Step size between elements in input array * @param {number} inv Scaling factor for inverse transform * * @returns {void} */ _singleTransform4(data, out, outOff, off, step, inv) { const step2 = step * 2; const step3 = step * 3; const Ar4 = data[off]; const Ai3 = data[off + 1]; const Br4 = data[off + step]; const Bi3 = data[off + step + 1]; const Cr4 = data[off + step2]; const Ci3 = data[off + step2 + 1]; const Dr3 = data[off + step3]; const Di2 = data[off + step3 + 1]; const T0r = Ar4 + Cr4; const T0i = Ai3 + Ci3; const T1r = Ar4 - Cr4; const T1i = Ai3 - Ci3; const T2r = Br4 + Dr3; const T2i = Bi3 + Di2; const T3r = inv * (Br4 - Dr3); const T3i = inv * (Bi3 - Di2); out[outOff] = T0r + T2r; out[outOff + 1] = T0i + T2i; out[outOff + 2] = T1r + T3i; out[outOff + 3] = T1i - T3r; out[outOff + 4] = T0r - T2r; out[outOff + 5] = T0i - T2i; out[outOff + 6] = T1r - T3i; out[outOff + 7] = T1i + T3r; } /** * Real input radix-4 implementation * @param {Float64Array} out Output array for the transformed data * @param {Float64Array} data Input array of real data to be transformed * @param {number} inv The scale factor used to normalize the inverse transform */ _realTransform4(out, data, inv) { const size = this._csize; const width = this._width; let step = 1 << width; let len = size / step << 1; let outOff; let t; const bitrev = this._bitrev; if (len === 4) { for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { const off = bitrev[t]; this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); } } else { for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { const off = bitrev[t]; this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); } } const table = this.table; for (step >>= 2; step >= 2; step >>= 2) { len = size / step << 1; const halfLen = len >>> 1; const quarterLen = halfLen >>> 1; const hquarterLen = quarterLen >>> 1; for (outOff = 0; outOff < size; outOff += len) { for (let i = 0, k4 = 0; i <= hquarterLen; i += 2, k4 += step) { const A2 = outOff + i; const B3 = A2 + quarterLen; const C = B3 + quarterLen; const D3 = C + quarterLen; const Ar4 = out[A2]; const Ai3 = out[A2 + 1]; const Br4 = out[B3]; const Bi3 = out[B3 + 1]; const Cr4 = out[C]; const Ci3 = out[C + 1]; const Dr3 = out[D3]; const Di2 = out[D3 + 1]; const MAr = Ar4; const MAi = Ai3; const tableBr = table[k4]; const tableBi = inv * table[k4 + 1]; const MBr = Br4 * tableBr - Bi3 * tableBi; const MBi = Br4 * tableBi + Bi3 * tableBr; const tableCr = table[2 * k4]; const tableCi = inv * table[2 * k4 + 1]; const MCr = Cr4 * tableCr - Ci3 * tableCi; const MCi = Cr4 * tableCi + Ci3 * tableCr; const tableDr = table[3 * k4]; const tableDi = inv * table[3 * k4 + 1]; const MDr = Dr3 * tableDr - Di2 * tableDi; const MDi = Dr3 * tableDi + Di2 * tableDr; const T0r = MAr + MCr; const T0i = MAi + MCi; const T1r = MAr - MCr; const T1i = MAi - MCi; const T2r = MBr + MDr; const T2i = MBi + MDi; const T3r = inv * (MBr - MDr); const T3i = inv * (MBi - MDi); out[A2] = T0r + T2r; out[A2 + 1] = T0i + T2i; out[B3] = T1r + T3i; out[B3 + 1] = T1i - T3r; if (i === 0) { out[C] = T0r - T2r; out[C + 1] = T0i - T2i; continue; } if (i === hquarterLen) continue; const SA = outOff + quarterLen - i; const SB = outOff + halfLen - i; out[SA] = T1r - inv * T3i; out[SA + 1] = -T1i - inv * T3r; out[SB] = T0r - inv * T2r; out[SB + 1] = -T0i + inv * T2i; } } } const half = size >>> 1; for (let i = 2; i < half; i += 2) { out[size - i] = out[i]; out[size - i + 1] = -out[i + 1]; } } /** * Performs a single real input radix-2 transformation on the provided data * * @param {Float64Array} data The input data array * @param {Float64Array} out The output data array * @param {number} outOff The output offset * @param {number} off The input offset * @param {number} step The step * * @returns {void} */ _singleRealTransform2(data, out, outOff, off, step) { const evenR = data[off]; const oddR = data[off + step]; out[outOff] = evenR + oddR; out[outOff + 1] = 0; out[outOff + 2] = evenR - oddR; out[outOff + 3] = 0; } /** * Computes a single real-valued transform using radix-4 algorithm. * This method is only called for len=8. * * @param {Float64Array} data The input data array. * @param {Float64Array} out The output data array. * @param {number} outOff The offset into the output array. * @param {number} off The offset into the input array. * @param {number} step The step size for the input array. * @param {number} inv The value of inverse. */ _singleRealTransform4(data, out, outOff, off, step, inv) { const step2 = step * 2; const step3 = step * 3; const Ar4 = data[off]; const Br4 = data[off + step]; const Cr4 = data[off + step2]; const Dr3 = data[off + step3]; const T0r = Ar4 + Cr4; const T1r = Ar4 - Cr4; const T2r = Br4 + Dr3; const T3r = inv * (Br4 - Dr3); out[outOff] = T0r + T2r; out[outOff + 1] = 0; out[outOff + 2] = T1r; out[outOff + 3] = -T3r; out[outOff + 4] = T0r - T2r; out[outOff + 5] = 0; out[outOff + 6] = T1r; out[outOff + 7] = T3r; } }; NP2FFT = class { /** * Constructs a new NP2FFT object. * @param {number} fft_length The length of the FFT */ constructor(fft_length) { const a = 2 * (fft_length - 1); const b = 2 * (2 * fft_length - 1); const nextP2 = 2 ** Math.ceil(Math.log2(b)); this.bufferSize = nextP2; this._a = a; const chirp = new Float64Array(b); const ichirp = new Float64Array(nextP2); this._chirpBuffer = new Float64Array(nextP2); this._buffer1 = new Float64Array(nextP2); this._buffer2 = new Float64Array(nextP2); this._outBuffer1 = new Float64Array(nextP2); this._outBuffer2 = new Float64Array(nextP2); const theta = -2 * Math.PI / fft_length; const baseR = Math.cos(theta); const baseI = Math.sin(theta); for (let i = 0; i < b >> 1; ++i) { const e = (i + 1 - fft_length) ** 2 / 2; const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; const result_arg = e * Math.atan2(baseI, baseR); const i2 = 2 * i; chirp[i2] = result_mod * Math.cos(result_arg); chirp[i2 + 1] = result_mod * Math.sin(result_arg); ichirp[i2] = chirp[i2]; ichirp[i2 + 1] = -chirp[i2 + 1]; } this._slicedChirpBuffer = chirp.subarray(a, b); this._f = new P2FFT(nextP2 >> 1); this._f.transform(this._chirpBuffer, ichirp); } _transform(output, input, real) { const ib1 = this._buffer1; const ib2 = this._buffer2; const ob2 = this._outBuffer1; const ob3 = this._outBuffer2; const cb2 = this._chirpBuffer; const sb2 = this._slicedChirpBuffer; const a = this._a; if (real) { for (let j3 = 0; j3 < sb2.length; j3 += 2) { const j22 = j3 + 1; const j32 = j3 >> 1; const a_real = input[j32]; ib1[j3] = a_real * sb2[j3]; ib1[j22] = a_real * sb2[j22]; } } else { for (let j3 = 0; j3 < sb2.length; j3 += 2) { const j22 = j3 + 1; ib1[j3] = input[j3] * sb2[j3] - input[j22] * sb2[j22]; ib1[j22] = input[j3] * sb2[j22] + input[j22] * sb2[j3]; } } this._f.transform(ob2, ib1); for (let j3 = 0; j3 < cb2.length; j3 += 2) { const j22 = j3 + 1; ib2[j3] = ob2[j3] * cb2[j3] - ob2[j22] * cb2[j22]; ib2[j22] = ob2[j3] * cb2[j22] + ob2[j22] * cb2[j3]; } this._f.inverseTransform(ob3, ib2); for (let j3 = 0; j3 < ob3.length; j3 += 2) { const a_real = ob3[j3 + a]; const a_imag = ob3[j3 + a + 1]; const b_real = sb2[j3]; const b_imag = sb2[j3 + 1]; output[j3] = a_real * b_real - a_imag * b_imag; output[j3 + 1] = a_real * b_imag + a_imag * b_real; } } transform(output, input) { this._transform(output, input, false); } realTransform(output, input) { this._transform(output, input, true); } }; FFT = class { constructor(fft_length) { this.fft_length = fft_length; this.isPowerOfTwo = isPowerOfTwo(fft_length); if (this.isPowerOfTwo) { this.fft = new P2FFT(fft_length); this.outputBufferSize = 2 * fft_length; } else { this.fft = new NP2FFT(fft_length); this.outputBufferSize = this.fft.bufferSize; } } realTransform(out, input) { this.fft.realTransform(out, input); } transform(out, input) { this.fft.transform(out, input); } }; } }); // node_modules/@xenova/transformers/src/utils/tensor.js function reshape(data, dimensions) { const totalElements = data.length; const dimensionSize = dimensions.reduce((a, b) => a * b); if (totalElements !== dimensionSize) { throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); } let reshapedArray = data; for (let i = dimensions.length - 1; i >= 0; i--) { reshapedArray = reshapedArray.reduce((acc, val) => { let lastArray = acc[acc.length - 1]; if (lastArray.length < dimensions[i]) { lastArray.push(val); } else { acc.push([val]); } return acc; }, [[]]); } return reshapedArray[0]; } function permute(tensor, axes) { const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes); return new Tensor(tensor.type, permutedData, shape); } function interpolate(input, [out_height, out_width], mode = "bilinear", align_corners = false) { const in_channels = input.dims.at(-3) ?? 1; const in_height = input.dims.at(-2); const in_width = input.dims.at(-1); let output = interpolate_data( /** @type {import('./maths.js').TypedArray}*/ input.data, [in_channels, in_height, in_width], [out_height, out_width], mode, align_corners ); return new Tensor(input.type, output, [in_channels, out_height, out_width]); } function mean_pooling(last_hidden_state, attention_mask) { let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]); let [batchSize, seqLength, embedDim] = last_hidden_state.dims; let outIndex = 0; for (let i = 0; i < batchSize; ++i) { let offset = i * embedDim * seqLength; for (let k4 = 0; k4 < embedDim; ++k4) { let sum = 0; let count = 0; let attnMaskOffset = i * seqLength; let offset2 = offset + k4; for (let j3 = 0; j3 < seqLength; ++j3) { let attn = Number(attention_mask.data[attnMaskOffset + j3]); count += attn; sum += last_hidden_state.data[offset2 + j3 * embedDim] * attn; } let avg = sum / count; returnedData[outIndex++] = avg; } } return new Tensor( last_hidden_state.type, returnedData, shape ); } function calc_squeeze_dims(dims, dim) { dims = dims.slice(); if (dim === null) { dims = dims.filter((d) => d !== 1); } else if (typeof dim === "number") { if (dims[dim] === 1) { dims.splice(dim, 1); } } else if (Array.isArray(dim)) { dims = dims.filter((x2, i) => { return x2 !== 1 || !dim.includes(i); }); } return dims; } function calc_unsqueeze_dims(dims, dim) { dim = safeIndex(dim, dims.length + 1); dims = dims.slice(); dims.splice(dim, 0, 1); return dims; } function safeIndex(index, size, dimension = null) { if (index < -size || index >= size) { throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}`); } if (index < 0) { index = (index % size + size) % size; } return index; } function cat(tensors, dim = 0) { dim = safeIndex(dim, tensors[0].dims.length); const resultDims = tensors[0].dims.slice(); resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); const resultSize = resultDims.reduce((a, b) => a * b, 1); const result = new tensors[0].data.constructor(resultSize); const resultType = tensors[0].type; if (dim === 0) { let offset = 0; for (let t of tensors) { result.set(t.data, offset); offset += t.data.length; } } else { let currentDim = 0; for (let t = 0; t < tensors.length; ++t) { let tensor = tensors[t]; for (let i = 0; i < tensor.data.length; ++i) { let resultIndex = 0; for (let j3 = tensor.dims.length - 1, num = i, resultMultiplier = 1; j3 >= 0; --j3) { const size = tensor.dims[j3]; let index = num % size; if (j3 === dim) { index += currentDim; } resultIndex += index * resultMultiplier; resultMultiplier *= resultDims[j3]; num = Math.floor(num / size); } result[resultIndex] = tensor.data[i]; } currentDim += tensor.dims[dim]; } } return new Tensor(resultType, result, resultDims); } function stack(tensors, dim = 0) { return cat(tensors.map((t) => t.unsqueeze(dim)), dim); } function std_mean(input, dim = null, correction = 1, keepdim = false) { if (dim === null) { const sum = input.data.reduce((a, b) => a + b, 0); const mean2 = sum / input.data.length; const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean2) ** 2, 0) / (input.data.length - correction)); const meanTensor2 = new Tensor(input.type, [mean2], [ /* scalar */ ]); const stdTensor2 = new Tensor(input.type, [std], [ /* scalar */ ]); return [stdTensor2, meanTensor2]; } dim = safeIndex(dim, input.dims.length); const meanTensor = mean(input, dim, keepdim); const resultDims = input.dims.slice(); resultDims[dim] = 1; const result = new input.data.constructor(input.data.length / input.dims[dim]); for (let i = 0; i < input.data.length; ++i) { let resultIndex = 0; for (let j3 = input.dims.length - 1, num = i, resultMultiplier = 1; j3 >= 0; --j3) { const size = input.dims[j3]; if (j3 !== dim) { const index = num % size; resultIndex += index * resultMultiplier; resultMultiplier *= resultDims[j3]; } num = Math.floor(num / size); } result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2; } for (let i = 0; i < result.length; ++i) { result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction)); } if (!keepdim) { resultDims.splice(dim, 1); } const stdTensor = new Tensor(input.type, result, resultDims); return [stdTensor, meanTensor]; } function mean(input, dim = null, keepdim = false) { if (dim === null) { let val = input.data.reduce((a, b) => a + b, 0); return new Tensor(input.type, [val / input.data.length], [ /* scalar */ ]); } dim = safeIndex(dim, input.dims.length); const resultDims = input.dims.slice(); resultDims[dim] = 1; const result = new input.data.constructor(input.data.length / input.dims[dim]); for (let i = 0; i < input.data.length; ++i) { let resultIndex = 0; for (let j3 = input.dims.length - 1, num = i, resultMultiplier = 1; j3 >= 0; --j3) { const size = input.dims[j3]; if (j3 !== dim) { const index = num % size; resultIndex += index * resultMultiplier; resultMultiplier *= resultDims[j3]; } num = Math.floor(num / size); } result[resultIndex] += input.data[i]; } if (input.dims[dim] !== 1) { for (let i = 0; i < result.length; ++i) { result[i] = result[i] / input.dims[dim]; } } if (!keepdim) { resultDims.splice(dim, 1); } return new Tensor(input.type, result, resultDims); } function dynamicTimeWarping(matrix) { const [output_length, input_length] = matrix.dims; const outputShape = [output_length + 1, input_length + 1]; const cost = new Tensor( "float32", new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity), outputShape ); const trace = new Tensor( "float32", new Float32Array(outputShape[0] * outputShape[1]).fill(-1), outputShape ); cost[0].data[0] = 0; for (let j4 = 1; j4 < input_length + 1; ++j4) { for (let i2 = 1; i2 < output_length + 1; ++i2) { const c0 = cost[i2 - 1][j4 - 1].item(); const c1 = cost[i2 - 1][j4].item(); const c2 = cost[i2][j4 - 1].item(); let c, t; if (c0 < c1 && c0 < c2) { c = c0; t = 0; } else if (c1 < c0 && c1 < c2) { c = c1; t = 1; } else { c = c2; t = 2; } cost[i2].data[j4] = matrix[i2 - 1][j4 - 1].item() + c; trace[i2].data[j4] = t; } } let i = output_length; let j3 = input_length; trace.data.fill(2, 0, outputShape[1]); for (let i2 = 0; i2 < outputShape[0]; ++i2) { trace[i2].data[0] = 1; } let text_indices = []; let time_indices = []; while (i > 0 || j3 > 0) { text_indices.push(i - 1); time_indices.push(j3 - 1); const t = trace[i][j3].item(); switch (t) { case 0: --i; --j3; break; case 1: --i; break; case 2: --j3; break; default: throw new Error( `Internal error in dynamic time warping. Unexpected trace[${i}, ${j3}]. Please file a bug report.` ); } } text_indices.reverse(); time_indices.reverse(); return [text_indices, time_indices]; } function dimsToStride(dims) { const stride = new Array(dims.length); for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { stride[i] = s2; s2 *= dims[i]; } return stride; } function ones(size) { const numElements = size.reduce((a, b) => a * b, 1); return new Tensor( "int64", new BigInt64Array(numElements).fill(1n), size ); } function ones_like(tensor) { return ones(tensor.dims); } function quantize_embeddings(tensor, precision) { if (tensor.dims.length !== 2) { throw new Error("The tensor must have 2 dimensions"); } if (tensor.dims.at(-1) % 8 !== 0) { throw new Error("The last dimension of the tensor must be a multiple of 8"); } if (!["binary", "ubinary"].includes(precision)) { throw new Error("The precision must be either 'binary' or 'ubinary'"); } const signed = precision === "binary"; const dtype = signed ? "int8" : "uint8"; const cls = signed ? Int8Array : Uint8Array; const inputData = tensor.data; const outputData = new cls(inputData.length / 8); for (let i = 0; i < inputData.length; ++i) { const bit = inputData[i] > 0 ? 1 : 0; const arrayIndex = Math.floor(i / 8); const bitPosition = i % 8; outputData[arrayIndex] |= bit << 7 - bitPosition; if (signed && bitPosition === 0) { outputData[arrayIndex] -= 128; } } ; return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]); } var DataTypeMap, ONNXTensor, Tensor; var init_tensor = __esm({ "node_modules/@xenova/transformers/src/utils/tensor.js"() { init_onnx(); init_maths(); DataTypeMap = Object.freeze({ float32: Float32Array, float64: Float64Array, string: Array, // string[] int8: Int8Array, uint8: Uint8Array, int16: Int16Array, uint16: Uint16Array, int32: Int32Array, uint32: Uint32Array, int64: BigInt64Array, uint64: BigUint64Array, bool: Uint8Array }); ONNXTensor = ONNX.Tensor; Tensor = class _Tensor { /** @type {number[]} Dimensions of the tensor. */ dims; /** @type {DataType} Type of the tensor. */ type; /** @type {DataArray} The data stored in the tensor. */ data; /** @type {number} The number of elements in the tensor. */ size; /** * Create a new Tensor or copy an existing Tensor. * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args */ constructor(...args) { if (args[0] instanceof ONNXTensor) { Object.assign(this, args[0]); } else { Object.assign(this, new ONNXTensor( /** @type {DataType} */ args[0], /** @type {Exclude} */ args[1], args[2] )); } return new Proxy(this, { get: (obj, key) => { if (typeof key === "string") { let index = Number(key); if (Number.isInteger(index)) { return obj._getitem(index); } } return obj[key]; }, set: (obj, key, value) => { return obj[key] = value; } }); } /** * Returns an iterator object for iterating over the tensor data in row-major order. * If the tensor has more than one dimension, the iterator will yield subarrays. * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. */ *[Symbol.iterator]() { const [iterLength, ...iterDims] = this.dims; if (iterDims.length > 0) { const iterSize = iterDims.reduce((a, b) => a * b); for (let i = 0; i < iterLength; ++i) { yield this._subarray(i, iterSize, iterDims); } } else { yield* this.data; } } /** * Index into a Tensor object. * @param {number} index The index to access. * @returns {Tensor} The data at the specified index. */ _getitem(index) { const [iterLength, ...iterDims] = this.dims; index = safeIndex(index, iterLength); if (iterDims.length > 0) { const iterSize = iterDims.reduce((a, b) => a * b); return this._subarray(index, iterSize, iterDims); } else { return new _Tensor(this.type, [this.data[index]], iterDims); } } /** * @param {number|bigint} item The item to search for in the tensor * @returns {number} The index of the first occurrence of item in the tensor data. */ indexOf(item) { for (let index = 0; index < this.data.length; ++index) { if (this.data[index] == item) { return index; } } return -1; } /** * @param {number} index * @param {number} iterSize * @param {any} iterDims * @returns {Tensor} */ _subarray(index, iterSize, iterDims) { const o1 = index * iterSize; const o2 = (index + 1) * iterSize; const data = "subarray" in this.data ? this.data.subarray(o1, o2) : this.data.slice(o1, o2); return new _Tensor(this.type, data, iterDims); } /** * Returns the value of this tensor as a standard JavaScript Number. This only works * for tensors with one element. For other cases, see `Tensor.tolist()`. * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. * @throws {Error} If the tensor has more than one element. */ item() { if (this.data.length !== 1) { throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`); } return this.data[0]; } /** * Convert tensor data to a n-dimensional JS list * @returns {Array} */ tolist() { return reshape(this.data, this.dims); } /** * Return a new Tensor with the sigmoid function applied to each element. * @returns {Tensor} The tensor with the sigmoid function applied. */ sigmoid() { return this.clone().sigmoid_(); } /** * Applies the sigmoid function to the tensor in place. * @returns {Tensor} Returns `this`. */ sigmoid_() { for (let i = 0; i < this.data.length; ++i) { this.data[i] = 1 / (1 + Math.exp(-this.data[i])); } return this; } /** * Return a new Tensor with every element multiplied by a constant. * @param {number} val The value to multiply by. * @returns {Tensor} The new tensor. */ mul(val) { return this.clone().mul_(val); } /** * Multiply the tensor by a constant in place. * @param {number} val The value to multiply by. * @returns {Tensor} Returns `this`. */ mul_(val) { for (let i = 0; i < this.data.length; ++i) { this.data[i] *= val; } return this; } /** * Return a new Tensor with every element added by a constant. * @param {number} val The value to add by. * @returns {Tensor} The new tensor. */ add(val) { return this.clone().add_(val); } /** * Add the tensor by a constant in place. * @param {number} val The value to add by. * @returns {Tensor} Returns `this`. */ add_(val) { for (let i = 0; i < this.data.length; ++i) { this.data[i] += val; } return this; } clone() { return new _Tensor(this.type, this.data.slice(), this.dims.slice()); } slice(...slices) { let newTensorDims = []; let newOffsets = []; for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { let slice2 = slices[sliceIndex]; if (slice2 === null || slice2 === void 0) { newOffsets.push([0, this.dims[sliceIndex]]); newTensorDims.push(this.dims[sliceIndex]); } else if (typeof slice2 === "number") { slice2 = safeIndex(slice2, this.dims[sliceIndex], sliceIndex); newOffsets.push([slice2, slice2 + 1]); } else if (Array.isArray(slice2) && slice2.length === 2) { if (slice2[0] > slice2[1]) { throw new Error(`Invalid slice: ${slice2}`); } let offsets = [ Math.max(slice2[0], 0), Math.min(slice2[1], this.dims[sliceIndex]) ]; newOffsets.push(offsets); newTensorDims.push(offsets[1] - offsets[0]); } else { throw new Error(`Invalid slice: ${slice2}`); } } let newDims = newOffsets.map(([start, end]) => end - start); let newBufferSize = newDims.reduce((a, b) => a * b); let data = new this.data.constructor(newBufferSize); const stride = this.stride(); for (let i = 0; i < newBufferSize; ++i) { let originalIndex = 0; for (let j3 = newDims.length - 1, num = i; j3 >= 0; --j3) { const size = newDims[j3]; originalIndex += (num % size + newOffsets[j3][0]) * stride[j3]; num = Math.floor(num / size); } data[i] = this.data[originalIndex]; } return new _Tensor(this.type, data, newTensorDims); } /** * Return a permuted version of this Tensor, according to the provided dimensions. * @param {...number} dims Dimensions to permute. * @returns {Tensor} The permuted tensor. */ permute(...dims) { return permute(this, dims); } // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute() transpose(...dims) { return this.permute(...dims); } // TODO add .max() and .min() methods /** * Returns the sum of each row of the input tensor in the given dimension dim. * * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. * @returns The summed tensor */ sum(dim = null, keepdim = false) { return this.norm(1, dim, keepdim); } /** * Returns the matrix norm or vector norm of a given tensor. * @param {number|string} [p='fro'] The order of norm * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. * If dim is None, the norm will be calculated across all dimensions of input. * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. * @returns {Tensor} The norm of the tensor. */ norm(p = "fro", dim = null, keepdim = false) { if (p === "fro") { p = 2; } else if (typeof p === "string") { throw Error(`Unsupported norm: ${p}`); } if (dim === null) { let val = this.data.reduce((a, b) => a + b ** p, 0) ** (1 / p); return new _Tensor(this.type, [val], []); } dim = safeIndex(dim, this.dims.length); const resultDims = this.dims.slice(); resultDims[dim] = 1; const result = new this.data.constructor(this.data.length / this.dims[dim]); for (let i = 0; i < this.data.length; ++i) { let resultIndex = 0; for (let j3 = this.dims.length - 1, num = i, resultMultiplier = 1; j3 >= 0; --j3) { const size = this.dims[j3]; if (j3 !== dim) { const index = num % size; resultIndex += index * resultMultiplier; resultMultiplier *= resultDims[j3]; } num = Math.floor(num / size); } result[resultIndex] += this.data[i] ** p; } if (p !== 1) { for (let i = 0; i < result.length; ++i) { result[i] = result[i] ** (1 / p); } } if (!keepdim) { resultDims.splice(dim, 1); } return new _Tensor(this.type, result, resultDims); } /** * Performs `L_p` normalization of inputs over specified dimension. Operates in place. * @param {number} [p=2] The exponent value in the norm formulation * @param {number} [dim=1] The dimension to reduce * @returns {Tensor} `this` for operation chaining. */ normalize_(p = 2, dim = 1) { dim = safeIndex(dim, this.dims.length); const norm = this.norm(p, dim, true); for (let i = 0; i < this.data.length; ++i) { let resultIndex = 0; for (let j3 = this.dims.length - 1, num = i, resultMultiplier = 1; j3 >= 0; --j3) { const size = this.dims[j3]; if (j3 !== dim) { const index = num % size; resultIndex += index * resultMultiplier; resultMultiplier *= this.dims[j3]; } num = Math.floor(num / size); } this.data[i] /= norm.data[resultIndex]; } return this; } /** * Performs `L_p` normalization of inputs over specified dimension. * @param {number} [p=2] The exponent value in the norm formulation * @param {number} [dim=1] The dimension to reduce * @returns {Tensor} The normalized tensor. */ normalize(p = 2, dim = 1) { return this.clone().normalize_(p, dim); } /** * Compute and return the stride of this tensor. * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. * @returns {number[]} The stride of this tensor. */ stride() { return dimsToStride(this.dims); } /** * Returns a tensor with all specified dimensions of input of size 1 removed. * * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. * If you would like a copy, use `tensor.clone()` before squeezing. * * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions. * @returns The squeezed tensor */ squeeze(dim = null) { return new _Tensor( this.type, this.data, calc_squeeze_dims(this.dims, dim) ); } /** * In-place version of @see {@link Tensor.squeeze} */ squeeze_(dim = null) { this.dims = calc_squeeze_dims(this.dims, dim); return this; } /** * Returns a new tensor with a dimension of size one inserted at the specified position. * * NOTE: The returned tensor shares the same underlying data with this tensor. * * @param {number} dim The index at which to insert the singleton dimension * @returns The unsqueezed tensor */ unsqueeze(dim = null) { return new _Tensor( this.type, this.data, calc_unsqueeze_dims(this.dims, dim) ); } /** * In-place version of @see {@link Tensor.unsqueeze} */ unsqueeze_(dim = null) { this.dims = calc_unsqueeze_dims(this.dims, dim); return this; } /** * In-place version of @see {@link Tensor.flatten} */ flatten_(start_dim = 0, end_dim = -1) { end_dim = (end_dim + this.dims.length) % this.dims.length; let dimsToKeepBefore = this.dims.slice(0, start_dim); let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); let dimsToKeepAfter = this.dims.slice(end_dim + 1); this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]; return this; } /** * Flattens input by reshaping it into a one-dimensional tensor. * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` * and ending with `end_dim` are flattened. The order of elements in input is unchanged. * @param {number} start_dim the first dim to flatten * @param {number} end_dim the last dim to flatten * @returns The flattened tensor. */ flatten(start_dim = 0, end_dim = -1) { return this.clone().flatten_(start_dim, end_dim); } /** * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. * @param {...number} dims the desired size * @returns {Tensor} The tensor with the same data but different shape */ view(...dims) { let inferredIndex = -1; for (let i = 0; i < dims.length; ++i) { if (dims[i] === -1) { if (inferredIndex !== -1) { throw new Error("Only one dimension can be inferred"); } inferredIndex = i; } } if (inferredIndex !== -1) { const productOther = dims.reduce((product2, curr, index) => { return index !== inferredIndex ? product2 * curr : product2; }, 1); dims[inferredIndex] = this.data.length / productOther; } return new _Tensor(this.type, this.data, dims); } neg_() { for (let i = 0; i < this.data.length; ++i) { this.data[i] = -this.data[i]; } return this; } neg() { return this.clone().neg_(); } /** * In-place version of @see {@link Tensor.clamp} */ clamp_(min2, max2) { for (let i = 0; i < this.data.length; ++i) { this.data[i] = Math.min(Math.max(this.data[i], min2), max2); } return this; } /** * Clamps all elements in input into the range [ min, max ] * @param {number} min lower-bound of the range to be clamped to * @param {number} max upper-bound of the range to be clamped to * @returns the output tensor. */ clamp(min2, max2) { return this.clone().clamp_(min2, max2); } /** * In-place version of @see {@link Tensor.round} */ round_() { for (let i = 0; i < this.data.length; ++i) { this.data[i] = Math.round(this.data[i]); } return this; } /** * Rounds elements of input to the nearest integer. * @returns the output tensor. */ round() { return this.clone().round_(); } /** * Performs Tensor dtype conversion. * @param {DataType} type The desired data type. * @returns {Tensor} The converted tensor. */ to(type) { if (this.type === type) return this; if (!DataTypeMap.hasOwnProperty(type)) { throw new Error(`Unsupported type: ${type}`); } return new _Tensor(type, DataTypeMap[type].from(this.data), this.dims); } }; } }); // node_modules/@xenova/transformers/src/utils/data-structures.js var PriorityQueue, CharTrie, CharTrieNode, TokenLattice, TokenLatticeNode; var init_data_structures = __esm({ "node_modules/@xenova/transformers/src/utils/data-structures.js"() { PriorityQueue = class { /** * Create a new PriorityQueue. * @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap. */ constructor(comparator = (a, b) => a > b) { this._heap = []; this._comparator = comparator; } /** * The size of the queue */ get size() { return this._heap.length; } /** * Check if the queue is empty. * @returns {boolean} `true` if the queue is empty, `false` otherwise. */ isEmpty() { return this.size === 0; } /** * Return the element with the highest priority in the queue. * @returns {any} The highest priority element in the queue. */ peek() { return this._heap[0]; } /** * Add one or more elements to the queue. * @param {...any} values The values to push into the queue. * @returns {number} The new size of the queue. */ push(...values) { return this.extend(values); } /** * Add multiple elements to the queue. * @param {any[]} values The values to push into the queue. * @returns {number} The new size of the queue. */ extend(values) { for (const value of values) { this._heap.push(value); this._siftUp(); } return this.size; } /** * Remove and return the element with the highest priority in the queue. * @returns {any} The element with the highest priority in the queue. */ pop() { const poppedValue = this.peek(); const bottom = this.size - 1; if (bottom > 0) { this._swap(0, bottom); } this._heap.pop(); this._siftDown(); return poppedValue; } /** * Replace the element with the highest priority in the queue with a new value. * @param {*} value The new value. * @returns {*} The replaced value. */ replace(value) { const replacedValue = this.peek(); this._heap[0] = value; this._siftDown(); return replacedValue; } /** * Compute the index for the parent of the node at index `i`. * @param {number} i The index of the node to get the parent of. * @returns {number} The index of the parent node. * @private */ _parent(i) { return (i + 1 >>> 1) - 1; } /** * Compute the index for the left child of the node at index `i`. * @param {number} i The index of the node to get the left child of. * @returns {number} The index of the left child. * @private */ _left(i) { return (i << 1) + 1; } /** * Compute the index for the right child of the node at index `i`. * @param {number} i The index of the node to get the right child of. * @returns {number} The index of the right child. * @private */ _right(i) { return i + 1 << 1; } /** * Check if the element at index `i` is greater than the element at index `j`. * @param {number} i The index of the first element to compare. * @param {number} j The index of the second element to compare. * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. * @private */ _greater(i, j3) { return this._comparator(this._heap[i], this._heap[j3]); } /** * Swap the elements at indices `i` and `j`. * @param {number} i The index of the first element to swap. * @param {number} j The index of the second element to swap. * @private */ _swap(i, j3) { const temp = this._heap[i]; this._heap[i] = this._heap[j3]; this._heap[j3] = temp; } /** * Maintain the heap property by updating positions in the heap, * starting at the last element and moving up the heap. * @private */ _siftUp() { let node = this.size - 1; while (node > 0 && this._greater(node, this._parent(node))) { this._swap(node, this._parent(node)); node = this._parent(node); } } /** * Maintain the heap property by updating positions in the heap, * starting at the first element and moving down the heap. * @private */ _siftDown() { let node = 0; while (this._left(node) < this.size && this._greater(this._left(node), node) || this._right(node) < this.size && this._greater(this._right(node), node)) { const maxChild = this._right(node) < this.size && this._greater(this._right(node), this._left(node)) ? this._right(node) : this._left(node); this._swap(node, maxChild); node = maxChild; } } }; CharTrie = class { constructor() { this.root = CharTrieNode.default(); } /** * Adds one or more `texts` to the trie. * @param {string[]} texts The strings to add to the trie. */ extend(texts) { for (let text of texts) { this.push(text); } } /** * Adds text to the trie. * @param {string} text The string to add to the trie. */ push(text) { let node = this.root; for (let ch2 of text) { let child = node.children.get(ch2); if (child === void 0) { child = CharTrieNode.default(); node.children.set(ch2, child); } node = child; } node.isLeaf = true; } /** * Searches the trie for all strings with a common prefix of `text`. * @param {string} text The common prefix to search for. * @yields {string} Each string in the trie that has `text` as a prefix. */ *commonPrefixSearch(text) { let node = this.root; let prefix = ""; for (let i = 0; i < text.length && node !== void 0; ++i) { const ch2 = text[i]; prefix += ch2; node = node.children.get(ch2); if (node !== void 0 && node.isLeaf) { yield prefix; } } } }; CharTrieNode = class _CharTrieNode { /** * Create a new CharTrieNode. * @param {boolean} isLeaf Whether the node is a leaf node or not. * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. */ constructor(isLeaf, children) { this.isLeaf = isLeaf; this.children = children; } /** * Returns a new `CharTrieNode` instance with default values. * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. */ static default() { return new _CharTrieNode(false, /* @__PURE__ */ new Map()); } }; TokenLattice = class { /** * Creates a new TokenLattice instance. * * @param {string} sentence The input sentence to be tokenized. * @param {number} bosTokenId The beginning-of-sequence token ID. * @param {number} eosTokenId The end-of-sequence token ID. */ constructor(sentence, bosTokenId, eosTokenId) { this.sentence = sentence; this.len = sentence.length; this.bosTokenId = bosTokenId; this.eosTokenId = eosTokenId; this.nodes = []; this.beginNodes = Array.from({ length: this.len + 1 }, () => []); this.endNodes = Array.from({ length: this.len + 1 }, () => []); const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0); const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0); this.nodes.push(bos.clone()); this.nodes.push(eos.clone()); this.beginNodes[this.len].push(eos); this.endNodes[0].push(bos); } /** * Inserts a new token node into the token lattice. * * @param {number} pos The starting position of the token. * @param {number} length The length of the token. * @param {number} score The score of the token. * @param {number} tokenId The token ID of the token. */ insert(pos, length, score, tokenId) { const nodeId = this.nodes.length; const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score); this.beginNodes[pos].push(node); this.endNodes[pos + length].push(node); this.nodes.push(node); } /** * Implements the Viterbi algorithm to compute the most likely sequence of tokens. * * @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens. */ viterbi() { const len = this.len; let pos = 0; while (pos <= len) { if (this.beginNodes[pos].length == 0) { return []; } for (let rnode of this.beginNodes[pos]) { rnode.prev = null; let bestScore = 0; let bestNode = null; for (let lnode of this.endNodes[pos]) { const score = lnode.backtraceScore + rnode.score; if (bestNode === null || score > bestScore) { bestNode = lnode.clone(); bestScore = score; } } if (bestNode !== null) { rnode.prev = bestNode; rnode.backtraceScore = bestScore; } else { return []; } } ++pos; } const results = []; const root = this.beginNodes[len][0]; const prev = root.prev; if (prev === null) { return []; } let node = prev.clone(); while (node.prev !== null) { results.push(node.clone()); const n = node.clone(); node = n.prev.clone(); } results.reverse(); return results; } /** * @param {TokenLatticeNode} node * @returns {string} The array of nodes representing the most likely sequence of tokens. */ piece(node) { return this.sentence.slice(node.pos, node.pos + node.length); } /** * @returns {Array} The array of nodes representing the most likely sequence of tokens. */ tokens() { const nodes = this.viterbi(); return nodes.map((x2) => this.piece(x2)); } /** * @returns {Array} The array of nodes representing the most likely sequence of tokens. */ tokenIds() { const nodes = this.viterbi(); return nodes.map((x2) => x2.tokenId); } }; TokenLatticeNode = class _TokenLatticeNode { /** * Represents a node in a token lattice for a given sentence. * @param {number} tokenId The ID of the token associated with this node. * @param {number} nodeId The ID of this node. * @param {number} pos The starting position of the token in the sentence. * @param {number} length The length of the token. * @param {number} score The score associated with the token. */ constructor(tokenId, nodeId, pos, length, score) { this.tokenId = tokenId; this.nodeId = nodeId; this.pos = pos; this.length = length; this.score = score; this.prev = null; this.backtraceScore = 0; } /** * Returns a clone of this node. * @returns {TokenLatticeNode} A clone of this node. */ clone() { const n = new _TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score); n.prev = this.prev; n.backtraceScore = this.backtraceScore; return n; } }; } }); // node_modules/@huggingface/jinja/dist/index.js function isWord(char) { return /\w/.test(char); } function isInteger(char) { return /[0-9]/.test(char); } function preprocess(template, options = {}) { if (template.endsWith("\n")) { template = template.slice(0, -1); } template = template.replace(/{#.*?#}/gs, "{##}"); if (options.lstrip_blocks) { template = template.replace(/^[ \t]*({[#%])/gm, "$1"); } if (options.trim_blocks) { template = template.replace(/([#%]})\n/g, "$1"); } return template.replace(/{##}/g, "").replace(/-%}\s*/g, "%}").replace(/\s*{%-/g, "{%").replace(/-}}\s*/g, "}}").replace(/\s*{{-/g, "{{"); } function tokenize(source, options = {}) { const tokens = []; const src = preprocess(source, options); let cursorPosition = 0; const consumeWhile = (predicate) => { let str = ""; while (predicate(src[cursorPosition])) { if (src[cursorPosition] === "\\") { ++cursorPosition; if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input"); const escaped = src[cursorPosition++]; const unescaped = ESCAPE_CHARACTERS.get(escaped); if (unescaped === void 0) { throw new SyntaxError(`Unexpected escaped character: ${escaped}`); } str += unescaped; continue; } str += src[cursorPosition++]; if (cursorPosition >= src.length) throw new SyntaxError("Unexpected end of input"); } return str; }; main: while (cursorPosition < src.length) { const lastTokenType = tokens.at(-1)?.type; if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) { let text = ""; while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{"))) { text += src[cursorPosition++]; } if (text.length > 0) { tokens.push(new Token(text, TOKEN_TYPES.Text)); continue; } } consumeWhile((char2) => /\s/.test(char2)); const char = src[cursorPosition]; if (char === "-" || char === "+") { const lastTokenType2 = tokens.at(-1)?.type; if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) { throw new SyntaxError(`Unexpected character: ${char}`); } switch (lastTokenType2) { case TOKEN_TYPES.Identifier: case TOKEN_TYPES.NumericLiteral: case TOKEN_TYPES.BooleanLiteral: case TOKEN_TYPES.StringLiteral: case TOKEN_TYPES.CloseParen: case TOKEN_TYPES.CloseSquareBracket: break; default: { ++cursorPosition; const num = consumeWhile(isInteger); tokens.push( new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator) ); continue; } } } for (const [char2, token] of ORDERED_MAPPING_TABLE) { const slice2 = src.slice(cursorPosition, cursorPosition + char2.length); if (slice2 === char2) { tokens.push(new Token(char2, token)); cursorPosition += char2.length; continue main; } } if (char === "'" || char === '"') { ++cursorPosition; const str = consumeWhile((c) => c !== char); tokens.push(new Token(str, TOKEN_TYPES.StringLiteral)); ++cursorPosition; continue; } if (isInteger(char)) { const num = consumeWhile(isInteger); tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral)); continue; } if (isWord(char)) { const word = consumeWhile(isWord); const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier; if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) { tokens.pop(); tokens.push(new Token("not in", TOKEN_TYPES.NotIn)); } else { tokens.push(new Token(word, type)); } continue; } throw new SyntaxError(`Unexpected character: ${char}`); } return tokens; } function parse(tokens) { const program = new Program([]); let current = 0; function expect(type, error) { const prev = tokens[current++]; if (!prev || prev.type !== type) { throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`); } return prev; } function parseAny() { switch (tokens[current].type) { case TOKEN_TYPES.Text: return parseText(); case TOKEN_TYPES.OpenStatement: return parseJinjaStatement(); case TOKEN_TYPES.OpenExpression: return parseJinjaExpression(); default: throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`); } } function not(...types) { return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type); } function is4(...types) { return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type); } function parseText() { return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value); } function parseJinjaStatement() { expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token"); let result; switch (tokens[current].type) { case TOKEN_TYPES.Set: ++current; result = parseSetStatement(); expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); break; case TOKEN_TYPES.If: ++current; result = parseIfStatement(); expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); expect(TOKEN_TYPES.EndIf, "Expected endif token"); expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); break; case TOKEN_TYPES.For: ++current; result = parseForStatement(); expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); expect(TOKEN_TYPES.EndFor, "Expected endfor token"); expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); break; default: throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`); } return result; } function parseJinjaExpression() { expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token"); const result = parseExpression(); expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token"); return result; } function parseSetStatement() { const left = parseExpression(); if (is4(TOKEN_TYPES.Equals)) { ++current; const value = parseSetStatement(); return new SetStatement(left, value); } return left; } function parseIfStatement() { const test = parseExpression(); expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); const body = []; const alternate = []; while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) { body.push(parseAny()); } if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) { ++current; if (is4(TOKEN_TYPES.ElseIf)) { expect(TOKEN_TYPES.ElseIf, "Expected elseif token"); alternate.push(parseIfStatement()); } else { expect(TOKEN_TYPES.Else, "Expected else token"); expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) { alternate.push(parseAny()); } } } return new If(test, body, alternate); } function parseExpressionSequence(primary = false) { const fn3 = primary ? parsePrimaryExpression : parseExpression; const expressions = [fn3()]; const isTuple = is4(TOKEN_TYPES.Comma); while (isTuple) { ++current; expressions.push(fn3()); if (!is4(TOKEN_TYPES.Comma)) { break; } } return isTuple ? new TupleLiteral(expressions) : expressions[0]; } function parseForStatement() { const loopVariable = parseExpressionSequence(true); if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) { throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`); } expect(TOKEN_TYPES.In, "Expected `in` keyword following loop variable"); const iterable = parseExpression(); expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); const body = []; while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) { body.push(parseAny()); } return new For(loopVariable, iterable, body); } function parseExpression() { return parseTernaryExpression(); } function parseTernaryExpression() { const a = parseLogicalOrExpression(); if (is4(TOKEN_TYPES.If)) { ++current; const predicate = parseLogicalOrExpression(); expect(TOKEN_TYPES.Else, "Expected else token"); const b = parseLogicalOrExpression(); return new If(predicate, [a], [b]); } return a; } function parseLogicalOrExpression() { let left = parseLogicalAndExpression(); while (is4(TOKEN_TYPES.Or)) { const operator = tokens[current]; ++current; const right = parseLogicalAndExpression(); left = new BinaryExpression(operator, left, right); } return left; } function parseLogicalAndExpression() { let left = parseLogicalNegationExpression(); while (is4(TOKEN_TYPES.And)) { const operator = tokens[current]; ++current; const right = parseLogicalNegationExpression(); left = new BinaryExpression(operator, left, right); } return left; } function parseLogicalNegationExpression() { let right; while (is4(TOKEN_TYPES.Not)) { const operator = tokens[current]; ++current; const arg = parseLogicalNegationExpression(); right = new UnaryExpression(operator, arg); } return right ?? parseComparisonExpression(); } function parseComparisonExpression() { let left = parseAdditiveExpression(); while (is4(TOKEN_TYPES.ComparisonBinaryOperator) || is4(TOKEN_TYPES.In) || is4(TOKEN_TYPES.NotIn)) { const operator = tokens[current]; ++current; const right = parseAdditiveExpression(); left = new BinaryExpression(operator, left, right); } return left; } function parseAdditiveExpression() { let left = parseMultiplicativeExpression(); while (is4(TOKEN_TYPES.AdditiveBinaryOperator)) { const operator = tokens[current]; ++current; const right = parseMultiplicativeExpression(); left = new BinaryExpression(operator, left, right); } return left; } function parseCallMemberExpression() { const member = parseMemberExpression(); if (is4(TOKEN_TYPES.OpenParen)) { return parseCallExpression(member); } return member; } function parseCallExpression(callee) { let callExpression = new CallExpression(callee, parseArgs()); if (is4(TOKEN_TYPES.OpenParen)) { callExpression = parseCallExpression(callExpression); } return callExpression; } function parseArgs() { expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list"); const args = parseArgumentsList(); expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"); return args; } function parseArgumentsList() { const args = []; while (!is4(TOKEN_TYPES.CloseParen)) { let argument = parseExpression(); if (is4(TOKEN_TYPES.Equals)) { ++current; if (!(argument instanceof Identifier)) { throw new SyntaxError(`Expected identifier for keyword argument`); } const value = parseExpression(); argument = new KeywordArgumentExpression(argument, value); } args.push(argument); if (is4(TOKEN_TYPES.Comma)) { ++current; } } return args; } function parseMemberExpressionArgumentsList() { const slices = []; let isSlice = false; while (!is4(TOKEN_TYPES.CloseSquareBracket)) { if (is4(TOKEN_TYPES.Colon)) { slices.push(void 0); ++current; isSlice = true; } else { slices.push(parseExpression()); if (is4(TOKEN_TYPES.Colon)) { ++current; isSlice = true; } } } if (slices.length === 0) { throw new SyntaxError(`Expected at least one argument for member/slice expression`); } if (isSlice) { if (slices.length > 3) { throw new SyntaxError(`Expected 0-3 arguments for slice expression`); } return new SliceExpression(...slices); } return slices[0]; } function parseMemberExpression() { let object = parsePrimaryExpression(); while (is4(TOKEN_TYPES.Dot) || is4(TOKEN_TYPES.OpenSquareBracket)) { const operator = tokens[current]; ++current; let property; const computed = operator.type !== TOKEN_TYPES.Dot; if (computed) { property = parseMemberExpressionArgumentsList(); expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket"); } else { property = parsePrimaryExpression(); if (property.type !== "Identifier") { throw new SyntaxError(`Expected identifier following dot operator`); } } object = new MemberExpression(object, property, computed); } return object; } function parseMultiplicativeExpression() { let left = parseTestExpression(); while (is4(TOKEN_TYPES.MultiplicativeBinaryOperator)) { const operator = tokens[current]; ++current; const right = parseTestExpression(); left = new BinaryExpression(operator, left, right); } return left; } function parseTestExpression() { let operand = parseFilterExpression(); while (is4(TOKEN_TYPES.Is)) { ++current; const negate = is4(TOKEN_TYPES.Not); if (negate) { ++current; } let filter = parsePrimaryExpression(); if (filter instanceof BooleanLiteral) { filter = new Identifier(filter.value.toString()); } if (!(filter instanceof Identifier)) { throw new SyntaxError(`Expected identifier for the test`); } operand = new TestExpression(operand, negate, filter); } return operand; } function parseFilterExpression() { let operand = parseCallMemberExpression(); while (is4(TOKEN_TYPES.Pipe)) { ++current; let filter = parsePrimaryExpression(); if (!(filter instanceof Identifier)) { throw new SyntaxError(`Expected identifier for the filter`); } if (is4(TOKEN_TYPES.OpenParen)) { filter = parseCallExpression(filter); } operand = new FilterExpression(operand, filter); } return operand; } function parsePrimaryExpression() { const token = tokens[current]; switch (token.type) { case TOKEN_TYPES.NumericLiteral: ++current; return new NumericLiteral(Number(token.value)); case TOKEN_TYPES.StringLiteral: ++current; return new StringLiteral(token.value); case TOKEN_TYPES.BooleanLiteral: ++current; return new BooleanLiteral(token.value === "true"); case TOKEN_TYPES.Identifier: ++current; return new Identifier(token.value); case TOKEN_TYPES.OpenParen: { ++current; const expression = parseExpressionSequence(); if (tokens[current].type !== TOKEN_TYPES.CloseParen) { throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`); } ++current; return expression; } case TOKEN_TYPES.OpenSquareBracket: { ++current; const values = []; while (!is4(TOKEN_TYPES.CloseSquareBracket)) { values.push(parseExpression()); if (is4(TOKEN_TYPES.Comma)) { ++current; } } ++current; return new ArrayLiteral(values); } case TOKEN_TYPES.OpenCurlyBracket: { ++current; const values = /* @__PURE__ */ new Map(); while (!is4(TOKEN_TYPES.CloseCurlyBracket)) { const key = parseExpression(); expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal"); const value = parseExpression(); values.set(key, value); if (is4(TOKEN_TYPES.Comma)) { ++current; } } ++current; return new ObjectLiteral(values); } default: throw new SyntaxError(`Unexpected token: ${token.type}`); } } while (current < tokens.length) { program.body.push(parseAny()); } return program; } function range(start, stop, step = 1) { if (stop === void 0) { stop = start; start = 0; } const result = []; for (let i = start; i < stop; i += step) { result.push(i); } return result; } function slice(array, start, stop, step = 1) { const direction = Math.sign(step); if (direction >= 0) { start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length); stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length); } else { start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1); stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1); } const result = []; for (let i = start; direction * i < direction * stop; i += step) { result.push(array[i]); } return result; } function titleCase(value) { return value.replace(/\b\w/g, (c) => c.toUpperCase()); } function convertToRuntimeValues(input) { switch (typeof input) { case "number": return new NumericValue(input); case "string": return new StringValue(input); case "boolean": return new BooleanValue(input); case "object": if (input === null) { return new NullValue(); } else if (Array.isArray(input)) { return new ArrayValue(input.map(convertToRuntimeValues)); } else { return new ObjectValue( new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])) ); } case "function": return new FunctionValue((args, _scope) => { const result = input(...args.map((x2) => x2.value)) ?? null; return convertToRuntimeValues(result); }); default: throw new Error(`Cannot convert to runtime value: ${input}`); } } var TOKEN_TYPES, KEYWORDS, Token, ORDERED_MAPPING_TABLE, ESCAPE_CHARACTERS, Statement, Program, If, For, SetStatement, Expression, MemberExpression, CallExpression, Identifier, Literal, NumericLiteral, StringLiteral, BooleanLiteral, ArrayLiteral, TupleLiteral, ObjectLiteral, BinaryExpression, FilterExpression, TestExpression, UnaryExpression, SliceExpression, KeywordArgumentExpression, RuntimeValue, NumericValue, StringValue, BooleanValue, ObjectValue, ArrayValue, TupleValue, FunctionValue, NullValue, UndefinedValue, Environment, Interpreter, Template; var init_dist = __esm({ "node_modules/@huggingface/jinja/dist/index.js"() { TOKEN_TYPES = Object.freeze({ Text: "Text", // The text between Jinja statements or expressions NumericLiteral: "NumericLiteral", // e.g., 123 BooleanLiteral: "BooleanLiteral", // true or false StringLiteral: "StringLiteral", // 'string' Identifier: "Identifier", // Variables, functions, etc. Equals: "Equals", // = OpenParen: "OpenParen", // ( CloseParen: "CloseParen", // ) OpenStatement: "OpenStatement", // {% CloseStatement: "CloseStatement", // %} OpenExpression: "OpenExpression", // {{ CloseExpression: "CloseExpression", // }} OpenSquareBracket: "OpenSquareBracket", // [ CloseSquareBracket: "CloseSquareBracket", // ] OpenCurlyBracket: "OpenCurlyBracket", // { CloseCurlyBracket: "CloseCurlyBracket", // } Comma: "Comma", // , Dot: "Dot", // . Colon: "Colon", // : Pipe: "Pipe", // | CallOperator: "CallOperator", // () AdditiveBinaryOperator: "AdditiveBinaryOperator", // + - MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator", // * / % ComparisonBinaryOperator: "ComparisonBinaryOperator", // < > <= >= == != UnaryOperator: "UnaryOperator", // ! - + // Keywords Set: "Set", If: "If", For: "For", In: "In", Is: "Is", NotIn: "NotIn", Else: "Else", EndIf: "EndIf", ElseIf: "ElseIf", EndFor: "EndFor", And: "And", Or: "Or", Not: "UnaryOperator" }); KEYWORDS = Object.freeze({ set: TOKEN_TYPES.Set, for: TOKEN_TYPES.For, in: TOKEN_TYPES.In, is: TOKEN_TYPES.Is, if: TOKEN_TYPES.If, else: TOKEN_TYPES.Else, endif: TOKEN_TYPES.EndIf, elif: TOKEN_TYPES.ElseIf, endfor: TOKEN_TYPES.EndFor, and: TOKEN_TYPES.And, or: TOKEN_TYPES.Or, not: TOKEN_TYPES.Not, "not in": TOKEN_TYPES.NotIn, // Literals true: TOKEN_TYPES.BooleanLiteral, false: TOKEN_TYPES.BooleanLiteral }); Token = class { /** * Constructs a new Token. * @param {string} value The raw value as seen inside the source code. * @param {TokenType} type The type of token. */ constructor(value, type) { this.value = value; this.type = type; } }; ORDERED_MAPPING_TABLE = [ // Control sequences ["{%", TOKEN_TYPES.OpenStatement], ["%}", TOKEN_TYPES.CloseStatement], ["{{", TOKEN_TYPES.OpenExpression], ["}}", TOKEN_TYPES.CloseExpression], // Single character tokens ["(", TOKEN_TYPES.OpenParen], [")", TOKEN_TYPES.CloseParen], ["{", TOKEN_TYPES.OpenCurlyBracket], ["}", TOKEN_TYPES.CloseCurlyBracket], ["[", TOKEN_TYPES.OpenSquareBracket], ["]", TOKEN_TYPES.CloseSquareBracket], [",", TOKEN_TYPES.Comma], [".", TOKEN_TYPES.Dot], [":", TOKEN_TYPES.Colon], ["|", TOKEN_TYPES.Pipe], // Comparison operators ["<=", TOKEN_TYPES.ComparisonBinaryOperator], [">=", TOKEN_TYPES.ComparisonBinaryOperator], ["==", TOKEN_TYPES.ComparisonBinaryOperator], ["!=", TOKEN_TYPES.ComparisonBinaryOperator], ["<", TOKEN_TYPES.ComparisonBinaryOperator], [">", TOKEN_TYPES.ComparisonBinaryOperator], // Arithmetic operators ["+", TOKEN_TYPES.AdditiveBinaryOperator], ["-", TOKEN_TYPES.AdditiveBinaryOperator], ["*", TOKEN_TYPES.MultiplicativeBinaryOperator], ["/", TOKEN_TYPES.MultiplicativeBinaryOperator], ["%", TOKEN_TYPES.MultiplicativeBinaryOperator], // Assignment operator ["=", TOKEN_TYPES.Equals] ]; ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([ ["n", "\n"], // New line ["t", " "], // Horizontal tab ["r", "\r"], // Carriage return ["b", "\b"], // Backspace ["f", "\f"], // Form feed ["v", "\v"], // Vertical tab ["'", "'"], // Single quote ['"', '"'], // Double quote ["\\", "\\"] // Backslash ]); Statement = class { type = "Statement"; }; Program = class extends Statement { constructor(body) { super(); this.body = body; } type = "Program"; }; If = class extends Statement { constructor(test, body, alternate) { super(); this.test = test; this.body = body; this.alternate = alternate; } type = "If"; }; For = class extends Statement { constructor(loopvar, iterable, body) { super(); this.loopvar = loopvar; this.iterable = iterable; this.body = body; } type = "For"; }; SetStatement = class extends Statement { constructor(assignee, value) { super(); this.assignee = assignee; this.value = value; } type = "Set"; }; Expression = class extends Statement { type = "Expression"; }; MemberExpression = class extends Expression { constructor(object, property, computed) { super(); this.object = object; this.property = property; this.computed = computed; } type = "MemberExpression"; }; CallExpression = class extends Expression { constructor(callee, args) { super(); this.callee = callee; this.args = args; } type = "CallExpression"; }; Identifier = class extends Expression { /** * @param {string} value The name of the identifier */ constructor(value) { super(); this.value = value; } type = "Identifier"; }; Literal = class extends Expression { constructor(value) { super(); this.value = value; } type = "Literal"; }; NumericLiteral = class extends Literal { type = "NumericLiteral"; }; StringLiteral = class extends Literal { type = "StringLiteral"; }; BooleanLiteral = class extends Literal { type = "BooleanLiteral"; }; ArrayLiteral = class extends Literal { type = "ArrayLiteral"; }; TupleLiteral = class extends Literal { type = "TupleLiteral"; }; ObjectLiteral = class extends Literal { type = "ObjectLiteral"; }; BinaryExpression = class extends Expression { constructor(operator, left, right) { super(); this.operator = operator; this.left = left; this.right = right; } type = "BinaryExpression"; }; FilterExpression = class extends Expression { constructor(operand, filter) { super(); this.operand = operand; this.filter = filter; } type = "FilterExpression"; }; TestExpression = class extends Expression { constructor(operand, negate, test) { super(); this.operand = operand; this.negate = negate; this.test = test; } type = "TestExpression"; }; UnaryExpression = class extends Expression { constructor(operator, argument) { super(); this.operator = operator; this.argument = argument; } type = "UnaryExpression"; }; SliceExpression = class extends Expression { constructor(start = void 0, stop = void 0, step = void 0) { super(); this.start = start; this.stop = stop; this.step = step; } type = "SliceExpression"; }; KeywordArgumentExpression = class extends Expression { constructor(key, value) { super(); this.key = key; this.value = value; } type = "KeywordArgumentExpression"; }; RuntimeValue = class { type = "RuntimeValue"; value; /** * A collection of built-in functions for this type. */ builtins = /* @__PURE__ */ new Map(); /** * Creates a new RuntimeValue. */ constructor(value = void 0) { this.value = value; } /** * Determines truthiness or falsiness of the runtime value. * This function should be overridden by subclasses if it has custom truthiness criteria. * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise. */ __bool__() { return new BooleanValue(!!this.value); } }; NumericValue = class extends RuntimeValue { type = "NumericValue"; }; StringValue = class extends RuntimeValue { type = "StringValue"; builtins = /* @__PURE__ */ new Map([ [ "upper", new FunctionValue(() => { return new StringValue(this.value.toUpperCase()); }) ], [ "lower", new FunctionValue(() => { return new StringValue(this.value.toLowerCase()); }) ], [ "strip", new FunctionValue(() => { return new StringValue(this.value.trim()); }) ], [ "title", new FunctionValue(() => { return new StringValue(titleCase(this.value)); }) ], ["length", new NumericValue(this.value.length)] ]); }; BooleanValue = class extends RuntimeValue { type = "BooleanValue"; }; ObjectValue = class extends RuntimeValue { type = "ObjectValue"; /** * NOTE: necessary to override since all JavaScript arrays are considered truthy, * while only non-empty Python arrays are consider truthy. * * e.g., * - JavaScript: {} && 5 -> 5 * - Python: {} and 5 -> {} */ __bool__() { return new BooleanValue(this.value.size > 0); } builtins = /* @__PURE__ */ new Map([ [ "get", new FunctionValue(([key, defaultValue]) => { if (!(key instanceof StringValue)) { throw new Error(`Object key must be a string: got ${key.type}`); } return this.value.get(key.value) ?? defaultValue ?? new NullValue(); }) ], [ "items", new FunctionValue(() => { return new ArrayValue( Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) ); }) ] ]); }; ArrayValue = class extends RuntimeValue { type = "ArrayValue"; builtins = /* @__PURE__ */ new Map([["length", new NumericValue(this.value.length)]]); /** * NOTE: necessary to override since all JavaScript arrays are considered truthy, * while only non-empty Python arrays are consider truthy. * * e.g., * - JavaScript: [] && 5 -> 5 * - Python: [] and 5 -> [] */ __bool__() { return new BooleanValue(this.value.length > 0); } }; TupleValue = class extends ArrayValue { type = "TupleValue"; }; FunctionValue = class extends RuntimeValue { type = "FunctionValue"; }; NullValue = class extends RuntimeValue { type = "NullValue"; }; UndefinedValue = class extends RuntimeValue { type = "UndefinedValue"; }; Environment = class { constructor(parent) { this.parent = parent; } /** * The variables declared in this environment. */ variables = /* @__PURE__ */ new Map([ [ "namespace", new FunctionValue((args) => { if (args.length === 0) { return new ObjectValue(/* @__PURE__ */ new Map()); } if (args.length !== 1 || !(args[0] instanceof ObjectValue)) { throw new Error("`namespace` expects either zero arguments or a single object argument"); } return args[0]; }) ] ]); /** * The tests available in this environment. */ tests = /* @__PURE__ */ new Map([ ["boolean", (operand) => operand.type === "BooleanValue"], ["callable", (operand) => operand instanceof FunctionValue], [ "odd", (operand) => { if (operand.type !== "NumericValue") { throw new Error(`Cannot apply test "odd" to type: ${operand.type}`); } return operand.value % 2 !== 0; } ], [ "even", (operand) => { if (operand.type !== "NumericValue") { throw new Error(`Cannot apply test "even" to type: ${operand.type}`); } return operand.value % 2 === 0; } ], ["false", (operand) => operand.type === "BooleanValue" && !operand.value], ["true", (operand) => operand.type === "BooleanValue" && operand.value], ["number", (operand) => operand.type === "NumericValue"], ["integer", (operand) => operand.type === "NumericValue" && Number.isInteger(operand.value)], ["iterable", (operand) => operand instanceof ArrayValue || operand instanceof StringValue], [ "lower", (operand) => { const str = operand.value; return operand.type === "StringValue" && str === str.toLowerCase(); } ], [ "upper", (operand) => { const str = operand.value; return operand.type === "StringValue" && str === str.toUpperCase(); } ], ["none", (operand) => operand.type === "NullValue"], ["defined", (operand) => operand.type !== "UndefinedValue"], ["undefined", (operand) => operand.type === "UndefinedValue"], ["equalto", (a, b) => a.value === b.value] ]); /** * Set the value of a variable in the current environment. */ set(name2, value) { return this.declareVariable(name2, convertToRuntimeValues(value)); } declareVariable(name2, value) { if (this.variables.has(name2)) { throw new SyntaxError(`Variable already declared: ${name2}`); } this.variables.set(name2, value); return value; } // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue { // const env = this.resolve(name); // env.variables.set(name, value); // return value; // } /** * Set variable in the current scope. * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information. */ setVariable(name2, value) { this.variables.set(name2, value); return value; } /** * Resolve the environment in which the variable is declared. * @param {string} name The name of the variable. * @returns {Environment} The environment in which the variable is declared. */ resolve(name2) { if (this.variables.has(name2)) { return this; } if (this.parent) { return this.parent.resolve(name2); } throw new Error(`Unknown variable: ${name2}`); } lookupVariable(name2) { try { return this.resolve(name2).variables.get(name2) ?? new UndefinedValue(); } catch { return new UndefinedValue(); } } }; Interpreter = class { global; constructor(env3) { this.global = env3 ?? new Environment(); } /** * Run the program. */ run(program) { return this.evaluate(program, this.global); } /** * Evaluates expressions following the binary operation type. */ evaluateBinaryExpression(node, environment) { const left = this.evaluate(node.left, environment); switch (node.operator.value) { case "and": return left.__bool__().value ? this.evaluate(node.right, environment) : left; case "or": return left.__bool__().value ? left : this.evaluate(node.right, environment); } const right = this.evaluate(node.right, environment); switch (node.operator.value) { case "==": return new BooleanValue(left.value == right.value); case "!=": return new BooleanValue(left.value != right.value); } if (left instanceof UndefinedValue || right instanceof UndefinedValue) { throw new Error("Cannot perform operation on undefined values"); } else if (left instanceof NullValue || right instanceof NullValue) { throw new Error("Cannot perform operation on null values"); } else if (left instanceof NumericValue && right instanceof NumericValue) { switch (node.operator.value) { case "+": return new NumericValue(left.value + right.value); case "-": return new NumericValue(left.value - right.value); case "*": return new NumericValue(left.value * right.value); case "/": return new NumericValue(left.value / right.value); case "%": return new NumericValue(left.value % right.value); case "<": return new BooleanValue(left.value < right.value); case ">": return new BooleanValue(left.value > right.value); case ">=": return new BooleanValue(left.value >= right.value); case "<=": return new BooleanValue(left.value <= right.value); } } else if (left instanceof ArrayValue && right instanceof ArrayValue) { switch (node.operator.value) { case "+": return new ArrayValue(left.value.concat(right.value)); } } else if (right instanceof ArrayValue) { const member = right.value.find((x2) => x2.value === left.value) !== void 0; switch (node.operator.value) { case "in": return new BooleanValue(member); case "not in": return new BooleanValue(!member); } } if (left instanceof StringValue || right instanceof StringValue) { switch (node.operator.value) { case "+": return new StringValue(left.value.toString() + right.value.toString()); } } if (left instanceof StringValue && right instanceof StringValue) { switch (node.operator.value) { case "in": return new BooleanValue(right.value.includes(left.value)); case "not in": return new BooleanValue(!right.value.includes(left.value)); } } if (left instanceof StringValue && right instanceof ObjectValue) { switch (node.operator.value) { case "in": return new BooleanValue(right.value.has(left.value)); case "not in": return new BooleanValue(!right.value.has(left.value)); } } throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`); } /** * Evaluates expressions following the filter operation type. */ evaluateFilterExpression(node, environment) { const operand = this.evaluate(node.operand, environment); if (node.filter.type === "Identifier") { const filter = node.filter; if (operand instanceof ArrayValue) { switch (filter.value) { case "list": return operand; case "first": return operand.value[0]; case "last": return operand.value[operand.value.length - 1]; case "length": return new NumericValue(operand.value.length); case "reverse": return new ArrayValue(operand.value.reverse()); case "sort": return new ArrayValue( operand.value.sort((a, b) => { if (a.type !== b.type) { throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`); } switch (a.type) { case "NumericValue": return a.value - b.value; case "StringValue": return a.value.localeCompare(b.value); default: throw new Error(`Cannot compare type: ${a.type}`); } }) ); default: throw new Error(`Unknown ArrayValue filter: ${filter.value}`); } } else if (operand instanceof StringValue) { switch (filter.value) { case "length": return new NumericValue(operand.value.length); case "upper": return new StringValue(operand.value.toUpperCase()); case "lower": return new StringValue(operand.value.toLowerCase()); case "title": return new StringValue(titleCase(operand.value)); case "capitalize": return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1)); case "trim": return new StringValue(operand.value.trim()); default: throw new Error(`Unknown StringValue filter: ${filter.value}`); } } else if (operand instanceof NumericValue) { switch (filter.value) { case "abs": return new NumericValue(Math.abs(operand.value)); default: throw new Error(`Unknown NumericValue filter: ${filter.value}`); } } else if (operand instanceof ObjectValue) { switch (filter.value) { case "items": return new ArrayValue( Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) ); case "length": return new NumericValue(operand.value.size); default: throw new Error(`Unknown ObjectValue filter: ${filter.value}`); } } throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`); } else if (node.filter.type === "CallExpression") { const filter = node.filter; if (filter.callee.type !== "Identifier") { throw new Error(`Unknown filter: ${filter.callee.type}`); } const filterName = filter.callee.value; if (operand instanceof ArrayValue) { switch (filterName) { case "selectattr": { if (operand.value.some((x2) => !(x2 instanceof ObjectValue))) { throw new Error("`selectattr` can only be applied to array of objects"); } if (filter.args.some((x2) => x2.type !== "StringLiteral")) { throw new Error("arguments of `selectattr` must be strings"); } const [attr, testName, value] = filter.args.map((x2) => this.evaluate(x2, environment)); let testFunction; if (testName) { const test = environment.tests.get(testName.value); if (!test) { throw new Error(`Unknown test: ${testName.value}`); } testFunction = test; } else { testFunction = (...x2) => x2[0].__bool__().value; } const filtered = operand.value.filter((item) => { const a = item.value.get(attr.value); if (a) { return testFunction(a, value); } return false; }); return new ArrayValue(filtered); } } throw new Error(`Unknown ArrayValue filter: ${filterName}`); } else { throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); } } throw new Error(`Unknown filter: ${node.filter.type}`); } /** * Evaluates expressions following the test operation type. */ evaluateTestExpression(node, environment) { const operand = this.evaluate(node.operand, environment); const test = environment.tests.get(node.test.value); if (!test) { throw new Error(`Unknown test: ${node.test.value}`); } const result = test(operand); return new BooleanValue(node.negate ? !result : result); } /** * Evaluates expressions following the unary operation type. */ evaluateUnaryExpression(node, environment) { const argument = this.evaluate(node.argument, environment); switch (node.operator.value) { case "not": return new BooleanValue(!argument.value); default: throw new SyntaxError(`Unknown operator: ${node.operator.value}`); } } evalProgram(program, environment) { return this.evaluateBlock(program.body, environment); } evaluateBlock(statements, environment) { let result = ""; for (const statement of statements) { const lastEvaluated = this.evaluate(statement, environment); if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") { result += lastEvaluated.value; } } return new StringValue(result); } evaluateIdentifier(node, environment) { return environment.lookupVariable(node.value); } evaluateCallExpression(expr, environment) { const args = []; const kwargs = /* @__PURE__ */ new Map(); for (const argument of expr.args) { if (argument.type === "KeywordArgumentExpression") { const kwarg = argument; kwargs.set(kwarg.key.value, this.evaluate(kwarg.value, environment)); } else { args.push(this.evaluate(argument, environment)); } } if (kwargs.size > 0) { args.push(new ObjectValue(kwargs)); } const fn3 = this.evaluate(expr.callee, environment); if (fn3.type !== "FunctionValue") { throw new Error(`Cannot call something that is not a function: got ${fn3.type}`); } return fn3.value(args, environment); } evaluateSliceExpression(object, expr, environment) { if (!(object instanceof ArrayValue || object instanceof StringValue)) { throw new Error("Slice object must be an array or string"); } const start = this.evaluate(expr.start, environment); const stop = this.evaluate(expr.stop, environment); const step = this.evaluate(expr.step, environment); if (!(start instanceof NumericValue || start instanceof UndefinedValue)) { throw new Error("Slice start must be numeric or undefined"); } if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) { throw new Error("Slice stop must be numeric or undefined"); } if (!(step instanceof NumericValue || step instanceof UndefinedValue)) { throw new Error("Slice step must be numeric or undefined"); } if (object instanceof ArrayValue) { return new ArrayValue(slice(object.value, start.value, stop.value, step.value)); } else { return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join("")); } } evaluateMemberExpression(expr, environment) { const object = this.evaluate(expr.object, environment); let property; if (expr.computed) { if (expr.property.type === "SliceExpression") { return this.evaluateSliceExpression(object, expr.property, environment); } else { property = this.evaluate(expr.property, environment); } } else { property = new StringValue(expr.property.value); } let value; if (object instanceof ObjectValue) { if (!(property instanceof StringValue)) { throw new Error(`Cannot access property with non-string: got ${property.type}`); } value = object.value.get(property.value) ?? object.builtins.get(property.value); } else if (object instanceof ArrayValue || object instanceof StringValue) { if (property instanceof NumericValue) { value = object.value.at(property.value); if (object instanceof StringValue) { value = new StringValue(object.value.at(property.value)); } } else if (property instanceof StringValue) { value = object.builtins.get(property.value); } else { throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`); } } else { if (!(property instanceof StringValue)) { throw new Error(`Cannot access property with non-string: got ${property.type}`); } value = object.builtins.get(property.value); } return value instanceof RuntimeValue ? value : new UndefinedValue(); } evaluateSet(node, environment) { const rhs = this.evaluate(node.value, environment); if (node.assignee.type === "Identifier") { const variableName = node.assignee.value; environment.setVariable(variableName, rhs); } else if (node.assignee.type === "MemberExpression") { const member = node.assignee; const object = this.evaluate(member.object, environment); if (!(object instanceof ObjectValue)) { throw new Error("Cannot assign to member of non-object"); } if (member.property.type !== "Identifier") { throw new Error("Cannot assign to member with non-identifier property"); } object.value.set(member.property.value, rhs); } else { throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`); } return new NullValue(); } evaluateIf(node, environment) { const test = this.evaluate(node.test, environment); return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment); } evaluateFor(node, environment) { const scope = new Environment(environment); const iterable = this.evaluate(node.iterable, scope); if (!(iterable instanceof ArrayValue)) { throw new Error(`Expected iterable type in for loop: got ${iterable.type}`); } let result = ""; for (let i = 0; i < iterable.value.length; ++i) { const loop = /* @__PURE__ */ new Map([ ["index", new NumericValue(i + 1)], ["index0", new NumericValue(i)], ["revindex", new NumericValue(iterable.value.length - i)], ["revindex0", new NumericValue(iterable.value.length - i - 1)], ["first", new BooleanValue(i === 0)], ["last", new BooleanValue(i === iterable.value.length - 1)], ["length", new NumericValue(iterable.value.length)], ["previtem", i > 0 ? iterable.value[i - 1] : new UndefinedValue()], ["nextitem", i < iterable.value.length - 1 ? iterable.value[i + 1] : new UndefinedValue()] ]); scope.setVariable("loop", new ObjectValue(loop)); const current = iterable.value[i]; if (node.loopvar.type === "Identifier") { scope.setVariable(node.loopvar.value, current); } else if (node.loopvar.type === "TupleLiteral") { const loopvar = node.loopvar; if (current.type !== "ArrayValue") { throw new Error(`Cannot unpack non-iterable type: ${current.type}`); } const c = current; if (loopvar.value.length !== c.value.length) { throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`); } for (let j3 = 0; j3 < loopvar.value.length; ++j3) { if (loopvar.value[j3].type !== "Identifier") { throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j3].type}`); } scope.setVariable(loopvar.value[j3].value, c.value[j3]); } } const evaluated = this.evaluateBlock(node.body, scope); result += evaluated.value; } return new StringValue(result); } evaluate(statement, environment) { if (statement === void 0) return new UndefinedValue(); switch (statement.type) { case "Program": return this.evalProgram(statement, environment); case "Set": return this.evaluateSet(statement, environment); case "If": return this.evaluateIf(statement, environment); case "For": return this.evaluateFor(statement, environment); case "NumericLiteral": return new NumericValue(Number(statement.value)); case "StringLiteral": return new StringValue(statement.value); case "BooleanLiteral": return new BooleanValue(statement.value); case "ArrayLiteral": return new ArrayValue(statement.value.map((x2) => this.evaluate(x2, environment))); case "TupleLiteral": return new TupleValue(statement.value.map((x2) => this.evaluate(x2, environment))); case "ObjectLiteral": { const mapping = /* @__PURE__ */ new Map(); for (const [key, value] of statement.value) { const evaluatedKey = this.evaluate(key, environment); if (!(evaluatedKey instanceof StringValue)) { throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`); } mapping.set(evaluatedKey.value, this.evaluate(value, environment)); } return new ObjectValue(mapping); } case "Identifier": return this.evaluateIdentifier(statement, environment); case "CallExpression": return this.evaluateCallExpression(statement, environment); case "MemberExpression": return this.evaluateMemberExpression(statement, environment); case "UnaryExpression": return this.evaluateUnaryExpression(statement, environment); case "BinaryExpression": return this.evaluateBinaryExpression(statement, environment); case "FilterExpression": return this.evaluateFilterExpression(statement, environment); case "TestExpression": return this.evaluateTestExpression(statement, environment); default: throw new SyntaxError(`Unknown node type: ${statement.type}`); } } }; Template = class { parsed; /** * @param {string} template The template string */ constructor(template) { const tokens = tokenize(template, { lstrip_blocks: true, trim_blocks: true }); this.parsed = parse(tokens); } render(items) { const env3 = new Environment(); env3.set("false", false); env3.set("true", true); env3.set("raise_exception", (args) => { throw new Error(args); }); env3.set("range", range); for (const [key, value] of Object.entries(items)) { env3.set(key, value); } const interpreter = new Interpreter(env3); const result = interpreter.run(this.parsed); return result.value; } }; } }); // node_modules/@xenova/transformers/src/tokenizers.js async function loadTokenizer(pretrained_model_name_or_path, options) { const info = await Promise.all([ getModelJSON(pretrained_model_name_or_path, "tokenizer.json", true, options), getModelJSON(pretrained_model_name_or_path, "tokenizer_config.json", true, options) ]); if (options.legacy !== null) { info[1].legacy = options.legacy; } return info; } function regexSplit(text, regex) { const result = []; let prev = 0; for (const match of text.matchAll(regex)) { const fullMatch = match[0]; if (prev < match.index) { result.push(text.slice(prev, match.index)); } if (fullMatch.length > 0) { result.push(fullMatch); } prev = match.index + fullMatch.length; } if (prev < text.length) { result.push(text.slice(prev)); } return result; } function createPattern(pattern, invert = true) { if (pattern.Regex !== void 0) { let regex = pattern.Regex.replace(/\\([#&~])/g, "$1"); for (const [key, value] of PROBLEMATIC_REGEX_MAP) { regex = regex.replaceAll(key, value); } return new RegExp(regex, "gu"); } else if (pattern.String !== void 0) { const escaped = escapeRegExp(pattern.String); return new RegExp(invert ? escaped : `(${escaped})`, "gu"); } else { console.warn("Unknown pattern type:", pattern); return null; } } function objectToMap(obj) { return new Map(Object.entries(obj)); } function prepareTensorForDecode(tensor) { const dims = tensor.dims; switch (dims.length) { case 1: return tensor.tolist(); case 2: if (dims[0] !== 1) { throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs."); } return tensor.tolist()[0]; default: throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`); } } function clean_up_tokenization(text) { return text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n\'t/g, "n't").replace(/ \'m/g, "'m").replace(/ \'s/g, "'s").replace(/ \'ve/g, "'ve").replace(/ \'re/g, "'re"); } function remove_accents(text) { return text.replace(/[\u0300-\u036f]/g, ""); } function lowercase_and_remove_accent(text) { return remove_accents(text.toLowerCase()); } function fuse(arr, value, mapping) { const fused = []; let i = 0; while (i < arr.length) { fused.push(arr[i]); if ((mapping.get(arr[i]) ?? value) !== value) { ++i; continue; } while (i < arr.length && (mapping.get(arr[i]) ?? value) === value) { ++i; } } return fused; } function whitespace_split(text) { return text.match(/\S+/g) || []; } function padHelper(item, length, value_fn, side) { for (const key of Object.keys(item)) { const diff = length - item[key].length; const value = value_fn(key); const padData = new Array(diff).fill(value); item[key] = side === "right" ? mergeArrays(item[key], padData) : mergeArrays(padData, item[key]); } } function truncateHelper(item, length) { for (const key of Object.keys(item)) { item[key].length = length; } } function _build_translation_inputs(self2, raw_inputs, tokenizer_options, generate_kwargs) { if (!("language_codes" in self2) || !Array.isArray(self2.language_codes)) { throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids."); } if (!("languageRegex" in self2) || !(self2.languageRegex instanceof RegExp)) { throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression."); } if (!("lang_to_token" in self2) || typeof self2.lang_to_token !== "function") { throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function."); } const src_lang_token = generate_kwargs.src_lang; const tgt_lang_token = generate_kwargs.tgt_lang; if (!self2.language_codes.includes(tgt_lang_token)) { throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); } if (src_lang_token !== void 0) { if (!self2.language_codes.includes(src_lang_token)) { throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); } for (const item of self2.post_processor.config.single) { if ("SpecialToken" in item && self2.languageRegex.test(item.SpecialToken.id)) { item.SpecialToken.id = self2.lang_to_token(src_lang_token); break; } } } generate_kwargs.forced_bos_token_id = self2.model.convert_tokens_to_ids([self2.lang_to_token(tgt_lang_token)])[0]; return self2._call(raw_inputs, tokenizer_options); } var PUNCTUATION_REGEX, PROBLEMATIC_REGEX_MAP, AddedToken, TokenizerModel, WordPieceTokenizer, Unigram, BYTES_TO_UNICODE, UNICODE_TO_BYTES, BPE, LegacyTokenizerModel, Normalizer, Replace, NFC, NFKC, NFKD, StripNormalizer, StripAccents, Lowercase, Prepend, NormalizerSequence, BertNormalizer, PreTokenizer, BertPreTokenizer, ByteLevelPreTokenizer, SplitPreTokenizer, PunctuationPreTokenizer, DigitsPreTokenizer, PostProcessor, BertProcessing, RobertaProcessing, TemplateProcessing, ByteLevelPostProcessor, PostProcessorSequence, Decoder, ReplaceDecoder, ByteFallback, FuseDecoder, StripDecoder, WordPieceDecoder, ByteLevelDecoder, CTCDecoder, DecoderSequence, BPEDecoder, VitsDecoder, MetaspacePreTokenizer, MetaspaceDecoder, Precompiled, PreTokenizerSequence, WhitespacePreTokenizer, WhitespaceSplit, ReplacePreTokenizer, SPECIAL_TOKEN_ATTRIBUTES, PreTrainedTokenizer, BertTokenizer, AlbertTokenizer, MobileBertTokenizer, SqueezeBertTokenizer, DebertaTokenizer, DebertaV2Tokenizer, HerbertTokenizer, ConvBertTokenizer, RoFormerTokenizer, DistilBertTokenizer, CamembertTokenizer, XLMTokenizer, ElectraTokenizer, T5Tokenizer, GPT2Tokenizer, BartTokenizer, MBartTokenizer, MBart50Tokenizer, RobertaTokenizer, BloomTokenizer, SPIECE_UNDERLINE, LlamaTokenizer, CodeLlamaTokenizer, XLMRobertaTokenizer, MPNetTokenizer, FalconTokenizer, GPTNeoXTokenizer, EsmTokenizer, Qwen2Tokenizer, GemmaTokenizer, Grok1Tokenizer, NllbTokenizer, M2M100Tokenizer, WHISPER_LANGUAGES, WHISPER_LANGUAGE_MAPPING, WHISPER_TO_LANGUAGE_CODE_MAPPING, WhisperTokenizer, CodeGenTokenizer, CLIPTokenizer, SiglipTokenizer, MarianTokenizer, Wav2Vec2CTCTokenizer, BlenderbotTokenizer, BlenderbotSmallTokenizer, SpeechT5Tokenizer, NougatTokenizer, VitsTokenizer, CohereTokenizer, AutoTokenizer; var init_tokenizers = __esm({ "node_modules/@xenova/transformers/src/tokenizers.js"() { init_core(); init_hub(); init_maths(); init_tensor(); init_data_structures(); init_dist(); PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E"; PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ new Map([ // This uses the case insensitive group modifier, which is not supported in JavaScript. // When parsing the regex, an "Invalid group" error is thrown. ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"] ]); AddedToken = class { /** * Creates a new instance of AddedToken. * @param {Object} config Added token configuration object. * @param {string} config.content The content of the added token. * @param {number} config.id The id of the added token. * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. * @param {boolean} [config.normalized=false] Whether this token should be normalized. * @param {boolean} [config.special=false] Whether this token is special. */ constructor(config) { this.content = config.content; this.id = config.id; this.single_word = config.single_word ?? false; this.lstrip = config.lstrip ?? false; this.rstrip = config.rstrip ?? false; this.special = config.special ?? false; this.normalized = config.normalized ?? null; } }; TokenizerModel = class extends Callable { /** * Creates a new instance of TokenizerModel. * @param {Object} config The configuration object for the TokenizerModel. */ constructor(config) { super(); this.config = config; this.vocab = []; this.tokens_to_ids = /* @__PURE__ */ new Map(); this.unk_token_id = void 0; this.unk_token = void 0; this.end_of_word_suffix = void 0; this.fuse_unk = this.config.fuse_unk ?? false; } /** * Instantiates a new TokenizerModel instance based on the configuration object provided. * @param {Object} config The configuration object for the TokenizerModel. * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. * @returns {TokenizerModel} A new instance of a TokenizerModel. * @throws Will throw an error if the TokenizerModel type in the config is not recognized. */ static fromConfig(config, ...args) { switch (config.type) { case "WordPiece": return new WordPieceTokenizer(config); case "Unigram": return new Unigram(config, ...args); case "BPE": return new BPE(config); default: if (config.vocab) { return new LegacyTokenizerModel(config, ...args); } throw new Error(`Unknown TokenizerModel type: ${config.type}`); } } /** * Internal function to call the TokenizerModel instance. * @param {string[]} tokens The tokens to encode. * @returns {string[]} The encoded token IDs. */ _call(tokens) { let ids = this.encode(tokens); if (this.fuse_unk) { ids = fuse(ids, this.unk_token_id, this.tokens_to_ids); } return ids; } /** * Encodes a list of tokens into a list of token IDs. * @param {string[]} tokens The tokens to encode. * @returns {string[]} The encoded tokens. * @throws Will throw an error if not implemented in a subclass. */ encode(tokens) { throw Error("encode should be implemented in subclass."); } /** * Converts a list of tokens into a list of token IDs. * @param {string[]} tokens The tokens to convert. * @returns {number[]} The converted token IDs. */ convert_tokens_to_ids(tokens) { return tokens.map((t) => this.tokens_to_ids.get(t) ?? this.unk_token_id); } /** * Converts a list of token IDs into a list of tokens. * @param {number[]} ids The token IDs to convert. * @returns {string[]} The converted tokens. */ convert_ids_to_tokens(ids) { return ids.map((i) => this.vocab[i] ?? this.unk_token); } }; WordPieceTokenizer = class extends TokenizerModel { /** * @param {Object} config The configuration object. * @param {Object} config.vocab A mapping of tokens to ids. * @param {string} config.unk_token The unknown token string. * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords. * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word. */ constructor(config) { super(config); this.tokens_to_ids = objectToMap(config.vocab); this.unk_token_id = this.tokens_to_ids.get(config.unk_token); this.unk_token = config.unk_token; this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; this.vocab = new Array(this.tokens_to_ids.size); for (const [key, value] of this.tokens_to_ids) { this.vocab[value] = key; } } /** * Encodes an array of tokens using WordPiece encoding. * @param {string[]} tokens The tokens to encode. * @returns {string[]} An array of encoded tokens. */ encode(tokens) { const outputTokens = []; for (const token of tokens) { const chars = [...token]; if (chars.length > this.max_input_chars_per_word) { outputTokens.push(this.unk_token); continue; } let isUnknown = false; let start = 0; const subTokens = []; while (start < chars.length) { let end = chars.length; let currentSubstring = null; while (start < end) { let substr = chars.slice(start, end).join(""); if (start > 0) { substr = this.config.continuing_subword_prefix + substr; } if (this.tokens_to_ids.has(substr)) { currentSubstring = substr; break; } --end; } if (currentSubstring === null) { isUnknown = true; break; } subTokens.push(currentSubstring); start = end; } if (isUnknown) { outputTokens.push(this.unk_token); } else { outputTokens.push(...subTokens); } } return outputTokens; } }; Unigram = class extends TokenizerModel { /** * Create a new Unigram tokenizer model. * @param {Object} config The configuration object for the Unigram model. * @param {number} config.unk_id The ID of the unknown token * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores. * @param {Object} moreConfig Additional configuration object for the Unigram model. */ constructor(config, moreConfig) { super(config); const vocabSize = config.vocab.length; this.vocab = new Array(vocabSize); this.scores = new Array(vocabSize); for (let i = 0; i < vocabSize; ++i) { const piece = config.vocab[i]; this.vocab[i] = piece[0]; this.scores[i] = piece[1]; } this.unk_token_id = config.unk_id; this.unk_token = this.vocab[config.unk_id]; this.tokens_to_ids = new Map(this.vocab.map((x2, i) => [x2, i])); this.bosToken = " "; this.bosTokenId = this.tokens_to_ids.get(this.bosToken); this.eosToken = moreConfig.eos_token; this.eosTokenId = this.tokens_to_ids.get(this.eosToken); this.unkToken = this.vocab[this.unk_token_id]; this.minScore = min(this.scores)[0]; this.unkScore = this.minScore - 10; this.scores[this.unk_token_id] = this.unkScore; this.trie = new CharTrie(); this.trie.extend(this.vocab); this.fuse_unk = true; } /** * Populates lattice nodes. * @param {TokenLattice} lattice The token lattice to populate with nodes. */ populateNodes(lattice) { const sentence = lattice.sentence; const len = sentence.length; let beginPos = 0; while (beginPos < len) { const mblen = 1; let hasSingleNode = false; const tokens = []; for (let token of this.trie.commonPrefixSearch(sentence.slice(beginPos))) { tokens.push(token); const tokenId = this.tokens_to_ids.get(token); const tokenScore = this.scores[tokenId]; const n = token.length; lattice.insert(beginPos, n, tokenScore, tokenId); if (!hasSingleNode && n === mblen) { hasSingleNode = true; } } if (!hasSingleNode) { lattice.insert(beginPos, mblen, this.unkScore, this.unk_token_id); } beginPos += mblen; } } /** * Encodes an array of tokens into an array of subtokens using the unigram model. * * @param {string} normalized The normalized string. * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model. */ tokenize(normalized) { const lattice = new TokenLattice(normalized, this.bosTokenId, this.eosTokenId); this.populateNodes(lattice); return lattice.tokens(); } /** * Encodes an array of tokens using Unigram encoding. * @param {string[]} tokens The tokens to encode. * @returns {string[]} An array of encoded tokens. */ encode(tokens) { const toReturn = []; for (const token of tokens) { const tokenized = this.tokenize(token); toReturn.push(...tokenized); } return toReturn; } }; BYTES_TO_UNICODE = (() => { const bs4 = [ ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)), ...Array.from({ length: "\xAC".charCodeAt(0) - "\xA1".charCodeAt(0) + 1 }, (_, i) => i + "\xA1".charCodeAt(0)), ...Array.from({ length: "\xFF".charCodeAt(0) - "\xAE".charCodeAt(0) + 1 }, (_, i) => i + "\xAE".charCodeAt(0)) ]; const cs4 = bs4.slice(); let n = 0; for (let b = 0; b < 256; ++b) { if (!bs4.includes(b)) { bs4.push(b); cs4.push(256 + n); n += 1; } } const ccs = cs4.map((n2) => String.fromCharCode(n2)); return Object.fromEntries(bs4.map((b, i) => [b, ccs[i]])); })(); UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE); BPE = class extends TokenizerModel { /** * Create a BPE instance. * @param {Object} config The configuration object for BPE. * @param {Object} config.vocab A mapping of tokens to ids. * @param {string[]} config.merges An array of BPE merges as strings. * @param {string} config.unk_token The unknown token used for out of vocabulary words. * @param {string} config.end_of_word_suffix The suffix to place at the end of each word. * @param {string} [config.continuing_subword_suffix] The suffix to insert between words. * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False) * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges. */ constructor(config) { super(config); this.BPE_SPLIT_TOKEN = " "; this.tokens_to_ids = objectToMap(config.vocab); this.unk_token_id = this.tokens_to_ids.get(config.unk_token); this.unk_token = config.unk_token; this.vocab = new Array(this.tokens_to_ids.size); for (const [key, value] of this.tokens_to_ids) { this.vocab[value] = key; } this.bpe_ranks = new Map(config.merges.map((x2, i) => [x2, i])); this.merges = config.merges.map((x2) => x2.split(this.BPE_SPLIT_TOKEN)); this.end_of_word_suffix = config.end_of_word_suffix; this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; this.byte_fallback = this.config.byte_fallback ?? false; if (this.byte_fallback) { this.text_encoder = new TextEncoder(); } this.ignore_merges = this.config.ignore_merges ?? false; this.cache = /* @__PURE__ */ new Map(); } /** * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. * @param {string} token The token to encode. * @returns {string[]} The BPE encoded tokens. */ bpe(token) { if (token.length === 0) { return []; } const cached = this.cache.get(token); if (cached !== void 0) { return cached; } const word = Array.from(token); if (this.end_of_word_suffix) { word[word.length - 1] += this.end_of_word_suffix; } let result = []; if (word.length > 1) { const queue = new PriorityQueue((a, b) => a.score < b.score); let startingNode = { token: word[0], bias: 0, prev: null, next: null }; let previousNode = startingNode; for (let i = 1; i < word.length; ++i) { const currentNode = { bias: i / word.length, // Add fractional component to break ties token: word[i], prev: previousNode, next: null }; previousNode.next = currentNode; this._add_node(queue, previousNode); previousNode = currentNode; } while (!queue.isEmpty()) { const node = queue.pop(); if (node.deleted || !node.next || node.next.deleted) continue; node.deleted = true; node.next.deleted = true; if (node.prev) { const newPreviousNode = { ...node.prev }; node.prev.deleted = true; node.prev = newPreviousNode; if (newPreviousNode.prev) { newPreviousNode.prev.next = newPreviousNode; } else { startingNode = newPreviousNode; } } const merged = { token: node.token + node.next.token, bias: node.bias, prev: node.prev, next: node.next.next }; if (merged.prev) { merged.prev.next = merged; this._add_node(queue, merged.prev); } else { startingNode = merged; } if (merged.next) { merged.next.prev = merged; this._add_node(queue, merged); } } for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) { result.push(currentNode.token); } } else { result = word; } if (this.continuing_subword_suffix) { for (let i = 0; i < result.length - 1; ++i) { result[i] += this.continuing_subword_suffix; } } this.cache.set(token, result); return result; } /** * Helper function to add a node to the priority queue. * @param {PriorityQueue} queue * @param {BPENode} node * @private */ _add_node(queue, node) { const rank = this.bpe_ranks.get(node.token + this.BPE_SPLIT_TOKEN + node.next.token); if (rank !== void 0) { node.score = rank + node.bias; queue.push(node); } } /** * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. * @param {string[]} tokens The input sequence of tokens to encode. * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. */ encode(tokens) { const outputTokens = []; for (const token of tokens) { if (this.ignore_merges && this.tokens_to_ids.has(token)) { outputTokens.push(token); continue; } const bpe_token_list = this.bpe(token); for (const t of bpe_token_list) { if (this.tokens_to_ids.has(t)) { outputTokens.push(t); } else { if (this.byte_fallback) { outputTokens.push( ...Array.from(this.text_encoder.encode(t)).map((x2) => `<0x${x2.toString(16).toUpperCase().padStart(2, "0")}>`) ); } else { outputTokens.push(this.unk_token); } } } } return outputTokens; } }; LegacyTokenizerModel = class extends TokenizerModel { /** * Create a LegacyTokenizerModel instance. * @param {Object} config The configuration object for LegacyTokenizerModel. * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids. * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model. */ constructor(config, moreConfig) { super(config); this.tokens_to_ids = objectToMap( moreConfig.target_lang ? config.vocab[moreConfig.target_lang] : config.vocab ); this.bos_token = moreConfig.bos_token; this.bos_token_id = this.tokens_to_ids.get(this.bos_token); this.eos_token = moreConfig.eos_token; this.eos_token_id = this.tokens_to_ids.get(this.eos_token); this.pad_token = moreConfig.pad_token; this.pad_token_id = this.tokens_to_ids.get(this.pad_token); this.unk_token = moreConfig.unk_token; this.unk_token_id = this.tokens_to_ids.get(this.unk_token); this.vocab = new Array(this.tokens_to_ids.size); for (const [key, value] of this.tokens_to_ids) { this.vocab[value] = key; } } encode(tokens) { return tokens; } }; Normalizer = class extends Callable { /** * @param {Object} config The configuration object for the normalizer. */ constructor(config) { super(); this.config = config; } /** * Factory method for creating normalizers from config objects. * @static * @param {Object} config The configuration object for the normalizer. * @returns {Normalizer} A Normalizer object. * @throws {Error} If an unknown Normalizer type is specified in the config. */ static fromConfig(config) { if (config === null) return null; switch (config.type) { case "BertNormalizer": return new BertNormalizer(config); case "Precompiled": return new Precompiled(config); case "Sequence": return new NormalizerSequence(config); case "Replace": return new Replace(config); case "NFC": return new NFC(config); case "NFKC": return new NFKC(config); case "NFKD": return new NFKD(config); case "Strip": return new StripNormalizer(config); case "StripAccents": return new StripAccents(config); case "Lowercase": return new Lowercase(config); case "Prepend": return new Prepend(config); default: throw new Error(`Unknown Normalizer type: ${config.type}`); } } /** * Normalize the input text. * @abstract * @param {string} text The text to normalize. * @returns {string} The normalized text. * @throws {Error} If this method is not implemented in a subclass. */ normalize(text) { throw Error("normalize should be implemented in subclass."); } /** * Alias for {@link Normalizer#normalize}. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ _call(text) { return this.normalize(text); } }; Replace = class extends Normalizer { /** * Normalize the input text by replacing the pattern with the content. * @param {string} text The input text to be normalized. * @returns {string} The normalized text after replacing the pattern with the content. */ normalize(text) { const pattern = createPattern(this.config.pattern); return pattern === null ? text : text.replaceAll(pattern, this.config.content); } }; NFC = class extends Normalizer { /** * Normalize the input text by applying Unicode normalization form C (NFC). * @param {string} text The input text to be normalized. * @returns {string} The normalized text. */ normalize(text) { text = text.normalize("NFC"); return text; } }; NFKC = class extends Normalizer { /** * Normalize text using NFKC normalization. * @param {string} text The text to be normalized. * @returns {string} The normalized text. */ normalize(text) { text = text.normalize("NFKC"); return text; } }; NFKD = class extends Normalizer { /** * Normalize text using NFKD normalization. * @param {string} text The text to be normalized. * @returns {string} The normalized text. */ normalize(text) { text = text.normalize("NFKD"); return text; } }; StripNormalizer = class extends Normalizer { /** * Strip leading and/or trailing whitespace from the input text. * @param {string} text The input text. * @returns {string} The normalized text. */ normalize(text) { if (this.config.strip_left && this.config.strip_right) { text = text.trim(); } else { if (this.config.strip_left) { text = text.trimStart(); } if (this.config.strip_right) { text = text.trimEnd(); } } return text; } }; StripAccents = class extends Normalizer { /** * Remove all accents from the text. * @param {string} text The input text. * @returns {string} The normalized text without accents. */ normalize(text) { text = remove_accents(text); return text; } }; Lowercase = class extends Normalizer { /** * Lowercases the input string. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(text) { text = text.toLowerCase(); return text; } }; Prepend = class extends Normalizer { /** * Prepends the input string. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(text) { text = this.config.prepend + text; return text; } }; NormalizerSequence = class extends Normalizer { /** * Create a new instance of NormalizerSequence. * @param {Object} config The configuration object. * @param {Object[]} config.normalizers An array of Normalizer configuration objects. */ constructor(config) { super(config); this.normalizers = config.normalizers.map((x2) => Normalizer.fromConfig(x2)); } /** * Apply a sequence of Normalizers to the input text. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(text) { return this.normalizers.reduce((t, normalizer) => { return normalizer.normalize(t); }, text); } }; BertNormalizer = class extends Normalizer { /** * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. * * @param {string} text The input text to tokenize. * @returns {string} The tokenized text with whitespace added around CJK characters. */ _tokenize_chinese_chars(text) { const output = []; for (let i = 0; i < text.length; ++i) { const char = text[i]; const cp4 = char.charCodeAt(0); if (this._is_chinese_char(cp4)) { output.push(" "); output.push(char); output.push(" "); } else { output.push(char); } } return output.join(""); } /** * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character. * * A "chinese character" is defined as anything in the CJK Unicode block: * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) * * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name. * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana. * Those alphabets are used to write space-separated words, so they are not treated specially * and are handled like all other languages. * * @param {number} cp The Unicode codepoint to check. * @returns {boolean} True if the codepoint represents a CJK character, false otherwise. */ _is_chinese_char(cp4) { return cp4 >= 19968 && cp4 <= 40959 || cp4 >= 13312 && cp4 <= 19903 || cp4 >= 131072 && cp4 <= 173791 || cp4 >= 173824 && cp4 <= 177983 || cp4 >= 177984 && cp4 <= 178207 || cp4 >= 178208 && cp4 <= 183983 || cp4 >= 63744 && cp4 <= 64255 || cp4 >= 194560 && cp4 <= 195103; } /** * Strips accents from the given text. * @param {string} text The text to strip accents from. * @returns {string} The text with accents removed. */ stripAccents(text) { return text.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); } /** * Checks whether `char` is a control character. * @param {string} char The character to check. * @returns {boolean} Whether `char` is a control character. * @private */ _is_control(char) { switch (char) { case " ": case "\n": case "\r": return false; default: return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); } } /** * Performs invalid character removal and whitespace cleanup on text. * @param {string} text The text to clean. * @returns {string} The cleaned text. * @private */ _clean_text(text) { const output = []; for (const char of text) { const cp4 = char.charCodeAt(0); if (cp4 === 0 || cp4 === 65533 || this._is_control(char)) { continue; } if (/^\s$/.test(char)) { output.push(" "); } else { output.push(char); } } return output.join(""); } /** * Normalizes the given text based on the configuration. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(text) { if (this.config.clean_text) { text = this._clean_text(text); } if (this.config.handle_chinese_chars) { text = this._tokenize_chinese_chars(text); } if (this.config.lowercase) { text = text.toLowerCase(); if (this.config.strip_accents !== false) { text = this.stripAccents(text); } } else if (this.config.strip_accents) { text = this.stripAccents(text); } return text; } }; PreTokenizer = class extends Callable { /** * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. * * @static * @param {Object} config A configuration object for the pre-tokenizer. * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. */ static fromConfig(config) { if (config === null) return null; switch (config.type) { case "BertPreTokenizer": return new BertPreTokenizer(config); case "Sequence": return new PreTokenizerSequence(config); case "Whitespace": return new WhitespacePreTokenizer(config); case "WhitespaceSplit": return new WhitespaceSplit(config); case "Metaspace": return new MetaspacePreTokenizer(config); case "ByteLevel": return new ByteLevelPreTokenizer(config); case "Split": return new SplitPreTokenizer(config); case "Punctuation": return new PunctuationPreTokenizer(config); case "Digits": return new DigitsPreTokenizer(config); case "Replace": return new ReplacePreTokenizer(config); default: throw new Error(`Unknown PreTokenizer type: ${config.type}`); } } /** * Method that should be implemented by subclasses to define the specific pre-tokenization logic. * * @abstract * @param {string} text The text to pre-tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} The pre-tokenized text. * @throws {Error} If the method is not implemented in the subclass. */ pre_tokenize_text(text, options) { throw Error("pre_tokenize_text should be implemented in subclass."); } /** * Tokenizes the given text into pre-tokens. * @param {string|string[]} text The text or array of texts to pre-tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of pre-tokens. */ pre_tokenize(text, options) { return (Array.isArray(text) ? text.map((x2) => this.pre_tokenize_text(x2, options)) : this.pre_tokenize_text(text, options)).flat(); } /** * Alias for {@link PreTokenizer#pre_tokenize}. * @param {string|string[]} text The text or array of texts to pre-tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of pre-tokens. */ _call(text, options) { return this.pre_tokenize(text, options); } }; BertPreTokenizer = class extends PreTokenizer { /** * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme * similar to that used in the original implementation of BERT. * * @param {Object} config The configuration object. */ constructor(config) { super(); this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, "gu"); } /** * Tokenizes a single text using the BERT pre-tokenization scheme. * * @param {string} text The text to tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens. */ pre_tokenize_text(text, options) { return text.trim().match(this.pattern) || []; } }; ByteLevelPreTokenizer = class extends PreTokenizer { /** * Creates a new instance of the `ByteLevelPreTokenizer` class. * @param {Object} config The configuration object. */ constructor(config) { super(); this.config = config; this.add_prefix_space = this.config.add_prefix_space; this.trim_offsets = this.config.trim_offsets; this.use_regex = this.config.use_regex ?? true; this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu; this.byte_encoder = BYTES_TO_UNICODE; this.text_encoder = new TextEncoder(); } /** * Tokenizes a single piece of text using byte-level tokenization. * @param {string} text The text to tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens. */ pre_tokenize_text(text, options) { if (this.add_prefix_space && !text.startsWith(" ")) { text = " " + text; } const tokens = this.use_regex ? text.match(this.pattern) || [] : [text]; return tokens.map( (token) => Array.from(this.text_encoder.encode(token), (byte) => this.byte_encoder[byte]).join("") ); } }; SplitPreTokenizer = class extends PreTokenizer { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string. * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex. * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern. */ constructor(config) { super(); this.config = config; this.pattern = createPattern(this.config.pattern, this.config.invert); } /** * Tokenizes text by splitting it using the given pattern. * @param {string} text The text to tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens. */ pre_tokenize_text(text, options) { if (this.pattern === null) { return []; } if (this.config.invert) { return text.match(this.pattern) || []; } else { return regexSplit(text, this.pattern); } } }; PunctuationPreTokenizer = class extends PreTokenizer { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. */ constructor(config) { super(); this.config = config; this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, "gu"); } /** * Tokenizes text by splitting it using the given pattern. * @param {string} text The text to tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens. */ pre_tokenize_text(text, options) { return text.match(this.pattern) || []; } }; DigitsPreTokenizer = class extends PreTokenizer { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {boolean} config.individual_digits Whether to split on individual digits. */ constructor(config) { super(); this.config = config; const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`; this.pattern = new RegExp(digit_pattern, "gu"); } /** * Tokenizes text by splitting it using the given pattern. * @param {string} text The text to tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens. */ pre_tokenize_text(text, options) { return text.match(this.pattern) || []; } }; PostProcessor = class extends Callable { /** * @param {Object} config The configuration for the post-processor. */ constructor(config) { super(); this.config = config; } /** * Factory method to create a PostProcessor object from a configuration object. * * @param {Object} config Configuration object representing a PostProcessor. * @returns {PostProcessor} A PostProcessor object created from the given configuration. * @throws {Error} If an unknown PostProcessor type is encountered. */ static fromConfig(config) { if (config === null) return null; switch (config.type) { case "TemplateProcessing": return new TemplateProcessing(config); case "ByteLevel": return new ByteLevelPostProcessor(config); case "RobertaProcessing": return new RobertaProcessing(config); case "BertProcessing": return new BertProcessing(config); case "Sequence": return new PostProcessorSequence(config); default: throw new Error(`Unknown PostProcessor type: ${config.type}`); } } /** * Method to be implemented in subclass to apply post-processing on the given tokens. * * @param {Array} tokens The input tokens to be post-processed. * @param {...*} args Additional arguments required by the post-processing logic. * @returns {PostProcessedOutput} The post-processed tokens. * @throws {Error} If the method is not implemented in subclass. */ post_process(tokens, ...args) { throw Error("post_process should be implemented in subclass."); } /** * Alias for {@link PostProcessor#post_process}. * @param {Array} tokens The text or array of texts to post-process. * @param {...*} args Additional arguments required by the post-processing logic. * @returns {PostProcessedOutput} The post-processed tokens. */ _call(tokens, ...args) { return this.post_process(tokens, ...args); } }; BertProcessing = class extends PostProcessor { /** * @param {Object} config The configuration for the post-processor. * @param {string[]} config.cls The special tokens to add to the beginning of the input. * @param {string[]} config.sep The special tokens to add to the end of the input. */ constructor(config) { super(config); this.cls = config.cls[0]; this.sep = config.sep[0]; } /** * Adds the special tokens to the beginning and end of the input. * @param {string[]} tokens The input tokens. * @param {string[]} [tokens_pair=null] An optional second set of input tokens. * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end. */ post_process(tokens, tokens_pair = null, { add_special_tokens = true } = {}) { if (add_special_tokens) { tokens = mergeArrays([this.cls], tokens, [this.sep]); } let token_type_ids = new Array(tokens.length).fill(0); if (tokens_pair !== null) { const middle = add_special_tokens && this instanceof RobertaProcessing ? [this.sep] : []; const after = add_special_tokens ? [this.sep] : []; tokens = mergeArrays(tokens, middle, tokens_pair, after); token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1)); } return { tokens, token_type_ids }; } }; RobertaProcessing = class extends BertProcessing { }; TemplateProcessing = class extends PostProcessor { /** * Creates a new instance of `TemplateProcessing`. * @param {Object} config The configuration options for the post processor. * @param {Array} config.single The template for a single sequence of tokens. * @param {Array} config.pair The template for a pair of sequences of tokens. */ constructor(config) { super(config); this.single = config.single; this.pair = config.pair; } /** * Replaces special tokens in the template with actual tokens. * @param {string[]} tokens The list of tokens for the first sequence. * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens. */ post_process(tokens, tokens_pair = null, { add_special_tokens = true } = {}) { const type = tokens_pair === null ? this.single : this.pair; let processedTokens = []; let types = []; for (const item of type) { if ("SpecialToken" in item) { if (add_special_tokens) { processedTokens.push(item.SpecialToken.id); types.push(item.SpecialToken.type_id); } } else if ("Sequence" in item) { if (item.Sequence.id === "A") { processedTokens = mergeArrays(processedTokens, tokens); types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id)); } else if (item.Sequence.id === "B") { processedTokens = mergeArrays(processedTokens, tokens_pair); types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id)); } } } return { tokens: processedTokens, token_type_ids: types }; } }; ByteLevelPostProcessor = class extends PostProcessor { /** * Post process the given tokens. * @param {string[]} tokens The list of tokens for the first sequence. * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). * @returns {PostProcessedOutput} An object containing the post-processed tokens. */ post_process(tokens, tokens_pair = null) { if (tokens_pair) { tokens = mergeArrays(tokens, tokens_pair); } return { tokens }; } }; PostProcessorSequence = class extends PostProcessor { /** * Creates a new instance of PostProcessorSequence. * @param {Object} config The configuration object. * @param {Object[]} config.processors The list of post-processors to apply. */ constructor(config) { super(config); this.processors = config.processors.map((x2) => PostProcessor.fromConfig(x2)); } /** * Post process the given tokens. * @param {string[]} tokens The list of tokens for the first sequence. * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). * @returns {PostProcessedOutput} An object containing the post-processed tokens. */ post_process(tokens, tokens_pair = null, options = {}) { let token_type_ids; for (const processor of this.processors) { if (processor instanceof ByteLevelPostProcessor) { const output = processor.post_process(tokens); tokens = output.tokens; if (tokens_pair) { const pair_output = processor.post_process(tokens_pair); tokens_pair = pair_output.tokens; } } else { const output = processor.post_process(tokens, tokens_pair, options); tokens = output.tokens; token_type_ids = output.token_type_ids; } } return { tokens, token_type_ids }; } }; Decoder = class extends Callable { /** * Creates an instance of `Decoder`. * * @param {Object} config The configuration object. */ constructor(config) { super(); this.config = config; this.added_tokens = []; this.end_of_word_suffix = null; this.trim_offsets = config.trim_offsets; } /** * Creates a decoder instance based on the provided configuration. * * @param {Object} config The configuration object. * @returns {Decoder} A decoder instance. * @throws {Error} If an unknown decoder type is provided. */ static fromConfig(config) { if (config === null) return null; switch (config.type) { case "WordPiece": return new WordPieceDecoder(config); case "Metaspace": return new MetaspaceDecoder(config); case "ByteLevel": return new ByteLevelDecoder(config); case "Replace": return new ReplaceDecoder(config); case "ByteFallback": return new ByteFallback(config); case "Fuse": return new FuseDecoder(config); case "Strip": return new StripDecoder(config); case "Sequence": return new DecoderSequence(config); case "CTC": return new CTCDecoder(config); case "BPEDecoder": return new BPEDecoder(config); default: throw new Error(`Unknown Decoder type: ${config.type}`); } } /** * Calls the `decode` method. * * @param {string[]} tokens The list of tokens. * @returns {string} The decoded string. */ _call(tokens) { return this.decode(tokens); } /** * Decodes a list of tokens. * @param {string[]} tokens The list of tokens. * @returns {string} The decoded string. */ decode(tokens) { return this.decode_chain(tokens).join(""); } /** * Apply the decoder to a list of tokens. * * @param {string[]} tokens The list of tokens. * @returns {string[]} The decoded list of tokens. * @throws {Error} If the `decode_chain` method is not implemented in the subclass. */ decode_chain(tokens) { throw Error("`decode_chain` should be implemented in subclass."); } }; ReplaceDecoder = class extends Decoder { /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { const pattern = createPattern(this.config.pattern); return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, this.config.content)); } }; ByteFallback = class extends Decoder { constructor(config) { super(config); this.text_decoder = new TextDecoder(); } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { const new_tokens = []; let previous_byte_tokens = []; for (const token of tokens) { let bytes = null; if (token.length === 6 && token.startsWith("<0x") && token.endsWith(">")) { const byte = parseInt(token.slice(3, 5), 16); if (!isNaN(byte)) { bytes = byte; } } if (bytes !== null) { previous_byte_tokens.push(bytes); } else { if (previous_byte_tokens.length > 0) { const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); new_tokens.push(string); previous_byte_tokens = []; } new_tokens.push(token); } } if (previous_byte_tokens.length > 0) { const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); new_tokens.push(string); previous_byte_tokens = []; } return new_tokens; } }; FuseDecoder = class extends Decoder { /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return [tokens.join("")]; } }; StripDecoder = class extends Decoder { constructor(config) { super(config); this.content = this.config.content; this.start = this.config.start; this.stop = this.config.stop; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return tokens.map((token) => { let start_cut = 0; for (let i = 0; i < this.start; ++i) { if (token[i] === this.content) { start_cut = i + 1; continue; } else { break; } } let stop_cut = token.length; for (let i = 0; i < this.stop; ++i) { const index = token.length - i - 1; if (token[index] === this.content) { stop_cut = index; continue; } else { break; } } return token.slice(start_cut, stop_cut); }); } }; WordPieceDecoder = class extends Decoder { /** * Creates a new instance of WordPieceDecoder. * @param {Object} config The configuration object. * @param {string} config.prefix The prefix used for WordPiece encoding. * @param {boolean} config.cleanup Whether to cleanup the decoded string. */ constructor(config) { super(config); this.cleanup = config.cleanup; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return tokens.map((token, i) => { if (i !== 0) { if (token.startsWith(this.config.prefix)) { token = token.replace(this.config.prefix, ""); } else { token = " " + token; } } if (this.cleanup) { token = clean_up_tokenization(token); } return token; }); } }; ByteLevelDecoder = class extends Decoder { /** * Create a `ByteLevelDecoder` object. * @param {Object} config Configuration object. */ constructor(config) { super(config); this.byte_decoder = UNICODE_TO_BYTES; this.text_decoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true }); this.end_of_word_suffix = null; } /** * Convert an array of tokens to string by decoding each byte. * @param {string[]} tokens Array of tokens to be decoded. * @returns {string} The decoded string. */ convert_tokens_to_string(tokens) { const text = tokens.join(""); const byteArray = new Uint8Array([...text].map((c) => this.byte_decoder[c])); const decoded_text = this.text_decoder.decode(byteArray); return decoded_text; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { const sub_texts = []; let current_sub_text = []; for (const token of tokens) { if (this.added_tokens.find((x2) => x2.content === token) !== void 0) { if (current_sub_text.length > 0) { sub_texts.push(this.convert_tokens_to_string(current_sub_text)); current_sub_text = []; } sub_texts.push(token); } else { current_sub_text.push(token); } } if (current_sub_text.length > 0) { sub_texts.push(this.convert_tokens_to_string(current_sub_text)); } return sub_texts; } }; CTCDecoder = class extends Decoder { constructor(config) { super(config); this.pad_token = this.config.pad_token; this.word_delimiter_token = this.config.word_delimiter_token; this.cleanup = this.config.cleanup; } /** * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. * @param {string[]} tokens Array of tokens to be decoded. * @returns {string} The decoded string. */ convert_tokens_to_string(tokens) { if (tokens.length === 0) return ""; const grouped_tokens = [tokens[0]]; for (let i = 1; i < tokens.length; ++i) { if (tokens[i] !== grouped_tokens.at(-1)) { grouped_tokens.push(tokens[i]); } } const filtered_tokens = grouped_tokens.filter((token) => token !== this.pad_token); let text = filtered_tokens.join(""); if (this.cleanup) { text = clean_up_tokenization(text).replaceAll(this.word_delimiter_token, " ").trim(); } return text; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return [this.convert_tokens_to_string(tokens)]; } }; DecoderSequence = class extends Decoder { /** * Creates a new instance of DecoderSequence. * @param {Object} config The configuration object. * @param {Object[]} config.decoders The list of decoders to apply. */ constructor(config) { super(config); this.decoders = config.decoders.map((x2) => Decoder.fromConfig(x2)); } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return this.decoders.reduce((toks, decoder) => { return decoder.decode_chain(toks); }, tokens); } }; BPEDecoder = class extends Decoder { constructor(config) { super(config); this.suffix = this.config.suffix; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { return tokens.map((token, i) => { return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " "); }); } }; VitsDecoder = class extends Decoder { /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { let decoded = ""; for (let i = 1; i < tokens.length; i += 2) { decoded += tokens[i]; } return [decoded]; } }; MetaspacePreTokenizer = class extends PreTokenizer { /** * @param {Object} config The configuration object for the MetaspacePreTokenizer. * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token. * @param {string} config.replacement The character to replace spaces with. * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character. * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme. */ constructor(config) { super(); this.addPrefixSpace = config.add_prefix_space; this.replacement = config.replacement; this.strRep = config.str_rep || this.replacement; this.prepend_scheme = config.prepend_scheme ?? "always"; } /** * This method takes a string, replaces spaces with the replacement character, * adds a prefix space if requested, and returns a new list of tokens. * @param {string} text The text to pre-tokenize. * @param {Object} [options] The options for the pre-tokenization. * @param {number} [options.section_index] The index of the section to pre-tokenize. * @returns {string[]} A new list of pre-tokenized tokens. */ pre_tokenize_text(text, { section_index = void 0 } = {}) { let normalized = text.replaceAll(" ", this.strRep); if ( // We add a prefix space if: // (1) The addPrefixSpace option is enabled and the normalized // token does not already start with the replacement character. this.addPrefixSpace && !normalized.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0) ) { normalized = this.strRep + normalized; } return [normalized]; } }; MetaspaceDecoder = class extends Decoder { /** * Constructs a new MetaspaceDecoder object. * @param {Object} config The configuration object for the MetaspaceDecoder. * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string. * @param {string} config.replacement The string to replace spaces with. */ constructor(config) { super(config); this.addPrefixSpace = config.add_prefix_space; this.replacement = config.replacement; } /** @type {Decoder['decode_chain']} */ decode_chain(tokens) { const result = []; for (let i = 0; i < tokens.length; ++i) { let normalized = tokens[i].replaceAll(this.replacement, " "); if (this.addPrefixSpace && i == 0 && normalized.startsWith(" ")) { normalized = normalized.substring(1); } result.push(normalized); } return result; } }; Precompiled = class extends Normalizer { /** * Create a new instance of Precompiled normalizer. * @param {Object} config The configuration object. * @param {any} config.precompiled_charsmap Precompiled chars mapping. */ constructor(config) { super(config); this.charsmap = config.precompiled_charsmap; } /** * Normalizes the given text by applying the precompiled charsmap. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(text) { text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ""); text = text.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm, " "); if (text.includes("\uFF5E")) { const parts = text.split("\uFF5E"); text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E"); } else { text = text.normalize("NFKC"); } return text; } }; PreTokenizerSequence = class extends PreTokenizer { /** * Creates an instance of PreTokenizerSequence. * @param {Object} config The configuration object for the pre-tokenizer sequence. * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations. */ constructor(config) { super(); this.tokenizers = config.pretokenizers.map((x2) => PreTokenizer.fromConfig(x2)); } /** * Applies each pre-tokenizer in the sequence to the input text in turn. * @param {string} text The text to pre-tokenize. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} The pre-tokenized text. */ pre_tokenize_text(text, options) { return this.tokenizers.reduce((preTokenizedText, tokenizer) => { return tokenizer.pre_tokenize(preTokenizedText, options); }, [text]); } }; WhitespacePreTokenizer = class extends PreTokenizer { /** * Creates an instance of WhitespacePreTokenizer. * @param {Object} config The configuration object for the pre-tokenizer. */ constructor(config) { super(); } /** * Pre-tokenizes the input text by splitting it on word boundaries. * @param {string} text The text to be pre-tokenized. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. */ pre_tokenize_text(text, options) { return text.match(/\w+|[^\w\s]+/g) || []; } }; WhitespaceSplit = class extends PreTokenizer { /** * Creates an instance of WhitespaceSplit. * @param {Object} config The configuration object for the pre-tokenizer. */ constructor(config) { super(); } /** * Pre-tokenizes the input text by splitting it on whitespace characters. * @param {string} text The text to be pre-tokenized. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. */ pre_tokenize_text(text, options) { return whitespace_split(text); } }; ReplacePreTokenizer = class extends PreTokenizer { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. * @param {string} config.content What to replace the pattern with. */ constructor(config) { super(); this.config = config; this.pattern = createPattern(this.config.pattern); this.content = this.config.content; } /** * Pre-tokenizes the input text by replacing certain characters. * @param {string} text The text to be pre-tokenized. * @param {Object} [options] Additional options for the pre-tokenization logic. * @returns {string[]} An array of tokens produced by replacing certain characters. */ pre_tokenize_text(text, options) { if (this.pattern === null) { return [text]; } return [text.replaceAll(this.pattern, this.config.content)]; } }; SPECIAL_TOKEN_ATTRIBUTES = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token" // additional_special_tokens (TODO) ]; PreTrainedTokenizer = class extends Callable { return_token_type_ids = false; _default_chat_template = `{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`; /** * Create a new PreTrainedTokenizer instance. * @param {Object} tokenizerJSON The JSON of the tokenizer. * @param {Object} tokenizerConfig The config of the tokenizer. */ constructor(tokenizerJSON, tokenizerConfig) { super(); this._tokenizer_config = tokenizerConfig; this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer); this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer); this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig); this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor); this.decoder = Decoder.fromConfig(tokenizerJSON.decoder); this.special_tokens = []; this.all_special_ids = []; this.added_tokens = []; for (const addedToken of tokenizerJSON.added_tokens) { const token = new AddedToken(addedToken); this.added_tokens.push(token); this.model.tokens_to_ids.set(token.content, token.id); this.model.vocab[token.id] = token.content; if (token.special) { this.special_tokens.push(token.content); this.all_special_ids.push(token.id); } } this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? []; this.special_tokens.push(...this.additional_special_tokens); this.special_tokens = [...new Set(this.special_tokens)]; if (this.decoder) { this.decoder.added_tokens = this.added_tokens; this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; } this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp( this.added_tokens.map((x2) => `${x2.lstrip ? "\\s*" : ""}(${escapeRegExp(x2.content)})${x2.rstrip ? "\\s*" : ""}`).join("|") ) : null; this.mask_token = this.getToken("mask_token"); this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token); this.pad_token = this.getToken("pad_token", "eos_token"); this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token); this.sep_token = this.getToken("sep_token"); this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token); this.unk_token = this.getToken("unk_token"); this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token); this.model_max_length = tokenizerConfig.model_max_length; this.remove_space = tokenizerConfig.remove_space; this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true; this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false; this.padding_side = "right"; this.legacy = false; this.chat_template = tokenizerConfig.chat_template ?? null; if (Array.isArray(this.chat_template)) { const chat_template = /* @__PURE__ */ Object.create(null); for (const { name: name2, template } of this.chat_template) { if (typeof name2 !== "string" || typeof template !== "string") { throw new Error('Chat template must be a list of objects with "name" and "template" properties'); } chat_template[name2] = template; } this.chat_template = chat_template; } this._compiled_template_cache = /* @__PURE__ */ new Map(); } /** * Returns the value of the first matching key in the tokenizer config object. * @param {...string} keys One or more keys to search for in the tokenizer config object. * @returns {string|null} The value associated with the first matching key, or null if no match is found. * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". */ getToken(...keys) { for (const key of keys) { const item = this._tokenizer_config[key]; if (!item) continue; if (typeof item === "object") { if (item.__type === "AddedToken") { return item.content; } else { throw Error(`Unknown token: ${item}`); } } else { return item; } } return null; } /** * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. * * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. * * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. */ static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main", legacy = null } = {}) { const info = await loadTokenizer(pretrained_model_name_or_path, { progress_callback, config, cache_dir, local_files_only, revision, legacy }); return new this(...info); } /** * @typedef {number[]|number[][]|Tensor} BatchEncodingItem * * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. */ /** * Encode/tokenize the given text(s). * @param {string|string[]} text The text to tokenize. * @param {Object} options An optional object containing the following properties: * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids. * @returns {BatchEncoding} Object to be passed to the model. */ _call(text, { text_pair = null, add_special_tokens = true, padding = false, truncation = null, max_length = null, return_tensor = true, // Different to HF return_token_type_ids = null } = {}) { const isBatched = Array.isArray(text); let encodedTokens; if (isBatched) { if (text.length === 0) { throw Error("text array must be non-empty"); } if (text_pair !== null) { if (!Array.isArray(text_pair)) { throw Error("text_pair must also be an array"); } else if (text.length !== text_pair.length) { throw Error("text and text_pair must have the same length"); } encodedTokens = text.map( (t, i) => this._encode_plus(t, text_pair[i], { add_special_tokens, return_token_type_ids }) ); } else { encodedTokens = text.map((x2) => this._encode_plus(x2, null, { add_special_tokens, return_token_type_ids })); } } else { if (text === null || text === void 0) { throw Error("text may not be null or undefined"); } if (Array.isArray(text_pair)) { throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array)."); } encodedTokens = [this._encode_plus(text, text_pair, { add_special_tokens, return_token_type_ids })]; } if (max_length === null) { if (padding === "max_length") { max_length = this.model_max_length; } else { max_length = max(encodedTokens.map((x2) => x2.input_ids.length))[0]; } } else { if (!truncation) { console.warn(`Truncation was not explicitly activated but \`max_length\` is provided a specific value, please use \`truncation=true\` to explicitly truncate examples to max length.`); } } max_length = Math.min(max_length, this.model_max_length); if (padding || truncation) { for (let i = 0; i < encodedTokens.length; ++i) { if (encodedTokens[i].input_ids.length === max_length) { continue; } else if (encodedTokens[i].input_ids.length > max_length) { if (truncation) { truncateHelper(encodedTokens[i], max_length); } } else { if (padding) { padHelper( encodedTokens[i], max_length, (key) => key === "input_ids" ? this.pad_token_id : 0, this.padding_side ); } } } } const result = {}; if (return_tensor) { if (!(padding && truncation)) { if (encodedTokens.some((x2) => { for (const key of Object.keys(x2)) { if (x2[key].length !== encodedTokens[0][key]?.length) { return true; } } return false; })) { throw Error( "Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length." ); } } const dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; for (const key of Object.keys(encodedTokens[0])) { result[key] = new Tensor( "int64", BigInt64Array.from(encodedTokens.flatMap((x2) => x2[key]).map(BigInt)), dims ); } } else { for (const key of Object.keys(encodedTokens[0])) { result[key] = encodedTokens.map((x2) => x2[key]); } if (!isBatched) { for (const key of Object.keys(result)) { result[key] = result[key][0]; } } } return ( /** @type {BatchEncoding} */ result ); } /** * Encodes a single text using the preprocessor pipeline of the tokenizer. * * @param {string|null} text The text to encode. * @returns {string[]|null} The encoded tokens. */ _encode_text(text) { if (text === null) return null; const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter((x2) => x2) : [text]; const tokens = sections.map((x2, section_index) => { const addedToken = this.added_tokens.find((t) => t.content === x2); if (addedToken !== void 0) { return x2; } else { if (this.remove_space === true) { x2 = x2.trim().split(/\s+/).join(" "); } if (this.do_lowercase_and_remove_accent) { x2 = lowercase_and_remove_accent(x2); } if (this.normalizer !== null) { x2 = this.normalizer(x2); } if (x2.length === 0) { return []; } const sectionTokens = this.pre_tokenizer !== null ? this.pre_tokenizer(x2, { section_index }) : [x2]; const tokens2 = this.model(sectionTokens); return tokens2; } }).flat(); return tokens; } /** * Encodes a single text or a pair of texts using the model's tokenizer. * * @param {string} text The text to encode. * @param {string|null} text_pair The optional second text to encode. * @param {Object} options An optional object containing the following properties: * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. * @returns {EncodingSingle} An object containing the encoded text. * @private */ _encode_plus(text, text_pair = null, { add_special_tokens = true, return_token_type_ids = null } = {}) { const tokens = this._encode_text(text); const tokens2 = this._encode_text(text_pair); const combinedTokens = this.post_processor ? this.post_processor(tokens, tokens2, { add_special_tokens }) : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) }; const input_ids = this.model.convert_tokens_to_ids(combinedTokens.tokens); const result = { input_ids, attention_mask: new Array(input_ids.length).fill(1) }; if ((return_token_type_ids ?? this.return_token_type_ids) && combinedTokens.token_type_ids) { result.token_type_ids = combinedTokens.token_type_ids; } return result; } /** * Encodes a single text or a pair of texts using the model's tokenizer. * * @param {string} text The text to encode. * @param {string|null} text_pair The optional second text to encode. * @param {Object} options An optional object containing the following properties: * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. * @returns {number[]} An array of token IDs representing the encoded text(s). */ encode(text, text_pair = null, { add_special_tokens = true, return_token_type_ids = null } = {}) { const { input_ids } = this._encode_plus(text, text_pair, { add_special_tokens, return_token_type_ids }); return input_ids; } /** * Decode a batch of tokenized sequences. * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. * @param {Object} decode_args (Optional) Object with decoding arguments. * @returns {string[]} List of decoded sequences. */ batch_decode(batch, decode_args = {}) { if (batch instanceof Tensor) { batch = batch.tolist(); } return batch.map((x2) => this.decode(x2, decode_args)); } /** * Decodes a sequence of token IDs back to a string. * * @param {number[]|Tensor} token_ids List/Tensor of token IDs to decode. * @param {Object} [decode_args={}] * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. * * @returns {string} The decoded string. * @throws {Error} If `token_ids` is not a non-empty array of integers. */ decode(token_ids, decode_args = {}) { if (token_ids instanceof Tensor) { token_ids = prepareTensorForDecode(token_ids); } if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) { throw Error("token_ids must be a non-empty array of integers."); } return this.decode_single(token_ids, decode_args); } /** * Decode a single list of token ids to a string. * @param {number[]} token_ids List of token ids to decode * @param {Object} decode_args Optional arguments for decoding * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. * @returns {string} The decoded string */ decode_single(token_ids, { skip_special_tokens = false, clean_up_tokenization_spaces = null }) { let tokens = this.model.convert_ids_to_tokens(token_ids); if (skip_special_tokens) { tokens = tokens.filter((x2) => !this.special_tokens.includes(x2)); } let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" "); if (this.decoder && this.decoder.end_of_word_suffix) { decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, " "); if (skip_special_tokens) { decoded = decoded.trim(); } } if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { decoded = clean_up_tokenization(decoded); } return decoded; } get default_chat_template() { if (!this._warned_about_chat_template) { console.warn( "No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information." ); this._warned_about_chat_template = true; } return this._default_chat_template; } /** * Converts a list of message objects with `"role"` and `"content"` keys to a list of token * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to * determine the format and control tokens to use when converting. When chat_template is None, it will fall back * to the default_chat_template specified at the class level. * * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. * * **Example:** Applying a chat template to a conversation. * * ```javascript * import { AutoTokenizer } from "@xenova/transformers"; * * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1"); * * const chat = [ * { "role": "user", "content": "Hello, how are you?" }, * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, * { "role": "user", "content": "I'd like to show off how chat templating works!" }, * ] * * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" * * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] * ``` * * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys. * @param {Object} options An optional object containing the following properties: * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If * this is not passed, the model's default chat template will be used instead. * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate * the start of an assistant message. This is useful when you want to generate a response from the model. * Note that this argument will be passed to the chat template, and so it must be supported in the * template for this argument to have any effect. * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. * If not specified, the tokenizer's `max_length` attribute will be used as a default. * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer. * @returns {string | Tensor | number[]| number[][]} The tokenized output. */ apply_chat_template(conversation, { chat_template = null, add_generation_prompt = false, tokenize: tokenize2 = true, padding = false, truncation = false, max_length = null, return_tensor = true, tokenizer_kwargs = {}, ...kwargs } = {}) { if (this.chat_template && typeof this.chat_template === "object" || this.chat_template === null && this.default_chat_template && typeof this.default_chat_template === "object") { const template_dict = this.chat_template ?? this.default_chat_template; if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) { chat_template = template_dict[chat_template]; } else if (chat_template === null && "default" in template_dict) { chat_template = template_dict["default"]; } else if (chat_template === null) { throw Error( `This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(template_dict).sort()}.` ); } } else { chat_template ??= this.chat_template ?? this.default_chat_template; } if (typeof chat_template !== "string") { throw Error(`chat_template must be a string, but got ${typeof chat_template}`); } let compiledTemplate = this._compiled_template_cache.get(chat_template); if (compiledTemplate === void 0) { compiledTemplate = new Template(chat_template); this._compiled_template_cache.set(chat_template, compiledTemplate); } const special_tokens_map = /* @__PURE__ */ Object.create(null); for (const key of SPECIAL_TOKEN_ATTRIBUTES) { const value = this.getToken(key); if (value) { special_tokens_map[key] = value; } } const rendered = compiledTemplate.render({ messages: conversation, add_generation_prompt, ...special_tokens_map, ...kwargs }); if (tokenize2) { return this._call(rendered, { add_special_tokens: false, padding, truncation, max_length, return_tensor, ...tokenizer_kwargs }).input_ids; } return rendered; } }; BertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; AlbertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; MobileBertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; SqueezeBertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; DebertaTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; DebertaV2Tokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; HerbertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; ConvBertTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; RoFormerTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; DistilBertTokenizer = class extends PreTrainedTokenizer { }; CamembertTokenizer = class extends PreTrainedTokenizer { }; XLMTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); } }; ElectraTokenizer = class extends PreTrainedTokenizer { return_token_type_ids = true; }; T5Tokenizer = class extends PreTrainedTokenizer { }; GPT2Tokenizer = class extends PreTrainedTokenizer { _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`; }; BartTokenizer = class extends PreTrainedTokenizer { }; MBartTokenizer = class extends PreTrainedTokenizer { constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; this.language_codes = this.special_tokens.filter((x2) => this.languageRegex.test(x2)); this.lang_to_token = (x2) => x2; } /** * Helper function to build translation inputs for an `MBartTokenizer`. * @param {string|string[]} raw_inputs The text to tokenize. * @param {Object} tokenizer_options Options to be sent to the tokenizer * @param {Object} generate_kwargs Generation options. * @returns {Object} Object to be passed to the model. */ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); } }; MBart50Tokenizer = class extends MBartTokenizer { }; RobertaTokenizer = class extends PreTrainedTokenizer { }; BloomTokenizer = class extends GPT2Tokenizer { // NOTE: `GPT2Tokenizer` to get the correct chat template constructor(tokenizerJSON, tokenizerConfig) { const splitChars = ".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C"; const patternObject = tokenizerJSON.pre_tokenizer?.pretokenizers[0]?.pattern; if (patternObject && patternObject.Regex === ` ?[^(\\s|[${splitChars}])]+`) { patternObject.Regex = ` ?[^\\s${splitChars}]+`; } super(tokenizerJSON, tokenizerConfig); } }; SPIECE_UNDERLINE = "\u2581"; LlamaTokenizer = class extends PreTrainedTokenizer { _default_chat_template = `{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`; DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."; constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.use_default_system_prompt = tokenizerConfig.use_default_system_prompt ?? false; this.legacy = tokenizerConfig.legacy ?? true; if (!this.legacy) { this.normalizer = null; this.pre_tokenizer = new MetaspacePreTokenizer({ replacement: SPIECE_UNDERLINE, add_prefix_space: true, prepend_scheme: "first" }); } } /** * Helper function to handle legacy encoding of SPM tokenizers. * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387 * @param {string} text The text to encode. * @returns {string[]} The encoded tokens. */ _encode_text(text) { if (text === null) return null; if (this.legacy || text.length === 0) { return super._encode_text(text); } let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " ")); if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) { tokens = tokens.slice(1); } return tokens; } get default_chat_template() { return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT", this.use_default_system_prompt ? "true" : "false").replaceAll("DEFAULT_SYSTEM_MESSAGE", this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n", "\\n").replaceAll("'", "\\'")); } }; CodeLlamaTokenizer = class extends LlamaTokenizer { }; XLMRobertaTokenizer = class extends PreTrainedTokenizer { }; MPNetTokenizer = class extends PreTrainedTokenizer { }; FalconTokenizer = class extends PreTrainedTokenizer { }; GPTNeoXTokenizer = class extends PreTrainedTokenizer { }; EsmTokenizer = class extends PreTrainedTokenizer { }; Qwen2Tokenizer = class extends PreTrainedTokenizer { }; GemmaTokenizer = class extends PreTrainedTokenizer { _default_chat_template = "{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + '\n' + message['content'] | trim + '\n' }}{% endfor %}{% if add_generation_prompt %}{{'model\n'}}{% endif %}"; }; Grok1Tokenizer = class extends PreTrainedTokenizer { }; NllbTokenizer = class extends PreTrainedTokenizer { constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; this.language_codes = this.special_tokens.filter((x2) => this.languageRegex.test(x2)); this.lang_to_token = (x2) => x2; } /** * Helper function to build translation inputs for an `NllbTokenizer`. * @param {string|string[]} raw_inputs The text to tokenize. * @param {Object} tokenizer_options Options to be sent to the tokenizer * @param {Object} generate_kwargs Generation options. * @returns {Object} Object to be passed to the model. */ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); } }; M2M100Tokenizer = class extends PreTrainedTokenizer { constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.languageRegex = /^__[a-z]{2,3}__$/; this.language_codes = this.special_tokens.filter((x2) => this.languageRegex.test(x2)).map((x2) => x2.slice(2, -2)); this.lang_to_token = (x2) => `__${x2}__`; } /** * Helper function to build translation inputs for an `M2M100Tokenizer`. * @param {string|string[]} raw_inputs The text to tokenize. * @param {Object} tokenizer_options Options to be sent to the tokenizer * @param {Object} generate_kwargs Generation options. * @returns {Object} Object to be passed to the model. */ _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); } }; WHISPER_LANGUAGES = [ ["en", "english"], ["zh", "chinese"], ["de", "german"], ["es", "spanish"], ["ru", "russian"], ["ko", "korean"], ["fr", "french"], ["ja", "japanese"], ["pt", "portuguese"], ["tr", "turkish"], ["pl", "polish"], ["ca", "catalan"], ["nl", "dutch"], ["ar", "arabic"], ["sv", "swedish"], ["it", "italian"], ["id", "indonesian"], ["hi", "hindi"], ["fi", "finnish"], ["vi", "vietnamese"], ["he", "hebrew"], ["uk", "ukrainian"], ["el", "greek"], ["ms", "malay"], ["cs", "czech"], ["ro", "romanian"], ["da", "danish"], ["hu", "hungarian"], ["ta", "tamil"], ["no", "norwegian"], ["th", "thai"], ["ur", "urdu"], ["hr", "croatian"], ["bg", "bulgarian"], ["lt", "lithuanian"], ["la", "latin"], ["mi", "maori"], ["ml", "malayalam"], ["cy", "welsh"], ["sk", "slovak"], ["te", "telugu"], ["fa", "persian"], ["lv", "latvian"], ["bn", "bengali"], ["sr", "serbian"], ["az", "azerbaijani"], ["sl", "slovenian"], ["kn", "kannada"], ["et", "estonian"], ["mk", "macedonian"], ["br", "breton"], ["eu", "basque"], ["is", "icelandic"], ["hy", "armenian"], ["ne", "nepali"], ["mn", "mongolian"], ["bs", "bosnian"], ["kk", "kazakh"], ["sq", "albanian"], ["sw", "swahili"], ["gl", "galician"], ["mr", "marathi"], ["pa", "punjabi"], ["si", "sinhala"], ["km", "khmer"], ["sn", "shona"], ["yo", "yoruba"], ["so", "somali"], ["af", "afrikaans"], ["oc", "occitan"], ["ka", "georgian"], ["be", "belarusian"], ["tg", "tajik"], ["sd", "sindhi"], ["gu", "gujarati"], ["am", "amharic"], ["yi", "yiddish"], ["lo", "lao"], ["uz", "uzbek"], ["fo", "faroese"], ["ht", "haitian creole"], ["ps", "pashto"], ["tk", "turkmen"], ["nn", "nynorsk"], ["mt", "maltese"], ["sa", "sanskrit"], ["lb", "luxembourgish"], ["my", "myanmar"], ["bo", "tibetan"], ["tl", "tagalog"], ["mg", "malagasy"], ["as", "assamese"], ["tt", "tatar"], ["haw", "hawaiian"], ["ln", "lingala"], ["ha", "hausa"], ["ba", "bashkir"], ["jw", "javanese"], ["su", "sundanese"] ]; WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ ...WHISPER_LANGUAGES.map(([k4, v]) => [v, k4]), ...[ ["burmese", "my"], ["valencian", "ca"], ["flemish", "nl"], ["haitian", "ht"], ["letzeburgesch", "lb"], ["pushto", "ps"], ["panjabi", "pa"], ["moldavian", "ro"], ["moldovan", "ro"], ["sinhalese", "si"], ["castilian", "es"] ] ]); WhisperTokenizer = class extends PreTrainedTokenizer { _default_chat_template = `{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`; /** * Decodes automatic speech recognition (ASR) sequences. * @param {Array<{tokens: number[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. * @param {Object} options The options to use for decoding. * @returns {Array, text: string}>}>} The decoded sequences. */ _decode_asr(sequences, { return_timestamps = false, return_language = false, time_precision = null, force_full_sequences = true } = {}) { if (time_precision === null) { throw Error("Must specify time_precision"); } let last_language = null; const returnWordTimestamps = return_timestamps === "word"; function new_chunk() { return { "language": last_language, "timestamp": [null, null], "text": "" }; } const chunks = []; let chunk = new_chunk(); let time_offset = 0; const timestamp_begin = this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; let previous_tokens = []; let previous_token_timestamps = []; let skip = false; let right_stride_start = null; const all_special_ids = new Set(this.all_special_ids); for (const output of sequences) { const token_ids = output.tokens; const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; let last_timestamp = null; let first_timestamp = timestamp_begin; if ("stride" in output) { const [chunk_len, stride_left, stride_right] = output.stride; time_offset -= stride_left; right_stride_start = chunk_len - stride_right; if (stride_left) { first_timestamp = stride_left / time_precision + timestamp_begin; } if (stride_right) { for (let i = token_ids.length - 1; i >= 0; --i) { const token = token_ids[i]; if (token >= timestamp_begin) { if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { break; } last_timestamp = token; } } } } let current_tokens = []; let current_token_timestamps = []; for (let i = 0; i < token_ids.length; ++i) { const token = token_ids[i]; if (all_special_ids.has(token)) { const text = this.decode([token]); const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); if (language !== void 0) { if (last_language !== null && language !== last_language && !return_timestamps) { previous_tokens.push(current_tokens); const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; const resolved_text = this.decode(resolved_tokens); chunk.text = resolved_text; chunks.push(chunk); previous_tokens = []; current_tokens = []; chunk = new_chunk(); } last_language = chunk.language = language; } else { } } else if (token >= timestamp_begin) { const time = (token - timestamp_begin) * time_precision + time_offset; const rounded_time = round(time, 2); if (last_timestamp !== null && token >= last_timestamp) { skip = true; } else if (skip || previous_tokens.length > 0 && token < first_timestamp) { skip = false; } else if (chunk.timestamp[0] === null) { chunk.timestamp[0] = rounded_time; } else { if (rounded_time === chunk.timestamp[0]) { } else { chunk.timestamp[1] = rounded_time; previous_tokens.push(current_tokens); if (returnWordTimestamps) { previous_token_timestamps.push(current_token_timestamps); } const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( previous_tokens, previous_token_timestamps ); const resolved_text = this.decode(resolved_tokens); chunk.text = resolved_text; if (returnWordTimestamps) { chunk.words = this.collateWordTimestamps( resolved_tokens, resolved_token_timestamps, last_language ); } chunks.push(chunk); previous_tokens = []; current_tokens = []; previous_token_timestamps = []; current_token_timestamps = []; chunk = new_chunk(); } } } else { current_tokens.push(token); if (returnWordTimestamps) { let start_time = round(token_timestamps[i] + time_offset, 2); let end_time; if (i + 1 < token_timestamps.length) { end_time = round(token_timestamps[i + 1] + time_offset, 2); } else { end_time = null; } current_token_timestamps.push([start_time, end_time]); } } } if ("stride" in output) { const [chunk_len, stride_left, stride_right] = output.stride; time_offset += chunk_len - stride_right; } if (current_tokens.length > 0) { previous_tokens.push(current_tokens); if (returnWordTimestamps) { previous_token_timestamps.push(current_token_timestamps); } } else if (previous_tokens.every((p) => p.length === 0)) { chunk = new_chunk(); previous_tokens = []; current_tokens = []; previous_token_timestamps = []; current_token_timestamps = []; } } if (previous_tokens.length > 0) { if (force_full_sequences && return_timestamps) { throw new Error( "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation." ); } const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps); const resolved_text = this.decode(resolved_tokens); chunk.text = resolved_text; if (returnWordTimestamps) { chunk.words = this.collateWordTimestamps( resolved_tokens, resolved_token_timestamps, last_language ); } chunks.push(chunk); } let optional = /* @__PURE__ */ Object.create(null); const full_text = chunks.map((chunk2) => chunk2.text).join(""); if (return_timestamps || return_language) { for (let i = 0; i < chunks.length; ++i) { const chunk2 = chunks[i]; if (!return_timestamps) { delete chunk2["timestamp"]; } if (!return_language) { delete chunk2["language"]; } } if (returnWordTimestamps) { const new_chunks = []; for (const chunk2 of chunks) { for (const word of chunk2.words) { new_chunks.push(word); } } optional = { "chunks": new_chunks }; } else { optional = { "chunks": chunks }; } } return [full_text, optional]; } /** * Finds the longest common sequence among the provided sequences. * @param {number[][]} sequences An array of sequences of token ids to compare. * @returns {number[][]} The longest common sequence found. * @throws {Error} If there is a bug within the function. * @private */ findLongestCommonSequence(sequences, token_timestamp_sequences = null) { let leftSequence = sequences[0]; let leftLength = leftSequence.length; let totalSequence = []; const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; for (let i = 1; i < sequences.length; ++i) { const rightSequence = sequences[i]; let max2 = 0; let maxIndices = [leftLength, leftLength, 0, 0]; const rightLength = rightSequence.length; for (let j3 = 1; j3 < leftLength + rightLength; ++j3) { const eps = j3 / 1e4; const leftStart2 = Math.max(0, leftLength - j3); const leftStop2 = Math.min(leftLength, leftLength + rightLength - j3); const left = leftSequence.slice(leftStart2, leftStop2); const rightStart2 = Math.max(0, j3 - leftLength); const rightStop2 = Math.min(rightLength, j3); const right = rightSequence.slice(rightStart2, rightStop2); if (left.length !== right.length) { throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); } const matches = left.filter((elem, idx) => elem === right[idx]).length; const matching = matches / j3 + eps; if (matches > 1 && matching > max2) { max2 = matching; maxIndices = [leftStart2, leftStop2, rightStart2, rightStop2]; } } const [leftStart, leftStop, rightStart, rightStop] = maxIndices; const leftMid = Math.floor((leftStop + leftStart) / 2); const rightMid = Math.floor((rightStop + rightStart) / 2); totalSequence.push(...leftSequence.slice(0, leftMid)); leftSequence = rightSequence.slice(rightMid); leftLength = leftSequence.length; if (use_token_timestamp_sequences) { total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); } } totalSequence.push(...leftSequence); if (use_token_timestamp_sequences) { total_token_timestamp_sequence.push(...left_token_timestamp_sequence); return [totalSequence, total_token_timestamp_sequence]; } else { return [totalSequence, []]; } } /** @private */ collateWordTimestamps(tokens, token_timestamps, language) { const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); const timings = []; for (let i = 0; i < words.length; ++i) { const indices = token_indices[i]; timings.push({ text: words[i], timestamp: [ token_timestamps[indices.at(0)][0], token_timestamps[indices.at(-1)][1] ] }); } return timings; } /** * Groups tokens by word. Returns a tuple containing a list of strings with the words, * and a list of `token_id` sequences with the tokens making up each word. * @param {number[]} tokens * @param {string} [language] * @param {string} prepend_punctionations * @param {string} append_punctuations * * @private */ combineTokensIntoWords(tokens, language, prepend_punctionations = `"'\u201C\xA1\xBF([{-`, append_punctuations = `"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`) { language = language ?? "english"; let words, word_tokens, token_indices; if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens); } else { [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens); } return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); } /** @type {PreTrainedTokenizer['decode']} */ decode(token_ids, decode_args) { let text; if (decode_args && decode_args.decode_with_timestamps) { if (token_ids instanceof Tensor) { token_ids = prepareTensorForDecode(token_ids); } text = this.decodeWithTimestamps(token_ids, decode_args); } else { text = super.decode(token_ids, decode_args); } return text; } /** * @param {number[]} token_ids List of token IDs to decode. * @param {Object} decode_args Optional arguments for decoding * @private */ decodeWithTimestamps(token_ids, decode_args) { const time_precision = decode_args?.time_precision ?? 0.02; const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1; let outputs = [[]]; for (const token of token_ids) { if (token >= timestamp_begin) { const timestamp = round((token - timestamp_begin) * time_precision, 2); outputs.push(`<|${timestamp}|>`); outputs.push([]); } else { outputs[outputs.length - 1].push(token); } } outputs = outputs.map( (s) => { if (typeof s === "string") { return s; } else { return super.decode(s, decode_args); } } ); return outputs.join(""); } /** * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. * @param {number[]} tokens * @returns {*} * @private */ splitTokensOnUnicode(tokens) { const decoded_full = this.decode(tokens, { // @ts-ignore decode_with_timestamps: true }); const replacement_char = "\uFFFD"; const words = []; const word_tokens = []; const token_indices = []; let current_tokens = []; let current_indices = []; let unicode_offset = 0; for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { const token = tokens[token_idx]; current_tokens.push(token); current_indices.push(token_idx); const decoded = this.decode(current_tokens, { // @ts-ignore decode_with_timestamps: true }); if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { words.push(decoded); word_tokens.push(current_tokens); token_indices.push(current_indices); current_tokens = []; current_indices = []; unicode_offset += decoded.length; } } return [words, word_tokens, token_indices]; } /** * Combine tokens into words by splitting at whitespace and punctuation tokens. * @param {number[]} tokens * @private */ splitTokensOnSpaces(tokens) { const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); const words = []; const word_tokens = []; const token_indices = []; const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, "gu"); for (let i = 0; i < subwords.length; ++i) { const subword = subwords[i]; const subword_tokens = subword_tokens_list[i]; const subword_indices = subword_indices_list[i]; const special = subword_tokens[0] >= this.model.tokens_to_ids.get("<|endoftext|>"); const with_space = subword.startsWith(" "); const trimmed = subword.trim(); const punctuation = punctuationRegex.test(trimmed); if (special || with_space || punctuation || words.length === 0) { words.push(subword); word_tokens.push(subword_tokens); token_indices.push(subword_indices); } else { const ix = words.length - 1; words[ix] += subword; word_tokens[ix].push(...subword_tokens); token_indices[ix].push(...subword_indices); } } return [words, word_tokens, token_indices]; } /** * Merges punctuation tokens with neighboring words. * @param {string[]} words * @param {number[][]} tokens * @param {number[][]} indices * @param {string} prepended * @param {string} appended * @private */ mergePunctuations(words, tokens, indices, prepended, appended) { const newWords = structuredClone(words); const newTokens = structuredClone(tokens); const newIndices = structuredClone(indices); let i = newWords.length - 2; let j3 = newWords.length - 1; while (i >= 0) { if (newWords[i].startsWith(" ") && prepended.includes(newWords[i].trim())) { newWords[j3] = newWords[i] + newWords[j3]; newTokens[j3] = mergeArrays(newTokens[i], newTokens[j3]); newIndices[j3] = mergeArrays(newIndices[i], newIndices[j3]); newWords[i] = ""; newTokens[i] = []; newIndices[i] = []; } else { j3 = i; } --i; } i = 0; j3 = 1; while (j3 < newWords.length) { if (!newWords[i].endsWith(" ") && appended.includes(newWords[j3])) { newWords[i] += newWords[j3]; newTokens[i] = mergeArrays(newTokens[i], newTokens[j3]); newIndices[i] = mergeArrays(newIndices[i], newIndices[j3]); newWords[j3] = ""; newTokens[j3] = []; newIndices[j3] = []; } else { i = j3; } ++j3; } return [ newWords.filter((x2) => x2), newTokens.filter((x2) => x2.length > 0), newIndices.filter((x2) => x2.length > 0) ]; } /** * Helper function to build translation inputs for a `WhisperTokenizer`, * depending on the language, task, and whether to predict timestamp tokens. * * Used to override the prefix tokens appended to the start of the label sequence. * * **Example: Get ids for a language** * ```javascript * // instantiate the tokenizer and set the prefix token to Spanish * const tokenizer = await WhisperTokenizer.from_pretrained('Xenova/whisper-tiny'); * const forced_decoder_ids = tokenizer.get_decoder_prompt_ids({ language: 'spanish' }); * // [(1, 50262), (2, 50363)] * ``` * * @param {Object} options Options to generate the decoder prompt. * @param {string} [options.language] The language of the transcription text. * The corresponding language id token is appended to the start of the sequence for multilingual * speech recognition and speech translation tasks, e.g. for "Spanish" the token "<|es|>" is appended * to the start of sequence. * @param {string} [options.task] Task identifier to append at the start of sequence (if any). * This should be used for mulitlingual fine-tuning, with "transcribe" for speech recognition and * "translate" for speech translation. * @param {boolean} [options.no_timestamps] Whether to add the <|notimestamps|> token at the start of the sequence. * @returns {number[][]} The decoder prompt ids. */ get_decoder_prompt_ids({ language = null, task = null, no_timestamps = true } = {}) { const forced_decoder_ids = []; if (language) { language = language.toLowerCase(); let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); if (language_code === void 0) { if (WHISPER_LANGUAGE_MAPPING.has(language)) { language_code = language; } else { const is_language_code = language.length === 2; const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(langs)}`); } } const language_token_id = this.model.tokens_to_ids.get(`<|${language_code}|>`); if (language_token_id === void 0) { throw new Error(`Unable to find language "${language_code}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`); } forced_decoder_ids.push(language_token_id); } else { forced_decoder_ids.push(null); } if (task) { task = task.toLowerCase(); if (task !== "transcribe" && task !== "translate") { throw new Error(`Task "${task}" is not supported. Must be one of: ["transcribe", "translate"]`); } const task_token_id = this.model.tokens_to_ids.get(`<|${task}|>`); if (task_token_id === void 0) { throw new Error(`Unable to find task "${task}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`); } forced_decoder_ids.push(task_token_id); } else { forced_decoder_ids.push(null); } if (no_timestamps) { const no_timestamps_id = this.model.tokens_to_ids.get(`<|notimestamps|>`); if (no_timestamps_id === void 0) { throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.'); } forced_decoder_ids.push(no_timestamps_id); } return forced_decoder_ids.map((x2, i) => [i + 1, x2]).filter((x2) => x2[1] !== null); } }; CodeGenTokenizer = class extends PreTrainedTokenizer { }; CLIPTokenizer = class extends PreTrainedTokenizer { }; SiglipTokenizer = class extends PreTrainedTokenizer { }; MarianTokenizer = class extends PreTrainedTokenizer { /** * Create a new MarianTokenizer instance. * @param {Object} tokenizerJSON The JSON of the tokenizer. * @param {Object} tokenizerConfig The config of the tokenizer. */ constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.languageRegex = /^(>>\w+<<)\s*/g; this.supported_language_codes = this.model.vocab.filter( (x2) => this.languageRegex.test(x2) ); console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); } /** * Encodes a single text. Overriding this method is necessary since the language codes * must be removed before encoding with sentencepiece model. * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 * * @param {string|null} text The text to encode. * @returns {Array} The encoded tokens. */ _encode_text(text) { if (text === null) return null; const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); if (remainder.length === 0) { return super._encode_text(matchInfo); } else if (remainder.length === 2) { const [language, text2] = remainder; if (!this.supported_language_codes.includes(language)) { console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`); } return mergeArrays([language], super._encode_text(text2)); } } }; Wav2Vec2CTCTokenizer = class extends PreTrainedTokenizer { }; BlenderbotTokenizer = class extends PreTrainedTokenizer { _default_chat_template = `{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}`; }; BlenderbotSmallTokenizer = class extends BlenderbotTokenizer { }; SpeechT5Tokenizer = class extends PreTrainedTokenizer { }; NougatTokenizer = class extends PreTrainedTokenizer { }; VitsTokenizer = class extends PreTrainedTokenizer { constructor(tokenizerJSON, tokenizerConfig) { super(tokenizerJSON, tokenizerConfig); this.decoder = new VitsDecoder({}); } }; CohereTokenizer = class extends PreTrainedTokenizer { }; AutoTokenizer = class { static TOKENIZER_CLASS_MAPPING = { T5Tokenizer, DistilBertTokenizer, CamembertTokenizer, DebertaTokenizer, DebertaV2Tokenizer, BertTokenizer, HerbertTokenizer, ConvBertTokenizer, RoFormerTokenizer, XLMTokenizer, ElectraTokenizer, MobileBertTokenizer, SqueezeBertTokenizer, AlbertTokenizer, GPT2Tokenizer, BartTokenizer, MBartTokenizer, MBart50Tokenizer, RobertaTokenizer, WhisperTokenizer, CodeGenTokenizer, CLIPTokenizer, SiglipTokenizer, MarianTokenizer, BloomTokenizer, NllbTokenizer, M2M100Tokenizer, LlamaTokenizer, CodeLlamaTokenizer, XLMRobertaTokenizer, MPNetTokenizer, FalconTokenizer, GPTNeoXTokenizer, EsmTokenizer, Wav2Vec2CTCTokenizer, BlenderbotTokenizer, BlenderbotSmallTokenizer, SpeechT5Tokenizer, NougatTokenizer, VitsTokenizer, Qwen2Tokenizer, GemmaTokenizer, Grok1Tokenizer, CohereTokenizer, // Base case: PreTrainedTokenizer }; /** * Instantiate one of the tokenizer classes of the library from a pretrained model. * * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) * * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a * user or organization name, like `dbmdz/bert-base-german-cased`. * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. * * @returns {Promise} A new instance of the PreTrainedTokenizer class. */ static async from_pretrained(pretrained_model_name_or_path, { quantized = true, progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main", legacy = null } = {}) { const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { quantized, progress_callback, config, cache_dir, local_files_only, revision, legacy }); const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer"; let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName]; if (!cls) { console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); cls = PreTrainedTokenizer; } return new cls(tokenizerJSON, tokenizerConfig); } }; } }); // node_modules/@xenova/transformers/src/configs.js async function loadConfig(pretrained_model_name_or_path, options) { let info = await getModelJSON(pretrained_model_name_or_path, "config.json", true, options); return info; } var PretrainedConfig, AutoConfig; var init_configs = __esm({ "node_modules/@xenova/transformers/src/configs.js"() { init_hub(); PretrainedConfig = class { // NOTE: Typo in original /** * Create a new PreTrainedTokenizer instance. * @param {Object} configJSON The JSON of the config. */ constructor(configJSON) { this.model_type = null; this.is_encoder_decoder = false; Object.assign(this, configJSON); } /** * Loads a pre-trained config from the given `pretrained_model_name_or_path`. * * @param {string} pretrained_model_name_or_path The path to the pre-trained config. * @param {PretrainedOptions} options Additional options for loading the config. * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. * * @returns {Promise} A new instance of the `PretrainedConfig` class. */ static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { let data = config ?? await loadConfig(pretrained_model_name_or_path, { progress_callback, config, cache_dir, local_files_only, revision }); return new this(data); } }; AutoConfig = class { /** @type {PretrainedConfig.from_pretrained} */ static async from_pretrained(...args) { return PretrainedConfig.from_pretrained(...args); } }; } }); // node_modules/@xenova/transformers/src/utils/generation.js var LogitsProcessorList, LogitsProcessor, ForceTokensLogitsProcessor, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, SuppressTokensAtBeginLogitsProcessor, WhisperTimeStampLogitsProcessor, NoRepeatNGramLogitsProcessor, RepetitionPenaltyLogitsProcessor, MinLengthLogitsProcessor, MinNewTokensLengthLogitsProcessor, NoBadWordsLogitsProcessor, GenerationConfig, Sampler, GreedySampler, MultinomialSampler, BeamSearchSampler; var init_generation = __esm({ "node_modules/@xenova/transformers/src/utils/generation.js"() { init_tensor(); init_core(); init_maths(); LogitsProcessorList = class extends Callable { /** * Constructs a new instance of `LogitsProcessorList`. */ constructor() { super(); this.processors = []; } /** * Adds a new logits processor to the list. * * @param {LogitsProcessor} item The logits processor function to add. */ push(item) { this.processors.push(item); } /** * Adds multiple logits processors to the list. * * @param {LogitsProcessor[]} items The logits processor functions to add. */ extend(items) { this.processors.push(...items); } /** * Applies all logits processors in the list to a batch of logits, modifying them in-place. * * @param {number[]} input_ids The input IDs for the language model. * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single * input sequence in the batch. */ _call(input_ids, batchedLogits) { for (let logits of batchedLogits) { this.processors.forEach( (func) => func(input_ids, logits) ); } } [Symbol.iterator]() { return this.processors.values(); } }; LogitsProcessor = class extends Callable { /** * Apply the processor to the input logits. * * @abstract * @param {Array} input_ids The input ids. * @param {Tensor} logits The logits to process. * @throws {Error} Throws an error if `_call` is not implemented in the subclass. */ _call(input_ids, logits) { throw Error("`_call` should be implemented in a subclass"); } }; ForceTokensLogitsProcessor = class extends LogitsProcessor { /** * Constructs a new instance of `ForceTokensLogitsProcessor`. * * @param {Array} forced_decoder_ids The ids of tokens that should be forced. */ constructor(forced_decoder_ids) { super(); this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []); } /** * Apply the processor to the input logits. * * @param {Array} input_ids The input ids. * @param {Tensor} logits The logits to process. * @returns {Tensor} The processed logits. */ _call(input_ids, logits) { let map = this.force_token_map[input_ids.length]; if (exists(map)) { logits.data.fill(-Infinity); logits.data[map] = 0; } return logits; } }; ForcedBOSTokenLogitsProcessor = class extends LogitsProcessor { /** * Create a ForcedBOSTokenLogitsProcessor. * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. */ constructor(bos_token_id) { super(); this.bos_token_id = bos_token_id; } /** * Apply the BOS token forcing to the logits. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The logits with BOS token forcing. */ _call(input_ids, logits) { if (input_ids.length === 1) { logits.data.fill(-Infinity); logits.data[this.bos_token_id] = 0; } return logits; } }; ForcedEOSTokenLogitsProcessor = class extends LogitsProcessor { /** * Create a ForcedEOSTokenLogitsProcessor. * @param {number} max_length Max length of the sequence. * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced. */ constructor(max_length, forced_eos_token_id) { super(); this.max_length = max_length; this.forced_eos_token_id = forced_eos_token_id; } /** * Apply the processor to input_ids and logits. * * @param {number[]} input_ids The input ids. * @param {Tensor} logits The logits tensor. */ _call(input_ids, logits) { } }; SuppressTokensAtBeginLogitsProcessor = class extends LogitsProcessor { /** * Create a SuppressTokensAtBeginLogitsProcessor. * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. * @param {number} begin_index The number of tokens to generate before suppressing tokens. */ constructor(begin_suppress_tokens, begin_index) { super(); this.begin_suppress_tokens = begin_suppress_tokens; this.begin_index = begin_index; } /** * Apply the BOS token forcing to the logits. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The logits with BOS token forcing. */ _call(input_ids, logits) { if (input_ids.length === this.begin_index) { for (let token_id of this.begin_suppress_tokens) { logits.data[token_id] = -Infinity; } } return logits; } }; WhisperTimeStampLogitsProcessor = class extends LogitsProcessor { /** * Constructs a new WhisperTimeStampLogitsProcessor. * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model. * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token. * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp. * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp. * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear. */ constructor(generate_config) { super(); this.eos_token_id = generate_config.eos_token_id; this.no_timestamps_token_id = generate_config.no_timestamps_token_id; this.timestamp_begin = this.no_timestamps_token_id + 1; this.begin_index = (generate_config.forced_decoder_ids || []).length + 2; if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) { this.begin_index -= 1; } this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; } /** * Modify the logits to handle timestamp tokens. * @param {Array} input_ids The input sequence of tokens. * @param {Tensor} logits The logits output by the model. * @returns {Tensor} The modified logits. */ _call(input_ids, logits) { const logitsData = ( /** @type {Float32Array} */ logits.data ); logitsData[this.no_timestamps_token_id] = -Infinity; if (input_ids.length === this.begin_index - 1) { logitsData.fill(-Infinity); logitsData[this.timestamp_begin] = 0; return logits; } const seq = input_ids.slice(this.begin_index); const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; if (last_was_timestamp) { if (penultimate_was_timestamp) { logitsData.subarray(this.timestamp_begin).fill(-Infinity); } else { logitsData.subarray(0, this.eos_token_id).fill(-Infinity); } } if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) { const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; logitsData.subarray(last_allowed + 1).fill(-Infinity); } const logprobs = log_softmax(logitsData); const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0]; if (timestamp_logprob > max_text_token_logprob) { logitsData.subarray(0, this.timestamp_begin).fill(-Infinity); } return logits; } }; NoRepeatNGramLogitsProcessor = class extends LogitsProcessor { /** * Create a NoRepeatNGramLogitsProcessor. * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. */ constructor(no_repeat_ngram_size) { super(); this.no_repeat_ngram_size = no_repeat_ngram_size; } /** * Generate n-grams from a sequence of token ids. * @param {number[]} prevInputIds List of previous input ids * @returns {Map} Map of generated n-grams */ getNgrams(prevInputIds) { const curLen = prevInputIds.length; const ngrams = []; for (let j3 = 0; j3 < curLen + 1 - this.no_repeat_ngram_size; ++j3) { const ngram = []; for (let k4 = 0; k4 < this.no_repeat_ngram_size; ++k4) { ngram.push(prevInputIds[j3 + k4]); } ngrams.push(ngram); } const generatedNgram = /* @__PURE__ */ new Map(); for (const ngram of ngrams) { const prevNgram = ngram.slice(0, ngram.length - 1); const prevNgramKey = JSON.stringify(prevNgram); const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; prevNgramValue.push(ngram[ngram.length - 1]); generatedNgram.set(prevNgramKey, prevNgramValue); } return generatedNgram; } /** * Generate n-grams from a sequence of token ids. * @param {Map} bannedNgrams Map of banned n-grams * @param {number[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ getGeneratedNgrams(bannedNgrams, prevInputIds) { const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); const banned = bannedNgrams.get(JSON.stringify(ngramIdx)) ?? []; return banned; } /** * Calculate banned n-gram tokens * @param {number[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ calcBannedNgramTokens(prevInputIds) { const bannedTokens = []; if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { return bannedTokens; } else { const generatedNgrams = this.getNgrams(prevInputIds); const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds); return bannedTokens2; } } /** * Apply the no-repeat-ngram processor to the logits. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The logits with no-repeat-ngram processing. */ _call(input_ids, logits) { const bannedTokens = this.calcBannedNgramTokens(input_ids); for (const token of bannedTokens) { logits.data[token] = -Infinity; } return logits; } }; RepetitionPenaltyLogitsProcessor = class extends LogitsProcessor { /** * Create a RepetitionPenaltyLogitsProcessor. * @param {number} penalty The penalty to apply for repeated tokens. */ constructor(penalty) { super(); this.penalty = penalty; } /** * Apply the repetition penalty to the logits. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The logits with repetition penalty processing. */ _call(input_ids, logits) { for (const input_id of input_ids) { if (logits.data[input_id] < 0) { logits.data[input_id] *= this.penalty; } else { logits.data[input_id] /= this.penalty; } } return logits; } }; MinLengthLogitsProcessor = class extends LogitsProcessor { /** * Create a MinLengthLogitsProcessor. * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. */ constructor(min_length, eos_token_id) { super(); this.min_length = min_length; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The processed logits. */ _call(input_ids, logits) { if (input_ids.length < this.min_length) { for (const eos_token of this.eos_token_id) { logits.data[eos_token] = -Infinity; } } return logits; } }; MinNewTokensLengthLogitsProcessor = class extends LogitsProcessor { /** * Create a MinNewTokensLengthLogitsProcessor. * @param {number} prompt_length_to_skip The input tokens length. * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. */ constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { super(); this.prompt_length_to_skip = prompt_length_to_skip; this.min_new_tokens = min_new_tokens; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The processed logits. */ _call(input_ids, logits) { const new_tokens_length = input_ids.length - this.prompt_length_to_skip; if (new_tokens_length < this.min_new_tokens) { for (const eos_token of this.eos_token_id) { logits.data[eos_token] = -Infinity; } } return logits; } }; NoBadWordsLogitsProcessor = class extends LogitsProcessor { /** * Create a `NoBadWordsLogitsProcessor`. * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. */ constructor(bad_words_ids, eos_token_id) { super(); this.bad_words_ids = bad_words_ids; this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; } /** * Apply logit processor. * @param {Array} input_ids The input IDs. * @param {Object} logits The logits. * @returns {Object} The processed logits. */ _call(input_ids, logits) { for (const bad_word_ids of this.bad_words_ids) { let mark = true; for (let i = 1; i <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i) { if (bad_word_ids.at(-i - 1) !== input_ids.at(-i)) { mark = false; break; } } if (mark) { logits.data[bad_word_ids.at(-1)] = -Infinity; } } return logits; } }; GenerationConfig = /** @type {any} */ class { /** * Create a new GenerationConfig object. * @param {GenerationConfigType} kwargs */ constructor(kwargs = {}) { this.max_length = kwargs.max_length ?? 20; this.max_new_tokens = kwargs.max_new_tokens ?? null; this.min_length = kwargs.min_length ?? 0; this.min_new_tokens = kwargs.min_new_tokens ?? null; this.early_stopping = kwargs.early_stopping ?? false; this.max_time = kwargs.max_time ?? null; this.do_sample = kwargs.do_sample ?? false; this.num_beams = kwargs.num_beams ?? 1; this.num_beam_groups = kwargs.num_beam_groups ?? 1; this.penalty_alpha = kwargs.penalty_alpha ?? null; this.use_cache = kwargs.use_cache ?? true; this.temperature = kwargs.temperature ?? 1; this.top_k = kwargs.top_k ?? 50; this.top_p = kwargs.top_p ?? 1; this.typical_p = kwargs.typical_p ?? 1; this.epsilon_cutoff = kwargs.epsilon_cutoff ?? 0; this.eta_cutoff = kwargs.eta_cutoff ?? 0; this.diversity_penalty = kwargs.diversity_penalty ?? 0; this.repetition_penalty = kwargs.repetition_penalty ?? 1; this.encoder_repetition_penalty = kwargs.encoder_repetition_penalty ?? 1; this.length_penalty = kwargs.length_penalty ?? 1; this.no_repeat_ngram_size = kwargs.no_repeat_ngram_size ?? 0; this.bad_words_ids = kwargs.bad_words_ids ?? null; this.force_words_ids = kwargs.force_words_ids ?? null; this.renormalize_logits = kwargs.renormalize_logits ?? false; this.constraints = kwargs.constraints ?? null; this.forced_bos_token_id = kwargs.forced_bos_token_id ?? null; this.forced_eos_token_id = kwargs.forced_eos_token_id ?? null; this.remove_invalid_values = kwargs.remove_invalid_values ?? false; this.exponential_decay_length_penalty = kwargs.exponential_decay_length_penalty ?? null; this.suppress_tokens = kwargs.suppress_tokens ?? null; this.begin_suppress_tokens = kwargs.begin_suppress_tokens ?? null; this.forced_decoder_ids = kwargs.forced_decoder_ids ?? null; this.num_return_sequences = kwargs.num_return_sequences ?? 1; this.output_attentions = kwargs.output_attentions ?? false; this.output_hidden_states = kwargs.output_hidden_states ?? false; this.output_scores = kwargs.output_scores ?? false; this.return_dict_in_generate = kwargs.return_dict_in_generate ?? false; this.pad_token_id = kwargs.pad_token_id ?? null; this.bos_token_id = kwargs.bos_token_id ?? null; this.eos_token_id = kwargs.eos_token_id ?? null; this.encoder_no_repeat_ngram_size = kwargs.encoder_no_repeat_ngram_size ?? 0; this.decoder_start_token_id = kwargs.decoder_start_token_id ?? null; this.generation_kwargs = kwargs.generation_kwargs ?? {}; } }; Sampler = class extends Callable { /** * Creates a new Sampler object with the specified generation config. * @param {GenerationConfigType} generation_config The generation config. */ constructor(generation_config) { super(); this.generation_config = generation_config; } /** * Executes the sampler, using the specified logits. * @param {Tensor} logits * @param {number} index * @returns {void} */ _call(logits, index = -1) { return this.sample(logits, index); } /** * Abstract method for sampling the logits. * @param {Tensor} logits * @param {number} index * @throws {Error} */ sample(logits, index) { throw Error("sample should be implemented in subclasses."); } /** * Returns the specified logits as an array, with temperature applied. * @param {Tensor} logits * @param {number} index * @returns {Float32Array} */ getLogits(logits, index) { let vocabSize = logits.dims.at(-1); let logs = ( /** @type {Float32Array} */ logits.data ); if (index === -1) { logs = logs.slice(-vocabSize); } else { let startIndex = index * vocabSize; logs = logs.slice(startIndex, startIndex + vocabSize); } if (this.generation_config.temperature > 0) { logs = logs.map((x2) => x2 / this.generation_config.temperature); } return logs; } /** * Selects an item randomly based on the specified probabilities. * @param {Array} probabilities An array of probabilities to use for selection. * @returns {number} The index of the selected item. */ randomSelect(probabilities) { let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0); let r = Math.random() * sumProbabilities; for (let i = 0; i < probabilities.length; ++i) { r -= probabilities[i]; if (r <= 0) { return i; } } return 0; } /** * Returns a Sampler object based on the specified options. * @param {GenerationConfigType} generation_config An object containing options for the sampler. * @returns {Sampler} A Sampler object. */ static getSampler(generation_config) { if (generation_config.do_sample) { return new MultinomialSampler(generation_config); } else if (generation_config.num_beams > 1) { return new BeamSearchSampler(generation_config); } else { if (generation_config.num_return_sequences > 1) { throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`); } return new GreedySampler(generation_config); } } }; GreedySampler = class extends Sampler { /** * Sample the maximum probability of a given logits tensor. * @param {Tensor} logits * @param {number} [index=-1] * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). */ sample(logits, index = -1) { let logs = this.getLogits(logits, index); let argmax = max(logs)[1]; return [ [argmax, 0] ]; } }; MultinomialSampler = class extends Sampler { /** * Sample from the logits. * @param {Tensor} logits * @param {number} index * @returns {Array} */ sample(logits, index = -1) { let k4 = logits.dims.at(-1); if (this.generation_config.top_k > 0) { k4 = Math.min(this.generation_config.top_k, k4); } const logs = this.getLogits(logits, index); const topLogits = getTopItems(logs, k4); const probabilities = softmax(topLogits.map((x2) => x2[1])); return Array.from({ length: this.generation_config.num_beams }, () => { const sampledIndex = this.randomSelect(probabilities); return [ topLogits[sampledIndex][0], // token id Math.log(probabilities[sampledIndex]) // score ]; }); } }; BeamSearchSampler = class extends Sampler { /** * Sample from the logits. * @param {Tensor} logits * @param {number} index * @returns {Array} */ sample(logits, index = -1) { let k4 = logits.dims.at(-1); if (this.generation_config.top_k > 0) { k4 = Math.min(this.generation_config.top_k, k4); } const logs = this.getLogits(logits, index); const topLogits = getTopItems(logs, k4); const probabilities = softmax(topLogits.map((x2) => x2[1])); return Array.from({ length: this.generation_config.num_beams }, (_, i) => { return [ topLogits[i][0], // token id Math.log(probabilities[i]) // score ]; }); } }; } }); // node_modules/@xenova/transformers/src/models.js async function constructSession(pretrained_model_name_or_path, fileName, options) { let modelFileName = `onnx/${fileName}${options.quantized ? "_quantized" : ""}.onnx`; let buffer = await getModelFile(pretrained_model_name_or_path, modelFileName, true, options); try { return await InferenceSession.create(buffer, { executionProviders }); } catch (err) { if (executionProviders.length === 1 && executionProviders[0] === "wasm") { throw err; } console.warn(err); console.warn( "Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. " ); return await InferenceSession.create(buffer, { executionProviders: ["wasm"] }); } } function validateInputs(session, inputs) { const checkedInputs = /* @__PURE__ */ Object.create(null); const missingInputs = []; for (const inputName of session.inputNames) { const tensor = inputs[inputName]; if (!(tensor instanceof Tensor)) { missingInputs.push(inputName); continue; } checkedInputs[inputName] = env2.wasm.proxy ? tensor.clone() : tensor; } if (missingInputs.length > 0) { throw new Error( `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.` ); } const numInputsProvided = Object.keys(inputs).length; const numInputsNeeded = session.inputNames.length; if (numInputsProvided > numInputsNeeded) { let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName)); console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`); } return checkedInputs; } async function sessionRun(session, inputs) { const checkedInputs = validateInputs(session, inputs); try { let output = await session.run(checkedInputs); output = replaceTensors(output); return output; } catch (e) { console.error(`An error occurred during model execution: "${e}".`); console.error("Inputs given to model:", checkedInputs); throw e; } } function replaceTensors(obj) { for (let prop in obj) { if (obj[prop] instanceof ONNXTensor2) { obj[prop] = new Tensor(obj[prop]); } else if (typeof obj[prop] === "object") { replaceTensors(obj[prop]); } } return obj; } function toI64Tensor(items) { if (items instanceof Tensor) { return items; } if (items.length === 0) { throw Error("items must be non-empty"); } if (Array.isArray(items[0])) { if (items.some((x2) => x2.length !== items[0].length)) { throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length."); } return new Tensor( "int64", BigInt64Array.from(items.flat().map((x2) => BigInt(x2))), [items.length, items[0].length] ); } else { return new Tensor( "int64", BigInt64Array.from(items.map((x2) => BigInt(x2))), [1, items.length] ); } } function prepareAttentionMask(self2, tokens) { let pad_token_id = self2.config.pad_token_id ?? null; let eos_token_id = self2.config.eos_token_id ?? null; if (isIntegralNumber(eos_token_id)) { eos_token_id = [eos_token_id]; } let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1; let is_pad_token_not_equal_to_eos_token_id = eos_token_id === null || !eos_token_id.includes(pad_token_id); if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) { let data = BigInt64Array.from( // Note: != so that int matches bigint // @ts-ignore tokens.data.map((x2) => x2 != pad_token_id) ); return new Tensor("int64", data, tokens.dims); } else { return ones_like(tokens); } } function preparePositionIds(session, feeds, use_cache_branch) { if (!session.inputNames.includes("position_ids")) return; const data = new BigInt64Array(feeds.attention_mask.data.length); for (let i = 0; i < feeds.attention_mask.dims[0]; ++i) { let start = i * feeds.attention_mask.dims[1]; let sum = BigInt(0); for (let j3 = 0; j3 < feeds.attention_mask.dims[1]; ++j3) { const index = start + j3; if (feeds.attention_mask.data[index] === 0n) { data[index] = BigInt(1); } else { data[index] = sum; sum += feeds.attention_mask.data[index]; } } } feeds.position_ids = new Tensor("int64", data, feeds.attention_mask.dims); if (use_cache_branch) { feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1); } } function boolTensor(value) { return new Tensor("bool", [value], [1]); } async function seq2seqForward(self2, model_inputs) { let { encoder_outputs, past_key_values } = model_inputs; if (!encoder_outputs) { encoder_outputs = (await encoderForward(self2, model_inputs)).last_hidden_state; } let decoderFeeds = { input_ids: model_inputs.decoder_input_ids, encoder_hidden_states: encoder_outputs }; const use_cache_branch = !!past_key_values; if (self2.decoder_merged_session.inputNames.includes("use_cache_branch")) { decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); } if (self2.decoder_merged_session.inputNames.includes("encoder_attention_mask")) { decoderFeeds.encoder_attention_mask = model_inputs.attention_mask; } preparePositionIds(self2.decoder_merged_session, decoderFeeds, use_cache_branch); self2.addPastKeyValues(decoderFeeds, past_key_values); const decoderResults = await sessionRun(self2.decoder_merged_session, decoderFeeds); let logits = decoderResults.logits; past_key_values = self2.getPastKeyValues(decoderResults, past_key_values); const attns = self2.getAttentions(decoderResults); return new Seq2SeqLMOutput({ logits, past_key_values, encoder_outputs, ...attns }); } function seq2seqStartBeams(self2, inputTokenIds, generation_config, numOutputTokens) { let beams = []; let beamId = 0; const requires_attention_mask = self2.requires_attention_mask ?? true; let decoder_input_ids = generation_config.decoder_input_ids ?? generation_config.decoder_start_token_id ?? generation_config.bos_token_id ?? generation_config.eos_token_id; if (decoder_input_ids instanceof Tensor) { decoder_input_ids = decoder_input_ids.tolist().flat(); } else if (!Array.isArray(decoder_input_ids)) { decoder_input_ids = [decoder_input_ids]; } for (let tokens of inputTokenIds) { tokens.dims = [1, ...tokens.dims]; let start = { inputs: tokens, encoder_outputs: null, prev_model_outputs: null, output_token_ids: decoder_input_ids, done: false, score: 0, id: beamId++ // assign unique id to beams }; if (requires_attention_mask) { start.attention_mask = prepareAttentionMask(self2, tokens); } beams.push(start); } return beams; } async function seq2seqRunBeam(self2, beam) { const input_name = self2.main_input_name; let decoder_input_ids = beam.output_token_ids; if (beam.prev_model_outputs) { decoder_input_ids = decoder_input_ids.slice(-1); } let model_inputs = { [input_name]: beam.inputs, decoder_input_ids: toI64Tensor(decoder_input_ids), encoder_outputs: beam.encoder_outputs, past_key_values: beam.prev_model_outputs?.past_key_values }; if (beam.attention_mask) { model_inputs.attention_mask = beam.attention_mask; } let output = await self2.forward(model_inputs); beam.prev_model_outputs = output; beam.encoder_outputs = output.encoder_outputs; return output; } function seq2seqUpdatebeam(beam, newTokenId) { beam.output_token_ids = [...beam.output_token_ids, newTokenId]; } async function encoderForward(self2, model_inputs) { const encoderFeeds = /* @__PURE__ */ Object.create(null); for (const key of self2.session.inputNames) { encoderFeeds[key] = model_inputs[key]; } if (self2.session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) { encoderFeeds.token_type_ids = new Tensor( "int64", new BigInt64Array(encoderFeeds.input_ids.data.length), encoderFeeds.input_ids.dims ); } return await sessionRun(self2.session, encoderFeeds); } async function decoderForward(self2, model_inputs) { let { input_ids, past_key_values, attention_mask } = model_inputs; let decoderFeeds = { input_ids, attention_mask: attention_mask ?? prepareAttentionMask(self2, input_ids) }; const use_cache_branch = !!past_key_values; if (self2.session.inputNames.includes("use_cache_branch")) { decoderFeeds.use_cache_branch = boolTensor(use_cache_branch); } preparePositionIds(self2.session, decoderFeeds, use_cache_branch); self2.addPastKeyValues(decoderFeeds, past_key_values); let decoderResults = await sessionRun(self2.session, decoderFeeds); let logits = decoderResults.logits; past_key_values = self2.getPastKeyValues(decoderResults, past_key_values); return { logits, past_key_values }; } function decoderStartBeams(self2, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { let beams = []; let beamId = 0; for (let tokens of inputTokenIds) { let output_token_ids = tokens.tolist().map(Number); tokens.dims = [1, ...tokens.dims]; let attn_mask; if (inputs_attention_mask) { attn_mask = inputs_attention_mask[beamId]; attn_mask.dims = [1, ...attn_mask.dims]; } else { attn_mask = prepareAttentionMask(self2, tokens); } let start = { input: tokens, model_input_ids: tokens, attention_mask: attn_mask, prev_model_outputs: null, output_token_ids, num_output_tokens: numOutputTokens, done: false, score: 0, id: beamId++ // assign unique id to beams }; beams.push(start); } return beams; } async function decoderRunBeam(self2, beam) { let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(1n); let model_inputs = { input_ids: beam.model_input_ids, attention_mask: new Tensor( "int64", attnMaskData, [1, attnMaskData.length] ), past_key_values: beam.prev_model_outputs?.past_key_values }; let output = await self2.forward(model_inputs); beam.prev_model_outputs = output; return output; } function decoderUpdatebeam(beam, newTokenId) { beam.output_token_ids = [...beam.output_token_ids, newTokenId]; beam.model_input_ids = new Tensor("int64", [BigInt(newTokenId)], [1, 1]); } var InferenceSession, ONNXTensor2, env2, MODEL_TYPES, MODEL_TYPE_MAPPING, MODEL_NAME_TO_CLASS_MAPPING, MODEL_CLASS_TO_NAME_MAPPING, PreTrainedModel, ModelOutput, BertPreTrainedModel, BertModel, BertForMaskedLM, BertForSequenceClassification, BertForTokenClassification, BertForQuestionAnswering, NomicBertPreTrainedModel, NomicBertModel, RoFormerPreTrainedModel, RoFormerModel, RoFormerForMaskedLM, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerForQuestionAnswering, ConvBertPreTrainedModel, ConvBertModel, ConvBertForMaskedLM, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertForQuestionAnswering, ElectraPreTrainedModel, ElectraModel, ElectraForMaskedLM, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraForQuestionAnswering, CamembertPreTrainedModel, CamembertModel, CamembertForMaskedLM, CamembertForSequenceClassification, CamembertForTokenClassification, CamembertForQuestionAnswering, DebertaPreTrainedModel, DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, DebertaV2PreTrainedModel, DebertaV2Model, DebertaV2ForMaskedLM, DebertaV2ForSequenceClassification, DebertaV2ForTokenClassification, DebertaV2ForQuestionAnswering, DistilBertPreTrainedModel, DistilBertModel, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertForQuestionAnswering, DistilBertForMaskedLM, EsmPreTrainedModel, EsmModel, EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, MobileBertPreTrainedModel, MobileBertModel, MobileBertForMaskedLM, MobileBertForSequenceClassification, MobileBertForQuestionAnswering, MPNetPreTrainedModel, MPNetModel, MPNetForMaskedLM, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetForQuestionAnswering, SqueezeBertPreTrainedModel, SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForSequenceClassification, SqueezeBertForQuestionAnswering, AlbertPreTrainedModel, AlbertModel, AlbertForSequenceClassification, AlbertForQuestionAnswering, AlbertForMaskedLM, T5PreTrainedModel, T5Model, T5ForConditionalGeneration, LongT5PreTrainedModel, LongT5Model, LongT5ForConditionalGeneration, MT5PreTrainedModel, MT5Model, MT5ForConditionalGeneration, BartPretrainedModel, BartModel, BartForConditionalGeneration, BartForSequenceClassification, MBartPreTrainedModel, MBartModel, MBartForConditionalGeneration, MBartForSequenceClassification, MBartForCausalLM, BlenderbotPreTrainedModel, BlenderbotModel, BlenderbotForConditionalGeneration, BlenderbotSmallPreTrainedModel, BlenderbotSmallModel, BlenderbotSmallForConditionalGeneration, RobertaPreTrainedModel, RobertaModel, RobertaForMaskedLM, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaForQuestionAnswering, XLMPreTrainedModel, XLMModel, XLMWithLMHeadModel, XLMForSequenceClassification, XLMForTokenClassification, XLMForQuestionAnswering, XLMRobertaPreTrainedModel, XLMRobertaModel, XLMRobertaForMaskedLM, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaForQuestionAnswering, ASTPreTrainedModel, ASTModel, ASTForAudioClassification, WhisperPreTrainedModel, WhisperModel, WhisperForConditionalGeneration, VisionEncoderDecoderModel, CLIPPreTrainedModel, CLIPModel, CLIPTextModelWithProjection, CLIPVisionModelWithProjection, SiglipPreTrainedModel, SiglipModel, SiglipTextModel, SiglipVisionModel, ChineseCLIPPreTrainedModel, ChineseCLIPModel, CLIPSegPreTrainedModel, CLIPSegModel, CLIPSegForImageSegmentation, GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel, GPTNeoPreTrainedModel, GPTNeoModel, GPTNeoForCausalLM, GPTNeoXPreTrainedModel, GPTNeoXModel, GPTNeoXForCausalLM, GPTJPreTrainedModel, GPTJModel, GPTJForCausalLM, GPTBigCodePreTrainedModel, GPTBigCodeModel, GPTBigCodeForCausalLM, CodeGenPreTrainedModel, CodeGenModel, CodeGenForCausalLM, LlamaPreTrainedModel, LlamaModel, LlamaForCausalLM, Qwen2PreTrainedModel, Qwen2Model, Qwen2ForCausalLM, PhiPreTrainedModel, PhiModel, PhiForCausalLM, BloomPreTrainedModel, BloomModel, BloomForCausalLM, MptPreTrainedModel, MptModel, MptForCausalLM, OPTPreTrainedModel, OPTModel, OPTForCausalLM, ViTPreTrainedModel, ViTModel, ViTForImageClassification, FastViTPreTrainedModel, FastViTModel, FastViTForImageClassification, VitMattePreTrainedModel, VitMatteForImageMatting, MobileViTPreTrainedModel, MobileViTModel, MobileViTForImageClassification, MobileViTV2PreTrainedModel, MobileViTV2Model, MobileViTV2ForImageClassification, OwlViTPreTrainedModel, OwlViTModel, OwlViTForObjectDetection, Owlv2PreTrainedModel, Owlv2Model, Owlv2ForObjectDetection, BeitPreTrainedModel, BeitModel, BeitForImageClassification, DetrPreTrainedModel, DetrModel, DetrForObjectDetection, DetrForSegmentation, DetrObjectDetectionOutput, DetrSegmentationOutput, TableTransformerPreTrainedModel, TableTransformerModel, TableTransformerForObjectDetection, TableTransformerObjectDetectionOutput, DeiTPreTrainedModel, DeiTModel, DeiTForImageClassification, ResNetPreTrainedModel, ResNetModel, ResNetForImageClassification, SwinPreTrainedModel, SwinModel, SwinForImageClassification, Swin2SRPreTrainedModel, Swin2SRModel, Swin2SRForImageSuperResolution, DPTPreTrainedModel, DPTModel, DPTForDepthEstimation, DepthAnythingPreTrainedModel, DepthAnythingForDepthEstimation, GLPNPreTrainedModel, GLPNModel, GLPNForDepthEstimation, DonutSwinPreTrainedModel, DonutSwinModel, ConvNextPreTrainedModel, ConvNextModel, ConvNextForImageClassification, ConvNextV2PreTrainedModel, ConvNextV2Model, ConvNextV2ForImageClassification, Dinov2PreTrainedModel, Dinov2Model, Dinov2ForImageClassification, YolosPreTrainedModel, YolosModel, YolosForObjectDetection, YolosObjectDetectionOutput, SamPreTrainedModel, SamModel, SamImageSegmentationOutput, MarianPreTrainedModel, MarianModel, MarianMTModel, M2M100PreTrainedModel, M2M100Model, M2M100ForConditionalGeneration, Wav2Vec2PreTrainedModel, Wav2Vec2Model, Wav2Vec2ForCTC, Wav2Vec2ForSequenceClassification, Wav2Vec2ForAudioFrameClassification, UniSpeechPreTrainedModel, UniSpeechModel, UniSpeechForCTC, UniSpeechForSequenceClassification, UniSpeechSatPreTrainedModel, UniSpeechSatModel, UniSpeechSatForCTC, UniSpeechSatForSequenceClassification, UniSpeechSatForAudioFrameClassification, Wav2Vec2BertPreTrainedModel, Wav2Vec2BertModel, Wav2Vec2BertForCTC, Wav2Vec2BertForSequenceClassification, HubertModel, HubertForCTC, HubertForSequenceClassification, WavLMPreTrainedModel, WavLMModel, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMForAudioFrameClassification, SpeechT5PreTrainedModel, SpeechT5ForSpeechToText, SpeechT5ForTextToSpeech, SpeechT5HifiGan, TrOCRPreTrainedModel, TrOCRForCausalLM, MistralPreTrainedModel, MistralModel, MistralForCausalLM, Starcoder2PreTrainedModel, Starcoder2Model, Starcoder2ForCausalLM, FalconPreTrainedModel, FalconModel, FalconForCausalLM, ClapPreTrainedModel, ClapModel, ClapTextModelWithProjection, ClapAudioModelWithProjection, VitsPreTrainedModel, VitsModel, SegformerPreTrainedModel, SegformerForImageClassification, SegformerForSemanticSegmentation, StableLmPreTrainedModel, StableLmForCausalLM, EfficientNetPreTrainedModel, EfficientNetModel, EfficientNetForImageClassification, PretrainedMixin, MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_CLASS_TYPE_MAPPING, CUSTOM_MAPPING, AutoModel, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelForSeq2SeqLM, AutoModelForSpeechSeq2Seq, AutoModelForTextToSpectrogram, AutoModelForTextToWaveform, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForVision2Seq, AutoModelForImageClassification, AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForObjectDetection, AutoModelForZeroShotObjectDetection, AutoModelForCTC, AutoModelForAudioClassification, AutoModelForDocumentQuestionAnswering, AutoModelForImageToImage, AutoModelForDepthEstimation, AutoModelForImageFeatureExtraction, Seq2SeqLMOutput, SequenceClassifierOutput, XVectorOutput, TokenClassifierOutput, MaskedLMOutput, QuestionAnsweringModelOutput, CausalLMOutput, ImageMattingOutput, VitsModelOutput; var init_models = __esm({ "node_modules/@xenova/transformers/src/models.js"() { init_configs(); init_core(); init_hub(); init_generation(); init_tensor(); init_onnx(); init_transformers(); ({ InferenceSession, Tensor: ONNXTensor2, env: env2 } = ONNX); MODEL_TYPES = { EncoderOnly: 0, EncoderDecoder: 1, Seq2Seq: 2, Vision2Seq: 3, DecoderOnly: 4, MaskGeneration: 5 }; MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map(); MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map(); MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map(); PreTrainedModel = class extends Callable { main_input_name = "input_ids"; /** * Creates a new instance of the `PreTrainedModel` class. * @param {Object} config The model configuration. * @param {any} session session for the model. */ constructor(config, session) { super(); this.config = config; this.session = session; const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); const modelType = MODEL_TYPE_MAPPING.get(modelName); this.can_generate = false; this._runBeam = null; this._getStartBeams = null; this._updateBeam = null; this._forward = null; if (modelType === MODEL_TYPES.DecoderOnly) { this.can_generate = true; this._runBeam = decoderRunBeam; this._getStartBeams = decoderStartBeams; this._updateBeam = decoderUpdatebeam; this._forward = decoderForward; } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { this.can_generate = true; this._runBeam = seq2seqRunBeam; this._getStartBeams = seq2seqStartBeams; this._updateBeam = seq2seqUpdatebeam; this._forward = seq2seqForward; } else if (modelType === MODEL_TYPES.EncoderDecoder) { this._forward = encoderForward; } else { this._forward = encoderForward; } } /** * Disposes of all the ONNX sessions that were created during inference. * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry */ async dispose() { const promises = []; for (let key of Object.keys(this)) { const item = this[key]; if (item instanceof InferenceSession) { promises.push(item.handler.dispose()); } } return await Promise.all(promises); } /** * Instantiate one of the model classes of the library from a pretrained model. * * The model class to instantiate is selected based on the `model_type` property of the config object * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) * * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a * user or organization name, like `dbmdz/bert-base-german-cased`. * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model. * * @returns {Promise} A new instance of the `PreTrainedModel` class. */ static async from_pretrained(pretrained_model_name_or_path, { quantized = true, progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main", model_file_name = null } = {}) { let options = { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name }; const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); const modelType = MODEL_TYPE_MAPPING.get(modelName); let info; if (modelType === MODEL_TYPES.DecoderOnly) { info = await Promise.all([ AutoConfig.from_pretrained(pretrained_model_name_or_path, options), constructSession(pretrained_model_name_or_path, options.model_file_name ?? "decoder_model_merged", options), getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options) ]); } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { info = await Promise.all([ AutoConfig.from_pretrained(pretrained_model_name_or_path, options), constructSession(pretrained_model_name_or_path, "encoder_model", options), constructSession(pretrained_model_name_or_path, "decoder_model_merged", options), getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options) ]); } else if (modelType === MODEL_TYPES.MaskGeneration) { info = await Promise.all([ AutoConfig.from_pretrained(pretrained_model_name_or_path, options), constructSession(pretrained_model_name_or_path, "vision_encoder", options), constructSession(pretrained_model_name_or_path, "prompt_encoder_mask_decoder", options) ]); } else if (modelType === MODEL_TYPES.EncoderDecoder) { info = await Promise.all([ AutoConfig.from_pretrained(pretrained_model_name_or_path, options), constructSession(pretrained_model_name_or_path, "encoder_model", options), constructSession(pretrained_model_name_or_path, "decoder_model_merged", options) ]); } else { if (modelType !== MODEL_TYPES.EncoderOnly) { console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`); } info = await Promise.all([ AutoConfig.from_pretrained(pretrained_model_name_or_path, options), constructSession(pretrained_model_name_or_path, options.model_file_name ?? "model", options) ]); } return new this(...info); } /** * Runs the model with the provided inputs * @param {Object} model_inputs Object containing input tensors * @returns {Promise} Object containing output tensors */ async _call(model_inputs) { return await this.forward(model_inputs); } /** * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method * will be chosen based on the model type. * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. * @returns {Promise} The output data from the model in the format specified in the ONNX model. * @throws {Error} This method must be implemented in subclasses. */ async forward(model_inputs) { return await this._forward(this, model_inputs); } /** * @param {import('./utils/generation.js').GenerationConfigType} generation_config * @param {number} input_ids_seq_length The starting sequence length for the input ids. * @returns {LogitsProcessorList} * @private */ _get_logits_processor(generation_config, input_ids_seq_length, logits_processor = null) { const processors = new LogitsProcessorList(); if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) { processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); } if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); } if (generation_config.bad_words_ids !== null) { processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)); } if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); } if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { processors.push(new MinNewTokensLengthLogitsProcessor( input_ids_seq_length, generation_config.min_new_tokens, generation_config.eos_token_id )); } if (generation_config.forced_bos_token_id !== null) { processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); } if (generation_config.forced_eos_token_id !== null) { processors.push(new ForcedEOSTokenLogitsProcessor( generation_config.max_length, generation_config.forced_eos_token_id )); } if (generation_config.begin_suppress_tokens !== null) { let begin_index = input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null ? input_ids_seq_length : input_ids_seq_length + 1; if (generation_config.forced_decoder_ids !== null) { begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0]; } processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)); } if (generation_config.forced_decoder_ids !== null) { processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids)); } if (logits_processor !== null) { processors.extend(logits_processor); } return processors; } /** * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters. * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation. */ _get_generation_config(generation_config) { let gen_config = new GenerationConfig(this.config); if ("generation_config" in this) { Object.assign(gen_config, this.generation_config); } if (generation_config !== null) { Object.assign(gen_config, generation_config); } return gen_config; } /** * @typedef {import('./utils/maths.js').TypedArray} TypedArray */ /** * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput * @typedef {Object} DecoderOutput * * Generates text based on the given inputs and generation configuration using the model. * @param {Tensor|Array|TypedArray} inputs An array of input token IDs. * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used. * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created. * @param {Object} options options * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs. * @returns {Promise} An array of generated output sequences, where each sequence is an array of token IDs. * @throws {Error} Throws an error if the inputs array is empty. */ async generate(inputs, generation_config = null, logits_processor = null, { inputs_attention_mask = null } = {}) { if (!this.can_generate) { const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; const modelType = this.config.model_type; const possibleInfo = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType) ?? MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType); if (possibleInfo) { errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`; } throw Error(errorMessage); } if (!(inputs instanceof Tensor) && !isTypedArray(inputs) && !Array.isArray(inputs)) { throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`); } let input_ids_seq_length; if (this.config.is_encoder_decoder) { input_ids_seq_length = 0; } else { input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length; if (input_ids_seq_length === 0) { throw Error("Must supply a non-empty array of input token ids."); } } generation_config = this._get_generation_config(generation_config); logits_processor = logits_processor ?? new LogitsProcessorList(); logits_processor = this._get_logits_processor( generation_config, input_ids_seq_length, logits_processor ); let eos_token_ids = generation_config.eos_token_id; if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) { eos_token_ids = [eos_token_ids]; } let numOutputTokens = 1; const maxOutputTokens = numOutputTokens + (generation_config.max_new_tokens ?? Infinity); const useMaxLength = Number.isInteger(generation_config.max_length) && (generation_config.max_new_tokens ?? null) === null; let sampler = Sampler.getSampler(generation_config); let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask); while (beams.some((x2) => !x2.done) && numOutputTokens < maxOutputTokens) { let newest_beams = []; for (let beam of beams) { if (beam.done) { newest_beams.push(beam); continue; } if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) { beam.done = true; newest_beams.push(beam); continue; } let output = await this.runBeam(beam); if (generation_config.output_attentions) { this.addAttentionsToBeam(beam, output); } if (generation_config.output_scores) { } let logits = output.logits.slice(null, -1, null); logits_processor(beam.output_token_ids, logits); let sampledTokens = sampler(logits); for (let [newTokenId, logProb] of sampledTokens) { let newBeam = { ...beam }; this.updateBeam(newBeam, newTokenId); newBeam.score += logProb; if (eos_token_ids && eos_token_ids.includes(newTokenId)) { newBeam.done = true; } newest_beams.push(newBeam); } } ++numOutputTokens; newest_beams = this.groupBeams(newest_beams).map( (group) => group.sort((a, b) => b.score - a.score).slice(0, generation_config.num_beams) // remove outside beam width ); beams = newest_beams.flat(); if (generation_config.callback_function) { generation_config.callback_function(beams); } } const groupedBeams = this.groupBeams(beams); const getFlattened = (key) => groupedBeams.map( (batch) => { if (generation_config.num_return_sequences > 1) { return batch.slice(0, generation_config.num_return_sequences).map((x2) => x2[key]); } else { return [batch[0][key]]; } } ).flat(); const sequences = getFlattened("output_token_ids"); if (generation_config.return_dict_in_generate) { const decoder_attentions = getFlattened("decoder_attentions"); const cross_attentions = getFlattened("cross_attentions"); return { sequences, decoder_attentions, cross_attentions }; } else { return sequences; } } /** * Helper function to add attentions to beam * @param {Object} beam * @param {Object} output * @private */ addAttentionsToBeam(beam, output) { if (this.config.is_encoder_decoder) { if (!output.cross_attentions || output.cross_attentions.length === 0) { throw Error( "`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`." ); } if (!beam.cross_attentions) { beam.cross_attentions = []; } beam.cross_attentions.push(output.cross_attentions); } if (!output.decoder_attentions || output.decoder_attentions.length === 0) { throw Error( "`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`." ); } if (!beam.decoder_attentions) { beam.decoder_attentions = []; } beam.decoder_attentions.push(output.decoder_attentions); } /** * Groups an array of beam objects by their ids. * * @param {Array} beams The array of beam objects to group. * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id. */ groupBeams(beams) { const groups = /* @__PURE__ */ Object.create(null); for (const obj of beams) { if (groups[obj.id] === void 0) { groups[obj.id] = [obj]; } else { groups[obj.id].push(obj); } } return Object.values(groups); } /** * Returns an object containing past key values from the given decoder results object. * * @param {Object} decoderResults The decoder results object. * @param {Object} pastKeyValues The previous past key values. * @returns {Object} An object containing past key values. */ getPastKeyValues(decoderResults, pastKeyValues) { const pkvs = /* @__PURE__ */ Object.create(null); for (const name2 in decoderResults) { if (name2.startsWith("present")) { let newName = name2.replace("present", "past_key_values"); if (pastKeyValues && name2.includes("encoder")) { pkvs[newName] = pastKeyValues[newName]; } else { pkvs[newName] = decoderResults[name2]; } } } return pkvs; } /** * Returns an object containing attentions from the given decoder results object. * * @param {Object} decoderResults The decoder results object. * @returns {Object} An object containing attentions. */ getAttentions(decoderResults) { const attns = /* @__PURE__ */ Object.create(null); for (const attnName of ["cross_attentions", "decoder_attentions"]) { const result = []; for (const name2 in decoderResults) { if (name2.startsWith(attnName)) { const index = name2.split(".").pop(); result[index] = decoderResults[name2]; } } attns[attnName] = result; } return attns; } /** * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. * * @param {Object} decoderFeeds The decoder feeds object to add past key values to. * @param {Object} pastKeyValues An object containing past key values. */ addPastKeyValues(decoderFeeds, pastKeyValues) { if (pastKeyValues) { Object.assign(decoderFeeds, pastKeyValues); } else { const batch_size = 1; if (this.config.is_encoder_decoder && (this.add_encoder_pkv ?? true)) { let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv]; let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv]; for (let i = 0; i < this.num_decoder_layers; ++i) { decoderFeeds[`past_key_values.${i}.encoder.key`] = new Tensor("float32", [], encoder_dims); decoderFeeds[`past_key_values.${i}.encoder.value`] = new Tensor("float32", [], encoder_dims); decoderFeeds[`past_key_values.${i}.decoder.key`] = new Tensor("float32", [], decoder_dims); decoderFeeds[`past_key_values.${i}.decoder.value`] = new Tensor("float32", [], decoder_dims); } } else if (this.config.model_type === "falcon") { let dims = [batch_size * this.num_heads, 0, this.dim_kv]; for (let i = 0; i < this.num_layers; ++i) { decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims); decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], dims); } } else if (this.config.multi_query) { let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv]; for (let i = 0; i < this.num_layers; ++i) { decoderFeeds[`past_key_values.${i}.key_value`] = new Tensor("float32", [], dims); } } else if (this.config.model_type === "bloom") { let keyDims = [batch_size * this.num_heads, this.dim_kv, 0]; let valueDims = [batch_size * this.num_heads, 0, this.dim_kv]; for (let i = 0; i < this.num_layers; ++i) { decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], keyDims); decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], valueDims); } } else { let dims = [batch_size, this.num_heads, 0, this.dim_kv]; for (let i = 0; i < this.num_layers; ++i) { decoderFeeds[`past_key_values.${i}.key`] = new Tensor("float32", [], dims); decoderFeeds[`past_key_values.${i}.value`] = new Tensor("float32", [], dims); } } } } /** * Initializes and returns the beam for text generation task * @param {Tensor} inputTokenIds The input token ids. * @param {Object} generation_config The generation config. * @param {number} numOutputTokens The number of tokens to be generated. * @param {Tensor} inputs_attention_mask Optional input attention mask. * @returns {any} A Beam object representing the initialized beam. * @private */ getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) { return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask); } /** * Runs a single step of the beam search generation algorithm. * @param {any} beam The current beam being generated. * @returns {Promise} The updated beam after a single generation step. * @private */ async runBeam(beam) { return await this._runBeam(this, beam); } /** * Update a beam with a new token ID. * @param {Object} beam The beam to update. * @param {number} newTokenId The new token ID to add to the beam's output. * @private */ updateBeam(beam, newTokenId) { return this._updateBeam(beam, newTokenId); } }; ModelOutput = class { }; BertPreTrainedModel = class extends PreTrainedModel { }; BertModel = class extends BertPreTrainedModel { }; BertForMaskedLM = class extends BertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; BertForSequenceClassification = class extends BertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; BertForTokenClassification = class extends BertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; BertForQuestionAnswering = class extends BertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; NomicBertPreTrainedModel = class extends PreTrainedModel { }; NomicBertModel = class extends NomicBertPreTrainedModel { }; RoFormerPreTrainedModel = class extends PreTrainedModel { }; RoFormerModel = class extends RoFormerPreTrainedModel { }; RoFormerForMaskedLM = class extends RoFormerPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; RoFormerForSequenceClassification = class extends RoFormerPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; RoFormerForTokenClassification = class extends RoFormerPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; RoFormerForQuestionAnswering = class extends RoFormerPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; ConvBertPreTrainedModel = class extends PreTrainedModel { }; ConvBertModel = class extends ConvBertPreTrainedModel { }; ConvBertForMaskedLM = class extends ConvBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; ConvBertForSequenceClassification = class extends ConvBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; ConvBertForTokenClassification = class extends ConvBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; ConvBertForQuestionAnswering = class extends ConvBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; ElectraPreTrainedModel = class extends PreTrainedModel { }; ElectraModel = class extends ElectraPreTrainedModel { }; ElectraForMaskedLM = class extends ElectraPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; ElectraForSequenceClassification = class extends ElectraPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; ElectraForTokenClassification = class extends ElectraPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; ElectraForQuestionAnswering = class extends ElectraPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; CamembertPreTrainedModel = class extends PreTrainedModel { }; CamembertModel = class extends CamembertPreTrainedModel { }; CamembertForMaskedLM = class extends CamembertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; CamembertForSequenceClassification = class extends CamembertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; CamembertForTokenClassification = class extends CamembertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; CamembertForQuestionAnswering = class extends CamembertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; DebertaPreTrainedModel = class extends PreTrainedModel { }; DebertaModel = class extends DebertaPreTrainedModel { }; DebertaForMaskedLM = class extends DebertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; DebertaForSequenceClassification = class extends DebertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; DebertaForTokenClassification = class extends DebertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; DebertaForQuestionAnswering = class extends DebertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; DebertaV2PreTrainedModel = class extends PreTrainedModel { }; DebertaV2Model = class extends DebertaV2PreTrainedModel { }; DebertaV2ForMaskedLM = class extends DebertaV2PreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; DebertaV2ForSequenceClassification = class extends DebertaV2PreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; DebertaV2ForTokenClassification = class extends DebertaV2PreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; DebertaV2ForQuestionAnswering = class extends DebertaV2PreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; DistilBertPreTrainedModel = class extends PreTrainedModel { }; DistilBertModel = class extends DistilBertPreTrainedModel { }; DistilBertForSequenceClassification = class extends DistilBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; DistilBertForTokenClassification = class extends DistilBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; DistilBertForQuestionAnswering = class extends DistilBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; DistilBertForMaskedLM = class extends DistilBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; EsmPreTrainedModel = class extends PreTrainedModel { }; EsmModel = class extends EsmPreTrainedModel { }; EsmForMaskedLM = class extends EsmPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; EsmForSequenceClassification = class extends EsmPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; EsmForTokenClassification = class extends EsmPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; MobileBertPreTrainedModel = class extends PreTrainedModel { }; MobileBertModel = class extends MobileBertPreTrainedModel { }; MobileBertForMaskedLM = class extends MobileBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; MobileBertForSequenceClassification = class extends MobileBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; MobileBertForQuestionAnswering = class extends MobileBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; MPNetPreTrainedModel = class extends PreTrainedModel { }; MPNetModel = class extends MPNetPreTrainedModel { }; MPNetForMaskedLM = class extends MPNetPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for masked language modeling. */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; MPNetForSequenceClassification = class extends MPNetPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; MPNetForTokenClassification = class extends MPNetPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; MPNetForQuestionAnswering = class extends MPNetPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for question answering. */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; SqueezeBertPreTrainedModel = class extends PreTrainedModel { }; SqueezeBertModel = class extends SqueezeBertPreTrainedModel { }; SqueezeBertForMaskedLM = class extends SqueezeBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; SqueezeBertForSequenceClassification = class extends SqueezeBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; SqueezeBertForQuestionAnswering = class extends SqueezeBertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; AlbertPreTrainedModel = class extends PreTrainedModel { }; AlbertModel = class extends AlbertPreTrainedModel { }; AlbertForSequenceClassification = class extends AlbertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; AlbertForQuestionAnswering = class extends AlbertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; AlbertForMaskedLM = class extends AlbertPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; T5PreTrainedModel = class extends PreTrainedModel { }; T5Model = class extends T5PreTrainedModel { }; T5ForConditionalGeneration = class extends T5PreTrainedModel { /** * Creates a new instance of the `T5ForConditionalGeneration` class. * @param {Object} config The model configuration. * @param {any} session session for the model. * @param {any} decoder_merged_session session for the decoder. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.num_decoder_layers; this.num_decoder_heads = this.config.num_heads; this.decoder_dim_kv = this.config.d_kv; this.num_encoder_layers = this.config.num_layers; this.num_encoder_heads = this.config.num_heads; this.encoder_dim_kv = this.config.d_kv; } }; LongT5PreTrainedModel = class extends PreTrainedModel { }; LongT5Model = class extends LongT5PreTrainedModel { }; LongT5ForConditionalGeneration = class extends LongT5PreTrainedModel { /** * Creates a new instance of the `LongT5ForConditionalGeneration` class. * @param {Object} config The model configuration. * @param {any} session session for the model. * @param {any} decoder_merged_session session for the decoder. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.num_decoder_layers; this.num_decoder_heads = this.config.num_heads; this.decoder_dim_kv = this.config.d_kv; this.num_encoder_layers = this.config.num_layers; this.num_encoder_heads = this.config.num_heads; this.encoder_dim_kv = this.config.d_kv; } }; MT5PreTrainedModel = class extends PreTrainedModel { }; MT5Model = class extends MT5PreTrainedModel { }; MT5ForConditionalGeneration = class extends MT5PreTrainedModel { /** * Creates a new instance of the `MT5ForConditionalGeneration` class. * @param {any} config The model configuration. * @param {any} session The ONNX session containing the encoder weights. * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.num_decoder_layers; this.num_decoder_heads = this.config.num_heads; this.decoder_dim_kv = this.config.d_kv; this.num_encoder_layers = this.config.num_layers; this.num_encoder_heads = this.config.num_heads; this.encoder_dim_kv = this.config.d_kv; } }; BartPretrainedModel = class extends PreTrainedModel { }; BartModel = class extends BartPretrainedModel { }; BartForConditionalGeneration = class extends BartPretrainedModel { /** * Creates a new instance of the `BartForConditionalGeneration` class. * @param {Object} config The configuration object for the Bart model. * @param {Object} session The ONNX session used to execute the model. * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. * @param {Object} generation_config The generation configuration object. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; BartForSequenceClassification = class extends BartPretrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; MBartPreTrainedModel = class extends PreTrainedModel { }; MBartModel = class extends MBartPreTrainedModel { }; MBartForConditionalGeneration = class extends MBartPreTrainedModel { /** * Creates a new instance of the `MBartForConditionalGeneration` class. * @param {Object} config The configuration object for the Bart model. * @param {Object} session The ONNX session used to execute the model. * @param {Object} decoder_merged_session The ONNX session used to execute the decoder. * @param {Object} generation_config The generation configuration object. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; MBartForSequenceClassification = class extends MBartPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; MBartForCausalLM = class extends MBartPreTrainedModel { /** * Creates a new instance of the `MBartForCausalLM` class. * @param {Object} config Configuration object for the model. * @param {Object} decoder_merged_session ONNX Session object for the decoder. * @param {Object} generation_config Configuration object for the generation process. */ constructor(config, decoder_merged_session, generation_config) { super(config, decoder_merged_session); this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; BlenderbotPreTrainedModel = class extends PreTrainedModel { }; BlenderbotModel = class extends BlenderbotPreTrainedModel { }; BlenderbotForConditionalGeneration = class extends BlenderbotPreTrainedModel { /** * Creates a new instance of the `BlenderbotForConditionalGeneration` class. * @param {any} config The model configuration. * @param {any} session The ONNX session containing the encoder weights. * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; BlenderbotSmallPreTrainedModel = class extends PreTrainedModel { }; BlenderbotSmallModel = class extends BlenderbotSmallPreTrainedModel { }; BlenderbotSmallForConditionalGeneration = class extends BlenderbotSmallPreTrainedModel { /** * Creates a new instance of the `BlenderbotForConditionalGeneration` class. * @param {any} config The model configuration. * @param {any} session The ONNX session containing the encoder weights. * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; RobertaPreTrainedModel = class extends PreTrainedModel { }; RobertaModel = class extends RobertaPreTrainedModel { }; RobertaForMaskedLM = class extends RobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; RobertaForSequenceClassification = class extends RobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; RobertaForTokenClassification = class extends RobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; RobertaForQuestionAnswering = class extends RobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; XLMPreTrainedModel = class extends PreTrainedModel { }; XLMModel = class extends XLMPreTrainedModel { }; XLMWithLMHeadModel = class extends XLMPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; XLMForSequenceClassification = class extends XLMPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; XLMForTokenClassification = class extends XLMPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; XLMForQuestionAnswering = class extends XLMPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; XLMRobertaPreTrainedModel = class extends PreTrainedModel { }; XLMRobertaModel = class extends XLMRobertaPreTrainedModel { }; XLMRobertaForMaskedLM = class extends XLMRobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new MaskedLMOutput(await super._call(model_inputs)); } }; XLMRobertaForSequenceClassification = class extends XLMRobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; XLMRobertaForTokenClassification = class extends XLMRobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for token classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; XLMRobertaForQuestionAnswering = class extends XLMRobertaPreTrainedModel { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(model_inputs) { return new QuestionAnsweringModelOutput(await super._call(model_inputs)); } }; ASTPreTrainedModel = class extends PreTrainedModel { }; ASTModel = class extends ASTPreTrainedModel { }; ASTForAudioClassification = class extends ASTPreTrainedModel { }; WhisperPreTrainedModel = class extends PreTrainedModel { }; WhisperModel = class extends WhisperPreTrainedModel { }; WhisperForConditionalGeneration = class extends WhisperPreTrainedModel { requires_attention_mask = false; main_input_name = "input_features"; /** * Creates a new instance of the `WhisperForConditionalGeneration` class. * @param {Object} config Configuration object for the model. * @param {Object} session ONNX Session object for the model. * @param {Object} decoder_merged_session ONNX Session object for the decoder. * @param {Object} generation_config Configuration object for the generation process. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } /** * @typedef {Object} WhisperGenerationConfig * @extends GenerationConfig * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps * with the text. This can be used with or without the `return_timestamps` option. To get word-level * timestamps, use the tokenizer to group the tokens into words. * @property {number} [num_frames=null] The number of audio frames available in this chunk. This is only used generating word-level timestamps. */ /** * Generates outputs based on input and generation configuration. * @param {Object} inputs Input data for the model. * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process. * @param {Object} logits_processor Optional logits processor object. * @returns {Promise} Promise object represents the generated outputs. */ async generate(inputs, generation_config = null, logits_processor = null) { generation_config = this._get_generation_config(generation_config); generation_config.return_timestamps ??= false; if (generation_config.return_timestamps) { logits_processor = [new WhisperTimeStampLogitsProcessor(generation_config)]; } if (generation_config.return_token_timestamps) { generation_config.output_attentions = true; generation_config.return_dict_in_generate = true; if (generation_config.task === "translate") { console.warn("Token-level timestamps may not be reliable for task 'translate'."); } if (!generation_config.alignment_heads) { throw new Error( "Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config." ); } } const outputs = await super.generate(inputs, generation_config, logits_processor); if (generation_config.return_token_timestamps && generation_config.alignment_heads) { outputs["token_timestamps"] = this._extract_token_timestamps( outputs, generation_config.alignment_heads, generation_config.num_frames ); } return outputs; } /** * Calculates token-level timestamps using the encoder-decoder cross-attentions and * dynamic time-warping (DTW) to map each output token to a position in the input audio. * @param {Object} generate_outputs Outputs generated by the model * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model * @param {number[][]} generate_outputs.sequences The sequences output by the model * @param {number[][]} alignment_heads Alignment heads of the model * @param {number} [num_frames=null] Number of frames in the input audio. * @param {number} [time_precision=0.02] Precision of the timestamps in seconds * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token */ _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) { if (!generate_outputs.cross_attentions) { throw new Error( "Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`." ); } let median_filter_width = this.config.median_filter_width; if (median_filter_width === void 0) { console.warn("Model config has no `median_filter_width`, using default value of 7."); median_filter_width = 7; } const batchedMatrices = generate_outputs.cross_attentions.map((batch) => { let cross_attentions = Array.from( { length: this.config.decoder_layers }, (_, i) => cat(batch.map((x2) => x2[i]), 2) ); let weights = stack(alignment_heads.map(([l, h]) => { return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h); })); weights = weights.transpose(1, 0, 2, 3); let [std, calculatedMean] = std_mean(weights, -2, 0, true); let smoothedWeights = weights.clone(); for (let a = 0; a < smoothedWeights.dims[0]; ++a) { let aTensor = smoothedWeights[a]; for (let b = 0; b < aTensor.dims[0]; ++b) { let bTensor = aTensor[b]; const stdTensor = std[a][b][0]; const meanTensor = calculatedMean[a][b][0]; for (let c = 0; c < bTensor.dims[0]; ++c) { let cTensor = bTensor[c]; for (let d = 0; d < cTensor.data.length; ++d) { cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d]; } cTensor.data.set(medianFilter(cTensor.data, median_filter_width)); } } } const matrix = mean(smoothedWeights, 1); return matrix; }); const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length]; const timestamps = new Tensor( "float32", new Float32Array(timestampsShape[0] * timestampsShape[1]), timestampsShape ); for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); let [text_indices, time_indices] = dynamicTimeWarping(matrix); let diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]); let jumps = mergeArrays([1], diffs).map((x2) => !!x2); let jump_times = []; for (let i = 0; i < jumps.length; ++i) { if (jumps[i]) { jump_times.push(time_indices[i] * time_precision); } } timestamps[batch_idx].data.set(jump_times, 1); } return timestamps; } }; VisionEncoderDecoderModel = class extends PreTrainedModel { main_input_name = "pixel_values"; /** * Creates a new instance of the `VisionEncoderDecoderModel` class. * @param {Object} config The configuration object specifying the hyperparameters and other model settings. * @param {Object} session The ONNX session containing the encoder model. * @param {any} decoder_merged_session The ONNX session containing the merged decoder model. * @param {Object} generation_config Configuration object for the generation process. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; const encoderConfig = this.config.encoder; const decoderConfig = this.config.decoder; const encoderModelType = encoderConfig.model_type; const encoderModel = MODEL_MAPPING_NAMES_ENCODER_ONLY.get(encoderModelType) ?? MODEL_MAPPING_NAMES_ENCODER_DECODER.get(encoderModelType); if (!encoderModel) { console.warn(`Model type for encoder '${encoderModelType}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`); } const decoderModel = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(decoderConfig.model_type); if (!decoderModel) { throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`); } const decoderModelClass = decoderModel[1]; const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config); this.add_encoder_pkv = "num_decoder_layers" in decoder; if (this.add_encoder_pkv) { this.num_decoder_layers = decoder.num_decoder_layers; this.num_decoder_heads = decoder.num_decoder_heads; this.decoder_dim_kv = decoder.decoder_dim_kv; this.num_encoder_layers = decoder.num_encoder_layers; this.num_encoder_heads = decoder.num_encoder_heads; this.encoder_dim_kv = decoder.encoder_dim_kv; } else { this.num_layers = decoder.num_layers; this.num_heads = decoder.num_heads; this.dim_kv = decoder.dim_kv; } } }; CLIPPreTrainedModel = class extends PreTrainedModel { }; CLIPModel = class extends CLIPPreTrainedModel { }; CLIPTextModelWithProjection = class extends CLIPPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "text_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; CLIPVisionModelWithProjection = class extends CLIPPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "vision_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; SiglipPreTrainedModel = class extends PreTrainedModel { }; SiglipModel = class extends SiglipPreTrainedModel { }; SiglipTextModel = class extends SiglipPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "text_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; SiglipVisionModel = class extends CLIPPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "vision_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; ChineseCLIPPreTrainedModel = class extends PreTrainedModel { }; ChineseCLIPModel = class extends ChineseCLIPPreTrainedModel { }; CLIPSegPreTrainedModel = class extends PreTrainedModel { }; CLIPSegModel = class extends CLIPSegPreTrainedModel { }; CLIPSegForImageSegmentation = class extends CLIPSegPreTrainedModel { }; GPT2PreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `GPT2PreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_head; this.num_layers = this.config.n_layer; this.dim_kv = this.config.n_embd / this.num_heads; } }; GPT2Model = class extends GPT2PreTrainedModel { }; GPT2LMHeadModel = class extends GPT2PreTrainedModel { }; GPTNeoPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `GPTNeoPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_heads; this.num_layers = this.config.num_layers; this.dim_kv = this.config.hidden_size / this.num_heads; } }; GPTNeoModel = class extends GPTNeoPreTrainedModel { }; GPTNeoForCausalLM = class extends GPTNeoPreTrainedModel { }; GPTNeoXPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `GPTNeoXPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.num_heads; } }; GPTNeoXModel = class extends GPTNeoXPreTrainedModel { }; GPTNeoXForCausalLM = class extends GPTNeoXPreTrainedModel { }; GPTJPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `GPTJPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_head; this.num_layers = this.config.n_layer; this.dim_kv = this.config.n_embd / this.num_heads; } }; GPTJModel = class extends GPTJPreTrainedModel { }; GPTJForCausalLM = class extends GPTJPreTrainedModel { }; GPTBigCodePreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `GPTBigCodePreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_head; this.num_layers = this.config.n_layer; this.dim_kv = this.config.n_embd / this.num_heads; } }; GPTBigCodeModel = class extends GPTBigCodePreTrainedModel { }; GPTBigCodeForCausalLM = class extends GPTBigCodePreTrainedModel { }; CodeGenPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `CodeGenPreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_head; this.num_layers = this.config.n_layer; this.dim_kv = this.config.n_embd / this.num_heads; } }; CodeGenModel = class extends CodeGenPreTrainedModel { }; CodeGenForCausalLM = class extends CodeGenPreTrainedModel { }; LlamaPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `LlamaPreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; } }; LlamaModel = class extends LlamaPreTrainedModel { }; LlamaForCausalLM = class extends LlamaPreTrainedModel { }; Qwen2PreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `Qwen2PreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_key_value_heads ?? this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; } }; Qwen2Model = class extends Qwen2PreTrainedModel { }; Qwen2ForCausalLM = class extends Qwen2PreTrainedModel { }; PhiPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `PhiPreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.num_heads; } }; PhiModel = class extends PhiPreTrainedModel { }; PhiForCausalLM = class extends PhiPreTrainedModel { }; BloomPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `BloomPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_head; this.num_layers = this.config.n_layer; this.dim_kv = this.config.hidden_size / this.num_heads; } }; BloomModel = class extends BloomPreTrainedModel { }; BloomForCausalLM = class extends BloomPreTrainedModel { }; MptPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `MptPreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.n_heads; this.num_layers = this.config.n_layers; this.dim_kv = this.config.d_model / this.num_heads; } }; MptModel = class extends MptPreTrainedModel { }; MptForCausalLM = class extends MptPreTrainedModel { }; OPTPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `OPTPreTrainedModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.num_heads; } }; OPTModel = class extends OPTPreTrainedModel { }; OPTForCausalLM = class extends OPTPreTrainedModel { }; ViTPreTrainedModel = class extends PreTrainedModel { }; ViTModel = class extends ViTPreTrainedModel { }; ViTForImageClassification = class extends ViTPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; FastViTPreTrainedModel = class extends PreTrainedModel { }; FastViTModel = class extends FastViTPreTrainedModel { }; FastViTForImageClassification = class extends FastViTPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; VitMattePreTrainedModel = class extends PreTrainedModel { }; VitMatteForImageMatting = class extends VitMattePreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new ImageMattingOutput(await super._call(model_inputs)); } }; MobileViTPreTrainedModel = class extends PreTrainedModel { }; MobileViTModel = class extends MobileViTPreTrainedModel { }; MobileViTForImageClassification = class extends MobileViTPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; MobileViTV2PreTrainedModel = class extends PreTrainedModel { }; MobileViTV2Model = class extends MobileViTV2PreTrainedModel { }; MobileViTV2ForImageClassification = class extends MobileViTV2PreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; OwlViTPreTrainedModel = class extends PreTrainedModel { }; OwlViTModel = class extends OwlViTPreTrainedModel { }; OwlViTForObjectDetection = class extends OwlViTPreTrainedModel { }; Owlv2PreTrainedModel = class extends PreTrainedModel { }; Owlv2Model = class extends Owlv2PreTrainedModel { }; Owlv2ForObjectDetection = class extends Owlv2PreTrainedModel { }; BeitPreTrainedModel = class extends PreTrainedModel { }; BeitModel = class extends BeitPreTrainedModel { }; BeitForImageClassification = class extends BeitPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; DetrPreTrainedModel = class extends PreTrainedModel { }; DetrModel = class extends DetrPreTrainedModel { }; DetrForObjectDetection = class extends DetrPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new DetrObjectDetectionOutput(await super._call(model_inputs)); } }; DetrForSegmentation = class extends DetrPreTrainedModel { /** * Runs the model with the provided inputs * @param {Object} model_inputs Model inputs * @returns {Promise} Object containing segmentation outputs */ async _call(model_inputs) { return new DetrSegmentationOutput(await super._call(model_inputs)); } }; DetrObjectDetectionOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Classification logits (including no-object) for all queries. * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). */ constructor({ logits, pred_boxes }) { super(); this.logits = logits; this.pred_boxes = pred_boxes; } }; DetrSegmentationOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits The output logits of the model. * @param {Tensor} output.pred_boxes Predicted boxes. * @param {Tensor} output.pred_masks Predicted masks. */ constructor({ logits, pred_boxes, pred_masks }) { super(); this.logits = logits; this.pred_boxes = pred_boxes; this.pred_masks = pred_masks; } }; TableTransformerPreTrainedModel = class extends PreTrainedModel { }; TableTransformerModel = class extends TableTransformerPreTrainedModel { }; TableTransformerForObjectDetection = class extends TableTransformerPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); } }; TableTransformerObjectDetectionOutput = class extends DetrObjectDetectionOutput { }; DeiTPreTrainedModel = class extends PreTrainedModel { }; DeiTModel = class extends DeiTPreTrainedModel { }; DeiTForImageClassification = class extends DeiTPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; ResNetPreTrainedModel = class extends PreTrainedModel { }; ResNetModel = class extends ResNetPreTrainedModel { }; ResNetForImageClassification = class extends ResNetPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; SwinPreTrainedModel = class extends PreTrainedModel { }; SwinModel = class extends SwinPreTrainedModel { }; SwinForImageClassification = class extends SwinPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; Swin2SRPreTrainedModel = class extends PreTrainedModel { }; Swin2SRModel = class extends Swin2SRPreTrainedModel { }; Swin2SRForImageSuperResolution = class extends Swin2SRPreTrainedModel { }; DPTPreTrainedModel = class extends PreTrainedModel { }; DPTModel = class extends DPTPreTrainedModel { }; DPTForDepthEstimation = class extends DPTPreTrainedModel { }; DepthAnythingPreTrainedModel = class extends PreTrainedModel { }; DepthAnythingForDepthEstimation = class extends DepthAnythingPreTrainedModel { }; GLPNPreTrainedModel = class extends PreTrainedModel { }; GLPNModel = class extends GLPNPreTrainedModel { }; GLPNForDepthEstimation = class extends GLPNPreTrainedModel { }; DonutSwinPreTrainedModel = class extends PreTrainedModel { }; DonutSwinModel = class extends DonutSwinPreTrainedModel { }; ConvNextPreTrainedModel = class extends PreTrainedModel { }; ConvNextModel = class extends ConvNextPreTrainedModel { }; ConvNextForImageClassification = class extends ConvNextPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; ConvNextV2PreTrainedModel = class extends PreTrainedModel { }; ConvNextV2Model = class extends ConvNextV2PreTrainedModel { }; ConvNextV2ForImageClassification = class extends ConvNextV2PreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; Dinov2PreTrainedModel = class extends PreTrainedModel { }; Dinov2Model = class extends Dinov2PreTrainedModel { }; Dinov2ForImageClassification = class extends Dinov2PreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; YolosPreTrainedModel = class extends PreTrainedModel { }; YolosModel = class extends YolosPreTrainedModel { }; YolosForObjectDetection = class extends YolosPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new YolosObjectDetectionOutput(await super._call(model_inputs)); } }; YolosObjectDetectionOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Classification logits (including no-object) for all queries. * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). */ constructor({ logits, pred_boxes }) { super(); this.logits = logits; this.pred_boxes = pred_boxes; } }; SamPreTrainedModel = class extends PreTrainedModel { }; SamModel = class extends SamPreTrainedModel { /** * Creates a new instance of the `SamModel` class. * @param {Object} config The configuration object specifying the hyperparameters and other model settings. * @param {Object} vision_encoder The ONNX session containing the vision encoder model. * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model. */ constructor(config, vision_encoder, prompt_encoder_mask_decoder) { super(config, vision_encoder); this.prompt_encoder_mask_decoder = prompt_encoder_mask_decoder; } /** * Compute image embeddings and positional image embeddings, given the pixel values of an image. * @param {Object} model_inputs Object containing the model inputs. * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. */ async get_image_embeddings({ pixel_values }) { return await encoderForward(this, { pixel_values }); } /** * @typedef {Object} SamModelInputs Object containing the model inputs. * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. * These can be obtained using a `SamProcessor`. * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`. * This is used by the prompt encoder to encode the prompt. * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: * - `1`: the point is a point that contains the object of interest * - `0`: the point is a point that does not contain the object of interest * - `-1`: the point corresponds to the background * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. */ /** * @param {SamModelInputs} model_inputs Object containing the model inputs. * @returns {Promise} The output of the model. */ async forward(model_inputs) { if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) { model_inputs = { ...model_inputs, ...await this.get_image_embeddings(model_inputs) }; } if (!model_inputs.input_labels) { const shape = model_inputs.input_points.dims.slice(0, -1); const numElements = shape.reduce((a, b) => a * b, 1); model_inputs.input_labels = new Tensor( "int64", new BigInt64Array(numElements).fill(1n), shape ); } return await sessionRun(this.prompt_encoder_mask_decoder, { input_points: model_inputs.input_points, input_labels: model_inputs.input_labels, image_embeddings: model_inputs.image_embeddings, image_positional_embeddings: model_inputs.image_positional_embeddings }); } /** * Runs the model with the provided inputs * @param {Object} model_inputs Model inputs * @returns {Promise} Object containing segmentation outputs */ async _call(model_inputs) { return new SamImageSegmentationOutput(await super._call(model_inputs)); } }; SamImageSegmentationOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.iou_scores The output logits of the model. * @param {Tensor} output.pred_masks Predicted boxes. */ constructor({ iou_scores, pred_masks }) { super(); this.iou_scores = iou_scores; this.pred_masks = pred_masks; } }; MarianPreTrainedModel = class extends PreTrainedModel { }; MarianModel = class extends MarianPreTrainedModel { }; MarianMTModel = class extends MarianPreTrainedModel { /** * Creates a new instance of the `MarianMTModel` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {any} decoder_merged_session * @param {any} generation_config */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; M2M100PreTrainedModel = class extends PreTrainedModel { }; M2M100Model = class extends M2M100PreTrainedModel { }; M2M100ForConditionalGeneration = class extends M2M100PreTrainedModel { /** * Creates a new instance of the `M2M100ForConditionalGeneration` class. * @param {Object} config The model configuration object. * @param {Object} session The ONNX session object. * @param {any} decoder_merged_session * @param {any} generation_config */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads; } }; Wav2Vec2PreTrainedModel = class extends PreTrainedModel { }; Wav2Vec2Model = class extends Wav2Vec2PreTrainedModel { }; Wav2Vec2ForCTC = class extends Wav2Vec2PreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; Wav2Vec2ForSequenceClassification = class extends Wav2Vec2PreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; Wav2Vec2ForAudioFrameClassification = class extends Wav2Vec2PreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; UniSpeechPreTrainedModel = class extends PreTrainedModel { }; UniSpeechModel = class extends UniSpeechPreTrainedModel { }; UniSpeechForCTC = class extends UniSpeechPreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; UniSpeechForSequenceClassification = class extends UniSpeechPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; UniSpeechSatPreTrainedModel = class extends PreTrainedModel { }; UniSpeechSatModel = class extends UniSpeechSatPreTrainedModel { }; UniSpeechSatForCTC = class extends UniSpeechSatPreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; UniSpeechSatForSequenceClassification = class extends UniSpeechSatPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; UniSpeechSatForAudioFrameClassification = class extends UniSpeechSatPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; Wav2Vec2BertPreTrainedModel = class extends PreTrainedModel { }; Wav2Vec2BertModel = class extends Wav2Vec2BertPreTrainedModel { }; Wav2Vec2BertForCTC = class extends Wav2Vec2BertPreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; Wav2Vec2BertForSequenceClassification = class extends Wav2Vec2BertPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; HubertModel = class extends Wav2Vec2PreTrainedModel { }; HubertForCTC = class extends Wav2Vec2PreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; HubertForSequenceClassification = class extends Wav2Vec2PreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; WavLMPreTrainedModel = class extends PreTrainedModel { }; WavLMModel = class extends WavLMPreTrainedModel { }; WavLMForCTC = class extends WavLMPreTrainedModel { /** * @param {Object} model_inputs * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] */ async _call(model_inputs) { return new CausalLMOutput(await super._call(model_inputs)); } }; WavLMForSequenceClassification = class extends WavLMPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; WavLMForXVector = class extends WavLMPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits and speaker embeddings. */ async _call(model_inputs) { return new XVectorOutput(await super._call(model_inputs)); } }; WavLMForAudioFrameClassification = class extends WavLMPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} An object containing the model's output logits for sequence classification. */ async _call(model_inputs) { return new TokenClassifierOutput(await super._call(model_inputs)); } }; SpeechT5PreTrainedModel = class extends PreTrainedModel { }; SpeechT5ForSpeechToText = class extends SpeechT5PreTrainedModel { }; SpeechT5ForTextToSpeech = class extends SpeechT5PreTrainedModel { /** * Creates a new instance of the `SpeechT5ForTextToSpeech` class. * @param {Object} config The model configuration. * @param {any} session session for the model. * @param {any} decoder_merged_session session for the decoder. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, decoder_merged_session, generation_config) { super(config, session); this.decoder_merged_session = decoder_merged_session; this.generation_config = generation_config; this.num_decoder_layers = this.config.decoder_layers; this.num_decoder_heads = this.config.decoder_attention_heads; this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads; this.num_encoder_layers = this.config.encoder_layers; this.num_encoder_heads = this.config.encoder_attention_heads; this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads; } /** * @typedef {Object} SpeechOutput * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. */ /** * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. * @param {Object} options Optional parameters for generating speech. * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. */ async generate_speech(input_values, speaker_embeddings, { threshold = 0.5, minlenratio = 0, maxlenratio = 20, vocoder = null // output_cross_attentions = false, // TODO add } = {}) { const model_inputs = { input_ids: input_values }; const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs); const r = encoder_outputs.dims[1] / this.config.reduction_factor; const maxlen = Math.floor(r * maxlenratio); const minlen = Math.floor(r * minlenratio); const num_mel_bins = this.config.num_mel_bins; let spectrogramParts = []; let past_key_values = null; let decoder_outputs = null; let idx = 0; while (true) { ++idx; const use_cache_branch = boolTensor(!!decoder_outputs); let output_sequence; if (decoder_outputs) { output_sequence = decoder_outputs.output_sequence_out; } else { output_sequence = new Tensor( "float32", new Float32Array(num_mel_bins), [1, 1, num_mel_bins] ); } let decoderFeeds = { use_cache_branch, output_sequence, encoder_attention_mask, speaker_embeddings, encoder_hidden_states: encoder_outputs }; this.addPastKeyValues(decoderFeeds, past_key_values); decoder_outputs = await sessionRun(this.decoder_merged_session, decoderFeeds); past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values); const { prob, spectrum } = decoder_outputs; spectrogramParts.push(spectrum); if (idx >= minlen && // Finished when stop token or maximum length is reached. (Array.from(prob.data).filter((p) => p >= threshold).length > 0 || idx >= maxlen)) { break; } } const spectrogram2 = cat(spectrogramParts); const { waveform } = await sessionRun(vocoder.session, { spectrogram: spectrogram2 }); return { spectrogram: spectrogram2, waveform // cross_attentions: null, // TODO add }; } }; SpeechT5HifiGan = class extends PreTrainedModel { main_input_name = "spectrogram"; }; TrOCRPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `TrOCRPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers; this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads; this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads; } }; TrOCRForCausalLM = class extends TrOCRPreTrainedModel { }; MistralPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `MistralPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_key_value_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; } }; MistralModel = class extends MistralPreTrainedModel { }; MistralForCausalLM = class extends MistralPreTrainedModel { }; Starcoder2PreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `Starcoder2PreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_key_value_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; } }; Starcoder2Model = class extends Starcoder2PreTrainedModel { }; Starcoder2ForCausalLM = class extends Starcoder2PreTrainedModel { }; FalconPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `FalconPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.config.num_attention_heads; } }; FalconModel = class extends FalconPreTrainedModel { }; FalconForCausalLM = class extends FalconPreTrainedModel { }; ClapPreTrainedModel = class extends PreTrainedModel { }; ClapModel = class extends ClapPreTrainedModel { }; ClapTextModelWithProjection = class extends ClapPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "text_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; ClapAudioModelWithProjection = class extends ClapPreTrainedModel { /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, options = {}) { options.model_file_name ??= "audio_model"; return super.from_pretrained(pretrained_model_name_or_path, options); } }; VitsPreTrainedModel = class extends PreTrainedModel { }; VitsModel = class extends VitsPreTrainedModel { /** * Calls the model on new inputs. * @param {Object} model_inputs The inputs to the model. * @returns {Promise} The outputs for the VITS model. */ async _call(model_inputs) { return new VitsModelOutput(await super._call(model_inputs)); } }; SegformerPreTrainedModel = class extends PreTrainedModel { }; SegformerForImageClassification = class extends SegformerPreTrainedModel { }; SegformerForSemanticSegmentation = class extends SegformerPreTrainedModel { }; StableLmPreTrainedModel = class extends PreTrainedModel { /** * Creates a new instance of the `StableLmPreTrainedModel` class. * @param {Object} config The configuration of the model. * @param {any} session The ONNX session containing the model weights. * @param {GenerationConfig} generation_config The generation configuration. */ constructor(config, session, generation_config) { super(config, session); this.generation_config = generation_config; this.config.pad_token_id = this.config.eos_token_id; this.num_heads = this.config.num_attention_heads; this.num_layers = this.config.num_hidden_layers; this.dim_kv = this.config.hidden_size / this.num_heads; } }; StableLmForCausalLM = class extends StableLmPreTrainedModel { }; EfficientNetPreTrainedModel = class extends PreTrainedModel { }; EfficientNetModel = class extends EfficientNetPreTrainedModel { }; EfficientNetForImageClassification = class extends EfficientNetPreTrainedModel { /** * @param {any} model_inputs */ async _call(model_inputs) { return new SequenceClassifierOutput(await super._call(model_inputs)); } }; PretrainedMixin = class { /** * Mapping from model type to model class. * @type {Map[]} */ static MODEL_CLASS_MAPPINGS = null; /** * Whether to attempt to instantiate the base class (`PretrainedModel`) if * the model type is not found in the mapping. */ static BASE_IF_FAIL = false; /** @type {PreTrainedModel.from_pretrained} */ static async from_pretrained(pretrained_model_name_or_path, { quantized = true, progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main", model_file_name = null } = {}) { let options = { quantized, progress_callback, config, cache_dir, local_files_only, revision, model_file_name }; config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options); if (!options.config) { options.config = config; } if (!this.MODEL_CLASS_MAPPINGS) { throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); } for (let MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { const modelInfo = MODEL_CLASS_MAPPING.get(config.model_type); if (!modelInfo) { continue; } return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options); } if (this.BASE_IF_FAIL) { console.warn(`Unknown model class "${config.model_type}", attempting to construct from base class.`); return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); } else { throw Error(`Unsupported model type: ${config.model_type}`); } } }; MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([ ["bert", ["BertModel", BertModel]], ["nomic_bert", ["NomicBertModel", NomicBertModel]], ["roformer", ["RoFormerModel", RoFormerModel]], ["electra", ["ElectraModel", ElectraModel]], ["esm", ["EsmModel", EsmModel]], ["convbert", ["ConvBertModel", ConvBertModel]], ["camembert", ["CamembertModel", CamembertModel]], ["deberta", ["DebertaModel", DebertaModel]], ["deberta-v2", ["DebertaV2Model", DebertaV2Model]], ["mpnet", ["MPNetModel", MPNetModel]], ["albert", ["AlbertModel", AlbertModel]], ["distilbert", ["DistilBertModel", DistilBertModel]], ["roberta", ["RobertaModel", RobertaModel]], ["xlm", ["XLMModel", XLMModel]], ["xlm-roberta", ["XLMRobertaModel", XLMRobertaModel]], ["clap", ["ClapModel", ClapModel]], ["clip", ["CLIPModel", CLIPModel]], ["clipseg", ["CLIPSegModel", CLIPSegModel]], ["chinese_clip", ["ChineseCLIPModel", ChineseCLIPModel]], ["siglip", ["SiglipModel", SiglipModel]], ["mobilebert", ["MobileBertModel", MobileBertModel]], ["squeezebert", ["SqueezeBertModel", SqueezeBertModel]], ["wav2vec2", ["Wav2Vec2Model", Wav2Vec2Model]], ["wav2vec2-bert", ["Wav2Vec2BertModel", Wav2Vec2BertModel]], ["unispeech", ["UniSpeechModel", UniSpeechModel]], ["unispeech-sat", ["UniSpeechSatModel", UniSpeechSatModel]], ["hubert", ["HubertModel", HubertModel]], ["wavlm", ["WavLMModel", WavLMModel]], ["audio-spectrogram-transformer", ["ASTModel", ASTModel]], ["vits", ["VitsModel", VitsModel]], ["detr", ["DetrModel", DetrModel]], ["table-transformer", ["TableTransformerModel", TableTransformerModel]], ["vit", ["ViTModel", ViTModel]], ["fastvit", ["FastViTModel", FastViTModel]], ["mobilevit", ["MobileViTModel", MobileViTModel]], ["mobilevitv2", ["MobileViTV2Model", MobileViTV2Model]], ["owlvit", ["OwlViTModel", OwlViTModel]], ["owlv2", ["Owlv2Model", Owlv2Model]], ["beit", ["BeitModel", BeitModel]], ["deit", ["DeiTModel", DeiTModel]], ["convnext", ["ConvNextModel", ConvNextModel]], ["convnextv2", ["ConvNextV2Model", ConvNextV2Model]], ["dinov2", ["Dinov2Model", Dinov2Model]], ["resnet", ["ResNetModel", ResNetModel]], ["swin", ["SwinModel", SwinModel]], ["swin2sr", ["Swin2SRModel", Swin2SRModel]], ["donut-swin", ["DonutSwinModel", DonutSwinModel]], ["yolos", ["YolosModel", YolosModel]], ["dpt", ["DPTModel", DPTModel]], ["glpn", ["GLPNModel", GLPNModel]], ["hifigan", ["SpeechT5HifiGan", SpeechT5HifiGan]], ["efficientnet", ["EfficientNetModel", EfficientNetModel]] ]); MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([ ["t5", ["T5Model", T5Model]], ["longt5", ["LongT5Model", LongT5Model]], ["mt5", ["MT5Model", MT5Model]], ["bart", ["BartModel", BartModel]], ["mbart", ["MBartModel", MBartModel]], ["marian", ["MarianModel", MarianModel]], ["whisper", ["WhisperModel", WhisperModel]], ["m2m_100", ["M2M100Model", M2M100Model]], ["blenderbot", ["BlenderbotModel", BlenderbotModel]], ["blenderbot-small", ["BlenderbotSmallModel", BlenderbotSmallModel]] ]); MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([ ["bloom", ["BloomModel", BloomModel]], ["gpt2", ["GPT2Model", GPT2Model]], ["gptj", ["GPTJModel", GPTJModel]], ["gpt_bigcode", ["GPTBigCodeModel", GPTBigCodeModel]], ["gpt_neo", ["GPTNeoModel", GPTNeoModel]], ["gpt_neox", ["GPTNeoXModel", GPTNeoXModel]], ["codegen", ["CodeGenModel", CodeGenModel]], ["llama", ["LlamaModel", LlamaModel]], ["qwen2", ["Qwen2Model", Qwen2Model]], ["phi", ["PhiModel", PhiModel]], ["mpt", ["MptModel", MptModel]], ["opt", ["OPTModel", OPTModel]], ["mistral", ["MistralModel", MistralModel]], ["starcoder2", ["Starcoder2Model", Starcoder2Model]], ["falcon", ["FalconModel", FalconModel]] ]); MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]], ["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]] ]); MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]] ]); MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["vits", ["VitsModel", VitsModel]] ]); MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["bert", ["BertForSequenceClassification", BertForSequenceClassification]], ["roformer", ["RoFormerForSequenceClassification", RoFormerForSequenceClassification]], ["electra", ["ElectraForSequenceClassification", ElectraForSequenceClassification]], ["esm", ["EsmForSequenceClassification", EsmForSequenceClassification]], ["convbert", ["ConvBertForSequenceClassification", ConvBertForSequenceClassification]], ["camembert", ["CamembertForSequenceClassification", CamembertForSequenceClassification]], ["deberta", ["DebertaForSequenceClassification", DebertaForSequenceClassification]], ["deberta-v2", ["DebertaV2ForSequenceClassification", DebertaV2ForSequenceClassification]], ["mpnet", ["MPNetForSequenceClassification", MPNetForSequenceClassification]], ["albert", ["AlbertForSequenceClassification", AlbertForSequenceClassification]], ["distilbert", ["DistilBertForSequenceClassification", DistilBertForSequenceClassification]], ["roberta", ["RobertaForSequenceClassification", RobertaForSequenceClassification]], ["xlm", ["XLMForSequenceClassification", XLMForSequenceClassification]], ["xlm-roberta", ["XLMRobertaForSequenceClassification", XLMRobertaForSequenceClassification]], ["bart", ["BartForSequenceClassification", BartForSequenceClassification]], ["mbart", ["MBartForSequenceClassification", MBartForSequenceClassification]], ["mobilebert", ["MobileBertForSequenceClassification", MobileBertForSequenceClassification]], ["squeezebert", ["SqueezeBertForSequenceClassification", SqueezeBertForSequenceClassification]] ]); MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["bert", ["BertForTokenClassification", BertForTokenClassification]], ["roformer", ["RoFormerForTokenClassification", RoFormerForTokenClassification]], ["electra", ["ElectraForTokenClassification", ElectraForTokenClassification]], ["esm", ["EsmForTokenClassification", EsmForTokenClassification]], ["convbert", ["ConvBertForTokenClassification", ConvBertForTokenClassification]], ["camembert", ["CamembertForTokenClassification", CamembertForTokenClassification]], ["deberta", ["DebertaForTokenClassification", DebertaForTokenClassification]], ["deberta-v2", ["DebertaV2ForTokenClassification", DebertaV2ForTokenClassification]], ["mpnet", ["MPNetForTokenClassification", MPNetForTokenClassification]], ["distilbert", ["DistilBertForTokenClassification", DistilBertForTokenClassification]], ["roberta", ["RobertaForTokenClassification", RobertaForTokenClassification]], ["xlm", ["XLMForTokenClassification", XLMForTokenClassification]], ["xlm-roberta", ["XLMRobertaForTokenClassification", XLMRobertaForTokenClassification]] ]); MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["t5", ["T5ForConditionalGeneration", T5ForConditionalGeneration]], ["longt5", ["LongT5ForConditionalGeneration", LongT5ForConditionalGeneration]], ["mt5", ["MT5ForConditionalGeneration", MT5ForConditionalGeneration]], ["bart", ["BartForConditionalGeneration", BartForConditionalGeneration]], ["mbart", ["MBartForConditionalGeneration", MBartForConditionalGeneration]], ["marian", ["MarianMTModel", MarianMTModel]], ["m2m_100", ["M2M100ForConditionalGeneration", M2M100ForConditionalGeneration]], ["blenderbot", ["BlenderbotForConditionalGeneration", BlenderbotForConditionalGeneration]], ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", BlenderbotSmallForConditionalGeneration]] ]); MODEL_WITH_LM_HEAD_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["bloom", ["BloomForCausalLM", BloomForCausalLM]], ["gpt2", ["GPT2LMHeadModel", GPT2LMHeadModel]], ["gptj", ["GPTJForCausalLM", GPTJForCausalLM]], ["gpt_bigcode", ["GPTBigCodeForCausalLM", GPTBigCodeForCausalLM]], ["gpt_neo", ["GPTNeoForCausalLM", GPTNeoForCausalLM]], ["gpt_neox", ["GPTNeoXForCausalLM", GPTNeoXForCausalLM]], ["codegen", ["CodeGenForCausalLM", CodeGenForCausalLM]], ["llama", ["LlamaForCausalLM", LlamaForCausalLM]], ["qwen2", ["Qwen2ForCausalLM", Qwen2ForCausalLM]], ["phi", ["PhiForCausalLM", PhiForCausalLM]], ["mpt", ["MptForCausalLM", MptForCausalLM]], ["opt", ["OPTForCausalLM", OPTForCausalLM]], ["mbart", ["MBartForCausalLM", MBartForCausalLM]], ["mistral", ["MistralForCausalLM", MistralForCausalLM]], ["starcoder2", ["Starcoder2ForCausalLM", Starcoder2ForCausalLM]], ["falcon", ["FalconForCausalLM", FalconForCausalLM]], ["trocr", ["TrOCRForCausalLM", TrOCRForCausalLM]], ["stablelm", ["StableLmForCausalLM", StableLmForCausalLM]] ]); MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["bert", ["BertForMaskedLM", BertForMaskedLM]], ["roformer", ["RoFormerForMaskedLM", RoFormerForMaskedLM]], ["electra", ["ElectraForMaskedLM", ElectraForMaskedLM]], ["esm", ["EsmForMaskedLM", EsmForMaskedLM]], ["convbert", ["ConvBertForMaskedLM", ConvBertForMaskedLM]], ["camembert", ["CamembertForMaskedLM", CamembertForMaskedLM]], ["deberta", ["DebertaForMaskedLM", DebertaForMaskedLM]], ["deberta-v2", ["DebertaV2ForMaskedLM", DebertaV2ForMaskedLM]], ["mpnet", ["MPNetForMaskedLM", MPNetForMaskedLM]], ["albert", ["AlbertForMaskedLM", AlbertForMaskedLM]], ["distilbert", ["DistilBertForMaskedLM", DistilBertForMaskedLM]], ["roberta", ["RobertaForMaskedLM", RobertaForMaskedLM]], ["xlm", ["XLMWithLMHeadModel", XLMWithLMHeadModel]], ["xlm-roberta", ["XLMRobertaForMaskedLM", XLMRobertaForMaskedLM]], ["mobilebert", ["MobileBertForMaskedLM", MobileBertForMaskedLM]], ["squeezebert", ["SqueezeBertForMaskedLM", SqueezeBertForMaskedLM]] ]); MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["bert", ["BertForQuestionAnswering", BertForQuestionAnswering]], ["roformer", ["RoFormerForQuestionAnswering", RoFormerForQuestionAnswering]], ["electra", ["ElectraForQuestionAnswering", ElectraForQuestionAnswering]], ["convbert", ["ConvBertForQuestionAnswering", ConvBertForQuestionAnswering]], ["camembert", ["CamembertForQuestionAnswering", CamembertForQuestionAnswering]], ["deberta", ["DebertaForQuestionAnswering", DebertaForQuestionAnswering]], ["deberta-v2", ["DebertaV2ForQuestionAnswering", DebertaV2ForQuestionAnswering]], ["mpnet", ["MPNetForQuestionAnswering", MPNetForQuestionAnswering]], ["albert", ["AlbertForQuestionAnswering", AlbertForQuestionAnswering]], ["distilbert", ["DistilBertForQuestionAnswering", DistilBertForQuestionAnswering]], ["roberta", ["RobertaForQuestionAnswering", RobertaForQuestionAnswering]], ["xlm", ["XLMForQuestionAnswering", XLMForQuestionAnswering]], ["xlm-roberta", ["XLMRobertaForQuestionAnswering", XLMRobertaForQuestionAnswering]], ["mobilebert", ["MobileBertForQuestionAnswering", MobileBertForQuestionAnswering]], ["squeezebert", ["SqueezeBertForQuestionAnswering", SqueezeBertForQuestionAnswering]] ]); MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]] ]); MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]] ]); MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["vit", ["ViTForImageClassification", ViTForImageClassification]], ["fastvit", ["FastViTForImageClassification", FastViTForImageClassification]], ["mobilevit", ["MobileViTForImageClassification", MobileViTForImageClassification]], ["mobilevitv2", ["MobileViTV2ForImageClassification", MobileViTV2ForImageClassification]], ["beit", ["BeitForImageClassification", BeitForImageClassification]], ["deit", ["DeiTForImageClassification", DeiTForImageClassification]], ["convnext", ["ConvNextForImageClassification", ConvNextForImageClassification]], ["convnextv2", ["ConvNextV2ForImageClassification", ConvNextV2ForImageClassification]], ["dinov2", ["Dinov2ForImageClassification", Dinov2ForImageClassification]], ["resnet", ["ResNetForImageClassification", ResNetForImageClassification]], ["swin", ["SwinForImageClassification", SwinForImageClassification]], ["segformer", ["SegformerForImageClassification", SegformerForImageClassification]], ["efficientnet", ["EfficientNetForImageClassification", EfficientNetForImageClassification]] ]); MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["detr", ["DetrForObjectDetection", DetrForObjectDetection]], ["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]], ["yolos", ["YolosForObjectDetection", YolosForObjectDetection]] ]); MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]], ["owlv2", ["Owlv2ForObjectDetection", Owlv2ForObjectDetection]] ]); MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["detr", ["DetrForSegmentation", DetrForSegmentation]], ["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]] ]); MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]] ]); MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["sam", ["SamModel", SamModel]] ]); MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]], ["wav2vec2-bert", ["Wav2Vec2BertForCTC", Wav2Vec2BertForCTC]], ["unispeech", ["UniSpeechForCTC", UniSpeechForCTC]], ["unispeech-sat", ["UniSpeechSatForCTC", UniSpeechSatForCTC]], ["wavlm", ["WavLMForCTC", WavLMForCTC]], ["hubert", ["HubertForCTC", HubertForCTC]] ]); MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Wav2Vec2ForSequenceClassification]], ["wav2vec2-bert", ["Wav2Vec2BertForSequenceClassification", Wav2Vec2BertForSequenceClassification]], ["unispeech", ["UniSpeechForSequenceClassification", UniSpeechForSequenceClassification]], ["unispeech-sat", ["UniSpeechSatForSequenceClassification", UniSpeechSatForSequenceClassification]], ["wavlm", ["WavLMForSequenceClassification", WavLMForSequenceClassification]], ["hubert", ["HubertForSequenceClassification", HubertForSequenceClassification]], ["audio-spectrogram-transformer", ["ASTForAudioClassification", ASTForAudioClassification]] ]); MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["wavlm", ["WavLMForXVector", WavLMForXVector]] ]); MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", UniSpeechSatForAudioFrameClassification]], ["wavlm", ["WavLMForAudioFrameClassification", WavLMForAudioFrameClassification]], ["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Wav2Vec2ForAudioFrameClassification]] ]); MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]] ]); MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]] ]); MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]], ["depth_anything", ["DepthAnythingForDepthEstimation", DepthAnythingForDepthEstimation]], ["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]] ]); MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ ["clip", ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection]], ["siglip", ["SiglipVisionModel", SiglipVisionModel]] ]); MODEL_CLASS_TYPE_MAPPING = [ [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly], [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration], [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], // Custom: [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly] ]; for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { for (const [name2, model] of mappings.values()) { MODEL_TYPE_MAPPING.set(name2, type); MODEL_CLASS_TO_NAME_MAPPING.set(model, name2); MODEL_NAME_TO_CLASS_MAPPING.set(name2, model); } } CUSTOM_MAPPING = [ ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly], ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly] ]; for (const [name2, model, type] of CUSTOM_MAPPING) { MODEL_TYPE_MAPPING.set(name2, type); MODEL_CLASS_TO_NAME_MAPPING.set(model, name2); MODEL_NAME_TO_CLASS_MAPPING.set(name2, model); } AutoModel = class extends PretrainedMixin { /** @type {Map[]} */ // @ts-ignore static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map((x2) => x2[0]); static BASE_IF_FAIL = true; }; AutoModelForSequenceClassification = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; }; AutoModelForTokenClassification = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; }; AutoModelForSeq2SeqLM = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; }; AutoModelForSpeechSeq2Seq = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; }; AutoModelForTextToSpectrogram = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; }; AutoModelForTextToWaveform = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; }; AutoModelForCausalLM = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_WITH_LM_HEAD_MAPPING_NAMES]; }; AutoModelForMaskedLM = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES]; }; AutoModelForQuestionAnswering = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; }; AutoModelForVision2Seq = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; }; AutoModelForImageClassification = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; }; AutoModelForImageSegmentation = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; }; AutoModelForSemanticSegmentation = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; }; AutoModelForObjectDetection = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; }; AutoModelForZeroShotObjectDetection = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; }; AutoModelForCTC = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES]; }; AutoModelForAudioClassification = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; }; AutoModelForDocumentQuestionAnswering = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; }; AutoModelForImageToImage = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; }; AutoModelForDepthEstimation = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; }; AutoModelForImageFeatureExtraction = class extends PretrainedMixin { static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]; }; Seq2SeqLMOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits The output logits of the model. * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. */ constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { super(); this.logits = logits; this.past_key_values = past_key_values; this.encoder_outputs = encoder_outputs; this.decoder_attentions = decoder_attentions; this.cross_attentions = cross_attentions; } }; SequenceClassifierOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). */ constructor({ logits }) { super(); this.logits = logits; } }; XVectorOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`. * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`. */ constructor({ logits, embeddings }) { super(); this.logits = logits; this.embeddings = embeddings; } }; TokenClassifierOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Classification scores (before SoftMax). */ constructor({ logits }) { super(); this.logits = logits; } }; MaskedLMOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). */ constructor({ logits }) { super(); this.logits = logits; } }; QuestionAnsweringModelOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.start_logits Span-start scores (before SoftMax). * @param {Tensor} output.end_logits Span-end scores (before SoftMax). */ constructor({ start_logits, end_logits }) { super(); this.start_logits = start_logits; this.end_logits = end_logits; } }; CausalLMOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). */ constructor({ logits }) { super(); this.logits = logits; } }; ImageMattingOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. */ constructor({ alphas }) { super(); this.alphas = alphas; } }; VitsModelOutput = class extends ModelOutput { /** * @param {Object} output The output of the model. * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. */ constructor({ waveform, spectrogram: spectrogram2 }) { super(); this.waveform = waveform; this.spectrogram = spectrogram2; } }; } }); // (disabled):node_modules/sharp/lib/index.js var require_lib = __commonJS({ "(disabled):node_modules/sharp/lib/index.js"() { } }); // node_modules/@xenova/transformers/src/utils/image.js var import_sharp, BROWSER_ENV, WEBWORKER_ENV, createCanvasFunction, ImageDataClass, loadImageFunction, RESAMPLING_MAPPING, CONTENT_TYPE_MAP, RawImage; var init_image = __esm({ "node_modules/@xenova/transformers/src/utils/image.js"() { init_hub(); init_env(); init_tensor(); import_sharp = __toESM(require_lib(), 1); BROWSER_ENV = typeof self !== "undefined"; WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === "DedicatedWorkerGlobalScope"; if (BROWSER_ENV) { createCanvasFunction = (width, height) => { if (!self.OffscreenCanvas) { throw new Error("OffscreenCanvas not supported by this browser."); } return new self.OffscreenCanvas(width, height); }; loadImageFunction = self.createImageBitmap; ImageDataClass = self.ImageData; } else if (import_sharp.default) { loadImageFunction = async (img) => { const metadata = await img.metadata(); const rawChannels = metadata.channels; let { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true }); const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); if (rawChannels !== void 0 && rawChannels !== info.channels) { newImage.convert(rawChannels); } return newImage; }; } else { throw new Error("Unable to load image processing library."); } RESAMPLING_MAPPING = { 0: "nearest", 1: "lanczos", 2: "bilinear", 3: "bicubic", 4: "box", 5: "hamming" }; CONTENT_TYPE_MAP = /* @__PURE__ */ new Map([ ["png", "image/png"], ["jpg", "image/jpeg"], ["jpeg", "image/jpeg"], ["gif", "image/gif"] ]); RawImage = class _RawImage { /** * Create a new `RawImage` object. * @param {Uint8ClampedArray|Uint8Array} data The pixel data. * @param {number} width The width of the image. * @param {number} height The height of the image. * @param {1|2|3|4} channels The number of channels. */ constructor(data, width, height, channels) { this.data = data; this.width = width; this.height = height; this.channels = channels; } /** * Returns the size of the image (width, height). * @returns {[number, number]} The size of the image (width, height). */ get size() { return [this.width, this.height]; } /** * Helper method for reading an image from a variety of input types. * @param {RawImage|string|URL} input * @returns The image object. * * **Example:** Read image from a URL. * ```javascript * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); * // RawImage { * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], * // "width": 800, * // "height": 533, * // "channels": 3 * // } * ``` */ static async read(input) { if (input instanceof _RawImage) { return input; } else if (typeof input === "string" || input instanceof URL) { return await this.fromURL(input); } else { throw new Error(`Unsupported input type: ${typeof input}`); } } /** * Read an image from a URL or file path. * @param {string|URL} url The URL or file path to read the image from. * @returns {Promise} The image object. */ static async fromURL(url2) { let response = await getFile(url2); if (response.status !== 200) { throw new Error(`Unable to read image from "${url2}" (${response.status} ${response.statusText})`); } let blob = await response.blob(); return this.fromBlob(blob); } /** * Helper method to create a new Image from a blob. * @param {Blob} blob The blob to read the image from. * @returns {Promise} The image object. */ static async fromBlob(blob) { if (BROWSER_ENV) { let img = await loadImageFunction(blob); const ctx = createCanvasFunction(img.width, img.height).getContext("2d"); ctx.drawImage(img, 0, 0); return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); } else { let img = (0, import_sharp.default)(await blob.arrayBuffer()); return await loadImageFunction(img); } } /** * Helper method to create a new Image from a tensor * @param {Tensor} tensor */ static fromTensor(tensor, channel_format = "CHW") { if (tensor.dims.length !== 3) { throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`); } if (channel_format === "CHW") { tensor = tensor.transpose(1, 2, 0); } else if (channel_format === "HWC") { } else { throw new Error(`Unsupported channel format: ${channel_format}`); } if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { throw new Error(`Unsupported tensor type: ${tensor.type}`); } switch (tensor.dims[2]) { case 1: case 2: case 3: case 4: return new _RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); default: throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); } } /** * Convert the image to grayscale format. * @returns {RawImage} `this` to support chaining. */ grayscale() { if (this.channels === 1) { return this; } let newData = new Uint8ClampedArray(this.width * this.height * 1); switch (this.channels) { case 3: // rgb to grayscale case 4: for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { const red = this.data[i]; const green = this.data[i + 1]; const blue = this.data[i + 2]; newData[offset++] = Math.round(0.2989 * red + 0.587 * green + 0.114 * blue); } break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(newData, this.width, this.height, 1); } /** * Convert the image to RGB format. * @returns {RawImage} `this` to support chaining. */ rgb() { if (this.channels === 3) { return this; } let newData = new Uint8ClampedArray(this.width * this.height * 3); switch (this.channels) { case 1: for (let i = 0, offset = 0; i < this.data.length; ++i) { newData[offset++] = this.data[i]; newData[offset++] = this.data[i]; newData[offset++] = this.data[i]; } break; case 4: for (let i = 0, offset = 0; i < this.data.length; i += 4) { newData[offset++] = this.data[i]; newData[offset++] = this.data[i + 1]; newData[offset++] = this.data[i + 2]; } break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(newData, this.width, this.height, 3); } /** * Convert the image to RGBA format. * @returns {RawImage} `this` to support chaining. */ rgba() { if (this.channels === 4) { return this; } let newData = new Uint8ClampedArray(this.width * this.height * 4); switch (this.channels) { case 1: for (let i = 0, offset = 0; i < this.data.length; ++i) { newData[offset++] = this.data[i]; newData[offset++] = this.data[i]; newData[offset++] = this.data[i]; newData[offset++] = 255; } break; case 3: for (let i = 0, offset = 0; i < this.data.length; i += 3) { newData[offset++] = this.data[i]; newData[offset++] = this.data[i + 1]; newData[offset++] = this.data[i + 2]; newData[offset++] = 255; } break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(newData, this.width, this.height, 4); } /** * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. * @param {number} width The width of the new image. * @param {number} height The height of the new image. * @param {Object} options Additional options for resizing. * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. * @returns {Promise} `this` to support chaining. */ async resize(width, height, { resample = 2 } = {}) { let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; if (BROWSER_ENV) { let numChannels = this.channels; let canvas = this.toCanvas(); const ctx = createCanvasFunction(width, height).getContext("2d"); ctx.drawImage(canvas, 0, 0, width, height); let resizedImage = new _RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); return resizedImage.convert(numChannels); } else { let img = this.toSharp(); switch (resampleMethod) { case "box": case "hamming": if (resampleMethod === "box" || resampleMethod === "hamming") { console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`); resampleMethod = "bilinear"; } case "nearest": case "bilinear": case "bicubic": img = img.affine([width / this.width, 0, 0, height / this.height], { interpolator: resampleMethod }); break; case "lanczos": img = img.resize({ width, height, fit: "fill", kernel: "lanczos3" // PIL Lanczos uses a kernel size of 3 }); break; default: throw new Error(`Resampling method ${resampleMethod} is not supported.`); } return await loadImageFunction(img); } } async pad([left, right, top, bottom]) { left = Math.max(left, 0); right = Math.max(right, 0); top = Math.max(top, 0); bottom = Math.max(bottom, 0); if (left === 0 && right === 0 && top === 0 && bottom === 0) { return this; } if (BROWSER_ENV) { let numChannels = this.channels; let canvas = this.toCanvas(); let newWidth = this.width + left + right; let newHeight = this.height + top + bottom; const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d"); ctx.drawImage( canvas, 0, 0, this.width, this.height, left, top, newWidth, newHeight ); let paddedImage = new _RawImage( ctx.getImageData(0, 0, newWidth, newHeight).data, newWidth, newHeight, 4 ); return paddedImage.convert(numChannels); } else { let img = this.toSharp().extend({ left, right, top, bottom }); return await loadImageFunction(img); } } async crop([x_min, y_min, x_max, y_max]) { x_min = Math.max(x_min, 0); y_min = Math.max(y_min, 0); x_max = Math.min(x_max, this.width - 1); y_max = Math.min(y_max, this.height - 1); if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { return this; } const crop_width = x_max - x_min + 1; const crop_height = y_max - y_min + 1; if (BROWSER_ENV) { const numChannels = this.channels; const canvas = this.toCanvas(); const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); ctx.drawImage( canvas, x_min, y_min, crop_width, crop_height, 0, 0, crop_width, crop_height ); const resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); return resizedImage.convert(numChannels); } else { const img = this.toSharp().extract({ left: x_min, top: y_min, width: crop_width, height: crop_height }); return await loadImageFunction(img); } } async center_crop(crop_width, crop_height) { if (this.width === crop_width && this.height === crop_height) { return this; } let width_offset = (this.width - crop_width) / 2; let height_offset = (this.height - crop_height) / 2; if (BROWSER_ENV) { let numChannels = this.channels; let canvas = this.toCanvas(); const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); let sourceX = 0; let sourceY = 0; let destX = 0; let destY = 0; if (width_offset >= 0) { sourceX = width_offset; } else { destX = -width_offset; } if (height_offset >= 0) { sourceY = height_offset; } else { destY = -height_offset; } ctx.drawImage( canvas, sourceX, sourceY, crop_width, crop_height, destX, destY, crop_width, crop_height ); let resizedImage = new _RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); return resizedImage.convert(numChannels); } else { let img = this.toSharp(); if (width_offset >= 0 && height_offset >= 0) { img = img.extract({ left: Math.floor(width_offset), top: Math.floor(height_offset), width: crop_width, height: crop_height }); } else if (width_offset <= 0 && height_offset <= 0) { let top = Math.floor(-height_offset); let left = Math.floor(-width_offset); img = img.extend({ top, left, // Ensures the resulting image has the desired dimensions right: crop_width - this.width - left, bottom: crop_height - this.height - top }); } else { let y_padding = [0, 0]; let y_extract = 0; if (height_offset < 0) { y_padding[0] = Math.floor(-height_offset); y_padding[1] = crop_height - this.height - y_padding[0]; } else { y_extract = Math.floor(height_offset); } let x_padding = [0, 0]; let x_extract = 0; if (width_offset < 0) { x_padding[0] = Math.floor(-width_offset); x_padding[1] = crop_width - this.width - x_padding[0]; } else { x_extract = Math.floor(width_offset); } img = img.extend({ top: y_padding[0], bottom: y_padding[1], left: x_padding[0], right: x_padding[1] }).extract({ left: x_extract, top: y_extract, width: crop_width, height: crop_height }); } return await loadImageFunction(img); } } async toBlob(type = "image/png", quality = 1) { if (!BROWSER_ENV) { throw new Error("toBlob() is only supported in browser environments."); } const canvas = this.toCanvas(); return await canvas.convertToBlob({ type, quality }); } toTensor(channel_format = "CHW") { let tensor = new Tensor( "uint8", new Uint8Array(this.data), [this.height, this.width, this.channels] ); if (channel_format === "HWC") { } else if (channel_format === "CHW") { tensor = tensor.permute(2, 0, 1); } else { throw new Error(`Unsupported channel format: ${channel_format}`); } return tensor; } toCanvas() { if (!BROWSER_ENV) { throw new Error("toCanvas() is only supported in browser environments."); } let cloned = this.clone().rgba(); let clonedCanvas = createCanvasFunction(cloned.width, cloned.height); let data = new ImageDataClass(cloned.data, cloned.width, cloned.height); clonedCanvas.getContext("2d").putImageData(data, 0, 0); return clonedCanvas; } /** * Helper method to update the image data. * @param {Uint8ClampedArray} data The new image data. * @param {number} width The new width of the image. * @param {number} height The new height of the image. * @param {1|2|3|4|null} [channels] The new number of channels of the image. * @private */ _update(data, width, height, channels = null) { this.data = data; this.width = width; this.height = height; if (channels !== null) { this.channels = channels; } return this; } /** * Clone the image * @returns {RawImage} The cloned image */ clone() { return new _RawImage(this.data.slice(), this.width, this.height, this.channels); } /** * Helper method for converting image to have a certain number of channels * @param {number} numChannels The number of channels. Must be 1, 3, or 4. * @returns {RawImage} `this` to support chaining. */ convert(numChannels) { if (this.channels === numChannels) return this; switch (numChannels) { case 1: this.grayscale(); break; case 3: this.rgb(); break; case 4: this.rgba(); break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this; } /** * Save the image to the given path. * @param {string} path The path to save the image to. */ async save(path3) { if (BROWSER_ENV) { if (WEBWORKER_ENV) { throw new Error("Unable to save an image from a Web Worker."); } const extension = path3.split(".").pop().toLowerCase(); const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png"; const blob = await this.toBlob(mime); const dataURL = URL.createObjectURL(blob); const downloadLink = document.createElement("a"); downloadLink.href = dataURL; downloadLink.download = path3; downloadLink.click(); downloadLink.remove(); } else if (!env.useFS) { throw new Error("Unable to save the image because filesystem is disabled in this environment."); } else { const img = this.toSharp(); return await img.toFile(path3); } } toSharp() { if (BROWSER_ENV) { throw new Error("toSharp() is only supported in server-side environments."); } return (0, import_sharp.default)(this.data, { raw: { width: this.width, height: this.height, channels: this.channels } }); } }; } }); // node_modules/@xenova/transformers/src/utils/audio.js async function read_audio(url2, sampling_rate) { if (typeof AudioContext === "undefined") { throw Error( "Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing." ); } const response = await (await getFile(url2)).arrayBuffer(); const audioCTX = new AudioContext({ sampleRate: sampling_rate }); if (typeof sampling_rate === "undefined") { console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`); } const decoded = await audioCTX.decodeAudioData(response); let audio; if (decoded.numberOfChannels === 2) { const SCALING_FACTOR = Math.sqrt(2); const left = decoded.getChannelData(0); const right = decoded.getChannelData(1); audio = new Float32Array(left.length); for (let i = 0; i < decoded.length; ++i) { audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; } } else { audio = decoded.getChannelData(0); } return audio; } function hanning(M3) { if (M3 < 1) { return new Float64Array(); } if (M3 === 1) { return new Float64Array([1]); } const denom = M3 - 1; const factor = Math.PI / denom; const cos_vals = new Float64Array(M3); for (let i = 0; i < M3; ++i) { const n = 2 * i - denom; cos_vals[i] = 0.5 + 0.5 * Math.cos(factor * n); } return cos_vals; } function hertz_to_mel(freq, mel_scale = "htk") { const fn3 = HERTZ_TO_MEL_MAPPING[mel_scale]; if (!fn3) { throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); } return typeof freq === "number" ? fn3(freq) : freq.map((x2) => fn3(x2)); } function mel_to_hertz(mels, mel_scale = "htk") { const fn3 = MEL_TO_HERTZ_MAPPING[mel_scale]; if (!fn3) { throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); } return typeof mels === "number" ? fn3(mels) : mels.map((x2) => fn3(x2)); } function _create_triangular_filter_bank(fft_freqs, filter_freqs) { const filter_diff = Float64Array.from( { length: filter_freqs.length - 1 }, (_, i) => filter_freqs[i + 1] - filter_freqs[i] ); const slopes = Array.from({ length: fft_freqs.length }, () => new Array(filter_freqs.length)); for (let j3 = 0; j3 < fft_freqs.length; ++j3) { const slope = slopes[j3]; for (let i = 0; i < filter_freqs.length; ++i) { slope[i] = filter_freqs[i] - fft_freqs[j3]; } } const numFreqs = filter_freqs.length - 2; const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); for (let j3 = 0; j3 < fft_freqs.length; ++j3) { const slope = slopes[j3]; for (let i = 0; i < numFreqs; ++i) { const down = -slope[i] / filter_diff[i]; const up4 = slope[i + 2] / filter_diff[i + 1]; ret[i][j3] = Math.max(0, Math.min(down, up4)); } } return ret; } function linspace(start, end, num) { const step = (end - start) / (num - 1); return Float64Array.from({ length: num }, (_, i) => start + step * i); } function mel_filter_bank(num_frequency_bins, num_mel_filters, min_frequency, max_frequency, sampling_rate, norm = null, mel_scale = "htk", triangularize_in_mel_space = false) { if (norm !== null && norm !== "slaney") { throw new Error('norm must be one of null or "slaney"'); } const mel_min = hertz_to_mel(min_frequency, mel_scale); const mel_max = hertz_to_mel(max_frequency, mel_scale); const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); let fft_freqs; if (triangularize_in_mel_space) { const fft_bin_width = sampling_rate / (num_frequency_bins * 2); fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale); filter_freqs = mel_freqs; } else { fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); } const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); if (norm !== null && norm === "slaney") { for (let i = 0; i < num_mel_filters; ++i) { const filter = mel_filters[i]; const enorm = 2 / (filter_freqs[i + 2] - filter_freqs[i]); for (let j3 = 0; j3 < num_frequency_bins; ++j3) { filter[j3] *= enorm; } } } return mel_filters; } function padReflect(array, left, right) { const padded = new array.constructor(array.length + left + right); const w = array.length - 1; for (let i = 0; i < array.length; ++i) { padded[left + i] = array[i]; } for (let i = 1; i <= left; ++i) { padded[left - i] = array[calculateReflectOffset(i, w)]; } for (let i = 1; i <= right; ++i) { padded[w + left + i] = array[calculateReflectOffset(w - i, w)]; } return padded; } function _db_conversion_helper(spectrogram2, factor, reference, min_value, db_range) { if (reference <= 0) { throw new Error("reference must be greater than zero"); } if (min_value <= 0) { throw new Error("min_value must be greater than zero"); } reference = Math.max(min_value, reference); const logReference = Math.log10(reference); for (let i = 0; i < spectrogram2.length; ++i) { spectrogram2[i] = factor * Math.log10(Math.max(min_value, spectrogram2[i]) - logReference); } if (db_range !== null) { if (db_range <= 0) { throw new Error("db_range must be greater than zero"); } const maxValue = max(spectrogram2)[0] - db_range; for (let i = 0; i < spectrogram2.length; ++i) { spectrogram2[i] = Math.max(spectrogram2[i], maxValue); } } return spectrogram2; } function amplitude_to_db(spectrogram2, reference = 1, min_value = 1e-5, db_range = null) { return _db_conversion_helper(spectrogram2, 20, reference, min_value, db_range); } function power_to_db(spectrogram2, reference = 1, min_value = 1e-10, db_range = null) { return _db_conversion_helper(spectrogram2, 10, reference, min_value, db_range); } function spectrogram(waveform, window2, frame_length, hop_length, { fft_length = null, power = 1, center = true, pad_mode = "reflect", onesided = true, preemphasis = null, mel_filters = null, mel_floor = 1e-10, log_mel = null, reference = 1, min_value = 1e-10, db_range = null, remove_dc_offset = null, // Custom parameters for efficiency reasons max_num_frames = null, do_pad = true, transpose = false } = {}) { const window_length = window2.length; if (fft_length === null) { fft_length = frame_length; } if (frame_length > fft_length) { throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`); } if (window_length !== frame_length) { throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); } if (hop_length <= 0) { throw new Error("hop_length must be greater than zero"); } if (power === null && mel_filters !== null) { throw new Error( "You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue." ); } if (center) { if (pad_mode !== "reflect") { throw new Error(`pad_mode="${pad_mode}" not implemented yet.`); } const half_window = Math.floor((fft_length - 1) / 2) + 1; waveform = padReflect(waveform, half_window, half_window); } const num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)); const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length; let d1 = num_frames; let d1Max = num_frames; if (max_num_frames !== null) { if (max_num_frames > num_frames) { if (do_pad) { d1Max = max_num_frames; } } else { d1Max = d1 = max_num_frames; } } const fft = new FFT(fft_length); const inputBuffer = new Float64Array(fft_length); const outputBuffer = new Float64Array(fft.outputBufferSize); const magnitudes = new Array(d1); for (let i = 0; i < d1; ++i) { const offset = i * hop_length; for (let j3 = 0; j3 < frame_length; ++j3) { inputBuffer[j3] = waveform[offset + j3]; } if (remove_dc_offset) { let sum = 0; for (let j3 = 0; j3 < frame_length; ++j3) { sum += inputBuffer[j3]; } const mean2 = sum / frame_length; for (let j3 = 0; j3 < frame_length; ++j3) { inputBuffer[j3] -= mean2; } } if (preemphasis !== null) { for (let j3 = frame_length - 1; j3 >= 1; --j3) { inputBuffer[j3] -= preemphasis * inputBuffer[j3 - 1]; } inputBuffer[0] *= 1 - preemphasis; } for (let j3 = 0; j3 < window2.length; ++j3) { inputBuffer[j3] *= window2[j3]; } fft.realTransform(outputBuffer, inputBuffer); const row = new Array(num_frequency_bins); for (let j3 = 0; j3 < row.length; ++j3) { const j22 = j3 << 1; row[j3] = outputBuffer[j22] ** 2 + outputBuffer[j22 + 1] ** 2; } magnitudes[i] = row; } if (power !== null && power !== 2) { const pow = 2 / power; for (let i = 0; i < magnitudes.length; ++i) { const magnitude = magnitudes[i]; for (let j3 = 0; j3 < magnitude.length; ++j3) { magnitude[j3] **= pow; } } } const num_mel_filters = mel_filters.length; const mel_spec = new Float32Array(num_mel_filters * d1Max); const dims = transpose ? [d1Max, num_mel_filters] : [num_mel_filters, d1Max]; for (let i = 0; i < num_mel_filters; ++i) { const filter = mel_filters[i]; for (let j3 = 0; j3 < d1; ++j3) { const magnitude = magnitudes[j3]; let sum = 0; for (let k4 = 0; k4 < num_frequency_bins; ++k4) { sum += filter[k4] * magnitude[k4]; } mel_spec[transpose ? j3 * num_mel_filters + i : i * d1 + j3] = Math.max(mel_floor, sum); } } if (power !== null && log_mel !== null) { const o = Math.min(mel_spec.length, d1 * num_mel_filters); switch (log_mel) { case "log": for (let i = 0; i < o; ++i) { mel_spec[i] = Math.log(mel_spec[i]); } break; case "log10": for (let i = 0; i < o; ++i) { mel_spec[i] = Math.log10(mel_spec[i]); } break; case "dB": if (power === 1) { amplitude_to_db(mel_spec, reference, min_value, db_range); } else if (power === 2) { power_to_db(mel_spec, reference, min_value, db_range); } else { throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`); } break; default: throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`); } } return { data: mel_spec, dims }; } function window_function(window_length, name2, { periodic = true, frame_length = null, center = true } = {}) { const length = periodic ? window_length + 1 : window_length; let window2; switch (name2) { case "boxcar": window2 = new Float64Array(length).fill(1); break; case "hann": case "hann_window": window2 = hanning(length); break; case "povey": window2 = hanning(length).map((x2) => Math.pow(x2, 0.85)); break; default: throw new Error(`Unknown window type ${name2}.`); } if (periodic) { window2 = window2.subarray(0, window_length); } if (frame_length === null) { return window2; } if (window_length > frame_length) { throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`); } return window2; } var HERTZ_TO_MEL_MAPPING, MEL_TO_HERTZ_MAPPING; var init_audio = __esm({ "node_modules/@xenova/transformers/src/utils/audio.js"() { init_hub(); init_maths(); init_core(); HERTZ_TO_MEL_MAPPING = { "htk": (freq) => 2595 * Math.log10(1 + freq / 700), "kaldi": (freq) => 1127 * Math.log(1 + freq / 700), "slaney": (freq, min_log_hertz = 1e3, min_log_mel = 15, logstep = 27 / Math.log(6.4)) => freq >= min_log_hertz ? min_log_mel + Math.log(freq / min_log_hertz) * logstep : 3 * freq / 200 }; MEL_TO_HERTZ_MAPPING = { "htk": (mels) => 700 * (10 ** (mels / 2595) - 1), "kaldi": (mels) => 700 * (Math.exp(mels / 1127) - 1), "slaney": (mels, min_log_hertz = 1e3, min_log_mel = 15, logstep = Math.log(6.4) / 27) => mels >= min_log_mel ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) : 200 * mels / 3 }; } }); // node_modules/@xenova/transformers/src/processors.js function center_to_corners_format([centerX, centerY, width, height]) { return [ centerX - width / 2, centerY - height / 2, centerX + width / 2, centerY + height / 2 ]; } function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { const out_logits = outputs.logits; const out_bbox = outputs.pred_boxes; const [batch_size, num_boxes, num_classes] = out_logits.dims; if (target_sizes !== null && target_sizes.length !== batch_size) { throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); } let toReturn = []; for (let i = 0; i < batch_size; ++i) { let target_size = target_sizes !== null ? target_sizes[i] : null; let info = { boxes: [], classes: [], scores: [] }; let logits = out_logits[i]; let bbox = out_bbox[i]; for (let j3 = 0; j3 < num_boxes; ++j3) { let logit = logits[j3]; let indices = []; let probs; if (is_zero_shot) { probs = logit.sigmoid().data; for (let k4 = 0; k4 < probs.length; ++k4) { if (probs[k4] > threshold) { indices.push(k4); } } } else { let maxIndex = max(logit.data)[1]; if (maxIndex === num_classes - 1) { continue; } indices.push(maxIndex); probs = softmax(logit.data); } for (const index of indices) { let box = bbox[j3].data; box = center_to_corners_format(box); if (target_size !== null) { box = box.map((x2, i2) => x2 * target_size[(i2 + 1) % 2]); } info.boxes.push(box); info.classes.push(index); info.scores.push(probs[index]); } } toReturn.push(info); } return toReturn; } function validate_audio_inputs(audio, feature_extractor) { if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { throw new Error( `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.` ); } } function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) { const a = val / multiple; let x2 = bankers_round(a) * multiple; if (maxVal !== null && x2 > maxVal) { x2 = Math.floor(a) * multiple; } if (x2 < minVal) { x2 = Math.ceil(a) * multiple; } return x2; } function enforce_size_divisibility([width, height], divisor) { return [ Math.max(Math.floor(width / divisor), 1) * divisor, Math.max(Math.floor(height / divisor), 1) * divisor ]; } var FeatureExtractor, ImageFeatureExtractor, SegformerFeatureExtractor, DPTFeatureExtractor, DPTImageProcessor, BitImageProcessor, GLPNFeatureExtractor, CLIPFeatureExtractor, ChineseCLIPFeatureExtractor, SiglipImageProcessor, ConvNextFeatureExtractor, ConvNextImageProcessor, ViTFeatureExtractor, ViTImageProcessor, EfficientNetImageProcessor, MobileViTFeatureExtractor, MobileViTImageProcessor, OwlViTFeatureExtractor, Owlv2ImageProcessor, DeiTFeatureExtractor, BeitFeatureExtractor, DonutFeatureExtractor, NougatImageProcessor, DetrFeatureExtractor, YolosFeatureExtractor, SamImageProcessor, Swin2SRImageProcessor, VitMatteImageProcessor, WhisperFeatureExtractor, Wav2Vec2FeatureExtractor, SeamlessM4TFeatureExtractor, ASTFeatureExtractor, ClapFeatureExtractor, SpeechT5FeatureExtractor, Processor, SamProcessor, WhisperProcessor, Wav2Vec2ProcessorWithLM, SpeechT5Processor, OwlViTProcessor, AutoProcessor; var init_processors = __esm({ "node_modules/@xenova/transformers/src/processors.js"() { init_core(); init_hub(); init_maths(); init_tensor(); init_image(); init_audio(); FeatureExtractor = class extends Callable { /** * Constructs a new FeatureExtractor instance. * * @param {Object} config The configuration for the feature extractor. */ constructor(config) { super(); this.config = config; } }; ImageFeatureExtractor = class extends FeatureExtractor { /** * Constructs a new ImageFeatureExtractor instance. * * @param {Object} config The configuration for the feature extractor. * @param {number[]} config.image_mean The mean values for image normalization. * @param {number[]} config.image_std The standard deviation values for image normalization. * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range. * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values. * @param {boolean} config.do_normalize Whether to normalize the image pixel values. * @param {boolean} config.do_resize Whether to resize the image. * @param {number} config.resample What method to use for resampling. * @param {number|Object} config.size The size to resize the image to. * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR. * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method. */ constructor(config) { super(config); this.image_mean = this.config.image_mean ?? this.config.mean; this.image_std = this.config.image_std ?? this.config.std; this.resample = this.config.resample ?? 2; this.do_rescale = this.config.do_rescale ?? true; this.rescale_factor = this.config.rescale_factor ?? 1 / 255; this.do_normalize = this.config.do_normalize; this.do_resize = this.config.do_resize; this.do_thumbnail = this.config.do_thumbnail; this.size = this.config.size; this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor; this.do_center_crop = this.config.do_center_crop; this.crop_size = this.config.crop_size; this.do_convert_rgb = this.config.do_convert_rgb ?? true; this.do_crop_margin = this.config.do_crop_margin; this.pad_size = this.config.pad_size; this.do_pad = this.config.do_pad; if (this.do_pad && !this.pad_size && this.size && this.size.width !== void 0 && this.size.height !== void 0) { this.pad_size = this.size; } this.do_flip_channel_order = this.config.do_flip_channel_order ?? false; } /** * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any * corresponding dimension of the specified size. * @param {RawImage} image The image to be resized. * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. * @returns {Promise} The resized image. */ async thumbnail(image, size, resample = 2) { const input_height = image.height; const input_width = image.width; const output_height = size.height; const output_width = size.width; let height = Math.min(input_height, output_height); let width = Math.min(input_width, output_width); if (height === input_height && width === input_width) { return image; } if (input_height > input_width) { width = Math.floor(input_width * height / input_height); } else if (input_width > input_height) { height = Math.floor(input_height * width / input_width); } return await image.resize(width, height, { resample }); } /** * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). * @param {RawImage} image The image to be cropped. * @param {number} gray_threshold Value below which pixels are considered to be gray. * @returns {Promise} The cropped image. */ async crop_margin(image, gray_threshold = 200) { const gray_image = image.clone().grayscale(); const minValue = min(gray_image.data)[0]; const maxValue = max(gray_image.data)[0]; const diff = maxValue - minValue; if (diff === 0) { return image; } const threshold = gray_threshold / 255; let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; for (let j3 = 0; j3 < gray_image.height; ++j3) { const row = j3 * gray_image.width; for (let i = 0; i < gray_image.width; ++i) { if ((gray_image.data[row + i] - minValue) / diff < threshold) { x_min = Math.min(x_min, i); y_min = Math.min(y_min, j3); x_max = Math.max(x_max, i); y_max = Math.max(y_max, j3); } } } image = await image.crop([x_min, y_min, x_max, y_max]); return image; } /** * Pad the image by a certain amount. * @param {Float32Array} pixelData The pixel data to pad. * @param {number[]} imgDims The dimensions of the image (height, width, channels). * @param {{width:number; height:number}|number} padSize The dimensions of the padded image. * @param {Object} options The options for padding. * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. * @param {boolean} [options.center=false] Whether to center the image. * @param {number} [options.constant_values=0] The constant value to use for padding. * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. */ pad_image(pixelData, imgDims, padSize, { mode = "constant", center = false, constant_values = 0 } = {}) { const [imageHeight, imageWidth, imageChannels] = imgDims; let paddedImageWidth, paddedImageHeight; if (typeof padSize === "number") { paddedImageWidth = padSize; paddedImageHeight = padSize; } else { paddedImageWidth = padSize.width; paddedImageHeight = padSize.height; } if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); if (Array.isArray(constant_values)) { for (let i = 0; i < paddedPixelData.length; ++i) { paddedPixelData[i] = constant_values[i % imageChannels]; } } else if (constant_values !== 0) { paddedPixelData.fill(constant_values); } const [left, top] = center ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] : [0, 0]; for (let i = 0; i < imageHeight; ++i) { const a = (i + top) * paddedImageWidth; const b = i * imageWidth; for (let j3 = 0; j3 < imageWidth; ++j3) { const c = (a + j3 + left) * imageChannels; const d = (b + j3) * imageChannels; for (let k4 = 0; k4 < imageChannels; ++k4) { paddedPixelData[c + k4] = pixelData[d + k4]; } } } if (mode === "symmetric") { if (center) { throw new Error("`center` padding is not supported when `mode` is set to `symmetric`."); } const h1 = imageHeight - 1; const w1 = imageWidth - 1; for (let i = 0; i < paddedImageHeight; ++i) { const a = i * paddedImageWidth; const b = calculateReflectOffset(i, h1) * imageWidth; for (let j3 = 0; j3 < paddedImageWidth; ++j3) { if (i < imageHeight && j3 < imageWidth) continue; const c = (a + j3) * imageChannels; const d = (b + calculateReflectOffset(j3, w1)) * imageChannels; for (let k4 = 0; k4 < imageChannels; ++k4) { paddedPixelData[c + k4] = pixelData[d + k4]; } } } } pixelData = paddedPixelData; imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]; } return [pixelData, imgDims]; } /** * Rescale the image' pixel values by `this.rescale_factor`. * @param {Float32Array} pixelData The pixel data to rescale. * @returns {void} */ rescale(pixelData) { for (let i = 0; i < pixelData.length; ++i) { pixelData[i] = this.rescale_factor * pixelData[i]; } } /** * Find the target (width, height) dimension of the output image after * resizing given the input image and the desired size. * @param {RawImage} image The image to resize. * @param {any} size The size to use for resizing the image. * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. */ get_resize_output_image_size(image, size) { const [srcWidth, srcHeight] = image.size; let shortest_edge; let longest_edge; if (this.do_thumbnail) { const { height, width } = size; shortest_edge = Math.min(height, width); } else if (Number.isInteger(size)) { shortest_edge = size; longest_edge = this.config.max_size ?? shortest_edge; } else if (size !== void 0) { shortest_edge = size.shortest_edge; longest_edge = size.longest_edge; } if (shortest_edge !== void 0 || longest_edge !== void 0) { const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); const newWidth = srcWidth * shortResizeFactor; const newHeight = srcHeight * shortResizeFactor; const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight); let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); if (this.size_divisibility !== void 0) { [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility); } return [finalWidth, finalHeight]; } else if (size !== void 0 && size.width !== void 0 && size.height !== void 0) { let newWidth = size.width; let newHeight = size.height; if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { let scale_height = newHeight / srcHeight; let scale_width = newWidth / srcWidth; if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) { scale_height = scale_width; } else { scale_width = scale_height; } newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of); newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of); } return [newWidth, newHeight]; } else if (this.size_divisibility !== void 0) { return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility); } else { throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`); } } /** * Resizes the image. * @param {RawImage} image The image to resize. * @returns {Promise} The resized image. */ async resize(image) { const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size); return await image.resize(newWidth, newHeight, { resample: this.resample }); } /** * @typedef {object} PreprocessedImage * @property {HeightWidth} original_size The original size of the image. * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. * @property {Tensor} pixel_values The pixel values of the preprocessed image. */ /** * Preprocesses the given image. * * @param {RawImage} image The image to preprocess. * @param {Object} overrides The overrides for the preprocessing options. * @returns {Promise} The preprocessed image. */ async preprocess(image, { do_normalize = null, do_pad = null, do_convert_rgb = null, do_convert_grayscale = null, do_flip_channel_order = null } = {}) { if (this.do_crop_margin) { image = await this.crop_margin(image); } const [srcWidth, srcHeight] = image.size; if (do_convert_rgb ?? this.do_convert_rgb) { image = image.rgb(); } else if (do_convert_grayscale) { image = image.grayscale(); } if (this.do_resize) { image = await this.resize(image); } if (this.do_thumbnail) { image = await this.thumbnail(image, this.size, this.resample); } if (this.do_center_crop) { let crop_width; let crop_height; if (Number.isInteger(this.crop_size)) { crop_width = this.crop_size; crop_height = this.crop_size; } else { crop_width = this.crop_size.width; crop_height = this.crop_size.height; } image = await image.center_crop(crop_width, crop_height); } const reshaped_input_size = [image.height, image.width]; let pixelData = Float32Array.from(image.data); let imgDims = [image.height, image.width, image.channels]; if (this.do_rescale) { this.rescale(pixelData); } if (do_normalize ?? this.do_normalize) { let image_mean = this.image_mean; if (!Array.isArray(this.image_mean)) { image_mean = new Array(image.channels).fill(image_mean); } let image_std = this.image_std; if (!Array.isArray(this.image_std)) { image_std = new Array(image.channels).fill(image_mean); } if (image_mean.length !== image.channels || image_std.length !== image.channels) { throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`); } for (let i = 0; i < pixelData.length; i += image.channels) { for (let j3 = 0; j3 < image.channels; ++j3) { pixelData[i + j3] = (pixelData[i + j3] - image_mean[j3]) / image_std[j3]; } } } if (do_pad ?? this.do_pad) { if (this.pad_size) { const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size); [pixelData, imgDims] = padded; } else if (this.size_divisibility) { const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility); [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight }); } } if (do_flip_channel_order ?? this.do_flip_channel_order) { if (imgDims[2] !== 3) { throw new Error("Flipping channel order is only supported for RGB images."); } for (let i = 0; i < pixelData.length; i += 3) { const temp = pixelData[i]; pixelData[i] = pixelData[i + 2]; pixelData[i + 2] = temp; } } const pixel_values = new Tensor("float32", pixelData, imgDims).permute(2, 0, 1); return { original_size: [srcHeight, srcWidth], reshaped_input_size, pixel_values }; } /** * Calls the feature extraction process on an array of images, * preprocesses each image, and concatenates the resulting * features into a single Tensor. * @param {RawImage[]} images The image(s) to extract features from. * @param {...any} args Additional arguments. * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. */ async _call(images, ...args) { if (!Array.isArray(images)) { images = [images]; } const imageData = await Promise.all(images.map((x2) => this.preprocess(x2))); const pixel_values = stack(imageData.map((x2) => x2.pixel_values), 0); return { pixel_values, // Original sizes of images original_sizes: imageData.map((x2) => x2.original_size), // Reshaped sizes of images, before padding or cropping reshaped_input_sizes: imageData.map((x2) => x2.reshaped_input_size) }; } }; SegformerFeatureExtractor = class extends ImageFeatureExtractor { /** * Converts the output of `SegformerForSemanticSegmentation` into semantic segmentation maps. * @param {*} outputs Raw outputs of the model. * @param {number[][]} [target_sizes=null] List of tuples corresponding to the requested final size * (height, width) of each prediction. If unset, predictions will not be resized. * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps. */ post_process_semantic_segmentation(outputs, target_sizes = null) { const logits = outputs.logits; const batch_size = logits.dims[0]; if (target_sizes !== null && target_sizes.length !== batch_size) { throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); } const toReturn = []; for (let i = 0; i < batch_size; ++i) { const target_size = target_sizes !== null ? target_sizes[i] : null; let data = logits[i]; if (target_size !== null) { data = interpolate(data, target_size, "bilinear", false); } const [height, width] = target_size ?? data.dims.slice(-2); const segmentation = new Tensor( "int32", new Int32Array(height * width), [height, width] ); const buffer = data[0].data; for (let j3 = 1; j3 < data.dims[0]; ++j3) { const row = data[j3].data; for (let k4 = 0; k4 < row.length; ++k4) { if (row[k4] > buffer[k4]) { buffer[k4] = row[k4]; segmentation.data[k4] = j3; } } } const hasLabel = new Array(data.dims[0]); const out = segmentation.data; for (let j3 = 0; j3 < out.length; ++j3) { const index = out[j3]; hasLabel[index] = index; } const labels = hasLabel.filter((x2) => x2 !== void 0); toReturn.push({ segmentation, labels }); } return toReturn; } }; DPTFeatureExtractor = class extends ImageFeatureExtractor { }; DPTImageProcessor = class extends DPTFeatureExtractor { }; BitImageProcessor = class extends ImageFeatureExtractor { }; GLPNFeatureExtractor = class extends ImageFeatureExtractor { }; CLIPFeatureExtractor = class extends ImageFeatureExtractor { }; ChineseCLIPFeatureExtractor = class extends ImageFeatureExtractor { }; SiglipImageProcessor = class extends ImageFeatureExtractor { }; ConvNextFeatureExtractor = class extends ImageFeatureExtractor { constructor(config) { super(config); this.crop_pct = this.config.crop_pct ?? 224 / 256; } async resize(image) { const shortest_edge = this.size?.shortest_edge; if (shortest_edge === void 0) { throw new Error(`Size dictionary must contain 'shortest_edge' key.`); } if (shortest_edge < 384) { const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct); const [newWidth, newHeight] = this.get_resize_output_image_size(image, { shortest_edge: resize_shortest_edge }); image = await image.resize(newWidth, newHeight, { resample: this.resample }); image = await image.center_crop(shortest_edge, shortest_edge); } else { image = await image.resize(shortest_edge, shortest_edge, { resample: this.resample }); } return image; } }; ConvNextImageProcessor = class extends ConvNextFeatureExtractor { }; ViTFeatureExtractor = class extends ImageFeatureExtractor { }; ViTImageProcessor = class extends ImageFeatureExtractor { }; EfficientNetImageProcessor = class extends ImageFeatureExtractor { constructor(config) { super(config); this.include_top = this.config.include_top ?? true; if (this.include_top) { this.image_std = this.image_std.map((x2) => x2 * x2); } } }; MobileViTFeatureExtractor = class extends ImageFeatureExtractor { }; MobileViTImageProcessor = class extends MobileViTFeatureExtractor { }; OwlViTFeatureExtractor = class extends ImageFeatureExtractor { /** @type {post_process_object_detection} */ post_process_object_detection(...args) { return post_process_object_detection(...args); } }; Owlv2ImageProcessor = class extends OwlViTFeatureExtractor { }; DeiTFeatureExtractor = class extends ImageFeatureExtractor { }; BeitFeatureExtractor = class extends ImageFeatureExtractor { }; DonutFeatureExtractor = class extends ImageFeatureExtractor { pad_image(pixelData, imgDims, padSize, options = {}) { const [imageHeight, imageWidth, imageChannels] = imgDims; let image_mean = this.image_mean; if (!Array.isArray(this.image_mean)) { image_mean = new Array(imageChannels).fill(image_mean); } let image_std = this.image_std; if (!Array.isArray(image_std)) { image_std = new Array(imageChannels).fill(image_mean); } const constant_values = image_mean.map((x2, i) => -x2 / image_std[i]); return super.pad_image(pixelData, imgDims, padSize, { center: true, // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 constant_values, ...options }); } }; NougatImageProcessor = class extends DonutFeatureExtractor { }; DetrFeatureExtractor = class extends ImageFeatureExtractor { /** * Calls the feature extraction process on an array of images, preprocesses * each image, and concatenates the resulting features into a single Tensor. * @param {RawImage[]} images The image(s) to extract features from. * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. */ async _call(images) { const result = await super._call(images); const maskSize = [result.pixel_values.dims[0], 64, 64]; const pixel_mask = new Tensor( "int64", new BigInt64Array(maskSize.reduce((a, b) => a * b)).fill(1n), maskSize ); return { ...result, pixel_mask }; } /** * Post-processes the outputs of the model (for object detection). * @param {Object} outputs The outputs of the model that must be post-processed * @param {Tensor} outputs.logits The logits * @param {Tensor} outputs.pred_boxes The predicted boxes. * @return {Object[]} An array of objects containing the post-processed outputs. */ /** @type {post_process_object_detection} */ post_process_object_detection(...args) { return post_process_object_detection(...args); } /** * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. * @param {Tensor} class_logits The class logits. * @param {Tensor} mask_logits The mask logits. * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks. * @param {number} num_labels The number of labels. * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels. */ remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { let mask_probs_item = []; let pred_scores_item = []; let pred_labels_item = []; for (let j3 = 0; j3 < class_logits.dims[0]; ++j3) { let cls = class_logits[j3]; let mask = mask_logits[j3]; let pred_label = max(cls.data)[1]; if (pred_label === num_labels) { continue; } let scores = softmax(cls.data); let pred_score = scores[pred_label]; if (pred_score > object_mask_threshold) { mask_probs_item.push(mask); pred_scores_item.push(pred_score); pred_labels_item.push(pred_label); } } return [mask_probs_item, pred_scores_item, pred_labels_item]; } /** * Checks whether the segment is valid or not. * @param {Int32Array} mask_labels Labels for each pixel in the mask. * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks. * @param {number} k The class id of the segment. * @param {number} mask_threshold The mask threshold. * @param {number} overlap_mask_area_threshold The overlap mask area threshold. * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels. */ check_segment_validity(mask_labels, mask_probs, k4, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8) { let mask_k = []; let mask_k_area = 0; let original_area = 0; for (let i = 0; i < mask_labels.length; ++i) { if (mask_labels[i] === k4) { mask_k.push(i); ++mask_k_area; } if (mask_probs[k4].data[i] >= mask_threshold) { ++original_area; } } let mask_exists = mask_k_area > 0 && original_area > 0; if (mask_exists) { let area_ratio = mask_k_area / original_area; mask_exists = area_ratio > overlap_mask_area_threshold; } return [mask_exists, mask_k]; } /** * Computes the segments. * @param {Tensor[]} mask_probs The mask probabilities. * @param {number[]} pred_scores The predicted scores. * @param {number[]} pred_labels The predicted labels. * @param {number} mask_threshold The mask threshold. * @param {number} overlap_mask_area_threshold The overlap mask area threshold. * @param {Set} label_ids_to_fuse The label ids to fuse. * @param {number[]} target_size The target size of the image. * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments. */ compute_segments(mask_probs, pred_scores, pred_labels, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse = null, target_size = null) { let [height, width] = target_size ?? mask_probs[0].dims; let segmentation = new Tensor( "int32", new Int32Array(height * width), [height, width] ); let segments = []; if (target_size !== null) { for (let i = 0; i < mask_probs.length; ++i) { mask_probs[i] = interpolate(mask_probs[i], target_size, "bilinear", false); } } let mask_labels = new Int32Array(mask_probs[0].data.length); let bestScores = new Float32Array(mask_probs[0].data.length); for (let i = 0; i < mask_probs.length; ++i) { let score = pred_scores[i]; for (let j3 = 0; j3 < mask_probs[i].data.length; ++j3) { mask_probs[i].data[j3] *= score; if (mask_probs[i].data[j3] > bestScores[j3]) { mask_labels[j3] = i; bestScores[j3] = mask_probs[i].data[j3]; } } } let current_segment_id = 0; for (let k4 = 0; k4 < pred_labels.length; ++k4) { let pred_class = pred_labels[k4]; let [mask_exists, mask_k] = this.check_segment_validity( mask_labels, mask_probs, k4, mask_threshold, overlap_mask_area_threshold ); if (!mask_exists) { continue; } ++current_segment_id; for (let index of mask_k) { segmentation.data[index] = current_segment_id; } segments.push({ id: current_segment_id, label_id: pred_class, // was_fused: should_fuse, TODO score: pred_scores[k4] }); } return [segmentation, segments]; } /** * Post-process the model output to generate the final panoptic segmentation. * @param {*} outputs The model output to post process * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask. * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together. * @param {number[][]} [target_sizes=null] The target sizes to resize the masks to. * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} */ post_process_panoptic_segmentation(outputs, threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null) { if (label_ids_to_fuse === null) { console.warn("`label_ids_to_fuse` unset. No instance will be fused."); label_ids_to_fuse = /* @__PURE__ */ new Set(); } const class_queries_logits = outputs.logits; const masks_queries_logits = outputs.pred_masks; const mask_probs = masks_queries_logits.sigmoid(); let [batch_size, num_queries, num_labels] = class_queries_logits.dims; num_labels -= 1; if (target_sizes !== null && target_sizes.length !== batch_size) { throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); } let toReturn = []; for (let i = 0; i < batch_size; ++i) { let target_size = target_sizes !== null ? target_sizes[i] : null; let class_logits = class_queries_logits[i]; let mask_logits = mask_probs[i]; let [mask_probs_item, pred_scores_item, pred_labels_item] = this.remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels); if (pred_labels_item.length === 0) { let [height, width] = target_size ?? mask_logits.dims.slice(-2); let segmentation2 = new Tensor( "int32", new Int32Array(height * width).fill(-1), [height, width] ); toReturn.push({ segmentation: segmentation2, segments_info: [] }); continue; } let [segmentation, segments] = this.compute_segments( mask_probs_item, pred_scores_item, pred_labels_item, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse, target_size ); toReturn.push({ segmentation, segments_info: segments }); } return toReturn; } post_process_instance_segmentation() { throw Error("Not implemented yet"); } }; YolosFeatureExtractor = class extends ImageFeatureExtractor { /** @type {post_process_object_detection} */ post_process_object_detection(...args) { return post_process_object_detection(...args); } }; SamImageProcessor = class extends ImageFeatureExtractor { /** * * @param {any} input_points * @param {HeightWidth[]} original_sizes * @param {HeightWidth[]} reshaped_input_sizes * @returns {Tensor} */ reshape_input_points(input_points, original_sizes, reshaped_input_sizes) { input_points = structuredClone(input_points); let shape = calculateDimensions(input_points); if (shape.length === 3) { shape = [1, ...shape]; input_points = [input_points]; } else if (shape.length !== 4) { throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."); } for (let i = 0; i < input_points.length; ++i) { let originalImageSize = original_sizes[i]; let reshapedImageSize = reshaped_input_sizes[i]; let resizeFactors = [ reshapedImageSize[0] / originalImageSize[0], reshapedImageSize[1] / originalImageSize[1] ]; for (let j3 = 0; j3 < input_points[i].length; ++j3) { for (let k4 = 0; k4 < input_points[i][j3].length; ++k4) { for (let w = 0; w < input_points[i][j3][k4].length; ++w) { input_points[i][j3][k4][w] *= resizeFactors[w]; } } } } return new Tensor( "float32", Float32Array.from(input_points.flat(Infinity)), shape ); } /** * * @param {any} input_labels * @param {Tensor} input_points * @returns {Tensor} */ add_input_labels(input_labels, input_points) { let shape = calculateDimensions(input_labels); if (shape.length === 2) { shape = [1, ...shape]; input_labels = [input_labels]; } else if (shape.length !== 3) { throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."); } if (shape.some((x2, i) => x2 !== input_points.dims[i])) { throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`); } return new Tensor( "int64", input_labels.flat(Infinity).map(BigInt), shape ); } /** * @param {any[]} images The URL(s) of the image(s) to extract features from. * @param {any} [input_points] A 3D or 4D array, representing the input points provided by the user. * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. * @param {any} [input_labels] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. * @returns {Promise} */ async _call(images, input_points = null, input_labels = null) { const processed = await super._call(images); if (input_points) { processed.input_points = this.reshape_input_points( input_points, processed.original_sizes, processed.reshaped_input_sizes ); } if (input_labels) { if (!processed.input_points) { throw Error("`input_points` must be provided if `input_labels` are provided."); } processed.input_labels = this.add_input_labels(input_labels, processed.input_points); } return processed; } /** * Remove padding and upscale masks to the original image size. * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. * @param {number[][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. * @param {number[][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. * @param {Object} options Optional parameters for post-processing. * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. * @param {boolean} [options.binarize] Whether to binarize the masks. * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. * @param {number} [options.pad_size.height] The height the images were padded to. * @param {number} [options.pad_size.width] The width the images were padded to. * @returns {Tensor[]} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. */ post_process_masks(masks, original_sizes, reshaped_input_sizes, { mask_threshold = 0, binarize = true, pad_size = null } = {}) { const output_masks = []; pad_size = pad_size ?? this.pad_size; const target_image_size = [pad_size.height, pad_size.width]; for (let i = 0; i < original_sizes.length; ++i) { const original_size = original_sizes[i]; const reshaped_input_size = reshaped_input_sizes[i]; const mask = masks[i]; const interpolated_masks = []; for (let j3 = 0; j3 < mask.dims[0]; ++j3) { const m2 = mask[j3]; let interpolated_mask = interpolate(m2, target_image_size, "bilinear", false); interpolated_mask = interpolated_mask.slice(null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); interpolated_mask = interpolate(interpolated_mask, original_size, "bilinear", false); if (binarize) { const binarizedMaskData = new Uint8Array(interpolated_mask.data.length); for (let i2 = 0; i2 < interpolated_mask.data.length; ++i2) { if (interpolated_mask.data[i2] > mask_threshold) { binarizedMaskData[i2] = 1; } } interpolated_mask = new Tensor( "bool", binarizedMaskData, interpolated_mask.dims ); } interpolated_masks.push(interpolated_mask); } output_masks.push(stack(interpolated_masks)); } return output_masks; } }; Swin2SRImageProcessor = class extends ImageFeatureExtractor { pad_image(pixelData, imgDims, padSize, options = {}) { const [imageHeight, imageWidth, imageChannels] = imgDims; return super.pad_image(pixelData, imgDims, { // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. width: imageWidth + (padSize - imageWidth % padSize) % padSize, height: imageHeight + (padSize - imageHeight % padSize) % padSize }, { mode: "symmetric", center: false, constant_values: -1, ...options }); } }; VitMatteImageProcessor = class extends ImageFeatureExtractor { /** * Calls the feature extraction process on an array of images, preprocesses * each image, and concatenates the resulting features into a single Tensor. * @param {RawImage[]} images The image(s) to extract features from. * @param {RawImage[]} trimaps The trimaps(s) to extract features from. * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. */ async _call(images, trimaps) { if (!Array.isArray(images)) { images = [images]; } if (!Array.isArray(trimaps)) { trimaps = [trimaps]; } const imageData = await Promise.all(images.map((x2) => this.preprocess(x2))); const trimapData = await Promise.all(trimaps.map((x2) => this.preprocess(x2, { do_normalize: false, do_convert_rgb: false, do_convert_grayscale: true }))); const pixel_values = stack(imageData.map( // Concatenate images and trimaps (x2, i) => cat([x2.pixel_values, trimapData[i].pixel_values], 0) ), 0); return { pixel_values, // Original sizes of images original_sizes: imageData.map((x2) => x2.original_size), // Reshaped sizes of images, before padding or cropping reshaped_input_sizes: imageData.map((x2) => x2.reshaped_input_size) }; } }; WhisperFeatureExtractor = class extends FeatureExtractor { constructor(config) { super(config); this.config.mel_filters ??= mel_filter_bank( Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins this.config.feature_size, // num_mel_filters 0, // min_frequency 8e3, // max_frequency this.config.sampling_rate, // sampling_rate "slaney", // norm "slaney" // mel_scale ); this.window = window_function(this.config.n_fft, "hann"); } /** * Computes the log-Mel spectrogram of the provided audio waveform. * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ _extract_fbank_features(waveform) { const { data, dims } = spectrogram( waveform, this.window, // window this.config.n_fft, // frame_length this.config.hop_length, // hop_length { power: 2, mel_filters: this.config.mel_filters, log_mel: "log10", // Custom max_num_frames: this.config.nb_max_frames // 3000 } ); const maxValue = max(data)[0]; for (let i = 0; i < data.length; ++i) { data[i] = (Math.max(data[i], maxValue - 8) + 4) / 4; } return { data, dims }; } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. */ async _call(audio) { validate_audio_inputs(audio, "WhisperFeatureExtractor"); let waveform; if (audio.length > this.config.n_samples) { console.warn( "Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`." ); waveform = audio.slice(0, this.config.n_samples); } else { waveform = new Float32Array(this.config.n_samples); waveform.set(audio); } const { data, dims } = this._extract_fbank_features(waveform); return { input_features: new Tensor( "float32", data, [1, ...dims] ) }; } }; Wav2Vec2FeatureExtractor = class extends FeatureExtractor { /** * @param {Float32Array} input_values * @returns {Float32Array} */ _zero_mean_unit_var_norm(input_values) { const sum = input_values.reduce((a, b) => a + b, 0); const mean2 = sum / input_values.length; const variance = input_values.reduce((a, b) => a + (b - mean2) ** 2, 0) / input_values.length; return input_values.map((x2) => (x2 - mean2) / Math.sqrt(variance + 1e-7)); } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. */ async _call(audio) { validate_audio_inputs(audio, "Wav2Vec2FeatureExtractor"); if (audio instanceof Float64Array) { audio = new Float32Array(audio); } let input_values = audio; if (this.config.do_normalize) { input_values = this._zero_mean_unit_var_norm(input_values); } const shape = [1, input_values.length]; return { input_values: new Tensor("float32", input_values, shape), attention_mask: new Tensor("int64", new BigInt64Array(input_values.length).fill(1n), shape) }; } }; SeamlessM4TFeatureExtractor = class extends FeatureExtractor { constructor(config) { super(config); const sampling_rate = this.config.sampling_rate; const mel_filters = mel_filter_bank( 256, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(sampling_rate / 2), // max_frequency sampling_rate, // sampling_rate null, // norm "kaldi", // mel_scale true // triangularize_in_mel_space ); for (let i = 0; i < mel_filters.length; ++i) { mel_filters[i].push(0); } this.mel_filters = mel_filters; this.window = window_function(400, "povey", { periodic: false }); } /** * Computes the log-Mel spectrogram of the provided audio waveform. * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @param {number} max_length The maximum number of frames to return. * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ _extract_fbank_features(waveform, max_length) { waveform = waveform.map((x2) => x2 * 32768); return spectrogram( waveform, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2, center: false, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: "log", mel_floor: 1192092955078125e-22, remove_dc_offset: true, // Custom max_num_frames: max_length, transpose: true } ); } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @param {Object} options Optional parameters for feature extraction. * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of. * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel. * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask. * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. */ async _call(audio, { padding = true, pad_to_multiple_of = 2, do_normalize_per_mel_bins = true, return_attention_mask = true } = {}) { validate_audio_inputs(audio, "SeamlessM4TFeatureExtractor"); let features = this._extract_fbank_features(audio, this.config.max_length); if (do_normalize_per_mel_bins) { const [num_features, feature_size] = features.dims; for (let i = 0; i < feature_size; ++i) { let sum = 0; for (let j3 = 0; j3 < num_features; ++j3) { sum += features.data[j3 * feature_size + i]; } const mean2 = sum / num_features; let variance = 0; for (let j3 = 0; j3 < num_features; ++j3) { variance += (features.data[j3 * feature_size + i] - mean2) ** 2; } variance /= num_features - 1; const std = Math.sqrt(variance + 1e-7); for (let j3 = 0; j3 < num_features; ++j3) { const index = j3 * feature_size + i; features.data[index] = (features.data[index] - mean2) / std; } } } let padded_attention_mask; if (padding) { const [num_frames2, num_channels2] = features.dims; const pad_size = num_frames2 % pad_to_multiple_of; if (pad_size > 0) { const padded_data = new Float32Array(num_channels2 * (num_frames2 + pad_size)); padded_data.set(features.data); padded_data.fill(this.config.padding_value, features.data.length); const numPaddedFrames = num_frames2 + pad_size; features = { data: padded_data, dims: [numPaddedFrames, num_channels2] }; if (return_attention_mask) { padded_attention_mask = new Tensor( "int64", new BigInt64Array(numPaddedFrames), [1, numPaddedFrames] ); padded_attention_mask.data.fill(1n, 0, num_frames2); } } } const [num_frames, num_channels] = features.dims; const stride = this.config.stride; const remainder = num_frames % stride; if (remainder !== 0) { throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`); } const input_features = new Tensor( "float32", features.data, features.dims ).view( 1, Math.floor(num_frames / stride), num_channels * stride ); const result = { input_features }; if (return_attention_mask) { const reshapedNumFrames = input_features.dims[1]; const attention_mask = new Tensor( "int64", new BigInt64Array(reshapedNumFrames), [1, reshapedNumFrames] ); if (padded_attention_mask) { for (let i = 1, j3 = 0; i < num_frames; i += stride, ++j3) { attention_mask.data[j3] = padded_attention_mask.data[i]; } } else { attention_mask.data.fill(1n); } result.attention_mask = attention_mask; } return result; } }; ASTFeatureExtractor = class extends FeatureExtractor { constructor(config) { super(config); const sampling_rate = this.config.sampling_rate; const mel_filters = mel_filter_bank( 256, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(sampling_rate / 2), // max_frequency sampling_rate, // sampling_rate null, // norm "kaldi", // mel_scale true // triangularize_in_mel_space ); for (let i = 0; i < mel_filters.length; ++i) { mel_filters[i].push(0); } this.mel_filters = mel_filters; this.window = window_function(400, "hann", { periodic: false }); this.mean = this.config.mean; this.std = this.config.std; } /** * Computes the log-Mel spectrogram of the provided audio waveform. * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @param {number} max_length The maximum number of frames to return. * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ _extract_fbank_features(waveform, max_length) { return spectrogram( waveform, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2, center: false, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: "log", mel_floor: 1192092955078125e-22, remove_dc_offset: true, // Custom max_num_frames: max_length, transpose: true } ); } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. */ async _call(audio) { validate_audio_inputs(audio, "ASTFeatureExtractor"); const features = this._extract_fbank_features(audio, this.config.max_length); if (this.config.do_normalize) { const denom = this.std * 2; for (let i = 0; i < features.data.length; ++i) { features.data[i] = (features.data[i] - this.mean) / denom; } } return { input_values: new Tensor( "float32", features.data, [1, ...features.dims] ) }; } }; ClapFeatureExtractor = class extends FeatureExtractor { constructor(config) { super(config); this.mel_filters = mel_filter_bank( this.config.nb_frequency_bins, // num_frequency_bins this.config.feature_size, // num_mel_filters this.config.frequency_min, // min_frequency this.config.frequency_max, // max_frequency this.config.sampling_rate, // sampling_rate null, // norm "htk" // mel_scale ); this.mel_filters_slaney = mel_filter_bank( this.config.nb_frequency_bins, // num_frequency_bins this.config.feature_size, // num_mel_filters this.config.frequency_min, // min_frequency this.config.frequency_max, // max_frequency this.config.sampling_rate, // sampling_rate "slaney", // norm "slaney" // mel_scale ); this.window = window_function(this.config.fft_window_size, "hann"); } /** * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. * * Four different path are possible: * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram * are then stacked together. They will later be used for `feature_fusion`. * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is * padded based on `padding`. * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded * based on `padding`, and is repeated `4` times. * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel * spectrogram will be computed on a random crop of the waveform. * * @param {Float32Array|Float64Array} waveform The input waveform. * @param {number} max_length The maximum length of the waveform. * @param {string} truncation The truncation strategy to use. * @param {string} padding The padding strategy to use. * @returns {{ data: Float32Array; dims: number[]; longer: boolean; }} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. */ _get_input_mel(waveform, max_length, truncation, padding) { let input_mel; let longer = false; const diff = waveform.length - max_length; if (diff > 0) { if (truncation === "rand_trunc") { longer = true; const idx = Math.floor(Math.random() * (diff + 1)); waveform = waveform.subarray(idx, idx + max_length); input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); input_mel.dims = [1, ...input_mel.dims]; } else { throw new Error(`Truncation strategy "${truncation}" not implemented`); } } else { if (diff < 0) { let padded = new Float64Array(max_length); padded.set(waveform); if (padding === "repeat") { for (let i = waveform.length; i < max_length; i += waveform.length) { padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); } } else if (padding === "repeatpad") { for (let i = waveform.length; i < -diff; i += waveform.length) { padded.set(waveform, i); } } waveform = padded; } if (truncation === "fusion") { throw new Error(`Truncation strategy "${truncation}" not implemented`); } input_mel = this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); input_mel.dims = [1, ...input_mel.dims]; } return { ...input_mel, longer }; } /** * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. * In CLAP, two different filter banks are used depending on the truncation pattern: * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` * is set to `"fusion"`. * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original * implementation when the truncation mode is not `"fusion"`. * * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @param {number[][]} mel_filters The mel filters to use. * @param {number} [max_length=null] The maximum number of frames to return. * @returns {{data: Float32Array, dims: number[]}} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ _extract_fbank_features(waveform, mel_filters, max_length = null) { return spectrogram( waveform, this.window, // window this.config.fft_window_size, // frame_length this.config.hop_length, // hop_length { power: 2, mel_filters, log_mel: "dB", // Custom max_num_frames: max_length, do_pad: false, transpose: true } ); } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. */ async _call(audio, { max_length = null } = {}) { validate_audio_inputs(audio, "ClapFeatureExtractor"); const padded_inputs = this._get_input_mel( audio, max_length ?? this.config.nb_max_samples, this.config.truncation, this.config.padding ); return { input_features: new Tensor( "float32", padded_inputs.data, [1, ...padded_inputs.dims] ) }; } }; SpeechT5FeatureExtractor = class extends FeatureExtractor { }; Processor = class extends Callable { /** * Creates a new Processor with the given feature extractor. * @param {FeatureExtractor} feature_extractor The function used to extract features from the input. */ constructor(feature_extractor) { super(); this.feature_extractor = feature_extractor; } /** * Calls the feature_extractor function with the given input. * @param {any} input The input to extract features from. * @param {...any} args Additional arguments. * @returns {Promise} A Promise that resolves with the extracted features. */ async _call(input, ...args) { return await this.feature_extractor(input, ...args); } }; SamProcessor = class extends Processor { /** * @borrows SamImageProcessor#_call as _call */ async _call(...args) { return await this.feature_extractor(...args); } /** * @borrows SamImageProcessor#post_process_masks as post_process_masks */ post_process_masks(...args) { return this.feature_extractor.post_process_masks(...args); } /** * @borrows SamImageProcessor#reshape_input_points as reshape_input_points */ reshape_input_points(...args) { return this.feature_extractor.reshape_input_points(...args); } }; WhisperProcessor = class extends Processor { /** * Calls the feature_extractor function with the given audio input. * @param {any} audio The audio input to extract features from. * @returns {Promise} A Promise that resolves with the extracted features. */ async _call(audio) { return await this.feature_extractor(audio); } }; Wav2Vec2ProcessorWithLM = class extends Processor { /** * Calls the feature_extractor function with the given audio input. * @param {any} audio The audio input to extract features from. * @returns {Promise} A Promise that resolves with the extracted features. */ async _call(audio) { return await this.feature_extractor(audio); } }; SpeechT5Processor = class extends Processor { /** * Calls the feature_extractor function with the given input. * @param {any} input The input to extract features from. * @returns {Promise} A Promise that resolves with the extracted features. */ async _call(input) { return await this.feature_extractor(input); } }; OwlViTProcessor = class extends Processor { }; AutoProcessor = class { static FEATURE_EXTRACTOR_CLASS_MAPPING = { ImageFeatureExtractor, WhisperFeatureExtractor, ViTFeatureExtractor, MobileViTFeatureExtractor, MobileViTImageProcessor, OwlViTFeatureExtractor, Owlv2ImageProcessor, CLIPFeatureExtractor, ChineseCLIPFeatureExtractor, SiglipImageProcessor, ConvNextFeatureExtractor, ConvNextImageProcessor, SegformerFeatureExtractor, BitImageProcessor, DPTImageProcessor, DPTFeatureExtractor, GLPNFeatureExtractor, BeitFeatureExtractor, DeiTFeatureExtractor, DetrFeatureExtractor, YolosFeatureExtractor, DonutFeatureExtractor, NougatImageProcessor, EfficientNetImageProcessor, ViTImageProcessor, VitMatteImageProcessor, SamImageProcessor, Swin2SRImageProcessor, Wav2Vec2FeatureExtractor, SeamlessM4TFeatureExtractor, SpeechT5FeatureExtractor, ASTFeatureExtractor, ClapFeatureExtractor }; static PROCESSOR_CLASS_MAPPING = { WhisperProcessor, Wav2Vec2ProcessorWithLM, SamProcessor, SpeechT5Processor, OwlViTProcessor }; /** * Instantiate one of the processor classes of the library from a pretrained model. * * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) * * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a * user or organization name, like `dbmdz/bert-base-german-cased`. * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor. * * @returns {Promise} A new instance of the Processor class. */ static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, "preprocessor_config.json", true, { progress_callback, config, cache_dir, local_files_only, revision }); let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type; let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key]; if (!feature_extractor_class) { if (preprocessorConfig.size !== void 0) { console.warn(`Feature extractor type "${key}" not found, assuming ImageFeatureExtractor due to size parameter in config.`); feature_extractor_class = ImageFeatureExtractor; } else { throw new Error(`Unknown Feature Extractor type: ${key}`); } } let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor; let feature_extractor = new feature_extractor_class(preprocessorConfig); return new processor_class(feature_extractor); } }; } }); // node_modules/@xenova/transformers/src/pipelines.js async function prepareImages(images) { if (!Array.isArray(images)) { images = [images]; } return await Promise.all(images.map((x2) => RawImage.read(x2))); } async function prepareAudios(audios, sampling_rate) { if (!Array.isArray(audios)) { audios = [audios]; } return await Promise.all(audios.map((x2) => { if (typeof x2 === "string" || x2 instanceof URL) { return read_audio(x2, sampling_rate); } else if (x2 instanceof Float64Array) { return new Float32Array(x2); } return x2; })); } function get_bounding_box(box, asInteger) { if (asInteger) { box = box.map((x2) => x2 | 0); } const [xmin, ymin, xmax, ymax] = box; return { xmin, ymin, xmax, ymax }; } function isChat(x2) { return Array.isArray(x2) && x2.every((x3) => "role" in x3 && "content" in x3); } var Pipeline, TextClassificationPipeline, TokenClassificationPipeline, QuestionAnsweringPipeline, FillMaskPipeline, Text2TextGenerationPipeline, SummarizationPipeline, TranslationPipeline, TextGenerationPipeline, ZeroShotClassificationPipeline, FeatureExtractionPipeline, ImageFeatureExtractionPipeline, AudioClassificationPipeline, ZeroShotAudioClassificationPipeline, AutomaticSpeechRecognitionPipeline, ImageToTextPipeline, ImageClassificationPipeline, ImageSegmentationPipeline, ZeroShotImageClassificationPipeline, ObjectDetectionPipeline, ZeroShotObjectDetectionPipeline, DocumentQuestionAnsweringPipeline, TextToAudioPipeline, ImageToImagePipeline, DepthEstimationPipeline, SUPPORTED_TASKS, TASK_ALIASES; var init_pipelines = __esm({ "node_modules/@xenova/transformers/src/pipelines.js"() { init_tokenizers(); init_models(); init_processors(); init_core(); init_maths(); init_audio(); init_tensor(); init_image(); Pipeline = class extends Callable { /** * Create a new Pipeline. * @param {Object} options An object containing the following properties: * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. * @param {PreTrainedModel} [options.model] The model used by the pipeline. * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). */ constructor({ task, model, tokenizer = null, processor = null }) { super(); this.task = task; this.model = model; this.tokenizer = tokenizer; this.processor = processor; } /** @type {DisposeType} */ async dispose() { await this.model.dispose(); } }; TextClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ Pipeline { /** * Create a new TextClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {TextClassificationPipelineCallback} */ async _call(texts, { topk = 1 } = {}) { const model_inputs = this.tokenizer(texts, { padding: true, truncation: true }); const outputs = await this.model(model_inputs); const function_to_apply = this.model.config.problem_type === "multi_label_classification" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data); const id2label = this.model.config.id2label; const toReturn = []; for (const batch of outputs.logits) { const output = function_to_apply(batch); const scores = getTopItems(output, topk); const vals = scores.map((x2) => ({ label: id2label[x2[0]], score: x2[1] })); if (topk === 1) { toReturn.push(...vals); } else { toReturn.push(vals); } } return Array.isArray(texts) || topk === 1 ? ( /** @type {TextClassificationOutput} */ toReturn ) : ( /** @type {TextClassificationOutput[]} */ toReturn[0] ); } }; TokenClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ Pipeline { /** * Create a new TokenClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {TokenClassificationPipelineCallback} */ async _call(texts, { ignore_labels = ["O"] } = {}) { const isBatched = Array.isArray(texts); const model_inputs = this.tokenizer(isBatched ? texts : [texts], { padding: true, truncation: true }); const outputs = await this.model(model_inputs); const logits = outputs.logits; const id2label = this.model.config.id2label; const toReturn = []; for (let i = 0; i < logits.dims[0]; ++i) { const ids = model_inputs.input_ids[i]; const batch = logits[i]; const tokens = []; for (let j3 = 0; j3 < batch.dims[0]; ++j3) { const tokenData = batch[j3]; const topScoreIndex = max(tokenData.data)[1]; const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; if (ignore_labels.includes(entity)) { continue; } const word = this.tokenizer.decode([ids[j3].item()], { skip_special_tokens: true }); if (word === "") { continue; } const scores = softmax(tokenData.data); tokens.push({ entity, score: scores[topScoreIndex], index: j3, word, // TODO: null for now, but will add start: null, end: null }); } toReturn.push(tokens); } return isBatched ? toReturn : toReturn[0]; } }; QuestionAnsweringPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ Pipeline { /** * Create a new QuestionAnsweringPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {QuestionAnsweringPipelineCallback} */ async _call(question, context, { topk = 1 } = {}) { const inputs = this.tokenizer(question, { text_pair: context, padding: true, truncation: true }); const output = await this.model(inputs); const toReturn = []; for (let j3 = 0; j3 < output.start_logits.dims[0]; ++j3) { const ids = inputs.input_ids[j3]; const sepIndex = ids.indexOf(this.tokenizer.sep_token_id); const s1 = Array.from(softmax(output.start_logits[j3].data)).map((x2, i) => [x2, i]).filter((x2) => x2[1] > sepIndex); const e1 = Array.from(softmax(output.end_logits[j3].data)).map((x2, i) => [x2, i]).filter((x2) => x2[1] > sepIndex); const options = product(s1, e1).filter((x2) => x2[0][1] <= x2[1][1]).map((x2) => [x2[0][1], x2[1][1], x2[0][0] * x2[1][0]]).sort((a, b) => b[2] - a[2]); for (let k4 = 0; k4 < Math.min(options.length, topk); ++k4) { const [start, end, score] = options[k4]; const answer_tokens = [...ids].slice(start, end + 1); const answer = this.tokenizer.decode(answer_tokens, { skip_special_tokens: true }); toReturn.push({ answer, score }); } } return topk === 1 ? toReturn[0] : toReturn; } }; FillMaskPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ Pipeline { /** * Create a new FillMaskPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {FillMaskPipelineCallback} */ async _call(texts, { topk = 5 } = {}) { const model_inputs = this.tokenizer(texts, { padding: true, truncation: true }); const outputs = await this.model(model_inputs); const toReturn = []; for (let i = 0; i < model_inputs.input_ids.dims[0]; ++i) { const ids = model_inputs.input_ids[i]; const mask_token_index = ids.indexOf(this.tokenizer.mask_token_id); if (mask_token_index === -1) { throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`); } const logits = outputs.logits[i]; const itemLogits = logits[mask_token_index]; const scores = getTopItems(softmax(itemLogits.data), topk); toReturn.push(scores.map((x2) => { const sequence = [...ids]; sequence[mask_token_index] = x2[0]; return { score: x2[1], token: x2[0], token_str: this.tokenizer.model.vocab[x2[0]], sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }) }; })); } return Array.isArray(texts) ? toReturn : toReturn[0]; } }; Text2TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ Pipeline { /** @type {'generated_text'} */ _key = "generated_text"; /** * Create a new Text2TextGenerationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {Text2TextGenerationPipelineCallback} */ async _call(texts, generate_kwargs = {}) { if (!Array.isArray(texts)) { texts = [texts]; } if (this.model.config.prefix) { texts = texts.map((x2) => this.model.config.prefix + x2); } const task_specific_params = this.model.config.task_specific_params; if (task_specific_params && task_specific_params[this.task]) { if (task_specific_params[this.task].prefix) { texts = texts.map((x2) => task_specific_params[this.task].prefix + x2); } } const tokenizer = this.tokenizer; const tokenizer_options = { padding: true, truncation: true }; let input_ids; if (this instanceof TranslationPipeline && "_build_translation_inputs" in tokenizer) { input_ids = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs).input_ids; } else { input_ids = tokenizer(texts, tokenizer_options).input_ids; } const outputTokenIds = await this.model.generate(input_ids, generate_kwargs); return tokenizer.batch_decode(outputTokenIds, { skip_special_tokens: true }).map((text) => ({ [this._key]: text })); } }; SummarizationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ /** @type {any} */ Text2TextGenerationPipeline { /** @type {'summary_text'} */ _key = "summary_text"; /** * Create a new SummarizationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } }; TranslationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ /** @type {any} */ Text2TextGenerationPipeline { /** @type {'translation_text'} */ _key = "translation_text"; /** * Create a new TranslationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } }; TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ Pipeline { /** * Create a new TextGenerationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {TextGenerationPipelineCallback} */ async _call(texts, generate_kwargs = {}) { let isBatched = false; let isChatInput = false; let inputs; if (typeof texts === "string") { inputs = texts = [texts]; } else if (Array.isArray(texts) && texts.every((x2) => typeof x2 === "string")) { isBatched = true; inputs = /** @type {string[]} */ texts; } else { if (isChat(texts)) { texts = [ /** @type {Chat} */ texts ]; } else if (Array.isArray(texts) && texts.every(isChat)) { isBatched = true; } else { throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats"); } isChatInput = true; inputs = /** @type {string[]} */ /** @type {Chat[]} */ texts.map( (x2) => this.tokenizer.apply_chat_template(x2, { tokenize: false, add_generation_prompt: true }) ); } const add_special_tokens = generate_kwargs.add_special_tokens ?? false; const return_full_text = isChatInput ? false : generate_kwargs.return_full_text ?? true; this.tokenizer.padding_side = "left"; const { input_ids, attention_mask } = this.tokenizer(inputs, { add_special_tokens, padding: true, truncation: true }); const outputTokenIds = await this.model.generate(input_ids, generate_kwargs, null, { inputs_attention_mask: attention_mask }); let decoded = this.tokenizer.batch_decode(outputTokenIds, { skip_special_tokens: true }); let promptLengths; if (!return_full_text && input_ids.dims.at(-1) > 0) { promptLengths = this.tokenizer.batch_decode(input_ids, { skip_special_tokens: true }).map((x2) => x2.length); } const toReturn = Array.from({ length: texts.length }, (_) => []); for (let i = 0; i < decoded.length; ++i) { const textIndex = Math.floor(i / outputTokenIds.length * texts.length); if (promptLengths) { decoded[i] = decoded[i].slice(promptLengths[textIndex]); } toReturn[textIndex].push({ generated_text: isChatInput ? [ .../** @type {Chat[]} */ texts[textIndex], { role: "assistant", content: decoded[i] } ] : decoded[i] }); } return !isBatched && toReturn.length === 1 ? toReturn[0] : toReturn; } }; ZeroShotClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ Pipeline { /** * Create a new ZeroShotClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); this.label2id = Object.fromEntries( Object.entries( /** @type {any} */ this.model.config.label2id ).map( ([k4, v]) => [k4.toLowerCase(), v] ) ); this.entailment_id = this.label2id["entailment"]; if (this.entailment_id === void 0) { console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."); this.entailment_id = 2; } this.contradiction_id = this.label2id["contradiction"] ?? this.label2id["not_entailment"]; if (this.contradiction_id === void 0) { console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); this.contradiction_id = 0; } } /** @type {ZeroShotClassificationPipelineCallback} */ async _call(texts, candidate_labels, { hypothesis_template = "This example is {}.", multi_label = false } = {}) { const isBatched = Array.isArray(texts); if (!isBatched) { texts = [ /** @type {string} */ texts ]; } if (!Array.isArray(candidate_labels)) { candidate_labels = [candidate_labels]; } const hypotheses = candidate_labels.map( (x2) => hypothesis_template.replace("{}", x2) ); const softmaxEach = multi_label || candidate_labels.length === 1; const toReturn = []; for (const premise of texts) { const entails_logits = []; for (const hypothesis of hypotheses) { const inputs = this.tokenizer(premise, { text_pair: hypothesis, padding: true, truncation: true }); const outputs = await this.model(inputs); if (softmaxEach) { entails_logits.push([ outputs.logits.data[this.contradiction_id], outputs.logits.data[this.entailment_id] ]); } else { entails_logits.push(outputs.logits.data[this.entailment_id]); } } const scores = softmaxEach ? entails_logits.map((x2) => softmax(x2)[1]) : softmax(entails_logits); const scores_sorted = scores.map((x2, i) => [x2, i]).sort((a, b) => b[0] - a[0]); toReturn.push({ sequence: premise, labels: scores_sorted.map((x2) => candidate_labels[x2[1]]), scores: scores_sorted.map((x2) => x2[0]) }); } return isBatched ? toReturn : toReturn[0]; } }; FeatureExtractionPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ Pipeline { /** * Create a new FeatureExtractionPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {FeatureExtractionPipelineCallback} */ async _call(texts, { pooling = ( /** @type {'none'} */ "none" ), normalize = false, quantize = false, precision = ( /** @type {'binary'} */ "binary" ) } = {}) { const model_inputs = this.tokenizer(texts, { padding: true, truncation: true }); const outputs = await this.model(model_inputs); let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings; if (pooling === "none") { } else if (pooling === "mean") { result = mean_pooling(result, model_inputs.attention_mask); } else if (pooling === "cls") { result = result.slice(null, 0); } else { throw Error(`Pooling method '${pooling}' not supported.`); } if (normalize) { result = result.normalize(2, -1); } if (quantize) { result = quantize_embeddings(result, precision); } return result; } }; ImageFeatureExtractionPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ Pipeline { /** * Create a new ImageFeatureExtractionPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ImageFeatureExtractionPipelineCallback} */ async _call(images, { pool = null } = {}) { const preparedImages = await prepareImages(images); const { pixel_values } = await this.processor(preparedImages); const outputs = await this.model({ pixel_values }); let result; if (pool) { if (!("pooler_output" in outputs)) { throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`); } result = outputs.pooler_output; } else { result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds; } return result; } }; AudioClassificationPipeline = class extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ Pipeline { /** * Create a new AudioClassificationPipeline. * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {AudioClassificationPipelineCallback} */ async _call(audio, { topk = null } = {}) { const single = !Array.isArray(audio); const sampling_rate = this.processor.feature_extractor.config.sampling_rate; const preparedAudios = await prepareAudios(audio, sampling_rate); const id2label = this.model.config.id2label; const toReturn = []; for (const aud of preparedAudios) { const inputs = await this.processor(aud); const output = await this.model(inputs); const logits = output.logits[0]; const scores = getTopItems(softmax(logits.data), topk); const vals = scores.map((x2) => ({ label: ( /** @type {string} */ id2label[x2[0]] ), score: ( /** @type {number} */ x2[1] ) })); if (topk === 1) { toReturn.push(...vals); } else { toReturn.push(vals); } } return !single || topk === 1 ? ( /** @type {AudioClassificationOutput} */ toReturn ) : ( /** @type {AudioClassificationOutput[]} */ toReturn[0] ); } }; ZeroShotAudioClassificationPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ Pipeline { /** * Create a new ZeroShotAudioClassificationPipeline. * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ZeroShotAudioClassificationPipelineCallback} */ async _call(audio, candidate_labels, { hypothesis_template = "This is a sound of {}." } = {}) { const single = !Array.isArray(audio); if (single) { audio = [ /** @type {AudioInput} */ audio ]; } const texts = candidate_labels.map( (x2) => hypothesis_template.replace("{}", x2) ); const text_inputs = this.tokenizer(texts, { padding: true, truncation: true }); const sampling_rate = this.processor.feature_extractor.config.sampling_rate; const preparedAudios = await prepareAudios(audio, sampling_rate); const toReturn = []; for (const aud of preparedAudios) { const audio_inputs = await this.processor(aud); const output = await this.model({ ...text_inputs, ...audio_inputs }); const probs = softmax(output.logits_per_audio.data); toReturn.push([...probs].map((x2, i) => ({ score: x2, label: candidate_labels[i] }))); } return single ? toReturn[0] : toReturn; } }; AutomaticSpeechRecognitionPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ Pipeline { /** * Create a new AutomaticSpeechRecognitionPipeline. * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {AutomaticSpeechRecognitionPipelineCallback} */ async _call(audio, kwargs = {}) { switch (this.model.config.model_type) { case "whisper": return this._call_whisper(audio, kwargs); case "wav2vec2": case "wav2vec2-bert": case "unispeech": case "unispeech-sat": case "hubert": return this._call_wav2vec2(audio, kwargs); default: throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`); } } /** * @type {AutomaticSpeechRecognitionPipelineCallback} * @private */ async _call_wav2vec2(audio, kwargs = {}) { if (kwargs.language) { console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); } if (kwargs.task) { console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); } const single = !Array.isArray(audio); if (single) { audio = [ /** @type {AudioInput} */ audio ]; } const sampling_rate = this.processor.feature_extractor.config.sampling_rate; const preparedAudios = await prepareAudios(audio, sampling_rate); const toReturn = []; for (const aud of preparedAudios) { const inputs = await this.processor(aud); const output = await this.model(inputs); const logits = output.logits[0]; const predicted_ids = []; for (const item of logits) { predicted_ids.push(max(item.data)[1]); } const predicted_sentences = this.tokenizer.decode(predicted_ids); toReturn.push({ text: predicted_sentences }); } return single ? toReturn[0] : toReturn; } /** * @type {AutomaticSpeechRecognitionPipelineCallback} * @private */ async _call_whisper(audio, kwargs = {}) { const return_timestamps = kwargs.return_timestamps ?? false; const chunk_length_s = kwargs.chunk_length_s ?? 0; const chunk_callback = kwargs.chunk_callback ?? null; const force_full_sequences = kwargs.force_full_sequences ?? false; let stride_length_s = kwargs.stride_length_s ?? null; if (return_timestamps === "word") { kwargs["return_token_timestamps"] = true; } const language = pop(kwargs, "language", null); const task = pop(kwargs, "task", null); if (language || task || return_timestamps) { if (kwargs.forced_decoder_ids) { throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time."); } const decoder_prompt_ids = this.tokenizer.get_decoder_prompt_ids({ language, task, no_timestamps: !return_timestamps }); if (decoder_prompt_ids.length > 0) { kwargs.forced_decoder_ids = decoder_prompt_ids; } } const single = !Array.isArray(audio); if (single) { audio = [ /** @type {AudioInput} */ audio ]; } const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions; const hop_length = this.processor.feature_extractor.config.hop_length; const sampling_rate = this.processor.feature_extractor.config.sampling_rate; const preparedAudios = await prepareAudios(audio, sampling_rate); const toReturn = []; for (const aud of preparedAudios) { let chunks = []; if (chunk_length_s > 0) { if (stride_length_s === null) { stride_length_s = chunk_length_s / 6; } else if (chunk_length_s <= stride_length_s) { throw Error("`chunk_length_s` must be larger than `stride_length_s`."); } const window2 = sampling_rate * chunk_length_s; const stride = sampling_rate * stride_length_s; const jump = window2 - 2 * stride; let offset = 0; while (offset < aud.length) { const subarr = aud.subarray(offset, offset + window2); const feature = await this.processor(subarr); const isFirst = offset === 0; const isLast = offset + jump >= aud.length; chunks.push({ stride: [ subarr.length, isFirst ? 0 : stride, isLast ? 0 : stride ], input_features: feature.input_features, is_last: isLast }); offset += jump; } } else { chunks = [{ stride: [aud.length, 0, 0], input_features: (await this.processor(aud)).input_features, is_last: true }]; } for (const chunk of chunks) { kwargs.num_frames = Math.floor(chunk.stride[0] / hop_length); const data = await this.model.generate(chunk.input_features, kwargs); if (return_timestamps === "word") { chunk.tokens = data.sequences[0]; chunk.token_timestamps = data.token_timestamps.tolist()[0].map( (x2) => round(x2, 2) ); } else { chunk.tokens = data[0]; } chunk.stride = chunk.stride.map((x2) => x2 / sampling_rate); if (chunk_callback !== null) { chunk_callback(chunk); } } const [full_text, optional] = this.tokenizer._decode_asr(chunks, { time_precision, return_timestamps, force_full_sequences }); toReturn.push({ text: full_text, ...optional }); } return single ? toReturn[0] : toReturn; } }; ImageToTextPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ Pipeline { /** * Create a new ImageToTextPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ImageToTextPipelineCallback} */ async _call(images, generate_kwargs = {}) { const isBatched = Array.isArray(images); const preparedImages = await prepareImages(images); const { pixel_values } = await this.processor(preparedImages); const toReturn = []; for (const batch of pixel_values) { batch.dims = [1, ...batch.dims]; const output = await this.model.generate(batch, generate_kwargs); const decoded = this.tokenizer.batch_decode(output, { skip_special_tokens: true }).map((x2) => ({ generated_text: x2.trim() })); toReturn.push(decoded); } return isBatched ? toReturn : toReturn[0]; } }; ImageClassificationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ Pipeline { /** * Create a new ImageClassificationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ImageClassificationPipelineCallback} */ async _call(images, { topk = 1 } = {}) { const isBatched = Array.isArray(images); const preparedImages = await prepareImages(images); const { pixel_values } = await this.processor(preparedImages); const output = await this.model({ pixel_values }); const id2label = this.model.config.id2label; const toReturn = []; for (const batch of output.logits) { const scores = getTopItems(softmax(batch.data), topk); const vals = scores.map((x2) => ({ label: id2label[x2[0]], score: x2[1] })); if (topk === 1) { toReturn.push(...vals); } else { toReturn.push(vals); } } return isBatched || topk === 1 ? ( /** @type {ImageClassificationOutput} */ toReturn ) : ( /** @type {ImageClassificationOutput[]} */ toReturn[0] ); } }; ImageSegmentationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ Pipeline { /** * Create a new ImageSegmentationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); this.subtasks_mapping = { // Mapping of subtasks to their corresponding post-processing function names. panoptic: "post_process_panoptic_segmentation", instance: "post_process_instance_segmentation", semantic: "post_process_semantic_segmentation" }; } /** @type {ImageSegmentationPipelineCallback} */ async _call(images, { threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null, subtask = null } = {}) { const isBatched = Array.isArray(images); if (isBatched && images.length !== 1) { throw Error("Image segmentation pipeline currently only supports a batch size of 1."); } const preparedImages = await prepareImages(images); const imageSizes = preparedImages.map((x2) => [x2.height, x2.width]); const { pixel_values, pixel_mask } = await this.processor(preparedImages); const output = await this.model({ pixel_values, pixel_mask }); let fn3 = null; if (subtask !== null) { fn3 = this.subtasks_mapping[subtask]; } else { for (let [task, func] of Object.entries(this.subtasks_mapping)) { if (func in this.processor.feature_extractor) { fn3 = this.processor.feature_extractor[func].bind(this.processor.feature_extractor); subtask = task; break; } } } const id2label = this.model.config.id2label; const annotation = []; if (subtask === "panoptic" || subtask === "instance") { const processed = fn3( output, threshold, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse, target_sizes ?? imageSizes // TODO FIX? )[0]; const segmentation = processed.segmentation; for (const segment of processed.segments_info) { const maskData = new Uint8ClampedArray(segmentation.data.length); for (let i = 0; i < segmentation.data.length; ++i) { if (segmentation.data[i] === segment.id) { maskData[i] = 255; } } const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); annotation.push({ score: segment.score, label: id2label[segment.label_id], mask }); } } else if (subtask === "semantic") { const { segmentation, labels } = fn3(output, target_sizes ?? imageSizes)[0]; for (const label of labels) { const maskData = new Uint8ClampedArray(segmentation.data.length); for (let i = 0; i < segmentation.data.length; ++i) { if (segmentation.data[i] === label) { maskData[i] = 255; } } const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); annotation.push({ score: null, label: id2label[label], mask }); } } else { throw Error(`Subtask ${subtask} not supported.`); } return annotation; } }; ZeroShotImageClassificationPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ Pipeline { /** * Create a new ZeroShotImageClassificationPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ZeroShotImageClassificationPipelineCallback} */ async _call(images, candidate_labels, { hypothesis_template = "This is a photo of {}" } = {}) { const isBatched = Array.isArray(images); const preparedImages = await prepareImages(images); const texts = candidate_labels.map( (x2) => hypothesis_template.replace("{}", x2) ); const text_inputs = this.tokenizer(texts, { padding: this.model.config.model_type === "siglip" ? "max_length" : true, truncation: true }); const { pixel_values } = await this.processor(preparedImages); const output = await this.model({ ...text_inputs, pixel_values }); const function_to_apply = this.model.config.model_type === "siglip" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data); const toReturn = []; for (const batch of output.logits_per_image) { const probs = function_to_apply(batch); const result = [...probs].map((x2, i) => ({ score: x2, label: candidate_labels[i] })); result.sort((a, b) => b.score - a.score); toReturn.push(result); } return isBatched ? toReturn : toReturn[0]; } }; ObjectDetectionPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ Pipeline { /** * Create a new ObjectDetectionPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ObjectDetectionPipelineCallback} */ async _call(images, { threshold = 0.9, percentage = false } = {}) { const isBatched = Array.isArray(images); if (isBatched && images.length !== 1) { throw Error("Object detection pipeline currently only supports a batch size of 1."); } const preparedImages = await prepareImages(images); const imageSizes = percentage ? null : preparedImages.map((x2) => [x2.height, x2.width]); const { pixel_values, pixel_mask } = await this.processor(preparedImages); const output = await this.model({ pixel_values, pixel_mask }); const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes); const id2label = this.model.config.id2label; const result = processed.map((batch) => batch.boxes.map((box, i) => ({ score: batch.scores[i], label: id2label[batch.classes[i]], box: get_bounding_box(box, !percentage) }))); return isBatched ? result : result[0]; } }; ZeroShotObjectDetectionPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ Pipeline { /** * Create a new ZeroShotObjectDetectionPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ZeroShotObjectDetectionPipelineCallback} */ async _call(images, candidate_labels, { threshold = 0.1, topk = null, percentage = false } = {}) { const isBatched = Array.isArray(images); const preparedImages = await prepareImages(images); const text_inputs = this.tokenizer(candidate_labels, { padding: true, truncation: true }); const model_inputs = await this.processor(preparedImages); const toReturn = []; for (let i = 0; i < preparedImages.length; ++i) { const image = preparedImages[i]; const imageSize = percentage ? null : [[image.height, image.width]]; const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); const output = await this.model({ ...text_inputs, pixel_values }); const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0]; let result = processed.boxes.map((box, i2) => ({ score: processed.scores[i2], label: candidate_labels[processed.classes[i2]], box: get_bounding_box(box, !percentage) })).sort((a, b) => b.score - a.score); if (topk !== null) { result = result.slice(0, topk); } toReturn.push(result); } return isBatched ? toReturn : toReturn[0]; } }; DocumentQuestionAnsweringPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ Pipeline { /** * Create a new DocumentQuestionAnsweringPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {DocumentQuestionAnsweringPipelineCallback} */ async _call(image, question, generate_kwargs = {}) { const preparedImage = (await prepareImages(image))[0]; const { pixel_values } = await this.processor(preparedImage); const task_prompt = `${question}`; const decoder_input_ids = this.tokenizer(task_prompt, { add_special_tokens: false, padding: true, truncation: true }).input_ids; const output = await this.model.generate( pixel_values, { ...generate_kwargs, decoder_input_ids, max_length: this.model.config.decoder.max_position_embeddings } ); const decoded = this.tokenizer.batch_decode(output)[0]; const match = decoded.match(/(.*?)<\/s_answer>/); let answer = null; if (match && match.length >= 2) { answer = match[1].trim(); } return [{ answer }]; } }; TextToAudioPipeline = class extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ Pipeline { DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"; /** * Create a new TextToAudioPipeline. * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); this.vocoder = options.vocoder ?? null; } /** @type {TextToAudioPipelineCallback} */ async _call(text_inputs, { speaker_embeddings = null } = {}) { if (this.processor) { return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings }); } else { return this._call_text_to_waveform(text_inputs); } } async _call_text_to_waveform(text_inputs) { const inputs = this.tokenizer(text_inputs, { padding: true, truncation: true }); const { waveform } = await this.model(inputs); const sampling_rate = this.model.config.sampling_rate; return { audio: waveform.data, sampling_rate }; } async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { if (!this.vocoder) { console.log("No vocoder specified, using default HifiGan vocoder."); this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { quantized: false }); } if (typeof speaker_embeddings === "string" || speaker_embeddings instanceof URL) { speaker_embeddings = new Float32Array( await (await fetch(speaker_embeddings)).arrayBuffer() ); } if (speaker_embeddings instanceof Float32Array) { speaker_embeddings = new Tensor( "float32", speaker_embeddings, [1, speaker_embeddings.length] ); } else if (!(speaker_embeddings instanceof Tensor)) { throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`."); } const { input_ids } = this.tokenizer(text_inputs, { padding: true, truncation: true }); const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); const sampling_rate = this.processor.feature_extractor.config.sampling_rate; return { audio: waveform.data, sampling_rate }; } }; ImageToImagePipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ Pipeline { /** * Create a new ImageToImagePipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {ImageToImagePipelineCallback} */ async _call(images) { const preparedImages = await prepareImages(images); const inputs = await this.processor(preparedImages); const outputs = await this.model(inputs); const toReturn = []; for (const batch of outputs.reconstruction) { const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8"); toReturn.push(RawImage.fromTensor(output)); } return toReturn.length > 1 ? toReturn : toReturn[0]; } }; DepthEstimationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ Pipeline { /** * Create a new DepthEstimationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(options) { super(options); } /** @type {DepthEstimationPipelineCallback} */ async _call(images) { const preparedImages = await prepareImages(images); const inputs = await this.processor(preparedImages); const { predicted_depth } = await this.model(inputs); const toReturn = []; for (let i = 0; i < preparedImages.length; ++i) { const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), "bilinear", false); const formatted = prediction.mul_(255 / max(prediction.data)[0]).to("uint8"); toReturn.push({ predicted_depth: predicted_depth[i], depth: RawImage.fromTensor(formatted) }); } return toReturn.length > 1 ? toReturn : toReturn[0]; } }; SUPPORTED_TASKS = Object.freeze({ "text-classification": { "tokenizer": AutoTokenizer, "pipeline": TextClassificationPipeline, "model": AutoModelForSequenceClassification, "default": { // TODO: replace with original // "model": "distilbert-base-uncased-finetuned-sst-2-english", "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english" }, "type": "text" }, "token-classification": { "tokenizer": AutoTokenizer, "pipeline": TokenClassificationPipeline, "model": AutoModelForTokenClassification, "default": { // TODO: replace with original // "model": "Davlan/bert-base-multilingual-cased-ner-hrl", "model": "Xenova/bert-base-multilingual-cased-ner-hrl" }, "type": "text" }, "question-answering": { "tokenizer": AutoTokenizer, "pipeline": QuestionAnsweringPipeline, "model": AutoModelForQuestionAnswering, "default": { // TODO: replace with original // "model": "distilbert-base-cased-distilled-squad", "model": "Xenova/distilbert-base-cased-distilled-squad" }, "type": "text" }, "fill-mask": { "tokenizer": AutoTokenizer, "pipeline": FillMaskPipeline, "model": AutoModelForMaskedLM, "default": { // TODO: replace with original // "model": "bert-base-uncased", "model": "Xenova/bert-base-uncased" }, "type": "text" }, "summarization": { "tokenizer": AutoTokenizer, "pipeline": SummarizationPipeline, "model": AutoModelForSeq2SeqLM, "default": { // TODO: replace with original // "model": "sshleifer/distilbart-cnn-6-6", "model": "Xenova/distilbart-cnn-6-6" }, "type": "text" }, "translation": { "tokenizer": AutoTokenizer, "pipeline": TranslationPipeline, "model": AutoModelForSeq2SeqLM, "default": { // TODO: replace with original // "model": "t5-small", "model": "Xenova/t5-small" }, "type": "text" }, "text2text-generation": { "tokenizer": AutoTokenizer, "pipeline": Text2TextGenerationPipeline, "model": AutoModelForSeq2SeqLM, "default": { // TODO: replace with original // "model": "google/flan-t5-small", "model": "Xenova/flan-t5-small" }, "type": "text" }, "text-generation": { "tokenizer": AutoTokenizer, "pipeline": TextGenerationPipeline, "model": AutoModelForCausalLM, "default": { // TODO: replace with original // "model": "gpt2", "model": "Xenova/gpt2" }, "type": "text" }, "zero-shot-classification": { "tokenizer": AutoTokenizer, "pipeline": ZeroShotClassificationPipeline, "model": AutoModelForSequenceClassification, "default": { // TODO: replace with original // "model": "typeform/distilbert-base-uncased-mnli", "model": "Xenova/distilbert-base-uncased-mnli" }, "type": "text" }, "audio-classification": { "pipeline": AudioClassificationPipeline, "model": AutoModelForAudioClassification, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "superb/wav2vec2-base-superb-ks", "model": "Xenova/wav2vec2-base-superb-ks" }, "type": "audio" }, "zero-shot-audio-classification": { "tokenizer": AutoTokenizer, "pipeline": ZeroShotAudioClassificationPipeline, "model": AutoModel, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "laion/clap-htsat-fused", "model": "Xenova/clap-htsat-unfused" }, "type": "multimodal" }, "automatic-speech-recognition": { "tokenizer": AutoTokenizer, "pipeline": AutomaticSpeechRecognitionPipeline, "model": [AutoModelForSpeechSeq2Seq, AutoModelForCTC], "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "openai/whisper-tiny.en", "model": "Xenova/whisper-tiny.en" }, "type": "multimodal" }, "text-to-audio": { "tokenizer": AutoTokenizer, "pipeline": TextToAudioPipeline, "model": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram], "processor": [ AutoProcessor, /* Some don't use a processor */ null ], "default": { // TODO: replace with original // "model": "microsoft/speecht5_tts", "model": "Xenova/speecht5_tts" }, "type": "text" }, "image-to-text": { "tokenizer": AutoTokenizer, "pipeline": ImageToTextPipeline, "model": AutoModelForVision2Seq, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "nlpconnect/vit-gpt2-image-captioning", "model": "Xenova/vit-gpt2-image-captioning" }, "type": "multimodal" }, "image-classification": { // no tokenizer "pipeline": ImageClassificationPipeline, "model": AutoModelForImageClassification, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "google/vit-base-patch16-224", "model": "Xenova/vit-base-patch16-224" }, "type": "multimodal" }, "image-segmentation": { // no tokenizer "pipeline": ImageSegmentationPipeline, "model": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation], "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "facebook/detr-resnet-50-panoptic", "model": "Xenova/detr-resnet-50-panoptic" }, "type": "multimodal" }, "zero-shot-image-classification": { "tokenizer": AutoTokenizer, "pipeline": ZeroShotImageClassificationPipeline, "model": AutoModel, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "openai/clip-vit-base-patch32", "model": "Xenova/clip-vit-base-patch32" }, "type": "multimodal" }, "object-detection": { // no tokenizer "pipeline": ObjectDetectionPipeline, "model": AutoModelForObjectDetection, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "facebook/detr-resnet-50", "model": "Xenova/detr-resnet-50" }, "type": "multimodal" }, "zero-shot-object-detection": { "tokenizer": AutoTokenizer, "pipeline": ZeroShotObjectDetectionPipeline, "model": AutoModelForZeroShotObjectDetection, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "google/owlvit-base-patch32", "model": "Xenova/owlvit-base-patch32" }, "type": "multimodal" }, "document-question-answering": { "tokenizer": AutoTokenizer, "pipeline": DocumentQuestionAnsweringPipeline, "model": AutoModelForDocumentQuestionAnswering, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "naver-clova-ix/donut-base-finetuned-docvqa", "model": "Xenova/donut-base-finetuned-docvqa" }, "type": "multimodal" }, "image-to-image": { // no tokenizer "pipeline": ImageToImagePipeline, "model": AutoModelForImageToImage, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "caidas/swin2SR-classical-sr-x2-64", "model": "Xenova/swin2SR-classical-sr-x2-64" }, "type": "image" }, "depth-estimation": { // no tokenizer "pipeline": DepthEstimationPipeline, "model": AutoModelForDepthEstimation, "processor": AutoProcessor, "default": { // TODO: replace with original // "model": "Intel/dpt-large", "model": "Xenova/dpt-large" }, "type": "image" }, // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers). "feature-extraction": { "tokenizer": AutoTokenizer, "pipeline": FeatureExtractionPipeline, "model": AutoModel, "default": { // TODO: replace with original // "model": "sentence-transformers/all-MiniLM-L6-v2", "model": "Xenova/all-MiniLM-L6-v2" }, "type": "text" }, "image-feature-extraction": { "processor": AutoProcessor, "pipeline": ImageFeatureExtractionPipeline, "model": [AutoModelForImageFeatureExtraction, AutoModel], "default": { // TODO: replace with original // "model": "google/vit-base-patch16-224", "model": "Xenova/vit-base-patch16-224-in21k" }, "type": "image" } }); TASK_ALIASES = Object.freeze({ "sentiment-analysis": "text-classification", "ner": "token-classification", // "vqa": "visual-question-answering", // TODO: Add "asr": "automatic-speech-recognition", "text-to-speech": "text-to-audio", // Add for backwards compatibility "embeddings": "feature-extraction" }); } }); // node_modules/@xenova/transformers/src/transformers.js var init_transformers = __esm({ "node_modules/@xenova/transformers/src/transformers.js"() { init_pipelines(); init_env(); init_models(); init_tokenizers(); init_processors(); init_configs(); init_audio(); init_image(); init_tensor(); init_maths(); } }); // node_modules/gliner/node_modules/onnxruntime-web/dist/ort.bundle.min.mjs function Ie(i, e, o, t) { if (e === void 0) return Qd(i); if (o === void 0) dn(i, e, 1); else if (typeof o == "number" && t === void 0) dn(i, e, o); else if (typeof o == "string" && t === void 0) dn(i, o, 1, e); else if (typeof o == "string" && typeof t == "number") dn(i, o, t, e); else throw new TypeError("input is valid"); } function Qd(i) { return { verbose: Ie.verbose.bind(null, i), info: Ie.info.bind(null, i), warning: Ie.warning.bind(null, i), error: Ie.error.bind(null, i), fatal: Ie.fatal.bind(null, i) }; } function dn(i, e, o, t) { let r = Ar[t || ""] || Ar[""]; Es[i] < Es[r.minimalSeverity] || (r.logDateTime && (e = `${(/* @__PURE__ */ new Date()).toISOString()}|${e}`), r.logSourceLocation, Zd[r.provider].log(i, e, t)); } function Ls(i, e, o) { for (let t of o) { let r = t[0], n = t[1], s = t[2], a = t[3], u = t[4]; if (i.opType === r) { for (let l of e) if ((l.domain === n || l.domain === "ai.onnx" && n === "") && th(l.version, s)) return { opImpl: a, opInit: u }; } } throw new TypeError(`cannot resolve operator '${i.opType}' with opsets: ${e.map((t) => `${t.domain || "ai.onnx"} v${t.version}`).join(", ")}`); } function th(i, e) { if (e.endsWith("+")) { let o = Number.parseInt(e.substring(0, e.length - 1), 10); return !isNaN(o) && o <= i; } else if (e.split("-").length === 2) { let o = e.split("-"), t = Number.parseInt(o[0], 10), r = Number.parseInt(o[1], 10); return !isNaN(t) && !isNaN(r) && t <= i && i <= r; } else return Number.parseInt(e, 10) === i; } function rt(i, e, o) { this.low = i | 0, this.high = e | 0, this.unsigned = !!o; } function Pt(i) { return (i && i.__isLong__) === true; } function Bs(i) { var e = Math.clz32(i & -i); return i ? 31 - e : e; } function Ce(i, e) { var o, t, r; return e ? (i >>>= 0, (r = 0 <= i && i < 256) && (t = Cs[i], t) ? t : (o = J(i, 0, true), r && (Cs[i] = o), o)) : (i |= 0, (r = -128 <= i && i < 128) && (t = Fs[i], t) ? t : (o = J(i, i < 0 ? -1 : 0, false), r && (Fs[i] = o), o)); } function Vt(i, e) { if (isNaN(i)) return e ? he : Jt; if (e) { if (i < 0) return he; if (i >= Ms) return zs; } else { if (i <= -Rs) return Ft; if (i + 1 >= Rs) return Vs; } return i < 0 ? Vt(-i, e).neg() : J(i % ir | 0, i / ir | 0, e); } function J(i, e, o) { return new rt(i, e, o); } function Vo(i, e, o) { if (i.length === 0) throw Error("empty string"); if (typeof e == "number" ? (o = e, e = false) : e = !!e, i === "NaN" || i === "Infinity" || i === "+Infinity" || i === "-Infinity") return e ? he : Jt; if (o = o || 10, o < 2 || 36 < o) throw RangeError("radix"); var t; if ((t = i.indexOf("-")) > 0) throw Error("interior hyphen"); if (t === 0) return Vo(i.substring(1), e, o).neg(); for (var r = Vt(yn(o, 8)), n = Jt, s = 0; s < i.length; s += 8) { var a = Math.min(8, i.length - s), u = parseInt(i.substring(s, s + a), o); if (a < 8) { var l = Vt(yn(o, a)); n = n.mul(l).add(Vt(u)); } else n = n.mul(r), n = n.add(Vt(u)); } return n.unsigned = e, n; } function Yt(i, e) { return typeof i == "number" ? Vt(i, e) : typeof i == "string" ? Vo(i, e) : J(i.low, i.high, typeof e == "boolean" ? e : i.unsigned); } function ur(i, e) { if (!i) throw new Error(typeof e == "string" ? e : e()); } function kr(i) { return new TextDecoder().decode(i); } function ph(i) { switch (i) { case "bool": case "int8": case "uint8": return 1; case "int16": case "uint16": return 2; case "int32": case "uint32": case "float32": return 4; case "float64": return 8; default: throw new Error(`cannot calculate sizeof() on type ${i}`); } } function Vu(i) { switch (i) { case H.onnx.TensorProto.DataType.UINT8: case H.onnx.TensorProto.DataType.INT8: case H.onnx.TensorProto.DataType.BOOL: return 1; case H.onnx.TensorProto.DataType.UINT16: case H.onnx.TensorProto.DataType.INT16: return 2; case H.onnx.TensorProto.DataType.FLOAT: case H.onnx.TensorProto.DataType.INT32: case H.onnx.TensorProto.DataType.UINT32: return 4; case H.onnx.TensorProto.DataType.INT64: case H.onnx.TensorProto.DataType.DOUBLE: case H.onnx.TensorProto.DataType.UINT64: return 8; default: throw new Error(`cannot calculate sizeof() on type ${H.onnx.TensorProto.DataType[i]}`); } } function dh(i, e) { return new (Hu(e))(i); } function Hu(i) { switch (i) { case "bool": case "uint8": return Uint8Array; case "int8": return Int8Array; case "int16": return Int16Array; case "uint16": return Uint16Array; case "int32": return Int32Array; case "uint32": return Uint32Array; case "int64": return BigInt64Array; case "float32": return Float32Array; case "float64": return Float64Array; default: throw new Error("unspecified error"); } } function ii(i, e) { if (e === H.onnx.TensorProto.DataType.INT64 || e === oi.TensorDataType.INT64) { if (i.greaterThanOrEqual(2147483648) || i.lessThan(-2147483648)) throw new TypeError("int64 is not supported"); } else if (e === H.onnx.TensorProto.DataType.UINT32 || e === oi.TensorDataType.UINT32 || e === H.onnx.TensorProto.DataType.UINT64 || e === oi.TensorDataType.UINT64) { if (i.greaterThanOrEqual(4294967296) || i.lessThan(0)) throw new TypeError("uint64 is not supported"); } else throw new TypeError(`not a LONG type: ${H.onnx.TensorProto.DataType[e]}`); return i.toNumber(); } function zu(i, e, o) { switch (e) { case H.onnx.TensorProto.DataType.BOOL: case H.onnx.TensorProto.DataType.UINT8: return i.getUint8(o); case H.onnx.TensorProto.DataType.INT8: return i.getInt8(o); case H.onnx.TensorProto.DataType.UINT16: return i.getUint16(o, true); case H.onnx.TensorProto.DataType.INT16: return i.getInt16(o, true); case H.onnx.TensorProto.DataType.FLOAT: return i.getFloat32(o, true); case H.onnx.TensorProto.DataType.INT32: return i.getInt32(o, true); case H.onnx.TensorProto.DataType.UINT32: return i.getUint32(o, true); case H.onnx.TensorProto.DataType.INT64: return ii(me.fromBits(i.getUint32(o, true), i.getUint32(o + 4, true), false), e); case H.onnx.TensorProto.DataType.DOUBLE: return i.getFloat64(o, true); case H.onnx.TensorProto.DataType.UINT64: return ii(me.fromBits(i.getUint32(o, true), i.getUint32(o + 4, true), true), e); default: throw new Error(`cannot read from DataView for type ${H.onnx.TensorProto.DataType[e]}`); } } function G(i) { return i === 1 ? hh : mh; } function qu(i) { let e = G(i); return `${e.version} precision highp float; ${e.attribute} vec3 position; ${e.attribute} vec2 textureCoord; ${e.varyingVertex} vec2 TexCoords; void main() { gl_Position = vec4(position, 1.0); TexCoords = textureCoord; }`; } function ju(i) { let e = G(i); return `${e.version} precision highp float; precision highp int; precision highp sampler2D; ${e.varyingFrag} vec2 TexCoords; ${e.outputDeclaration} const vec2 halfCR = vec2(0.5, 0.5); // Custom vector types to handle higher dimenalities. struct ivec5 { int x; int y; int z; int w; int u; }; struct ivec6 { int x; int y; int z; int w; int u; int v; }; int imod(int x, int y) { return x - y * (x / y); } `; } function Xu(i, e) { let o = G(i); return ` void main() { int indices[${e}]; toVec(TexCoords, indices); vec4 result = vec4(process(indices)); ${o.output} = result; } `; } async function ai(i, e = (t) => 0, o) { return new Promise((t, r) => { let n = 0, s = () => { if (i()) { t(); return; } n++; let a = e(n); if (o != null && n >= o) { r(); return; } setTimeout(s, a); }; s(); }); } function On(i) { return ur(typeof i < "u" && i.length !== 0, () => "empty string found for sampler name"), "get" + i.charAt(0).toUpperCase() + i.slice(1); } function Ku(i) { return ur(typeof i < "u" && i.length !== 0, () => "empty string found for sampler name"), "get" + i.charAt(0).toUpperCase() + i.slice(1) + "AtOutCoords"; } function lr(i, e) { let o = JSON.parse(JSON.stringify(i)); return o = e, o; } function fr(i, e) { return e.map((o) => i[o]).join(", "); } function kt(i) { if (i <= 1) return "int"; if (i === 2) return "ivec2"; if (i === 3) return "ivec3"; if (i === 4) return "ivec4"; if (i === 5) return "ivec5"; if (i === 6) return "ivec6"; throw Error(`GPU for rank ${i} is not yet supported`); } function ee(i = 6) { return ["x", "y", "z", "w", "u", "v"].slice(0, i); } function bh(i, e) { return ee(e).map((o) => `${i}.${o}`); } function cr(i, e) { return e === 1 ? [i] : bh(i, e); } function le() { return ` float getChannel(vec4 frag, int dim) { int modCoord = imod(dim, 2); return modCoord == 0 ? frag.r : frag.g; } float getChannel(vec4 frag, vec2 innerDims) { vec2 modCoord = mod(innerDims, 2.); return modCoord.x == 0. ? (modCoord.y == 0. ? frag.r : frag.g) : (modCoord.y == 0. ? frag.b : frag.a); } `; } function yh(i, e, o) { if (i === 0) return "false"; if (i === 1) return `rc > ${e[0]}`; let t = ""; for (let r = i - 2; r < i; r++) t += `${o[r]} >= ${e[r - i + 2]}`, r < i - 1 && (t += "||"); return t; } function xh(i, e) { let o = i.length; if (o === 0) return "getA(), 0, 0, 0"; if (o === 1) return `getA(rc), rc + 1 >= ${i[0]} ? 0. : getA(rc + 1), 0, 0`; let t = "r, c", r = "r, cp1", n = "rp1, c", s = "rp1, cp1", a = ""; if (o > 2) for (let u = 0; u < o - 2; ++u) a = a + `${e[u]},`; return `getA(${a}${t}), rEdge ? 0. : getA(${a}${n}), cEdge ? 0. : getA(${a}${r}), rEdge || cEdge ? 0. : getA(${a}${s})`; } function Th(i, e, o, t) { return i === 0 || i === 1 ? "" : ` int r = ${e[i - 2]}; int c = ${e[i - 1]}; int rp1 = ${e[i - 2]} + 1; int cp1 = ${e[i - 1]} + 1; bool rEdge = rp1 >= ${t}; bool cEdge = cp1 >= ${o}; `; } function si(i) { if (i.length === 0) return [1, 1, 1]; let e = 1; for (let o = 0; o < i.length - 2; ++o) e *= i[o]; return [e, i.length > 1 ? i[i.length - 2] : 1, i[i.length - 1]]; } function tl(i, e) { let o = false; return i.length === 0 || e.length === 0 ? o = true : i.length < 2 || e.length < 2 ? o = i[i.length - 1] === e[e.length - 1] : o = i[i.length - 1] === e[e.length - 1] && i[i.length - 2] === e[e.length - 2], o; } function Ih(i) { let e = B.computeStrides(i), o = ["b", "r", "c"], t = "index"; return ` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${e.map((n, s) => { let a = `int ${o[s]} = ${t} / ${n}`, u = s === e.length - 1 ? `int ${o[s + 1]} = ${t} - ${o[s]} * ${n}` : `index -= ${o[s]} * ${n}`; return `${a}; ${u};`; }).join("")} return ivec3(b, r, c); } `; } function _h(i) { let e = B.computeStrides(i); return ` int getFlattenedIndex(ivec3 coords) { // reverse y, z order return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; } `; } function Sh(i, e) { if (i === 1) return "rc"; let o = ""; for (let t = 0; t < i; t++) o += e[t], t < i - 1 && (o += ","); return o; } function $h() { let i = "add_"; return { body: ` float ${i}(float a, float b) { return a + b; } vec4 ${i}(vec4 v1, vec4 v2) { return v1 + v2; } `, name: i, type: 0 }; } function kh() { let i = "div_"; return { body: ` float ${i}(float a, float b) { return a / b; } vec4 ${i}(vec4 v1, vec4 v2) { return v1 / v2; } `, name: i, type: 0 }; } function Bh() { let i = "mul_"; return { body: ` float ${i}(float a, float b) { return a * b; } vec4 ${i}(vec4 v1, vec4 v2) { return v1 * v2; } `, name: i, type: 0 }; } function Fh() { let i = "sub_"; return { body: ` float ${i}(float a, float b) { return a - b; } vec4 ${i}(vec4 v1, vec4 v2) { return v1 - v2; } `, name: i, type: 0 }; } function Ch() { let i = "equal_"; return { body: ` float ${i}(float a, float b) { return float(a == b); } vec4 ${i}(vec4 v1, vec4 v2) { return vec4(equal(v1, v2)); } `, name: i, type: 0 }; } function Nh() { let i = "greater_"; return { body: ` float ${i}(float a, float b) { return float(a > b); } vec4 ${i}(vec4 v1, vec4 v2) { return vec4( v1.r > v2.r , v1.g > v2.g, v1.b > v2.b, v1.a > v2.a ); } `, name: i, type: 0 }; } function Rh() { let i = "less_"; return { body: ` float ${i}(float a, float b) { return float(a < b); } vec4 ${i}(vec4 v1, vec4 v2) { return vec4( v1.r < v2.r , v1.g < v2.g, v1.b < v2.b, v1.a < v2.a ); } `, name: i, type: 0 }; } function Gh() { let i = "and_"; return { body: ` float ${i}(float a, float b) { return float( bool(a) && bool(b) ); } vec4 ${i}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r && b2.r , b1.g && b2.g, b1.b && b2.b, b1.a && b2.a ); } `, name: i, type: 0 }; } function Mh() { let i = "or_"; return { body: ` float ${i}(float a, float b) { return float( bool(a) || bool(b) ); } vec4 ${i}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r || b2.r , b1.g || b2.g, b1.b || b2.b, b1.a || b2.a ); } `, name: i, type: 0 }; } function Uh() { let i = "xor_"; return { body: ` float ${i}(float a, float b) { return float( bool(a) ^^ bool(b) ); } vec4 ${i}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r ^^ b2.r , b1.g ^^ b2.g, b1.b ^^ b2.b, b1.a ^^ b2.a ); } `, name: i, type: 0 }; } function Vh() { return Wh("pow"); } function zh() { let i = "prelu_"; return { body: ` float ${i}(float a, float b) { return a < 0.0 ? a * b: a; } vec4 ${i}(vec4 v1, vec4 v2) { return vec4( v1.r < 0.0 ? v1.r * v2.r: v1.r, v1.g < 0.0 ? v1.g * v2.g: v1.g, v1.b < 0.0 ? v1.b * v2.b: v1.b, v1.a < 0.0 ? v1.a * v2.a: v1.a ); } `, name: i, type: 0 }; } function Wh(i) { let e = `${i}_`; return { body: ` float ${e}(float a, float b) { return ${i}(a, b); } vec4 ${e}(vec4 v1, vec4 v2) { return ${i}(v1, v2); } `, name: e, type: 0 }; } function nm() { return qt("abs"); } function om() { return qt("acos"); } function im() { return qt("asin"); } function am() { return qt("atan"); } function sm() { return qt("ceil"); } function um() { return qt("cos"); } function lm(i) { let e = "elu"; return { body: ` const float alpha = float(${i}); float ${e}_(float a) { return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; } vec4 ${e}_(vec4 v) { return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); } `, name: e, type: 0 }; } function fm() { return qt("exp"); } function cm() { return qt("floor"); } function ci(i, e) { let o = "clip"; return { body: ` const float min = float(${i}); const float max = float(${e}); float ${o}_(float a) { return clamp(a, min, max); } vec4 ${o}_(vec4 v) { return clamp(v, min, max); } `, name: o, type: 0 }; } function pm() { let i = "indentity"; return { body: ` float ${i}_(float a) { return a; } vec4 ${i}_(vec4 v) { return v; } `, name: i, type: 0 }; } function dm(i) { let e = "leakyRelu"; return { body: ` const float alpha = float(${i}); float ${e}_(float a) { return a < 0.0 ? a * alpha : a; } vec4 ${e}_(vec4 v) { return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); } `, name: e, type: 0 }; } function hm() { return qt("log"); } function mm() { let i = "neg"; return { body: ` float ${i}_(float a) { return -a; } vec4 ${i}_(vec4 v) { return -v; } `, name: i, type: 0 }; } function bm() { let i = "not"; return { body: ` float ${i}_(float a) { return float( ! bool(a) ); } bool ${i}_(bool a) { return !a; } vec4 ${i}_(vec4 v) { return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); } bvec4 ${i}_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } `, name: i, type: 0 }; } function gm() { return qt("sin"); } function pi() { let i = "relu"; return { body: ` float ${i}_(float a) { return max( a, 0.0 ); } vec4 ${i}_(vec4 v) { return max( v, 0.0 ); } `, name: i, type: 0 }; } function di() { let i = "sigmoid"; return { body: ` float ${i}_(float a) { return 1.0 / (1.0 + exp(-a)); } vec4 ${i}_(vec4 v) { return 1.0 / (1.0 + exp(-v)); } `, name: i, type: 0 }; } function ym() { return qt("sqrt"); } function xm() { return qt("tan"); } function Tm() { let i = "tanh"; return { body: ` float ${i}_(float a) { a = clamp(a, -10., 10.); a = exp(2.*a); return (a - 1.) / (a + 1.); } vec4 ${i}_(vec4 v) { v = clamp(v, -10., 10.); v = exp(2.*v); return (v - 1.) / (v + 1.); } `, name: i, type: 0 }; } function qt(i) { return { body: ` float ${i}_(float a) { return ${i}(a); } vec4 ${i}_(vec4 v) { return ${i}(v); } `, name: i, type: 0 }; } function fe(i) { let e; switch (i.activation) { case "Relu": e = pi(); break; case "Sigmoid": e = di(); break; case "Clip": e = ci(i.clipMin, i.clipMax); break; default: return { activationFunction: "", applyActivation: "" }; } let o = e.name, t = e.body, r = `value = ${o}_(value);`; return { activationFunction: t, applyActivation: r }; } function Em(i, e, o) { let t = e[0].dims, r = e[1].dims, n = $t.calcShape(t, r, true); if (!n) throw new Error("Can't use matmul on the given tensors"); let s = kt(n.length), a = ee(), { activationFunction: u, applyActivation: l } = fe(o), f = e.length > 2, p = f ? "value += getBiasForMatmul();" : "", d = f ? `${yi(s, a, e[2].dims, n, false)}` : "", y = n.length, w = t.length, v = r.length, S = t[t.length - 1], L = ` ${u} ${d} float process(int indices[${y}]) { int a[${w}]; int b[${v}]; bcastMatmulIndices_A(indices, a); bcastMatmulIndices_B(indices, b); float value; for (int k=0; k<${S}; ++k) { a[${w - 1}] = k; b[${v - 2}] = k; value += _A(a) * _B(b); } ${p} ${l} return value; }`; return { ...i, output: { dims: n, type: e[0].type, textureType: 0 }, shaderSource: L }; } function gi(i, e) { let o = Pm(i.length > 2, e.activationCacheKey); return { ...o, get: () => Em(o, i, e) }; } function yi(i, e, o, t, r) { let n = "", s = o.length, a = t.length, u = a - s; a < 2 && s > 0 ? n = "coords" : n = o.map((v, S) => `coords.${e[S + u]}`).join(", "); let f = $t.getBroadcastDims(o, t).map((v) => `coords.${e[v + u]} = 0;`).join(` `), d = B.size(o) === 1, y = "vec4(outputValue.xx, outputValue.yy)"; return d && (y = "vec4(outputValue.x)"), r ? ` vec4 getBiasForMatmul() { ${i} coords = getOutputCoords(); ${f} vec4 outputValue = getBias(${n}); return ${y}; }` : ` float getBiasForMatmul() { ${i} coords = getOutputCoords(); ${f} return getBias(coords.x); }`; } function km(i, e, o, t) { let r = [], n = [], s = o[0].dims, a = o[1].dims, u = s.length, l = a.length, f = t.length, p = f - u, d = f - l; r = s.map((P2, M3) => `coords.${e[M3 + p]}`), r[u - 1] = "i*2", r.join(", "), n = a.map((P2, M3) => `coords.${e[M3 + d]}`), n[l - 2] = "i*2", n.join(", "); let y = $t.getBroadcastDims(s, t), w = $t.getBroadcastDims(a, t), v = y.map((P2) => `coords.${e[P2 + p]} = 0;`).join(` `), S = w.map((P2) => `coords.${e[P2 + d]} = 0;`).join(` `), L = `int lastDim = coords.${e[f - 1]}; coords.${e[f - 1]} = coords.${e[f - 2]}; coords.${e[f - 2]} = lastDim;`; return ` vec4 getAAtOutCoordsMatmul(int i) { ${i} coords = getOutputCoords(); ${L} ${v} vec4 outputValue = getA(${r}); return outputValue; } vec4 getBAtOutCoordsMatmul(int i) { ${i} coords = getOutputCoords(); ${L} ${S} vec4 outputValue = getB(${n}); return outputValue; }`; } function Bm(i, e) { let o = ""; for (let t = 0; t < e - 2; t++) o += `rc.${i[t]}, `; return o += `rc.${i[e - 2]}, i*2`, o; } function Fm(i, e) { let o = ""; for (let t = 0; t < e - 2; t++) o += `rc.${i[t]}, `; return o += `i*2, rc.${i[e - 1]}`, o; } function Ob(i, e) { let o = i[0].dims[1], t = i[0].dims.length, r = -Math.floor((e.size - 1) / 2), n = Math.ceil((e.size - 1) / 2), s = `float(${e.alpha}) / float(${e.size})`, a = `float(${e.bias})`, u = `float(${e.beta})`, l = ` float process(int indices[${t}]) { int c = indices[1]; float x = _X(indices); float square_sum = 0.0; for (int i = ${r}; i <= ${n}; i++) { int idx = c + i; if (c >= 0 && c < ${o}) { indices[1] = idx; float j = _X(indices); square_sum += j * j; } } return x / pow(${a} + ${s} * square_sum, ${u}); }`; return { ...Hf, cacheHint: e.cacheKey, output: { dims: i[0].dims, type: i[0].type, textureType: 0 }, shaderSource: l }; } function Sb(i, e) { return { ...Hf, cacheHint: e.cacheKey, get: () => Ob(i, e) }; } function ap(i) { let e = {}, o; for (; (o = ip.exec(i)) !== null; ) { let t = o[3].split(",").map((r) => { let n = r.trim().split(" "); return n && n.length === 2 ? { type: n[0], name: n[1] } : null; }).filter((r) => r !== null); e[o[2]] = { params: t, body: o[4] }; } for (let t in e) { let r = fg.replace("__FUNC__", t), n = new RegExp(r, "gm"); for (; (o = n.exec(i)) !== null; ) { let s = o[1], a = o[2], u = o[3].split(","), l = s ? `${s} ${a};` : "", f = e[t].body, p = ""; e[t].params.forEach((y, w) => { y && (p += `${y.type} ${y.name} = ${u[w]}; `); }), f = `${p} ${f}`, f = f.replace("return", `${a} = `); let d = ` ${l} { ${f} } `; i = i.replace(o[0], d); } } return i = i.replace(ip, ""), i; } function hr(i, e) { let o = [], t = [], r = e != null && Array.isArray(e) && e.length === 0, n = e == null || r ? null : cg(e, i).sort(), s = 0; for (let a = 0; a < i.length; ++a) { if (n != null) { if (n[s] === a && i[a] !== 1) throw new Error(`Can't squeeze axis ${a} since its dim '${i[a]}' is not 1`); (n[s] == null || n[s] > a) && i[a] === 1 && (o.push(i[a]), t.push(a)), n[s] <= a && s++; } i[a] !== 1 && (o.push(i[a]), t.push(a)); } return { newShape: o, keptDims: t }; } function cg(i, e) { let o = e.length; return i = i == null ? e.map((t, r) => r) : [].concat(i), ur(i.every((t) => t >= -o && t < o), () => `All values in axis param must be in range [-${o}, ${o}) but got axis ${i}`), ur(i.every(pg), () => `All values in axis param must be integers but got axis ${i}`), i.map((t) => t < 0 ? o + t : t); } function pg(i) { return i % 1 === 0; } function dg(i) { if (i.length === 0) return 1; let e = i[0]; for (let o = 1; o < i.length; o++) e *= i[o]; return e; } function up(i) { let e = Math.ceil(Math.sqrt(i)); return [e, Math.ceil(i / e)]; } function hg(i) { let e = 0; for (; e < i.length && i[e](); ++e) ; return e - 1; } function Ci(i) { let e; if ((!i || i === "webgl2") && "webgl2" in mr ? e = mr.webgl2 : (!i || i === "webgl") && "webgl" in mr && (e = mr.webgl), !e) try { let t = bg(); e = Tp(t, i); } catch { let r = mg(); e = Tp(r, i); } i = i || e.version === 1 ? "webgl" : "webgl2"; let o = e.gl; return mr[i] = e, o.isContextLost() ? (delete mr[i], Ci(i)) : (o.disable(o.DEPTH_TEST), o.disable(o.STENCIL_TEST), o.disable(o.BLEND), o.disable(o.DITHER), o.disable(o.POLYGON_OFFSET_FILL), o.disable(o.SAMPLE_COVERAGE), o.enable(o.SCISSOR_TEST), o.enable(o.CULL_FACE), o.cullFace(o.BACK), e); } function Tp(i, e) { let o = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false }, t, r = o; if ((!e || e === "webgl2") && (t = i.getContext("webgl2", r), t)) try { return new Mr(t, 2); } catch (n) { tt.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${n}`); } if ((!e || e === "webgl") && (t = i.getContext("webgl", r) || i.getContext("experimental-webgl", r), t)) try { return new Mr(t, 1); } catch (n) { tt.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${n}`); } throw new Error("WebGL is not supported"); } function mg() { if (typeof document > "u") throw new TypeError("failed to create canvas: document is not supported"); let i = document.createElement("canvas"); return i.width = 1, i.height = 1, i; } function bg() { if (typeof OffscreenCanvas > "u") throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported"); return new OffscreenCanvas(1, 1); } async function Ni(i) { if (i) { let e = typeof i == "string" ? [i] : i; for (let o of e) { let t = Ip.get(o); if (t) return t; let r = await yg(o); if (r) return r; } } else return Ni(["webgl"]); throw new Error("no available backend to use"); } async function yg(i) { let e = gg; if (typeof e[i] < "u" && xg(e[i])) { let o = e[i], t = o.initialize(); if (typeof t == "object" && "then" in t && (t = await t), t) return Ip.set(i, o), o; } } function xg(i) { let e = i; return "initialize" in e && typeof e.initialize == "function" && "createSessionHandler" in e && typeof e.createSessionHandler == "function" && "dispose" in e && typeof e.dispose == "function"; } var zd, nn, Wd, Hd, qd, jd, ko, O, mt, Or, Za, rr, on, an, $e, nr, Xd, sn, un, Qa, ts, es, rs, Rt, Bo, z, ns, os, is, as, Fo, ss, us, ls, fs3, cs, ke, Sr, ps, ds, hs, ms, bs, gs, Lt, ln, Tt, fn, ys, xs, Be, Fe, Co, cn, Ts, Kd, ws, vs, Is, _s, Os, Jd, pn, Ss, Yd, As, No, Kt, Ro, Go, Es, Zd, Ds, Ar, tt, mn, bn, gn, hn, Mt, $s, ks, Ut, Fs, Cs, yn, Ns, rh, ir, Ms, Rs, Gs, Jt, he, or, Us, Uo, Vs, zs, Ft, D, me, zo, T, xn, F, Pr, Hs, Ks, Ys, ou, iu, su, lu, cu, Oe, Zo, Tu, ei, Eu, Lu, ku, Fu, Ru, Mu, sr, ot, Ge, ni, $t, _n, _t, Nt, B, $r, Me, Ue, Ve, Y, Wu, H, oi, bt, ze, hh, mh, st, j, ue, We, Ju, gh, Yu, Zu, wh, vh, Qu, el, ui, rl, nl, Oh, ol, il, Sn, Br, An, Fr, Cr, al, li, sl, Ph, Pn, ll, fi, W, vt, fl, cl, pl, Eh, Dh, dl, En, Wt, k, Nr, Dn, be, Ht, Hh, hl, ml, bl, gl, yl, xl, Tl, wl, vl, Il, _l, Ol, Sl, Al, Pl, jh, El, Xh, Kh, Dl, Ln, Ll, $l, Jh, Yh, Zh, kl, Qh, tm, em, Bl, rm, Fl, wm, dt, Cl, Nl, Rl, Gl, hi, Ml, Ul, vm, Vl, zl, Wl, Hl, ql, jl, mi, Xl, Kl, Jl, Yl, Zl, Ql, tf, ef, rf, nf, of, bi, pr, He, _m, Om, af, sf, Sm, Am, uf, lf, ff, cf, Pm, Dm, kn, Lm, $m, Bn, xi, pf, df, Cm, Nm, hf, Ti, wi, Rm, Gm, mf, bf, dr, vi, Mm, Um, Vm, zm, Ii, Wm, $n, Hm, qm, jm, gf, Xm, Km, Jm, Ym, Zm, Qm, yf, tb, xf, Tf, qe, wf, eb, vf, rb, nb, ob, Fn, If2, _f, ib, Of, Sf, Af, ab, Pf, Ae, Rr, Ef, Df, sb, ub, lb, fb, Lf, _i, $f, kf, Bf, cb, pb, db, Ff, Cf, Nf, hb, mb, bb, gb, yb, Rf, Mf, Uf, Gf, xb, Tb, wb, vb, Ib, _b, Vf, zf, Wf, Hf, Ab, qf, Pb, Oi, jf, Xf, Kf, Eb, Db, Lb, $b, kb, Bb, Fb, Cb, Jf, Zf, Qf, tc, ec, rc, nc, oc, ic, ac, Nb, Yf, sc, Nn, uc, Cn, Rb, lc, je, Pe, Gb, Mb, fc, cc, pc, dc, hc, mc, bc, gc, yc, xc, Tc, Si, wc, vc, Gr, Ub, Ai, Rn, Pi, Ei, Di, Ic, _c, Vb, zb, Wb, Hb, Oc, Sc, qb, Ac, Li, Pc, Ec, Dc, jb, Lc, Xb, Kb, $c, kc, Bc, Fc, Cc, Nc, Rc, Gc, Mc, Jb, Yb, Zb, Uc, Vc, zc, Wc, Hc, Qb, tg, eg, qc, $i, jc, Xc, rg, ng, Kc, Jc, og, ig, Yc, Zc, ag, sg, Qc, ki, tp, ep, ug, lg, rp, np, op, ip, fg, sp, Gn, Bi, Mn, lp, Un, fp, Vn, cp, zn, pp, Wn, dp, Fi, hp, Hn, mp, qn, bp, jn, gp, Xn, yp, Mr, xp, mr, wp, Kn, vp, Ip, gg, _p, Ri, Jn, Op, q, jt, Ur, Sp, Mi, Yn, Ui, ce, Zn, Gi, Ap, Pp, Tg, Qn, Ep, to, Dp, eo, Lp, $p, Vi, wg, kp, ro, Cp, Bp, Fp, vg, Np, Gp, Wi, Rp, Ig, Mp, br, _g, Og, Sg, Up, Vp, Ag, zp, Vr, Hi, qi, co, Wp, Pg, Eg, no, gt, Xe, yt, Wr, ht, po, Hp, qp, Dg, Lg, $g, kg, jp, Xp, ji, Kp, Xi, Jp, Yp, ho, Zp, Ki, Hr, Ji, Bg, oo, io, yr, Fg, zr, ao, so, Qp, uo, lo, fo, zi, Ke, Xt, qr, bo, go, mo, Yi, Zi, xr, Tr, Ng, td, ed, rd, nd, od, id, ad, Qi, sd, Rg, yo, ud, Gg, xo, ld, fd, Mg, cd, Ps, bO; var init_ort_bundle_min = __esm({ "node_modules/gliner/node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"() { zd = Object.create; nn = Object.defineProperty; Wd = Object.getOwnPropertyDescriptor; Hd = Object.getOwnPropertyNames; qd = Object.getPrototypeOf; jd = Object.prototype.hasOwnProperty; ko = ((i) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(i, { get: (e, o) => (typeof __require < "u" ? __require : e)[o] }) : i)(function(i) { if (typeof __require < "u") return __require.apply(this, arguments); throw Error('Dynamic require of "' + i + '" is not supported'); }); O = (i, e) => () => (i && (e = i(i = 0)), e); mt = (i, e) => () => (e || i((e = { exports: {} }).exports, e), e.exports); Or = (i, e) => { for (var o in e) nn(i, o, { get: e[o], enumerable: true }); }; Za = (i, e, o, t) => { if (e && typeof e == "object" || typeof e == "function") for (let r of Hd(e)) !jd.call(i, r) && r !== o && nn(i, r, { get: () => e[r], enumerable: !(t = Wd(e, r)) || t.enumerable }); return i; }; rr = (i, e, o) => (o = i != null ? zd(qd(i)) : {}, Za(e || !i || !i.__esModule ? nn(o, "default", { value: i, enumerable: true }) : o, i)); on = (i) => Za(nn({}, "__esModule", { value: true }), i); un = O(() => { "use strict"; an = /* @__PURE__ */ new Map(), $e = [], nr = (i, e, o) => { if (e && typeof e.init == "function" && typeof e.createInferenceSessionHandler == "function") { let t = an.get(i); if (t === void 0) an.set(i, { backend: e, priority: o }); else { if (t.priority > o) return; if (t.priority === o && t.backend !== e) throw new Error(`cannot register backend "${i}" using priority ${o}`); } if (o >= 0) { let r = $e.indexOf(i); r !== -1 && $e.splice(r, 1); for (let n = 0; n < $e.length; n++) if (an.get($e[n]).priority <= o) { $e.splice(n, 0, i); return; } $e.push(i); } return; } throw new TypeError("not a valid backend"); }, Xd = async (i) => { let e = an.get(i); if (!e) return "backend not found."; if (e.initialized) return e.backend; if (e.aborted) return e.error; { let o = !!e.initPromise; try { return o || (e.initPromise = e.backend.init(i)), await e.initPromise, e.initialized = true, e.backend; } catch (t) { return o || (e.error = `${t}`, e.aborted = true), e.error; } finally { delete e.initPromise; } } }, sn = async (i) => { let e = i.executionProviders || [], o = e.map((u) => typeof u == "string" ? u : u.name), t = o.length === 0 ? $e : o, r, n = [], s = /* @__PURE__ */ new Set(); for (let u of t) { let l = await Xd(u); typeof l == "string" ? n.push({ name: u, err: l }) : (r || (r = l), r === l && s.add(u)); } if (!r) throw new Error(`no available backend found. ERR: ${n.map((u) => `[${u.name}] ${u.err}`).join(", ")}`); for (let { name: u, err: l } of n) o.includes(u) && console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${l}`); let a = e.filter((u) => s.has(typeof u == "string" ? u : u.name)); return [r, new Proxy(i, { get: (u, l) => l === "executionProviders" ? a : Reflect.get(u, l) })]; }; }); Qa = O(() => { "use strict"; un(); }); es = O(() => { "use strict"; ts = "1.19.2"; }); Bo = O(() => { "use strict"; es(); rs = "warning", Rt = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: ts }, set logLevel(i) { if (i !== void 0) { if (typeof i != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(i) === -1) throw new Error(`Unsupported logging level: ${i}`); rs = i; } }, get logLevel() { return rs; } }; Object.defineProperty(Rt, "logLevel", { enumerable: true }); }); ns = O(() => { "use strict"; Bo(); z = Rt; }); as = O(() => { "use strict"; os = (i, e) => { let o = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); o.width = i.dims[3], o.height = i.dims[2]; let t = o.getContext("2d"); if (t != null) { let r, n; e?.tensorLayout !== void 0 && e.tensorLayout === "NHWC" ? (r = i.dims[2], n = i.dims[3]) : (r = i.dims[3], n = i.dims[2]); let s = e?.format !== void 0 ? e.format : "RGB", a = e?.norm, u, l; a === void 0 || a.mean === void 0 ? u = [255, 255, 255, 255] : typeof a.mean == "number" ? u = [a.mean, a.mean, a.mean, a.mean] : (u = [a.mean[0], a.mean[1], a.mean[2], 0], a.mean[3] !== void 0 && (u[3] = a.mean[3])), a === void 0 || a.bias === void 0 ? l = [0, 0, 0, 0] : typeof a.bias == "number" ? l = [a.bias, a.bias, a.bias, a.bias] : (l = [a.bias[0], a.bias[1], a.bias[2], 0], a.bias[3] !== void 0 && (l[3] = a.bias[3])); let f = n * r, p = 0, d = f, y = f * 2, w = -1; s === "RGBA" ? (p = 0, d = f, y = f * 2, w = f * 3) : s === "RGB" ? (p = 0, d = f, y = f * 2) : s === "RBG" && (p = 0, y = f, d = f * 2); for (let v = 0; v < n; v++) for (let S = 0; S < r; S++) { let L = (i.data[p++] - l[0]) * u[0], A2 = (i.data[d++] - l[1]) * u[1], P2 = (i.data[y++] - l[2]) * u[2], M3 = w === -1 ? 255 : (i.data[w++] - l[3]) * u[3]; t.fillStyle = "rgba(" + L + "," + A2 + "," + P2 + "," + M3 + ")", t.fillRect(S, v, 1, 1); } if ("toDataURL" in o) return o.toDataURL(); throw new Error("toDataURL is not supported"); } else throw new Error("Can not access image data"); }, is = (i, e) => { let o = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), t; if (o != null) { let r, n, s; e?.tensorLayout !== void 0 && e.tensorLayout === "NHWC" ? (r = i.dims[2], n = i.dims[1], s = i.dims[3]) : (r = i.dims[3], n = i.dims[2], s = i.dims[1]); let a = e !== void 0 && e.format !== void 0 ? e.format : "RGB", u = e?.norm, l, f; u === void 0 || u.mean === void 0 ? l = [255, 255, 255, 255] : typeof u.mean == "number" ? l = [u.mean, u.mean, u.mean, u.mean] : (l = [u.mean[0], u.mean[1], u.mean[2], 255], u.mean[3] !== void 0 && (l[3] = u.mean[3])), u === void 0 || u.bias === void 0 ? f = [0, 0, 0, 0] : typeof u.bias == "number" ? f = [u.bias, u.bias, u.bias, u.bias] : (f = [u.bias[0], u.bias[1], u.bias[2], 0], u.bias[3] !== void 0 && (f[3] = u.bias[3])); let p = n * r; if (e !== void 0 && (e.format !== void 0 && s === 4 && e.format !== "RGBA" || s === 3 && e.format !== "RGB" && e.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); let d = 4, y = 0, w = 1, v = 2, S = 3, L = 0, A2 = p, P2 = p * 2, M3 = -1; a === "RGBA" ? (L = 0, A2 = p, P2 = p * 2, M3 = p * 3) : a === "RGB" ? (L = 0, A2 = p, P2 = p * 2) : a === "RBG" && (L = 0, P2 = p, A2 = p * 2), t = o.createImageData(r, n); for (let V3 = 0; V3 < n * r; y += d, w += d, v += d, S += d, V3++) t.data[y] = (i.data[L++] - f[0]) * l[0], t.data[w] = (i.data[A2++] - f[1]) * l[1], t.data[v] = (i.data[P2++] - f[2]) * l[2], t.data[S] = M3 === -1 ? 255 : (i.data[M3++] - f[3]) * l[3]; } else throw new Error("Can not access image data"); return t; }; }); cs = O(() => { "use strict"; ln(); Fo = (i, e) => { if (i === void 0) throw new Error("Image buffer must be defined"); if (e.height === void 0 || e.width === void 0) throw new Error("Image height and width must be defined"); if (e.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet"); let { height: o, width: t } = e, r = e.norm ?? { mean: 255, bias: 0 }, n, s; typeof r.mean == "number" ? n = [r.mean, r.mean, r.mean, r.mean] : n = [r.mean[0], r.mean[1], r.mean[2], r.mean[3] ?? 255], typeof r.bias == "number" ? s = [r.bias, r.bias, r.bias, r.bias] : s = [r.bias[0], r.bias[1], r.bias[2], r.bias[3] ?? 0]; let a = e.format !== void 0 ? e.format : "RGBA", u = e.tensorFormat !== void 0 && e.tensorFormat !== void 0 ? e.tensorFormat : "RGB", l = o * t, f = u === "RGBA" ? new Float32Array(l * 4) : new Float32Array(l * 3), p = 4, d = 0, y = 1, w = 2, v = 3, S = 0, L = l, A2 = l * 2, P2 = -1; a === "RGB" && (p = 3, d = 0, y = 1, w = 2, v = -1), u === "RGBA" ? P2 = l * 3 : u === "RBG" ? (S = 0, A2 = l, L = l * 2) : u === "BGR" && (A2 = 0, L = l, S = l * 2); for (let V3 = 0; V3 < l; V3++, d += p, w += p, y += p, v += p) f[S++] = (i[d] + s[0]) / n[0], f[L++] = (i[y] + s[1]) / n[1], f[A2++] = (i[w] + s[2]) / n[2], P2 !== -1 && v !== -1 && (f[P2++] = (i[v] + s[3]) / n[3]); return u === "RGBA" ? new Lt("float32", f, [1, 4, o, t]) : new Lt("float32", f, [1, 3, o, t]); }, ss = async (i, e) => { let o = typeof HTMLImageElement < "u" && i instanceof HTMLImageElement, t = typeof ImageData < "u" && i instanceof ImageData, r = typeof ImageBitmap < "u" && i instanceof ImageBitmap, n = typeof i == "string", s, a = e ?? {}, u = () => { if (typeof document < "u") return document.createElement("canvas"); if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); throw new Error("Canvas is not supported"); }, l = (f) => f instanceof HTMLCanvasElement || f instanceof OffscreenCanvas ? f.getContext("2d") : null; if (o) { let f = u(); f.width = i.width, f.height = i.height; let p = l(f); if (p != null) { let d = i.height, y = i.width; if (e !== void 0 && e.resizedHeight !== void 0 && e.resizedWidth !== void 0 && (d = e.resizedHeight, y = e.resizedWidth), e !== void 0) { if (a = e, e.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); a.tensorFormat = "RGBA", a.height = d, a.width = y; } else a.tensorFormat = "RGBA", a.height = d, a.width = y; p.drawImage(i, 0, 0), s = p.getImageData(0, 0, y, d).data; } else throw new Error("Can not access image data"); } else if (t) { let f, p; if (e !== void 0 && e.resizedWidth !== void 0 && e.resizedHeight !== void 0 ? (f = e.resizedHeight, p = e.resizedWidth) : (f = i.height, p = i.width), e !== void 0 && (a = e), a.format = "RGBA", a.height = f, a.width = p, e !== void 0) { let d = u(); d.width = p, d.height = f; let y = l(d); if (y != null) y.putImageData(i, 0, 0), s = y.getImageData(0, 0, p, f).data; else throw new Error("Can not access image data"); } else s = i.data; } else if (r) { if (e === void 0) throw new Error("Please provide image config with format for Imagebitmap"); let f = u(); f.width = i.width, f.height = i.height; let p = l(f); if (p != null) { let d = i.height, y = i.width; return p.drawImage(i, 0, 0, y, d), s = p.getImageData(0, 0, y, d).data, a.height = d, a.width = y, Fo(s, a); } else throw new Error("Can not access image data"); } else { if (n) return new Promise((f, p) => { let d = u(), y = l(d); if (!i || !y) return p(); let w = new Image(); w.crossOrigin = "Anonymous", w.src = i, w.onload = () => { d.width = w.width, d.height = w.height, y.drawImage(w, 0, 0, d.width, d.height); let v = y.getImageData(0, 0, d.width, d.height); a.height = d.height, a.width = d.width, f(Fo(v.data, a)); }; }); throw new Error("Input data provided is not supported - aborted tensor creation"); } if (s !== void 0) return Fo(s, a); throw new Error("Input data provided is not supported - aborted tensor creation"); }, us = (i, e) => { let { width: o, height: t, download: r, dispose: n } = e, s = [1, t, o, 4]; return new Lt({ location: "texture", type: "float32", texture: i, dims: s, download: r, dispose: n }); }, ls = (i, e) => { let { dataType: o, dims: t, download: r, dispose: n } = e; return new Lt({ location: "gpu-buffer", type: o ?? "float32", gpuBuffer: i, dims: t, download: r, dispose: n }); }, fs3 = (i, e, o) => new Lt({ location: "cpu-pinned", type: i, data: e, dims: o ?? [e.length] }); }); hs = O(() => { "use strict"; ke = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), Sr = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), ps = false, ds = () => { if (!ps) { ps = true; let i = typeof BigInt64Array < "u" && BigInt64Array.from, e = typeof BigUint64Array < "u" && BigUint64Array.from, o = typeof Float16Array < "u" && Float16Array.from; i && (ke.set("int64", BigInt64Array), Sr.set(BigInt64Array, "int64")), e && (ke.set("uint64", BigUint64Array), Sr.set(BigUint64Array, "uint64")), o ? (ke.set("float16", Float16Array), Sr.set(Float16Array, "float16")) : ke.set("float16", Uint16Array); } }; }); gs = O(() => { "use strict"; ln(); ms = (i) => { let e = 1; for (let o = 0; o < i.length; o++) { let t = i[o]; if (typeof t != "number" || !Number.isSafeInteger(t)) throw new TypeError(`dims[${o}] must be an integer, got: ${t}`); if (t < 0) throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${t}`); e *= t; } return e; }, bs = (i, e) => { switch (i.location) { case "cpu": return new Lt(i.type, i.data, e); case "cpu-pinned": return new Lt({ location: "cpu-pinned", data: i.data, type: i.type, dims: e }); case "texture": return new Lt({ location: "texture", texture: i.texture, type: i.type, dims: e }); case "gpu-buffer": return new Lt({ location: "gpu-buffer", gpuBuffer: i.gpuBuffer, type: i.type, dims: e }); default: throw new Error(`tensorReshape: tensor location ${i.location} is not supported`); } }; }); ln = O(() => { "use strict"; as(); cs(); hs(); gs(); Lt = class { constructor(e, o, t) { ds(); let r, n; if (typeof e == "object" && "location" in e) switch (this.dataLocation = e.location, r = e.type, n = e.dims, e.location) { case "cpu-pinned": { let a = ke.get(r); if (!a) throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`); if (!(e.data instanceof a)) throw new TypeError(`buffer should be of type ${a.name}`); this.cpuData = e.data; break; } case "texture": { if (r !== "float32") throw new TypeError(`unsupported type "${r}" to create tensor from texture`); this.gpuTextureData = e.texture, this.downloader = e.download, this.disposer = e.dispose; break; } case "gpu-buffer": { if (r !== "float32" && r !== "float16" && r !== "int32" && r !== "int64" && r !== "uint32" && r !== "uint8" && r !== "bool") throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`); this.gpuBufferData = e.gpuBuffer, this.downloader = e.download, this.disposer = e.dispose; break; } default: throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); } else { let a, u; if (typeof e == "string") if (r = e, u = t, e === "string") { if (!Array.isArray(o)) throw new TypeError("A string tensor's data must be a string array."); a = o; } else { let l = ke.get(e); if (l === void 0) throw new TypeError(`Unsupported tensor type: ${e}.`); if (Array.isArray(o)) { if (e === "float16" && l === Uint16Array) throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data."); e === "uint64" || e === "int64" ? a = l.from(o, BigInt) : a = l.from(o); } else if (o instanceof l) a = o; else throw new TypeError(`A ${r} tensor's data must be type of ${l}`); } else if (u = o, Array.isArray(e)) { if (e.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); let l = typeof e[0]; if (l === "string") r = "string", a = e; else if (l === "boolean") r = "bool", a = Uint8Array.from(e); else throw new TypeError(`Invalid element type of data array: ${l}.`); } else { let l = Sr.get(e.constructor); if (l === void 0) throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`); r = l, a = e; } if (u === void 0) u = [a.length]; else if (!Array.isArray(u)) throw new TypeError("A tensor's dims must be a number array"); n = u, this.cpuData = a, this.dataLocation = "cpu"; } let s = ms(n); if (this.cpuData && s !== this.cpuData.length) throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`); this.type = r, this.dims = n, this.size = s; } static async fromImage(e, o) { return ss(e, o); } static fromTexture(e, o) { return us(e, o); } static fromGpuBuffer(e, o) { return ls(e, o); } static fromPinnedBuffer(e, o, t) { return fs3(e, o, t); } toDataURL(e) { return os(this, e); } toImageData(e) { return is(this, e); } get data() { if (this.ensureValid(), !this.cpuData) throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly."); return this.cpuData; } get location() { return this.dataLocation; } get texture() { if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture."); return this.gpuTextureData; } get gpuBuffer() { if (this.ensureValid(), !this.gpuBufferData) throw new Error("The data is not stored as a WebGPU buffer."); return this.gpuBufferData; } async getData(e) { switch (this.ensureValid(), this.dataLocation) { case "cpu": case "cpu-pinned": return this.data; case "texture": case "gpu-buffer": { if (!this.downloader) throw new Error("The current tensor is not created with a specified data downloader."); if (this.isDownloading) throw new Error("The current tensor is being downloaded."); try { this.isDownloading = true; let o = await this.downloader(); return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = o, e && this.disposer && (this.disposer(), this.disposer = void 0), o; } finally { this.isDownloading = false; } } default: throw new Error(`cannot get data from location: ${this.dataLocation}`); } } dispose() { if (this.isDownloading) throw new Error("The current tensor is being downloaded."); this.disposer && (this.disposer(), this.disposer = void 0), this.cpuData = void 0, this.gpuTextureData = void 0, this.gpuBufferData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none"; } ensureValid() { if (this.dataLocation === "none") throw new Error("The tensor is disposed."); } reshape(e) { if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource."); return bs(this, e); } }; }); fn = O(() => { "use strict"; ln(); Tt = Lt; }); Co = O(() => { "use strict"; Bo(); ys = (i, e) => { (typeof Rt.trace > "u" ? !Rt.wasm.trace : !Rt.trace) || console.timeStamp(`${i}::ORT::${e}`); }, xs = (i, e) => { let o = new Error().stack?.split(/\r\n|\r|\n/g) || [], t = false; for (let r = 0; r < o.length; r++) { if (t && !o[r].includes("TRACE_FUNC")) { let n = `FUNC_${i}::${o[r].trim().split(" ")[1]}`; e && (n += `::${e}`), ys("CPU", n); return; } o[r].includes("TRACE_FUNC") && (t = true); } }, Be = (i) => { (typeof Rt.trace > "u" ? !Rt.wasm.trace : !Rt.trace) || xs("BEGIN", i); }, Fe = (i) => { (typeof Rt.trace > "u" ? !Rt.wasm.trace : !Rt.trace) || xs("END", i); }; }); Ts = O(() => { "use strict"; un(); fn(); Co(); cn = class i { constructor(e) { this.handler = e; } async run(e, o, t) { Be(); let r = {}, n = {}; if (typeof e != "object" || e === null || e instanceof Tt || Array.isArray(e)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let s = true; if (typeof o == "object") { if (o === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (o instanceof Tt) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(o)) { if (o.length === 0) throw new TypeError("'fetches' cannot be an empty array."); s = false; for (let l of o) { if (typeof l != "string") throw new TypeError("'fetches' must be a string array or an object."); if (this.outputNames.indexOf(l) === -1) throw new RangeError(`'fetches' contains invalid output name: ${l}.`); r[l] = null; } if (typeof t == "object" && t !== null) n = t; else if (typeof t < "u") throw new TypeError("'options' must be an object."); } else { let l = false, f = Object.getOwnPropertyNames(o); for (let p of this.outputNames) if (f.indexOf(p) !== -1) { let d = o[p]; (d === null || d instanceof Tt) && (l = true, s = false, r[p] = d); } if (l) { if (typeof t == "object" && t !== null) n = t; else if (typeof t < "u") throw new TypeError("'options' must be an object."); } else n = o; } } else if (typeof o < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let l of this.inputNames) if (typeof e[l] > "u") throw new Error(`input '${l}' is missing in 'feeds'.`); if (s) for (let l of this.outputNames) r[l] = null; let a = await this.handler.run(e, r, n), u = {}; for (let l in a) if (Object.hasOwnProperty.call(a, l)) { let f = a[l]; f instanceof Tt ? u[l] = f : u[l] = new Tt(f.type, f.data, f.dims); } return Fe(), u; } async release() { return this.handler.dispose(); } static async create(e, o, t, r) { Be(); let n, s = {}; if (typeof e == "string") { if (n = e, typeof o == "object" && o !== null) s = o; else if (typeof o < "u") throw new TypeError("'options' must be an object."); } else if (e instanceof Uint8Array) { if (n = e, typeof o == "object" && o !== null) s = o; else if (typeof o < "u") throw new TypeError("'options' must be an object."); } else if (e instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && e instanceof SharedArrayBuffer) { let f = e, p = 0, d = e.byteLength; if (typeof o == "object" && o !== null) s = o; else if (typeof o == "number") { if (p = o, !Number.isSafeInteger(p)) throw new RangeError("'byteOffset' must be an integer."); if (p < 0 || p >= f.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${f.byteLength}).`); if (d = e.byteLength - p, typeof t == "number") { if (d = t, !Number.isSafeInteger(d)) throw new RangeError("'byteLength' must be an integer."); if (d <= 0 || p + d > f.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${f.byteLength - p}].`); if (typeof r == "object" && r !== null) s = r; else if (typeof r < "u") throw new TypeError("'options' must be an object."); } else if (typeof t < "u") throw new TypeError("'byteLength' must be a number."); } else if (typeof o < "u") throw new TypeError("'options' must be an object."); n = new Uint8Array(f, p, d); } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); let [a, u] = await sn(s), l = await a.createInferenceSessionHandler(n, u); return Fe(), new i(l); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } }; }); ws = O(() => { "use strict"; Ts(); Kd = cn; }); vs = O(() => { "use strict"; }); Is = O(() => { "use strict"; }); _s = O(() => { "use strict"; }); Os = O(() => { "use strict"; }); Ss = O(() => { "use strict"; un(); fn(); Jd = "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.", pn = class i { constructor(e, o, t) { this.handler = e, this.hasOptimizerModel = o, this.hasEvalModel = t; } get trainingInputNames() { return this.handler.inputNames; } get trainingOutputNames() { return this.handler.outputNames; } get evalInputNames() { if (this.hasEvalModel) return this.handler.evalInputNames; throw new Error("This training session has no evalModel loaded."); } get evalOutputNames() { if (this.hasEvalModel) return this.handler.evalOutputNames; throw new Error("This training session has no evalModel loaded."); } static async create(e, o) { let t = e.evalModel || "", r = e.optimizerModel || "", n = o || {}, [s, a] = await sn(n); if (s.createTrainingSessionHandler) { let u = await s.createTrainingSessionHandler(e.checkpointState, e.trainModel, t, r, a); return new i(u, !!e.optimizerModel, !!e.evalModel); } else throw new Error(Jd); } typeNarrowingForRunStep(e, o, t, r, n) { let s = {}, a = {}; if (typeof t != "object" || t === null || t instanceof Tt || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let u = true; if (typeof r == "object") { if (r === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (r instanceof Tt) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(r)) { if (r.length === 0) throw new TypeError("'fetches' cannot be an empty array."); u = false; for (let l of r) { if (typeof l != "string") throw new TypeError("'fetches' must be a string array or an object."); if (o.indexOf(l) === -1) throw new RangeError(`'fetches' contains invalid output name: ${l}.`); s[l] = null; } if (typeof n == "object" && n !== null) a = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else { let l = false, f = Object.getOwnPropertyNames(r); for (let p of o) if (f.indexOf(p) !== -1) { let d = r[p]; (d === null || d instanceof Tt) && (l = true, u = false, s[p] = d); } if (l) { if (typeof n == "object" && n !== null) a = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else a = r; } } else if (typeof r < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let l of e) if (typeof t[l] > "u") throw new Error(`input '${l}' is missing in 'feeds'.`); if (u) for (let l of o) s[l] = null; return [s, a]; } convertHandlerReturnTypeToMapOfTensors(e) { let o = {}; for (let t in e) if (Object.hasOwnProperty.call(e, t)) { let r = e[t]; r instanceof Tt ? o[t] = r : o[t] = new Tt(r.type, r.data, r.dims); } return o; } async lazyResetGrad() { await this.handler.lazyResetGrad(); } async runTrainStep(e, o, t) { let [r, n] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, e, o, t), s = await this.handler.runTrainStep(e, r, n); return this.convertHandlerReturnTypeToMapOfTensors(s); } async runOptimizerStep(e) { if (this.hasOptimizerModel) await this.handler.runOptimizerStep(e || {}); else throw new Error("This TrainingSession has no OptimizerModel loaded."); } async runEvalStep(e, o, t) { if (this.hasEvalModel) { let [r, n] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, e, o, t), s = await this.handler.runEvalStep(e, r, n); return this.convertHandlerReturnTypeToMapOfTensors(s); } else throw new Error("This TrainingSession has no EvalModel loaded."); } async getParametersSize(e = true) { return this.handler.getParametersSize(e); } async loadParametersBuffer(e, o = true) { let t = await this.getParametersSize(o); if (e.length !== 4 * t) throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check."); return this.handler.loadParametersBuffer(e, o); } async getContiguousParameters(e = true) { return this.handler.getContiguousParameters(e); } async release() { return this.handler.dispose(); } }; }); As = O(() => { "use strict"; Ss(); Yd = pn; }); No = {}; Or(No, { InferenceSession: () => Kd, TRACE: () => ys, TRACE_FUNC_BEGIN: () => Be, TRACE_FUNC_END: () => Fe, Tensor: () => Tt, TrainingSession: () => Yd, env: () => z, registerBackend: () => nr }); Kt = O(() => { "use strict"; Qa(); ns(); ws(); fn(); vs(); Is(); Co(); _s(); Os(); As(); }); Mt = O(() => { "use strict"; Ro = class { log(e, o, t) { } }, Go = class { log(e, o, t) { console.log(`${this.color(e)} ${t ? "\x1B[35m" + t + "\x1B[0m " : ""}${o}`); } color(e) { switch (e) { case "verbose": return "\x1B[34;40mv\x1B[0m"; case "info": return "\x1B[32mi\x1B[0m"; case "warning": return "\x1B[30;43mw\x1B[0m"; case "error": return "\x1B[31;40me\x1B[0m"; case "fatal": return "\x1B[101mf\x1B[0m"; default: throw new Error(`unsupported severity: ${e}`); } } }, Es = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, Zd = { none: new Ro(), console: new Go() }, Ds = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false }, Ar = { "": Ds }; ((u) => { function i(l, f) { u("verbose", l, f); } u.verbose = i; function e(l, f) { u("info", l, f); } u.info = e; function o(l, f) { u("warning", l, f); } u.warning = o; function t(l, f) { u("error", l, f); } u.error = t; function r(l, f) { u("fatal", l, f); } u.fatal = r; function n(l) { Ar = {}, s("", l || {}); } u.reset = n; function s(l, f) { if (l === "*") n(f); else { let p = Ar[l] || Ds; Ar[l] = { provider: f.provider || p.provider, minimalSeverity: f.minimalSeverity || p.minimalSeverity, logDateTime: f.logDateTime === void 0 ? p.logDateTime : f.logDateTime, logSourceLocation: f.logSourceLocation === void 0 ? p.logSourceLocation : f.logSourceLocation }; } } u.set = s; function a(l) { let f = {}; l.logLevel && (f.minimalSeverity = l.logLevel), s("", f); } u.setWithEnv = a; })(Ie ||= {}); tt = Ie, mn = class { constructor(e, o, t, r, n, s) { this.category = e; this.name = o; this.startTime = t; this.endCallback = r; this.timer = n; this.ctx = s; } async end() { return this.endCallback(this); } async checkTimer() { if (this.ctx === void 0 || this.timer === void 0) throw new Error("No webgl timer found"); return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer); } }, bn = class { constructor(e, o, t, r) { this.category = e; this.name = o; this.startTime = t; this.endTime = r; } }, gn = class { constructor(e, o, t) { this._started = false; this._flushPointer = 0; this._started = false, this._maxNumberEvents = e === void 0 ? 1e4 : e, this._flushBatchSize = o === void 0 ? 10 : o, this._flushIntervalInMilliseconds = t === void 0 ? 5e3 : t; } static create(e) { return e === void 0 ? new this() : new this(e.maxNumberEvents, e.flushBatchSize, e.flushIntervalInMilliseconds); } start() { this._started = true, this._timingEvents = [], this._flushTime = hn(), this._flushPointer = 0; } stop() { for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); } event(e, o, t, r) { let n = this._started ? this.begin(e, o, r) : void 0, s = false, a = t(); if (a && typeof a.then == "function") return s = true, new Promise((u, l) => { a.then(async (f) => { n && await n.end(), u(f); }, async (f) => { n && await n.end(), l(f); }); }); if (!s && n) { let u = n.end(); if (u && typeof u.then == "function") return new Promise((l, f) => { u.then(() => { l(a); }, (p) => { f(p); }); }); } return a; } begin(e, o, t) { if (!this._started) throw new Error("profiler is not started yet"); if (t === void 0) { let r = hn(); return this.flush(r), new mn(e, o, r, (n) => this.endSync(n)); } else { let r = t.beginTimer(); return new mn(e, o, 0, async (n) => this.end(n), r, t); } } async end(e) { let o = await e.checkTimer(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new bn(e.category, e.name, e.startTime, o)), this.flush(o)); } endSync(e) { let o = hn(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new bn(e.category, e.name, e.startTime, o)), this.flush(o)); } logOneEvent(e) { tt.verbose(`Profiler.${e.category}`, `${(e.endTime - e.startTime).toFixed(2)}ms on event '${e.name}' at ${e.endTime.toFixed(2)}`); } flush(e) { if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || e - this._flushTime >= this._flushIntervalInMilliseconds) { for (let o = this._flushPointer; this._flushPointer < o + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); this._flushTime = hn(); } } get started() { return this._started; } }, hn = typeof performance < "u" && performance.now ? () => performance.now() : Date.now; }); $s = O(() => { "use strict"; }); ks = mt((Mo) => { "use strict"; Mo.__esModule = true; var eh2 = (function() { function i(e) { if (!e) throw new TypeError("Invalid argument; `value` has no value."); this.value = i.EMPTY, e && i.isGuid(e) && (this.value = e); } return i.isGuid = function(e) { var o = e.toString(); return e && (e instanceof i || i.validator.test(o)); }, i.create = function() { return new i([i.gen(2), i.gen(1), i.gen(1), i.gen(1), i.gen(3)].join("-")); }, i.createEmpty = function() { return new i("emptyguid"); }, i.parse = function(e) { return new i(e); }, i.raw = function() { return [i.gen(2), i.gen(1), i.gen(1), i.gen(1), i.gen(3)].join("-"); }, i.gen = function(e) { for (var o = "", t = 0; t < e; t++) o += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1); return o; }, i.prototype.equals = function(e) { return i.isGuid(e) && this.value === e.toString(); }, i.prototype.isEmpty = function() { return this.value === i.EMPTY; }, i.prototype.toString = function() { return this.value; }, i.prototype.toJSON = function() { return { value: this.value }; }, i.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), i.EMPTY = "00000000-0000-0000-0000-000000000000", i; })(); Mo.Guid = eh2; }); zo = O(() => { Ut = null; try { Ut = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; } catch { } rt.prototype.__isLong__; Object.defineProperty(rt.prototype, "__isLong__", { value: true }); rt.isLong = Pt; Fs = {}, Cs = {}; rt.fromInt = Ce; rt.fromNumber = Vt; rt.fromBits = J; yn = Math.pow; rt.fromString = Vo; rt.fromValue = Yt; Ns = 65536, rh = 1 << 24, ir = Ns * Ns, Ms = ir * ir, Rs = Ms / 2, Gs = Ce(rh), Jt = Ce(0); rt.ZERO = Jt; he = Ce(0, true); rt.UZERO = he; or = Ce(1); rt.ONE = or; Us = Ce(1, true); rt.UONE = Us; Uo = Ce(-1); rt.NEG_ONE = Uo; Vs = J(-1, 2147483647, false); rt.MAX_VALUE = Vs; zs = J(-1, -1, true); rt.MAX_UNSIGNED_VALUE = zs; Ft = J(0, -2147483648, false); rt.MIN_VALUE = Ft; D = rt.prototype; D.toInt = function() { return this.unsigned ? this.low >>> 0 : this.low; }; D.toNumber = function() { return this.unsigned ? (this.high >>> 0) * ir + (this.low >>> 0) : this.high * ir + (this.low >>> 0); }; D.toString = function(e) { if (e = e || 10, e < 2 || 36 < e) throw RangeError("radix"); if (this.isZero()) return "0"; if (this.isNegative()) if (this.eq(Ft)) { var o = Vt(e), t = this.div(o), r = t.mul(o).sub(this); return t.toString(e) + r.toInt().toString(e); } else return "-" + this.neg().toString(e); for (var n = Vt(yn(e, 6), this.unsigned), s = this, a = ""; ; ) { var u = s.div(n), l = s.sub(u.mul(n)).toInt() >>> 0, f = l.toString(e); if (s = u, s.isZero()) return f + a; for (; f.length < 6; ) f = "0" + f; a = "" + f + a; } }; D.getHighBits = function() { return this.high; }; D.getHighBitsUnsigned = function() { return this.high >>> 0; }; D.getLowBits = function() { return this.low; }; D.getLowBitsUnsigned = function() { return this.low >>> 0; }; D.getNumBitsAbs = function() { if (this.isNegative()) return this.eq(Ft) ? 64 : this.neg().getNumBitsAbs(); for (var e = this.high != 0 ? this.high : this.low, o = 31; o > 0 && !(e & 1 << o); o--) ; return this.high != 0 ? o + 33 : o + 1; }; D.isZero = function() { return this.high === 0 && this.low === 0; }; D.eqz = D.isZero; D.isNegative = function() { return !this.unsigned && this.high < 0; }; D.isPositive = function() { return this.unsigned || this.high >= 0; }; D.isOdd = function() { return (this.low & 1) === 1; }; D.isEven = function() { return (this.low & 1) === 0; }; D.equals = function(e) { return Pt(e) || (e = Yt(e)), this.unsigned !== e.unsigned && this.high >>> 31 === 1 && e.high >>> 31 === 1 ? false : this.high === e.high && this.low === e.low; }; D.eq = D.equals; D.notEquals = function(e) { return !this.eq(e); }; D.neq = D.notEquals; D.ne = D.notEquals; D.lessThan = function(e) { return this.comp(e) < 0; }; D.lt = D.lessThan; D.lessThanOrEqual = function(e) { return this.comp(e) <= 0; }; D.lte = D.lessThanOrEqual; D.le = D.lessThanOrEqual; D.greaterThan = function(e) { return this.comp(e) > 0; }; D.gt = D.greaterThan; D.greaterThanOrEqual = function(e) { return this.comp(e) >= 0; }; D.gte = D.greaterThanOrEqual; D.ge = D.greaterThanOrEqual; D.compare = function(e) { if (Pt(e) || (e = Yt(e)), this.eq(e)) return 0; var o = this.isNegative(), t = e.isNegative(); return o && !t ? -1 : !o && t ? 1 : this.unsigned ? e.high >>> 0 > this.high >>> 0 || e.high === this.high && e.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(e).isNegative() ? -1 : 1; }; D.comp = D.compare; D.negate = function() { return !this.unsigned && this.eq(Ft) ? Ft : this.not().add(or); }; D.neg = D.negate; D.add = function(e) { Pt(e) || (e = Yt(e)); var o = this.high >>> 16, t = this.high & 65535, r = this.low >>> 16, n = this.low & 65535, s = e.high >>> 16, a = e.high & 65535, u = e.low >>> 16, l = e.low & 65535, f = 0, p = 0, d = 0, y = 0; return y += n + l, d += y >>> 16, y &= 65535, d += r + u, p += d >>> 16, d &= 65535, p += t + a, f += p >>> 16, p &= 65535, f += o + s, f &= 65535, J(d << 16 | y, f << 16 | p, this.unsigned); }; D.subtract = function(e) { return Pt(e) || (e = Yt(e)), this.add(e.neg()); }; D.sub = D.subtract; D.multiply = function(e) { if (this.isZero()) return this; if (Pt(e) || (e = Yt(e)), Ut) { var o = Ut.mul(this.low, this.high, e.low, e.high); return J(o, Ut.get_high(), this.unsigned); } if (e.isZero()) return this.unsigned ? he : Jt; if (this.eq(Ft)) return e.isOdd() ? Ft : Jt; if (e.eq(Ft)) return this.isOdd() ? Ft : Jt; if (this.isNegative()) return e.isNegative() ? this.neg().mul(e.neg()) : this.neg().mul(e).neg(); if (e.isNegative()) return this.mul(e.neg()).neg(); if (this.lt(Gs) && e.lt(Gs)) return Vt(this.toNumber() * e.toNumber(), this.unsigned); var t = this.high >>> 16, r = this.high & 65535, n = this.low >>> 16, s = this.low & 65535, a = e.high >>> 16, u = e.high & 65535, l = e.low >>> 16, f = e.low & 65535, p = 0, d = 0, y = 0, w = 0; return w += s * f, y += w >>> 16, w &= 65535, y += n * f, d += y >>> 16, y &= 65535, y += s * l, d += y >>> 16, y &= 65535, d += r * f, p += d >>> 16, d &= 65535, d += n * l, p += d >>> 16, d &= 65535, d += s * u, p += d >>> 16, d &= 65535, p += t * f + r * l + n * u + s * a, p &= 65535, J(y << 16 | w, p << 16 | d, this.unsigned); }; D.mul = D.multiply; D.divide = function(e) { if (Pt(e) || (e = Yt(e)), e.isZero()) throw Error("division by zero"); if (Ut) { if (!this.unsigned && this.high === -2147483648 && e.low === -1 && e.high === -1) return this; var o = (this.unsigned ? Ut.div_u : Ut.div_s)(this.low, this.high, e.low, e.high); return J(o, Ut.get_high(), this.unsigned); } if (this.isZero()) return this.unsigned ? he : Jt; var t, r, n; if (this.unsigned) { if (e.unsigned || (e = e.toUnsigned()), e.gt(this)) return he; if (e.gt(this.shru(1))) return Us; n = he; } else { if (this.eq(Ft)) { if (e.eq(or) || e.eq(Uo)) return Ft; if (e.eq(Ft)) return or; var s = this.shr(1); return t = s.div(e).shl(1), t.eq(Jt) ? e.isNegative() ? or : Uo : (r = this.sub(e.mul(t)), n = t.add(r.div(e)), n); } else if (e.eq(Ft)) return this.unsigned ? he : Jt; if (this.isNegative()) return e.isNegative() ? this.neg().div(e.neg()) : this.neg().div(e).neg(); if (e.isNegative()) return this.div(e.neg()).neg(); n = Jt; } for (r = this; r.gte(e); ) { t = Math.max(1, Math.floor(r.toNumber() / e.toNumber())); for (var a = Math.ceil(Math.log(t) / Math.LN2), u = a <= 48 ? 1 : yn(2, a - 48), l = Vt(t), f = l.mul(e); f.isNegative() || f.gt(r); ) t -= u, l = Vt(t, this.unsigned), f = l.mul(e); l.isZero() && (l = or), n = n.add(l), r = r.sub(f); } return n; }; D.div = D.divide; D.modulo = function(e) { if (Pt(e) || (e = Yt(e)), Ut) { var o = (this.unsigned ? Ut.rem_u : Ut.rem_s)(this.low, this.high, e.low, e.high); return J(o, Ut.get_high(), this.unsigned); } return this.sub(this.div(e).mul(e)); }; D.mod = D.modulo; D.rem = D.modulo; D.not = function() { return J(~this.low, ~this.high, this.unsigned); }; D.countLeadingZeros = function() { return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; }; D.clz = D.countLeadingZeros; D.countTrailingZeros = function() { return this.low ? Bs(this.low) : Bs(this.high) + 32; }; D.ctz = D.countTrailingZeros; D.and = function(e) { return Pt(e) || (e = Yt(e)), J(this.low & e.low, this.high & e.high, this.unsigned); }; D.or = function(e) { return Pt(e) || (e = Yt(e)), J(this.low | e.low, this.high | e.high, this.unsigned); }; D.xor = function(e) { return Pt(e) || (e = Yt(e)), J(this.low ^ e.low, this.high ^ e.high, this.unsigned); }; D.shiftLeft = function(e) { return Pt(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? J(this.low << e, this.high << e | this.low >>> 32 - e, this.unsigned) : J(0, this.low << e - 32, this.unsigned); }; D.shl = D.shiftLeft; D.shiftRight = function(e) { return Pt(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? J(this.low >>> e | this.high << 32 - e, this.high >> e, this.unsigned) : J(this.high >> e - 32, this.high >= 0 ? 0 : -1, this.unsigned); }; D.shr = D.shiftRight; D.shiftRightUnsigned = function(e) { return Pt(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? J(this.low >>> e | this.high << 32 - e, this.high >>> e, this.unsigned) : e === 32 ? J(this.high, 0, this.unsigned) : J(this.high >>> e - 32, 0, this.unsigned); }; D.shru = D.shiftRightUnsigned; D.shr_u = D.shiftRightUnsigned; D.rotateLeft = function(e) { var o; return Pt(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e === 32 ? J(this.high, this.low, this.unsigned) : e < 32 ? (o = 32 - e, J(this.low << e | this.high >>> o, this.high << e | this.low >>> o, this.unsigned)) : (e -= 32, o = 32 - e, J(this.high << e | this.low >>> o, this.low << e | this.high >>> o, this.unsigned)); }; D.rotl = D.rotateLeft; D.rotateRight = function(e) { var o; return Pt(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e === 32 ? J(this.high, this.low, this.unsigned) : e < 32 ? (o = 32 - e, J(this.high << o | this.low >>> e, this.low << o | this.high >>> e, this.unsigned)) : (e -= 32, o = 32 - e, J(this.low << o | this.high >>> e, this.high << o | this.low >>> e, this.unsigned)); }; D.rotr = D.rotateRight; D.toSigned = function() { return this.unsigned ? J(this.low, this.high, false) : this; }; D.toUnsigned = function() { return this.unsigned ? this : J(this.low, this.high, true); }; D.toBytes = function(e) { return e ? this.toBytesLE() : this.toBytesBE(); }; D.toBytesLE = function() { var e = this.high, o = this.low; return [o & 255, o >>> 8 & 255, o >>> 16 & 255, o >>> 24, e & 255, e >>> 8 & 255, e >>> 16 & 255, e >>> 24]; }; D.toBytesBE = function() { var e = this.high, o = this.low; return [e >>> 24, e >>> 16 & 255, e >>> 8 & 255, e & 255, o >>> 24, o >>> 16 & 255, o >>> 8 & 255, o & 255]; }; rt.fromBytes = function(e, o, t) { return t ? rt.fromBytesLE(e, o) : rt.fromBytesBE(e, o); }; rt.fromBytesLE = function(e, o) { return new rt(e[0] | e[1] << 8 | e[2] << 16 | e[3] << 24, e[4] | e[5] << 8 | e[6] << 16 | e[7] << 24, o); }; rt.fromBytesBE = function(e, o) { return new rt(e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7], e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], o); }; me = rt; }); xn = O(() => { T = {}; T.Offset; T.Table; T.SIZEOF_SHORT = 2; T.SIZEOF_INT = 4; T.FILE_IDENTIFIER_LENGTH = 4; T.SIZE_PREFIX_LENGTH = 4; T.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }; T.int32 = new Int32Array(2); T.float32 = new Float32Array(T.int32.buffer); T.float64 = new Float64Array(T.int32.buffer); T.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1; T.Long = function(i, e) { this.low = i | 0, this.high = e | 0; }; T.Long.create = function(i, e) { return i == 0 && e == 0 ? T.Long.ZERO : new T.Long(i, e); }; T.Long.prototype.toFloat64 = function() { return (this.low >>> 0) + this.high * 4294967296; }; T.Long.prototype.equals = function(i) { return this.low == i.low && this.high == i.high; }; T.Long.ZERO = new T.Long(0, 0); T.Builder = function(i) { if (i) var e = i; else var e = 1024; this.bb = T.ByteBuffer.allocate(e), this.space = e, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }; T.Builder.prototype.clear = function() { this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }; T.Builder.prototype.forceDefaults = function(i) { this.force_defaults = i; }; T.Builder.prototype.dataBuffer = function() { return this.bb; }; T.Builder.prototype.asUint8Array = function() { return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); }; T.Builder.prototype.prep = function(i, e) { i > this.minalign && (this.minalign = i); for (var o = ~(this.bb.capacity() - this.space + e) + 1 & i - 1; this.space < o + i + e; ) { var t = this.bb.capacity(); this.bb = T.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - t; } this.pad(o); }; T.Builder.prototype.pad = function(i) { for (var e = 0; e < i; e++) this.bb.writeInt8(--this.space, 0); }; T.Builder.prototype.writeInt8 = function(i) { this.bb.writeInt8(this.space -= 1, i); }; T.Builder.prototype.writeInt16 = function(i) { this.bb.writeInt16(this.space -= 2, i); }; T.Builder.prototype.writeInt32 = function(i) { this.bb.writeInt32(this.space -= 4, i); }; T.Builder.prototype.writeInt64 = function(i) { this.bb.writeInt64(this.space -= 8, i); }; T.Builder.prototype.writeFloat32 = function(i) { this.bb.writeFloat32(this.space -= 4, i); }; T.Builder.prototype.writeFloat64 = function(i) { this.bb.writeFloat64(this.space -= 8, i); }; T.Builder.prototype.addInt8 = function(i) { this.prep(1, 0), this.writeInt8(i); }; T.Builder.prototype.addInt16 = function(i) { this.prep(2, 0), this.writeInt16(i); }; T.Builder.prototype.addInt32 = function(i) { this.prep(4, 0), this.writeInt32(i); }; T.Builder.prototype.addInt64 = function(i) { this.prep(8, 0), this.writeInt64(i); }; T.Builder.prototype.addFloat32 = function(i) { this.prep(4, 0), this.writeFloat32(i); }; T.Builder.prototype.addFloat64 = function(i) { this.prep(8, 0), this.writeFloat64(i); }; T.Builder.prototype.addFieldInt8 = function(i, e, o) { (this.force_defaults || e != o) && (this.addInt8(e), this.slot(i)); }; T.Builder.prototype.addFieldInt16 = function(i, e, o) { (this.force_defaults || e != o) && (this.addInt16(e), this.slot(i)); }; T.Builder.prototype.addFieldInt32 = function(i, e, o) { (this.force_defaults || e != o) && (this.addInt32(e), this.slot(i)); }; T.Builder.prototype.addFieldInt64 = function(i, e, o) { (this.force_defaults || !e.equals(o)) && (this.addInt64(e), this.slot(i)); }; T.Builder.prototype.addFieldFloat32 = function(i, e, o) { (this.force_defaults || e != o) && (this.addFloat32(e), this.slot(i)); }; T.Builder.prototype.addFieldFloat64 = function(i, e, o) { (this.force_defaults || e != o) && (this.addFloat64(e), this.slot(i)); }; T.Builder.prototype.addFieldOffset = function(i, e, o) { (this.force_defaults || e != o) && (this.addOffset(e), this.slot(i)); }; T.Builder.prototype.addFieldStruct = function(i, e, o) { e != o && (this.nested(e), this.slot(i)); }; T.Builder.prototype.nested = function(i) { if (i != this.offset()) throw new Error("FlatBuffers: struct must be serialized inline."); }; T.Builder.prototype.notNested = function() { if (this.isNested) throw new Error("FlatBuffers: object serialization must not be nested."); }; T.Builder.prototype.slot = function(i) { this.vtable[i] = this.offset(); }; T.Builder.prototype.offset = function() { return this.bb.capacity() - this.space; }; T.Builder.growByteBuffer = function(i) { var e = i.capacity(); if (e & 3221225472) throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); var o = e << 1, t = T.ByteBuffer.allocate(o); return t.setPosition(o - e), t.bytes().set(i.bytes(), o - e), t; }; T.Builder.prototype.addOffset = function(i) { this.prep(T.SIZEOF_INT, 0), this.writeInt32(this.offset() - i + T.SIZEOF_INT); }; T.Builder.prototype.startObject = function(i) { this.notNested(), this.vtable == null && (this.vtable = []), this.vtable_in_use = i; for (var e = 0; e < i; e++) this.vtable[e] = 0; this.isNested = true, this.object_start = this.offset(); }; T.Builder.prototype.endObject = function() { if (this.vtable == null || !this.isNested) throw new Error("FlatBuffers: endObject called without startObject"); this.addInt32(0); for (var i = this.offset(), e = this.vtable_in_use - 1; e >= 0 && this.vtable[e] == 0; e--) ; for (var o = e + 1; e >= 0; e--) this.addInt16(this.vtable[e] != 0 ? i - this.vtable[e] : 0); var t = 2; this.addInt16(i - this.object_start); var r = (o + t) * T.SIZEOF_SHORT; this.addInt16(r); var n = 0, s = this.space; t: for (e = 0; e < this.vtables.length; e++) { var a = this.bb.capacity() - this.vtables[e]; if (r == this.bb.readInt16(a)) { for (var u = T.SIZEOF_SHORT; u < r; u += T.SIZEOF_SHORT) if (this.bb.readInt16(s + u) != this.bb.readInt16(a + u)) continue t; n = this.vtables[e]; break; } } return n ? (this.space = this.bb.capacity() - i, this.bb.writeInt32(this.space, n - i)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - i, this.offset() - i)), this.isNested = false, i; }; T.Builder.prototype.finish = function(i, e, o) { var t = o ? T.SIZE_PREFIX_LENGTH : 0; if (e) { var r = e; if (this.prep(this.minalign, T.SIZEOF_INT + T.FILE_IDENTIFIER_LENGTH + t), r.length != T.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + T.FILE_IDENTIFIER_LENGTH); for (var n = T.FILE_IDENTIFIER_LENGTH - 1; n >= 0; n--) this.writeInt8(r.charCodeAt(n)); } this.prep(this.minalign, T.SIZEOF_INT + t), this.addOffset(i), t && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space); }; T.Builder.prototype.finishSizePrefixed = function(i, e) { this.finish(i, e, true); }; T.Builder.prototype.requiredField = function(i, e) { var o = this.bb.capacity() - i, t = o - this.bb.readInt32(o), r = this.bb.readInt16(t + e) != 0; if (!r) throw new Error("FlatBuffers: field " + e + " must be set"); }; T.Builder.prototype.startVector = function(i, e, o) { this.notNested(), this.vector_num_elems = e, this.prep(T.SIZEOF_INT, i * e), this.prep(o, i * e); }; T.Builder.prototype.endVector = function() { return this.writeInt32(this.vector_num_elems), this.offset(); }; T.Builder.prototype.createString = function(i) { if (i instanceof Uint8Array) var e = i; else for (var e = [], o = 0; o < i.length; ) { var t, r = i.charCodeAt(o++); if (r < 55296 || r >= 56320) t = r; else { var n = i.charCodeAt(o++); t = (r << 10) + n + (65536 - 56623104 - 56320); } t < 128 ? e.push(t) : (t < 2048 ? e.push(t >> 6 & 31 | 192) : (t < 65536 ? e.push(t >> 12 & 15 | 224) : e.push(t >> 18 & 7 | 240, t >> 12 & 63 | 128), e.push(t >> 6 & 63 | 128)), e.push(t & 63 | 128)); } this.addInt8(0), this.startVector(1, e.length, 1), this.bb.setPosition(this.space -= e.length); for (var o = 0, s = this.space, a = this.bb.bytes(); o < e.length; o++) a[s++] = e[o]; return this.endVector(); }; T.Builder.prototype.createLong = function(i, e) { return T.Long.create(i, e); }; T.ByteBuffer = function(i) { this.bytes_ = i, this.position_ = 0; }; T.ByteBuffer.allocate = function(i) { return new T.ByteBuffer(new Uint8Array(i)); }; T.ByteBuffer.prototype.clear = function() { this.position_ = 0; }; T.ByteBuffer.prototype.bytes = function() { return this.bytes_; }; T.ByteBuffer.prototype.position = function() { return this.position_; }; T.ByteBuffer.prototype.setPosition = function(i) { this.position_ = i; }; T.ByteBuffer.prototype.capacity = function() { return this.bytes_.length; }; T.ByteBuffer.prototype.readInt8 = function(i) { return this.readUint8(i) << 24 >> 24; }; T.ByteBuffer.prototype.readUint8 = function(i) { return this.bytes_[i]; }; T.ByteBuffer.prototype.readInt16 = function(i) { return this.readUint16(i) << 16 >> 16; }; T.ByteBuffer.prototype.readUint16 = function(i) { return this.bytes_[i] | this.bytes_[i + 1] << 8; }; T.ByteBuffer.prototype.readInt32 = function(i) { return this.bytes_[i] | this.bytes_[i + 1] << 8 | this.bytes_[i + 2] << 16 | this.bytes_[i + 3] << 24; }; T.ByteBuffer.prototype.readUint32 = function(i) { return this.readInt32(i) >>> 0; }; T.ByteBuffer.prototype.readInt64 = function(i) { return new T.Long(this.readInt32(i), this.readInt32(i + 4)); }; T.ByteBuffer.prototype.readUint64 = function(i) { return new T.Long(this.readUint32(i), this.readUint32(i + 4)); }; T.ByteBuffer.prototype.readFloat32 = function(i) { return T.int32[0] = this.readInt32(i), T.float32[0]; }; T.ByteBuffer.prototype.readFloat64 = function(i) { return T.int32[T.isLittleEndian ? 0 : 1] = this.readInt32(i), T.int32[T.isLittleEndian ? 1 : 0] = this.readInt32(i + 4), T.float64[0]; }; T.ByteBuffer.prototype.writeInt8 = function(i, e) { this.bytes_[i] = e; }; T.ByteBuffer.prototype.writeUint8 = function(i, e) { this.bytes_[i] = e; }; T.ByteBuffer.prototype.writeInt16 = function(i, e) { this.bytes_[i] = e, this.bytes_[i + 1] = e >> 8; }; T.ByteBuffer.prototype.writeUint16 = function(i, e) { this.bytes_[i] = e, this.bytes_[i + 1] = e >> 8; }; T.ByteBuffer.prototype.writeInt32 = function(i, e) { this.bytes_[i] = e, this.bytes_[i + 1] = e >> 8, this.bytes_[i + 2] = e >> 16, this.bytes_[i + 3] = e >> 24; }; T.ByteBuffer.prototype.writeUint32 = function(i, e) { this.bytes_[i] = e, this.bytes_[i + 1] = e >> 8, this.bytes_[i + 2] = e >> 16, this.bytes_[i + 3] = e >> 24; }; T.ByteBuffer.prototype.writeInt64 = function(i, e) { this.writeInt32(i, e.low), this.writeInt32(i + 4, e.high); }; T.ByteBuffer.prototype.writeUint64 = function(i, e) { this.writeUint32(i, e.low), this.writeUint32(i + 4, e.high); }; T.ByteBuffer.prototype.writeFloat32 = function(i, e) { T.float32[0] = e, this.writeInt32(i, T.int32[0]); }; T.ByteBuffer.prototype.writeFloat64 = function(i, e) { T.float64[0] = e, this.writeInt32(i, T.int32[T.isLittleEndian ? 0 : 1]), this.writeInt32(i + 4, T.int32[T.isLittleEndian ? 1 : 0]); }; T.ByteBuffer.prototype.getBufferIdentifier = function() { if (this.bytes_.length < this.position_ + T.SIZEOF_INT + T.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier."); for (var i = "", e = 0; e < T.FILE_IDENTIFIER_LENGTH; e++) i += String.fromCharCode(this.readInt8(this.position_ + T.SIZEOF_INT + e)); return i; }; T.ByteBuffer.prototype.__offset = function(i, e) { var o = i - this.readInt32(i); return e < this.readInt16(o) ? this.readInt16(o + e) : 0; }; T.ByteBuffer.prototype.__union = function(i, e) { return i.bb_pos = e + this.readInt32(e), i.bb = this, i; }; T.ByteBuffer.prototype.__string = function(i, e) { i += this.readInt32(i); var o = this.readInt32(i), t = "", r = 0; if (i += T.SIZEOF_INT, e === T.Encoding.UTF8_BYTES) return this.bytes_.subarray(i, i + o); for (; r < o; ) { var n, s = this.readUint8(i + r++); if (s < 192) n = s; else { var a = this.readUint8(i + r++); if (s < 224) n = (s & 31) << 6 | a & 63; else { var u = this.readUint8(i + r++); if (s < 240) n = (s & 15) << 12 | (a & 63) << 6 | u & 63; else { var l = this.readUint8(i + r++); n = (s & 7) << 18 | (a & 63) << 12 | (u & 63) << 6 | l & 63; } } } n < 65536 ? t += String.fromCharCode(n) : (n -= 65536, t += String.fromCharCode((n >> 10) + 55296, (n & 1024 - 1) + 56320)); } return t; }; T.ByteBuffer.prototype.__indirect = function(i) { return i + this.readInt32(i); }; T.ByteBuffer.prototype.__vector = function(i) { return i + this.readInt32(i) + T.SIZEOF_INT; }; T.ByteBuffer.prototype.__vector_len = function(i) { return this.readInt32(i + this.readInt32(i)); }; T.ByteBuffer.prototype.__has_identifier = function(i) { if (i.length != T.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + T.FILE_IDENTIFIER_LENGTH); for (var e = 0; e < T.FILE_IDENTIFIER_LENGTH; e++) if (i.charCodeAt(e) != this.readInt8(this.position_ + T.SIZEOF_INT + e)) return false; return true; }; T.ByteBuffer.prototype.createLong = function(i, e) { return T.Long.create(i, e); }; }); Pr = O(() => { "use strict"; xn(); ((e) => { let i; ((t) => { let o; ((n) => { let r; ((P2) => (P2[P2.UNDEFINED = 0] = "UNDEFINED", P2[P2.FLOAT = 1] = "FLOAT", P2[P2.INT = 2] = "INT", P2[P2.STRING = 3] = "STRING", P2[P2.TENSOR = 4] = "TENSOR", P2[P2.GRAPH = 5] = "GRAPH", P2[P2.FLOATS = 6] = "FLOATS", P2[P2.INTS = 7] = "INTS", P2[P2.STRINGS = 8] = "STRINGS", P2[P2.TENSORS = 9] = "TENSORS", P2[P2.GRAPHS = 10] = "GRAPHS", P2[P2.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", P2[P2.SPARSE_TENSORS = 12] = "SPARSE_TENSORS"))(r = n.AttributeType ||= {}); })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { let r; ((l) => (l[l.UNKNOWN = 0] = "UNKNOWN", l[l.VALUE = 1] = "VALUE", l[l.PARAM = 2] = "PARAM"))(r = n.DimensionValueType ||= {}); })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { let r; ((C) => (C[C.UNDEFINED = 0] = "UNDEFINED", C[C.FLOAT = 1] = "FLOAT", C[C.UINT8 = 2] = "UINT8", C[C.INT8 = 3] = "INT8", C[C.UINT16 = 4] = "UINT16", C[C.INT16 = 5] = "INT16", C[C.INT32 = 6] = "INT32", C[C.INT64 = 7] = "INT64", C[C.STRING = 8] = "STRING", C[C.BOOL = 9] = "BOOL", C[C.FLOAT16 = 10] = "FLOAT16", C[C.DOUBLE = 11] = "DOUBLE", C[C.UINT32 = 12] = "UINT32", C[C.UINT64 = 13] = "UINT64", C[C.COMPLEX64 = 14] = "COMPLEX64", C[C.COMPLEX128 = 15] = "COMPLEX128", C[C.BFLOAT16 = 16] = "BFLOAT16", C[C.FLOAT8E4M3FN = 17] = "FLOAT8E4M3FN", C[C.FLOAT8E4M3FNUZ = 18] = "FLOAT8E4M3FNUZ", C[C.FLOAT8E5M2 = 19] = "FLOAT8E5M2", C[C.FLOAT8E5M2FNUZ = 20] = "FLOAT8E5M2FNUZ"))(r = n.TensorDataType ||= {}); })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { let r; ((u) => (u[u.Primitive = 0] = "Primitive", u[u.Fused = 1] = "Fused"))(r = n.NodeType ||= {}); })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { let r; ((f) => (f[f.NONE = 0] = "NONE", f[f.tensor_type = 1] = "tensor_type", f[f.sequence_type = 2] = "sequence_type", f[f.map_type = 3] = "map_type"))(r = n.TypeInfoValue ||= {}); })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsShape(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsShape(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } dim(a, u) { let l = this.bb.__offset(this.bb_pos, 4); return l ? (u || new e.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } dimLength() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startShape(a) { a.startObject(1); } static addDim(a, u) { a.addFieldOffset(0, u, 0); } static createDimVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startDimVector(a, u) { a.startVector(4, u, 4); } static endShape(a) { return a.endObject(); } static createShape(a, u) { return r.startShape(a), r.addDim(a, u), r.endShape(a); } } n.Shape = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsDimension(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsDimension(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } value(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (a || new e.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } denotation(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, a) : null; } static startDimension(a) { a.startObject(2); } static addValue(a, u) { a.addFieldOffset(0, u, 0); } static addDenotation(a, u) { a.addFieldOffset(1, u, 0); } static endDimension(a) { return a.endObject(); } static createDimension(a, u, l) { return r.startDimension(a), r.addValue(a, u), r.addDenotation(a, l), r.endDimension(a); } } n.Dimension = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsDimensionValue(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsDimensionValue(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } dimType() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.readInt8(this.bb_pos + a) : 0; } dimValue() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.readInt64(this.bb_pos + a) : this.bb.createLong(0, 0); } dimParam(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, a) : null; } static startDimensionValue(a) { a.startObject(3); } static addDimType(a, u) { a.addFieldInt8(0, u, 0); } static addDimValue(a, u) { a.addFieldInt64(1, u, a.createLong(0, 0)); } static addDimParam(a, u) { a.addFieldOffset(2, u, 0); } static endDimensionValue(a) { return a.endObject(); } static createDimensionValue(a, u, l, f) { return r.startDimensionValue(a), r.addDimType(a, u), r.addDimValue(a, l), r.addDimParam(a, f), r.endDimensionValue(a); } } n.DimensionValue = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsTensorTypeAndShape(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsTensorTypeAndShape(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } elemType() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } shape(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (a || new e.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startTensorTypeAndShape(a) { a.startObject(2); } static addElemType(a, u) { a.addFieldInt32(0, u, 0); } static addShape(a, u) { a.addFieldOffset(1, u, 0); } static endTensorTypeAndShape(a) { return a.endObject(); } static createTensorTypeAndShape(a, u, l) { return r.startTensorTypeAndShape(a), r.addElemType(a, u), r.addShape(a, l), r.endTensorTypeAndShape(a); } } n.TensorTypeAndShape = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsMapType(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsMapType(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } keyType() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } valueType(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (a || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startMapType(a) { a.startObject(2); } static addKeyType(a, u) { a.addFieldInt32(0, u, 0); } static addValueType(a, u) { a.addFieldOffset(1, u, 0); } static endMapType(a) { return a.endObject(); } static createMapType(a, u, l) { return r.startMapType(a), r.addKeyType(a, u), r.addValueType(a, l), r.endMapType(a); } } n.MapType = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsSequenceType(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsSequenceType(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } elemType(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (a || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startSequenceType(a) { a.startObject(1); } static addElemType(a, u) { a.addFieldOffset(0, u, 0); } static endSequenceType(a) { return a.endObject(); } static createSequenceType(a, u) { return r.startSequenceType(a), r.addElemType(a, u), r.endSequenceType(a); } } n.SequenceType = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } nodeIndex() { return this.bb.readUint32(this.bb_pos); } srcArgIndex() { return this.bb.readInt32(this.bb_pos + 4); } dstArgIndex() { return this.bb.readInt32(this.bb_pos + 8); } static createEdgeEnd(a, u, l, f) { return a.prep(4, 12), a.writeInt32(f), a.writeInt32(l), a.writeInt32(u), a.offset(); } } n.EdgeEnd = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsNodeEdge(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsNodeEdge(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } nodeIndex() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.readUint32(this.bb_pos + a) : 0; } inputEdges(a, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + l) + a * 12, this.bb) : null; } inputEdgesLength() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } outputEdges(a, u) { let l = this.bb.__offset(this.bb_pos, 8); return l ? (u || new e.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + l) + a * 12, this.bb) : null; } outputEdgesLength() { let a = this.bb.__offset(this.bb_pos, 8); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startNodeEdge(a) { a.startObject(3); } static addNodeIndex(a, u) { a.addFieldInt32(0, u, 0); } static addInputEdges(a, u) { a.addFieldOffset(1, u, 0); } static startInputEdgesVector(a, u) { a.startVector(12, u, 4); } static addOutputEdges(a, u) { a.addFieldOffset(2, u, 0); } static startOutputEdgesVector(a, u) { a.startVector(12, u, 4); } static endNodeEdge(a) { return a.endObject(); } static createNodeEdge(a, u, l, f) { return r.startNodeEdge(a), r.addNodeIndex(a, u), r.addInputEdges(a, l), r.addOutputEdges(a, f), r.endNodeEdge(a); } } n.NodeEdge = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsNode(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsNode(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } name(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } docString(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, a) : null; } domain(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, a) : null; } sinceVersion() { let a = this.bb.__offset(this.bb_pos, 10); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } index() { let a = this.bb.__offset(this.bb_pos, 12); return a ? this.bb.readUint32(this.bb_pos + a) : 0; } opType(a) { let u = this.bb.__offset(this.bb_pos, 14); return u ? this.bb.__string(this.bb_pos + u, a) : null; } type() { let a = this.bb.__offset(this.bb_pos, 16); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } executionProviderType(a) { let u = this.bb.__offset(this.bb_pos, 18); return u ? this.bb.__string(this.bb_pos + u, a) : null; } inputs(a, u) { let l = this.bb.__offset(this.bb_pos, 20); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } inputsLength() { let a = this.bb.__offset(this.bb_pos, 20); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } outputs(a, u) { let l = this.bb.__offset(this.bb_pos, 22); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } outputsLength() { let a = this.bb.__offset(this.bb_pos, 22); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } attributes(a, u) { let l = this.bb.__offset(this.bb_pos, 24); return l ? (u || new e.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } attributesLength() { let a = this.bb.__offset(this.bb_pos, 24); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } inputArgCounts(a) { let u = this.bb.__offset(this.bb_pos, 26); return u ? this.bb.readInt32(this.bb.__vector(this.bb_pos + u) + a * 4) : 0; } inputArgCountsLength() { let a = this.bb.__offset(this.bb_pos, 26); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } inputArgCountsArray() { let a = this.bb.__offset(this.bb_pos, 26); return a ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + a), this.bb.__vector_len(this.bb_pos + a)) : null; } implicitInputs(a, u) { let l = this.bb.__offset(this.bb_pos, 28); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } implicitInputsLength() { let a = this.bb.__offset(this.bb_pos, 28); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startNode(a) { a.startObject(13); } static addName(a, u) { a.addFieldOffset(0, u, 0); } static addDocString(a, u) { a.addFieldOffset(1, u, 0); } static addDomain(a, u) { a.addFieldOffset(2, u, 0); } static addSinceVersion(a, u) { a.addFieldInt32(3, u, 0); } static addIndex(a, u) { a.addFieldInt32(4, u, 0); } static addOpType(a, u) { a.addFieldOffset(5, u, 0); } static addType(a, u) { a.addFieldInt32(6, u, 0); } static addExecutionProviderType(a, u) { a.addFieldOffset(7, u, 0); } static addInputs(a, u) { a.addFieldOffset(8, u, 0); } static createInputsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startInputsVector(a, u) { a.startVector(4, u, 4); } static addOutputs(a, u) { a.addFieldOffset(9, u, 0); } static createOutputsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startOutputsVector(a, u) { a.startVector(4, u, 4); } static addAttributes(a, u) { a.addFieldOffset(10, u, 0); } static createAttributesVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startAttributesVector(a, u) { a.startVector(4, u, 4); } static addInputArgCounts(a, u) { a.addFieldOffset(11, u, 0); } static createInputArgCountsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addInt32(u[l]); return a.endVector(); } static startInputArgCountsVector(a, u) { a.startVector(4, u, 4); } static addImplicitInputs(a, u) { a.addFieldOffset(12, u, 0); } static createImplicitInputsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startImplicitInputsVector(a, u) { a.startVector(4, u, 4); } static endNode(a) { return a.endObject(); } static createNode(a, u, l, f, p, d, y, w, v, S, L, A2, P2, M3) { return r.startNode(a), r.addName(a, u), r.addDocString(a, l), r.addDomain(a, f), r.addSinceVersion(a, p), r.addIndex(a, d), r.addOpType(a, y), r.addType(a, w), r.addExecutionProviderType(a, v), r.addInputs(a, S), r.addOutputs(a, L), r.addAttributes(a, A2), r.addInputArgCounts(a, P2), r.addImplicitInputs(a, M3), r.endNode(a); } } n.Node = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsValueInfo(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsValueInfo(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } name(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } docString(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, a) : null; } type(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? (a || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startValueInfo(a) { a.startObject(3); } static addName(a, u) { a.addFieldOffset(0, u, 0); } static addDocString(a, u) { a.addFieldOffset(1, u, 0); } static addType(a, u) { a.addFieldOffset(2, u, 0); } static endValueInfo(a) { return a.endObject(); } static createValueInfo(a, u, l, f) { return r.startValueInfo(a), r.addName(a, u), r.addDocString(a, l), r.addType(a, f), r.endValueInfo(a); } } n.ValueInfo = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsTypeInfo(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsTypeInfo(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } denotation(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } valueType() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.readUint8(this.bb_pos + a) : 0; } value(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__union(a, this.bb_pos + u) : null; } static startTypeInfo(a) { a.startObject(3); } static addDenotation(a, u) { a.addFieldOffset(0, u, 0); } static addValueType(a, u) { a.addFieldInt8(1, u, 0); } static addValue(a, u) { a.addFieldOffset(2, u, 0); } static endTypeInfo(a) { return a.endObject(); } static createTypeInfo(a, u, l, f) { return r.startTypeInfo(a), r.addDenotation(a, u), r.addValueType(a, l), r.addValue(a, f), r.endTypeInfo(a); } } n.TypeInfo = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsOperatorSetId(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsOperatorSetId(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } domain(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } version() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.readInt64(this.bb_pos + a) : this.bb.createLong(0, 0); } static startOperatorSetId(a) { a.startObject(2); } static addDomain(a, u) { a.addFieldOffset(0, u, 0); } static addVersion(a, u) { a.addFieldInt64(1, u, a.createLong(0, 0)); } static endOperatorSetId(a) { return a.endObject(); } static createOperatorSetId(a, u, l) { return r.startOperatorSetId(a), r.addDomain(a, u), r.addVersion(a, l), r.endOperatorSetId(a); } } n.OperatorSetId = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsTensor(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsTensor(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } name(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } docString(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, a) : null; } dims(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + a * 8) : this.bb.createLong(0, 0); } dimsLength() { let a = this.bb.__offset(this.bb_pos, 8); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } dataType() { let a = this.bb.__offset(this.bb_pos, 10); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } rawData(a) { let u = this.bb.__offset(this.bb_pos, 12); return u ? this.bb.readUint8(this.bb.__vector(this.bb_pos + u) + a) : 0; } rawDataLength() { let a = this.bb.__offset(this.bb_pos, 12); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } rawDataArray() { let a = this.bb.__offset(this.bb_pos, 12); return a ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + a), this.bb.__vector_len(this.bb_pos + a)) : null; } stringData(a, u) { let l = this.bb.__offset(this.bb_pos, 14); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } stringDataLength() { let a = this.bb.__offset(this.bb_pos, 14); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startTensor(a) { a.startObject(6); } static addName(a, u) { a.addFieldOffset(0, u, 0); } static addDocString(a, u) { a.addFieldOffset(1, u, 0); } static addDims(a, u) { a.addFieldOffset(2, u, 0); } static createDimsVector(a, u) { a.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) a.addInt64(u[l]); return a.endVector(); } static startDimsVector(a, u) { a.startVector(8, u, 8); } static addDataType(a, u) { a.addFieldInt32(3, u, 0); } static addRawData(a, u) { a.addFieldOffset(4, u, 0); } static createRawDataVector(a, u) { a.startVector(1, u.length, 1); for (let l = u.length - 1; l >= 0; l--) a.addInt8(u[l]); return a.endVector(); } static startRawDataVector(a, u) { a.startVector(1, u, 1); } static addStringData(a, u) { a.addFieldOffset(5, u, 0); } static createStringDataVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startStringDataVector(a, u) { a.startVector(4, u, 4); } static endTensor(a) { return a.endObject(); } static createTensor(a, u, l, f, p, d, y) { return r.startTensor(a), r.addName(a, u), r.addDocString(a, l), r.addDims(a, f), r.addDataType(a, p), r.addRawData(a, d), r.addStringData(a, y), r.endTensor(a); } } n.Tensor = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsSparseTensor(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsSparseTensor(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } values(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (a || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } indices(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (a || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } dims(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + a * 8) : this.bb.createLong(0, 0); } dimsLength() { let a = this.bb.__offset(this.bb_pos, 8); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startSparseTensor(a) { a.startObject(3); } static addValues(a, u) { a.addFieldOffset(0, u, 0); } static addIndices(a, u) { a.addFieldOffset(1, u, 0); } static addDims(a, u) { a.addFieldOffset(2, u, 0); } static createDimsVector(a, u) { a.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) a.addInt64(u[l]); return a.endVector(); } static startDimsVector(a, u) { a.startVector(8, u, 8); } static endSparseTensor(a) { return a.endObject(); } static createSparseTensor(a, u, l, f) { return r.startSparseTensor(a), r.addValues(a, u), r.addIndices(a, l), r.addDims(a, f), r.endSparseTensor(a); } } n.SparseTensor = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsAttribute(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsAttribute(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } name(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } docString(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, a) : null; } type() { let a = this.bb.__offset(this.bb_pos, 8); return a ? this.bb.readInt32(this.bb_pos + a) : 0; } f() { let a = this.bb.__offset(this.bb_pos, 10); return a ? this.bb.readFloat32(this.bb_pos + a) : 0; } i() { let a = this.bb.__offset(this.bb_pos, 12); return a ? this.bb.readInt64(this.bb_pos + a) : this.bb.createLong(0, 0); } s(a) { let u = this.bb.__offset(this.bb_pos, 14); return u ? this.bb.__string(this.bb_pos + u, a) : null; } t(a) { let u = this.bb.__offset(this.bb_pos, 16); return u ? (a || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } g(a) { let u = this.bb.__offset(this.bb_pos, 18); return u ? (a || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } floats(a) { let u = this.bb.__offset(this.bb_pos, 20); return u ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + u) + a * 4) : 0; } floatsLength() { let a = this.bb.__offset(this.bb_pos, 20); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } floatsArray() { let a = this.bb.__offset(this.bb_pos, 20); return a ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + a), this.bb.__vector_len(this.bb_pos + a)) : null; } ints(a) { let u = this.bb.__offset(this.bb_pos, 22); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + a * 8) : this.bb.createLong(0, 0); } intsLength() { let a = this.bb.__offset(this.bb_pos, 22); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } strings(a, u) { let l = this.bb.__offset(this.bb_pos, 24); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } stringsLength() { let a = this.bb.__offset(this.bb_pos, 24); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } tensors(a, u) { let l = this.bb.__offset(this.bb_pos, 26); return l ? (u || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } tensorsLength() { let a = this.bb.__offset(this.bb_pos, 26); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } graphs(a, u) { let l = this.bb.__offset(this.bb_pos, 28); return l ? (u || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } graphsLength() { let a = this.bb.__offset(this.bb_pos, 28); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startAttribute(a) { a.startObject(13); } static addName(a, u) { a.addFieldOffset(0, u, 0); } static addDocString(a, u) { a.addFieldOffset(1, u, 0); } static addType(a, u) { a.addFieldInt32(2, u, 0); } static addF(a, u) { a.addFieldFloat32(3, u, 0); } static addI(a, u) { a.addFieldInt64(4, u, a.createLong(0, 0)); } static addS(a, u) { a.addFieldOffset(5, u, 0); } static addT(a, u) { a.addFieldOffset(6, u, 0); } static addG(a, u) { a.addFieldOffset(7, u, 0); } static addFloats(a, u) { a.addFieldOffset(8, u, 0); } static createFloatsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addFloat32(u[l]); return a.endVector(); } static startFloatsVector(a, u) { a.startVector(4, u, 4); } static addInts(a, u) { a.addFieldOffset(9, u, 0); } static createIntsVector(a, u) { a.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) a.addInt64(u[l]); return a.endVector(); } static startIntsVector(a, u) { a.startVector(8, u, 8); } static addStrings(a, u) { a.addFieldOffset(10, u, 0); } static createStringsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startStringsVector(a, u) { a.startVector(4, u, 4); } static addTensors(a, u) { a.addFieldOffset(11, u, 0); } static createTensorsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startTensorsVector(a, u) { a.startVector(4, u, 4); } static addGraphs(a, u) { a.addFieldOffset(12, u, 0); } static createGraphsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startGraphsVector(a, u) { a.startVector(4, u, 4); } static endAttribute(a) { return a.endObject(); } static createAttribute(a, u, l, f, p, d, y, w, v, S, L, A2, P2, M3) { return r.startAttribute(a), r.addName(a, u), r.addDocString(a, l), r.addType(a, f), r.addF(a, p), r.addI(a, d), r.addS(a, y), r.addT(a, w), r.addG(a, v), r.addFloats(a, S), r.addInts(a, L), r.addStrings(a, A2), r.addTensors(a, P2), r.addGraphs(a, M3), r.endAttribute(a); } } n.Attribute = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsGraph(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsGraph(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } initializers(a, u) { let l = this.bb.__offset(this.bb_pos, 4); return l ? (u || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } initializersLength() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } nodeArgs(a, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } nodeArgsLength() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } nodes(a, u) { let l = this.bb.__offset(this.bb_pos, 8); return l ? (u || new e.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } nodesLength() { let a = this.bb.__offset(this.bb_pos, 8); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } maxNodeIndex() { let a = this.bb.__offset(this.bb_pos, 10); return a ? this.bb.readUint32(this.bb_pos + a) : 0; } nodeEdges(a, u) { let l = this.bb.__offset(this.bb_pos, 12); return l ? (u || new e.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } nodeEdgesLength() { let a = this.bb.__offset(this.bb_pos, 12); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } inputs(a, u) { let l = this.bb.__offset(this.bb_pos, 14); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } inputsLength() { let a = this.bb.__offset(this.bb_pos, 14); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } outputs(a, u) { let l = this.bb.__offset(this.bb_pos, 16); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + a * 4, u) : null; } outputsLength() { let a = this.bb.__offset(this.bb_pos, 16); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } sparseInitializers(a, u) { let l = this.bb.__offset(this.bb_pos, 18); return l ? (u || new e.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } sparseInitializersLength() { let a = this.bb.__offset(this.bb_pos, 18); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startGraph(a) { a.startObject(8); } static addInitializers(a, u) { a.addFieldOffset(0, u, 0); } static createInitializersVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startInitializersVector(a, u) { a.startVector(4, u, 4); } static addNodeArgs(a, u) { a.addFieldOffset(1, u, 0); } static createNodeArgsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startNodeArgsVector(a, u) { a.startVector(4, u, 4); } static addNodes(a, u) { a.addFieldOffset(2, u, 0); } static createNodesVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startNodesVector(a, u) { a.startVector(4, u, 4); } static addMaxNodeIndex(a, u) { a.addFieldInt32(3, u, 0); } static addNodeEdges(a, u) { a.addFieldOffset(4, u, 0); } static createNodeEdgesVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startNodeEdgesVector(a, u) { a.startVector(4, u, 4); } static addInputs(a, u) { a.addFieldOffset(5, u, 0); } static createInputsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startInputsVector(a, u) { a.startVector(4, u, 4); } static addOutputs(a, u) { a.addFieldOffset(6, u, 0); } static createOutputsVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startOutputsVector(a, u) { a.startVector(4, u, 4); } static addSparseInitializers(a, u) { a.addFieldOffset(7, u, 0); } static createSparseInitializersVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startSparseInitializersVector(a, u) { a.startVector(4, u, 4); } static endGraph(a) { return a.endObject(); } static createGraph(a, u, l, f, p, d, y, w, v) { return r.startGraph(a), r.addInitializers(a, u), r.addNodeArgs(a, l), r.addNodes(a, f), r.addMaxNodeIndex(a, p), r.addNodeEdges(a, d), r.addInputs(a, y), r.addOutputs(a, w), r.addSparseInitializers(a, v), r.endGraph(a); } } n.Graph = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsModel(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsModel(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } irVersion() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.readInt64(this.bb_pos + a) : this.bb.createLong(0, 0); } opsetImport(a, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } opsetImportLength() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } producerName(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, a) : null; } producerVersion(a) { let u = this.bb.__offset(this.bb_pos, 10); return u ? this.bb.__string(this.bb_pos + u, a) : null; } domain(a) { let u = this.bb.__offset(this.bb_pos, 12); return u ? this.bb.__string(this.bb_pos + u, a) : null; } modelVersion() { let a = this.bb.__offset(this.bb_pos, 14); return a ? this.bb.readInt64(this.bb_pos + a) : this.bb.createLong(0, 0); } docString(a) { let u = this.bb.__offset(this.bb_pos, 16); return u ? this.bb.__string(this.bb_pos + u, a) : null; } graph(a) { let u = this.bb.__offset(this.bb_pos, 18); return u ? (a || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } graphDocString(a) { let u = this.bb.__offset(this.bb_pos, 20); return u ? this.bb.__string(this.bb_pos + u, a) : null; } static startModel(a) { a.startObject(9); } static addIrVersion(a, u) { a.addFieldInt64(0, u, a.createLong(0, 0)); } static addOpsetImport(a, u) { a.addFieldOffset(1, u, 0); } static createOpsetImportVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startOpsetImportVector(a, u) { a.startVector(4, u, 4); } static addProducerName(a, u) { a.addFieldOffset(2, u, 0); } static addProducerVersion(a, u) { a.addFieldOffset(3, u, 0); } static addDomain(a, u) { a.addFieldOffset(4, u, 0); } static addModelVersion(a, u) { a.addFieldInt64(5, u, a.createLong(0, 0)); } static addDocString(a, u) { a.addFieldOffset(6, u, 0); } static addGraph(a, u) { a.addFieldOffset(7, u, 0); } static addGraphDocString(a, u) { a.addFieldOffset(8, u, 0); } static endModel(a) { return a.endObject(); } static createModel(a, u, l, f, p, d, y, w, v, S) { return r.startModel(a), r.addIrVersion(a, u), r.addOpsetImport(a, l), r.addProducerName(a, f), r.addProducerVersion(a, p), r.addDomain(a, d), r.addModelVersion(a, y), r.addDocString(a, w), r.addGraph(a, v), r.addGraphDocString(a, S), r.endModel(a); } } n.Model = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsKernelCreateInfos(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsKernelCreateInfos(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } nodeIndices(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.readUint32(this.bb.__vector(this.bb_pos + u) + a * 4) : 0; } nodeIndicesLength() { let a = this.bb.__offset(this.bb_pos, 4); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } nodeIndicesArray() { let a = this.bb.__offset(this.bb_pos, 4); return a ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + a), this.bb.__vector_len(this.bb_pos + a)) : null; } kernelDefHashes(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.readUint64(this.bb.__vector(this.bb_pos + u) + a * 8) : this.bb.createLong(0, 0); } kernelDefHashesLength() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startKernelCreateInfos(a) { a.startObject(2); } static addNodeIndices(a, u) { a.addFieldOffset(0, u, 0); } static createNodeIndicesVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addInt32(u[l]); return a.endVector(); } static startNodeIndicesVector(a, u) { a.startVector(4, u, 4); } static addKernelDefHashes(a, u) { a.addFieldOffset(1, u, 0); } static createKernelDefHashesVector(a, u) { a.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) a.addInt64(u[l]); return a.endVector(); } static startKernelDefHashesVector(a, u) { a.startVector(8, u, 8); } static endKernelCreateInfos(a) { return a.endObject(); } static createKernelCreateInfos(a, u, l) { return r.startKernelCreateInfos(a), r.addNodeIndices(a, u), r.addKernelDefHashes(a, l), r.endKernelCreateInfos(a); } } n.KernelCreateInfos = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsSubGraphSessionState(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsSubGraphSessionState(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } graphId(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } sessionState(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (a || new e.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startSubGraphSessionState(a) { a.startObject(2); } static addGraphId(a, u) { a.addFieldOffset(0, u, 0); } static addSessionState(a, u) { a.addFieldOffset(1, u, 0); } static endSubGraphSessionState(a) { let u = a.endObject(); return a.requiredField(u, 4), u; } static createSubGraphSessionState(a, u, l) { return r.startSubGraphSessionState(a), r.addGraphId(a, u), r.addSessionState(a, l), r.endSubGraphSessionState(a); } } n.SubGraphSessionState = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsSessionState(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsSessionState(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } kernels(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (a || new e.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } subGraphSessionStates(a, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + a * 4), this.bb) : null; } subGraphSessionStatesLength() { let a = this.bb.__offset(this.bb_pos, 6); return a ? this.bb.__vector_len(this.bb_pos + a) : 0; } static startSessionState(a) { a.startObject(2); } static addKernels(a, u) { a.addFieldOffset(0, u, 0); } static addSubGraphSessionStates(a, u) { a.addFieldOffset(1, u, 0); } static createSubGraphSessionStatesVector(a, u) { a.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) a.addOffset(u[l]); return a.endVector(); } static startSubGraphSessionStatesVector(a, u) { a.startVector(4, u, 4); } static endSessionState(a) { return a.endObject(); } static createSessionState(a, u, l) { return r.startSessionState(a), r.addKernels(a, u), r.addSubGraphSessionStates(a, l), r.endSessionState(a); } } n.SessionState = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); ((e) => { let i; ((t) => { let o; ((n) => { class r { constructor() { this.bb = null; this.bb_pos = 0; } __init(a, u) { return this.bb_pos = a, this.bb = u, this; } static getRootAsInferenceSession(a, u) { return (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static getSizePrefixedRootAsInferenceSession(a, u) { return a.setPosition(a.position() + T.SIZE_PREFIX_LENGTH), (u || new r()).__init(a.readInt32(a.position()) + a.position(), a); } static bufferHasIdentifier(a) { return a.__has_identifier("ORTM"); } ortVersion(a) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, a) : null; } model(a) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (a || new e.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } sessionState(a) { let u = this.bb.__offset(this.bb_pos, 8); return u ? (a || new e.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startInferenceSession(a) { a.startObject(3); } static addOrtVersion(a, u) { a.addFieldOffset(0, u, 0); } static addModel(a, u) { a.addFieldOffset(1, u, 0); } static addSessionState(a, u) { a.addFieldOffset(2, u, 0); } static endInferenceSession(a) { return a.endObject(); } static finishInferenceSessionBuffer(a, u) { a.finish(u, "ORTM"); } static finishSizePrefixedInferenceSessionBuffer(a, u) { a.finish(u, "ORTM", true); } static createInferenceSession(a, u, l, f) { return r.startInferenceSession(a), r.addOrtVersion(a, u), r.addModel(a, l), r.addSessionState(a, f), r.endInferenceSession(a); } } n.InferenceSession = r; })(o = t.fbs ||= {}); })(i = e.experimental ||= {}); })(F ||= {}); }); Hs = mt((Uy, Ws3) => { "use strict"; Ws3.exports = nh2; function nh2(i, e) { for (var o = new Array(arguments.length - 1), t = 0, r = 2, n = true; r < arguments.length; ) o[t++] = arguments[r++]; return new Promise(function(a, u) { o[t] = function(f) { if (n) if (n = false, f) u(f); else { for (var p = new Array(arguments.length - 1), d = 0; d < p.length; ) p[d++] = arguments[d]; a.apply(null, p); } }; try { i.apply(e || null, o); } catch (l) { n && (n = false, u(l)); } }); } }); Ks = mt((Xs3) => { "use strict"; var Tn2 = Xs3; Tn2.length = function(e) { var o = e.length; if (!o) return 0; for (var t = 0; --o % 4 > 1 && e.charAt(o) === "="; ) ++t; return Math.ceil(e.length * 3) / 4 - t; }; var ar2 = new Array(64), js3 = new Array(123); for (Zt3 = 0; Zt3 < 64; ) js3[ar2[Zt3] = Zt3 < 26 ? Zt3 + 65 : Zt3 < 52 ? Zt3 + 71 : Zt3 < 62 ? Zt3 - 4 : Zt3 - 59 | 43] = Zt3++; var Zt3; Tn2.encode = function(e, o, t) { for (var r = null, n = [], s = 0, a = 0, u; o < t; ) { var l = e[o++]; switch (a) { case 0: n[s++] = ar2[l >> 2], u = (l & 3) << 4, a = 1; break; case 1: n[s++] = ar2[u | l >> 4], u = (l & 15) << 2, a = 2; break; case 2: n[s++] = ar2[u | l >> 6], n[s++] = ar2[l & 63], a = 0; break; } s > 8191 && ((r || (r = [])).push(String.fromCharCode.apply(String, n)), s = 0); } return a && (n[s++] = ar2[u], n[s++] = 61, a === 1 && (n[s++] = 61)), r ? (s && r.push(String.fromCharCode.apply(String, n.slice(0, s))), r.join("")) : String.fromCharCode.apply(String, n.slice(0, s)); }; var qs3 = "invalid encoding"; Tn2.decode = function(e, o, t) { for (var r = t, n = 0, s, a = 0; a < e.length; ) { var u = e.charCodeAt(a++); if (u === 61 && n > 1) break; if ((u = js3[u]) === void 0) throw Error(qs3); switch (n) { case 0: s = u, n = 1; break; case 1: o[t++] = s << 2 | (u & 48) >> 4, s = u, n = 2; break; case 2: o[t++] = (s & 15) << 4 | (u & 60) >> 2, s = u, n = 3; break; case 3: o[t++] = (s & 3) << 6 | u, n = 0; break; } } if (n === 1) throw Error(qs3); return t - r; }; Tn2.test = function(e) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e); }; }); Ys = mt((zy, Js3) => { "use strict"; Js3.exports = wn2; function wn2() { this._listeners = {}; } wn2.prototype.on = function(e, o, t) { return (this._listeners[e] || (this._listeners[e] = [])).push({ fn: o, ctx: t || this }), this; }; wn2.prototype.off = function(e, o) { if (e === void 0) this._listeners = {}; else if (o === void 0) this._listeners[e] = []; else for (var t = this._listeners[e], r = 0; r < t.length; ) t[r].fn === o ? t.splice(r, 1) : ++r; return this; }; wn2.prototype.emit = function(e) { var o = this._listeners[e]; if (o) { for (var t = [], r = 1; r < arguments.length; ) t.push(arguments[r++]); for (r = 0; r < o.length; ) o[r].fn.apply(o[r++].ctx, t); } return this; }; }); ou = mt((Wy, nu3) => { "use strict"; nu3.exports = Zs3(Zs3); function Zs3(i) { return typeof Float32Array < "u" ? (function() { var e = new Float32Array([-0]), o = new Uint8Array(e.buffer), t = o[3] === 128; function r(u, l, f) { e[0] = u, l[f] = o[0], l[f + 1] = o[1], l[f + 2] = o[2], l[f + 3] = o[3]; } function n(u, l, f) { e[0] = u, l[f] = o[3], l[f + 1] = o[2], l[f + 2] = o[1], l[f + 3] = o[0]; } i.writeFloatLE = t ? r : n, i.writeFloatBE = t ? n : r; function s(u, l) { return o[0] = u[l], o[1] = u[l + 1], o[2] = u[l + 2], o[3] = u[l + 3], e[0]; } function a(u, l) { return o[3] = u[l], o[2] = u[l + 1], o[1] = u[l + 2], o[0] = u[l + 3], e[0]; } i.readFloatLE = t ? s : a, i.readFloatBE = t ? a : s; })() : (function() { function e(t, r, n, s) { var a = r < 0 ? 1 : 0; if (a && (r = -r), r === 0) t(1 / r > 0 ? 0 : 2147483648, n, s); else if (isNaN(r)) t(2143289344, n, s); else if (r > 34028234663852886e22) t((a << 31 | 2139095040) >>> 0, n, s); else if (r < 11754943508222875e-54) t((a << 31 | Math.round(r / 1401298464324817e-60)) >>> 0, n, s); else { var u = Math.floor(Math.log(r) / Math.LN2), l = Math.round(r * Math.pow(2, -u) * 8388608) & 8388607; t((a << 31 | u + 127 << 23 | l) >>> 0, n, s); } } i.writeFloatLE = e.bind(null, Qs3), i.writeFloatBE = e.bind(null, tu3); function o(t, r, n) { var s = t(r, n), a = (s >> 31) * 2 + 1, u = s >>> 23 & 255, l = s & 8388607; return u === 255 ? l ? NaN : a * (1 / 0) : u === 0 ? a * 1401298464324817e-60 * l : a * Math.pow(2, u - 150) * (l + 8388608); } i.readFloatLE = o.bind(null, eu3), i.readFloatBE = o.bind(null, ru3); })(), typeof Float64Array < "u" ? (function() { var e = new Float64Array([-0]), o = new Uint8Array(e.buffer), t = o[7] === 128; function r(u, l, f) { e[0] = u, l[f] = o[0], l[f + 1] = o[1], l[f + 2] = o[2], l[f + 3] = o[3], l[f + 4] = o[4], l[f + 5] = o[5], l[f + 6] = o[6], l[f + 7] = o[7]; } function n(u, l, f) { e[0] = u, l[f] = o[7], l[f + 1] = o[6], l[f + 2] = o[5], l[f + 3] = o[4], l[f + 4] = o[3], l[f + 5] = o[2], l[f + 6] = o[1], l[f + 7] = o[0]; } i.writeDoubleLE = t ? r : n, i.writeDoubleBE = t ? n : r; function s(u, l) { return o[0] = u[l], o[1] = u[l + 1], o[2] = u[l + 2], o[3] = u[l + 3], o[4] = u[l + 4], o[5] = u[l + 5], o[6] = u[l + 6], o[7] = u[l + 7], e[0]; } function a(u, l) { return o[7] = u[l], o[6] = u[l + 1], o[5] = u[l + 2], o[4] = u[l + 3], o[3] = u[l + 4], o[2] = u[l + 5], o[1] = u[l + 6], o[0] = u[l + 7], e[0]; } i.readDoubleLE = t ? s : a, i.readDoubleBE = t ? a : s; })() : (function() { function e(t, r, n, s, a, u) { var l = s < 0 ? 1 : 0; if (l && (s = -s), s === 0) t(0, a, u + r), t(1 / s > 0 ? 0 : 2147483648, a, u + n); else if (isNaN(s)) t(0, a, u + r), t(2146959360, a, u + n); else if (s > 17976931348623157e292) t(0, a, u + r), t((l << 31 | 2146435072) >>> 0, a, u + n); else { var f; if (s < 22250738585072014e-324) f = s / 5e-324, t(f >>> 0, a, u + r), t((l << 31 | f / 4294967296) >>> 0, a, u + n); else { var p = Math.floor(Math.log(s) / Math.LN2); p === 1024 && (p = 1023), f = s * Math.pow(2, -p), t(f * 4503599627370496 >>> 0, a, u + r), t((l << 31 | p + 1023 << 20 | f * 1048576 & 1048575) >>> 0, a, u + n); } } } i.writeDoubleLE = e.bind(null, Qs3, 0, 4), i.writeDoubleBE = e.bind(null, tu3, 4, 0); function o(t, r, n, s, a) { var u = t(s, a + r), l = t(s, a + n), f = (l >> 31) * 2 + 1, p = l >>> 20 & 2047, d = 4294967296 * (l & 1048575) + u; return p === 2047 ? d ? NaN : f * (1 / 0) : p === 0 ? f * 5e-324 * d : f * Math.pow(2, p - 1075) * (d + 4503599627370496); } i.readDoubleLE = o.bind(null, eu3, 0, 4), i.readDoubleBE = o.bind(null, ru3, 4, 0); })(), i; } function Qs3(i, e, o) { e[o] = i & 255, e[o + 1] = i >>> 8 & 255, e[o + 2] = i >>> 16 & 255, e[o + 3] = i >>> 24; } function tu3(i, e, o) { e[o] = i >>> 24, e[o + 1] = i >>> 16 & 255, e[o + 2] = i >>> 8 & 255, e[o + 3] = i & 255; } function eu3(i, e) { return (i[e] | i[e + 1] << 8 | i[e + 2] << 16 | i[e + 3] << 24) >>> 0; } function ru3(i, e) { return (i[e] << 24 | i[e + 1] << 16 | i[e + 2] << 8 | i[e + 3]) >>> 0; } }); iu = mt((exports, module) => { "use strict"; module.exports = inquire; function inquire(moduleName) { try { var mod = eval("quire".replace(/^/, "re"))(moduleName); if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (i) { } return null; } }); su = mt((au3) => { "use strict"; var Wo = au3; Wo.length = function(e) { for (var o = 0, t = 0, r = 0; r < e.length; ++r) t = e.charCodeAt(r), t < 128 ? o += 1 : t < 2048 ? o += 2 : (t & 64512) === 55296 && (e.charCodeAt(r + 1) & 64512) === 56320 ? (++r, o += 4) : o += 3; return o; }; Wo.read = function(e, o, t) { var r = t - o; if (r < 1) return ""; for (var n = null, s = [], a = 0, u; o < t; ) u = e[o++], u < 128 ? s[a++] = u : u > 191 && u < 224 ? s[a++] = (u & 31) << 6 | e[o++] & 63 : u > 239 && u < 365 ? (u = ((u & 7) << 18 | (e[o++] & 63) << 12 | (e[o++] & 63) << 6 | e[o++] & 63) - 65536, s[a++] = 55296 + (u >> 10), s[a++] = 56320 + (u & 1023)) : s[a++] = (u & 15) << 12 | (e[o++] & 63) << 6 | e[o++] & 63, a > 8191 && ((n || (n = [])).push(String.fromCharCode.apply(String, s)), a = 0); return n ? (a && n.push(String.fromCharCode.apply(String, s.slice(0, a))), n.join("")) : String.fromCharCode.apply(String, s.slice(0, a)); }; Wo.write = function(e, o, t) { for (var r = t, n, s, a = 0; a < e.length; ++a) n = e.charCodeAt(a), n < 128 ? o[t++] = n : n < 2048 ? (o[t++] = n >> 6 | 192, o[t++] = n & 63 | 128) : (n & 64512) === 55296 && ((s = e.charCodeAt(a + 1)) & 64512) === 56320 ? (n = 65536 + ((n & 1023) << 10) + (s & 1023), ++a, o[t++] = n >> 18 | 240, o[t++] = n >> 12 & 63 | 128, o[t++] = n >> 6 & 63 | 128, o[t++] = n & 63 | 128) : (o[t++] = n >> 12 | 224, o[t++] = n >> 6 & 63 | 128, o[t++] = n & 63 | 128); return t - r; }; }); lu = mt((qy, uu3) => { "use strict"; uu3.exports = oh2; function oh2(i, e, o) { var t = o || 8192, r = t >>> 1, n = null, s = t; return function(u) { if (u < 1 || u > r) return i(u); s + u > t && (n = i(t), s = 0); var l = e.call(n, s, s += u); return s & 7 && (s = (s | 7) + 1), l; }; } }); cu = mt((jy, fu3) => { "use strict"; fu3.exports = wt; var Er3 = Oe(); function wt(i, e) { this.lo = i >>> 0, this.hi = e >>> 0; } var Ne3 = wt.zero = new wt(0, 0); Ne3.toNumber = function() { return 0; }; Ne3.zzEncode = Ne3.zzDecode = function() { return this; }; Ne3.length = function() { return 1; }; var ih2 = wt.zeroHash = "\0\0\0\0\0\0\0\0"; wt.fromNumber = function(e) { if (e === 0) return Ne3; var o = e < 0; o && (e = -e); var t = e >>> 0, r = (e - t) / 4294967296 >>> 0; return o && (r = ~r >>> 0, t = ~t >>> 0, ++t > 4294967295 && (t = 0, ++r > 4294967295 && (r = 0))), new wt(t, r); }; wt.from = function(e) { if (typeof e == "number") return wt.fromNumber(e); if (Er3.isString(e)) if (Er3.Long) e = Er3.Long.fromString(e); else return wt.fromNumber(parseInt(e, 10)); return e.low || e.high ? new wt(e.low >>> 0, e.high >>> 0) : Ne3; }; wt.prototype.toNumber = function(e) { if (!e && this.hi >>> 31) { var o = ~this.lo + 1 >>> 0, t = ~this.hi >>> 0; return o || (t = t + 1 >>> 0), -(o + t * 4294967296); } return this.lo + this.hi * 4294967296; }; wt.prototype.toLong = function(e) { return Er3.Long ? new Er3.Long(this.lo | 0, this.hi | 0, !!e) : { low: this.lo | 0, high: this.hi | 0, unsigned: !!e }; }; var _e3 = String.prototype.charCodeAt; wt.fromHash = function(e) { return e === ih2 ? Ne3 : new wt((_e3.call(e, 0) | _e3.call(e, 1) << 8 | _e3.call(e, 2) << 16 | _e3.call(e, 3) << 24) >>> 0, (_e3.call(e, 4) | _e3.call(e, 5) << 8 | _e3.call(e, 6) << 16 | _e3.call(e, 7) << 24) >>> 0); }; wt.prototype.toHash = function() { return String.fromCharCode(this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24); }; wt.prototype.zzEncode = function() { var e = this.hi >> 31; return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ e) >>> 0, this.lo = (this.lo << 1 ^ e) >>> 0, this; }; wt.prototype.zzDecode = function() { var e = -(this.lo & 1); return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ e) >>> 0, this.hi = (this.hi >>> 1 ^ e) >>> 0, this; }; wt.prototype.length = function() { var e = this.lo, o = (this.lo >>> 28 | this.hi << 4) >>> 0, t = this.hi >>> 24; return t === 0 ? o === 0 ? e < 16384 ? e < 128 ? 1 : 2 : e < 2097152 ? 3 : 4 : o < 16384 ? o < 128 ? 5 : 6 : o < 2097152 ? 7 : 8 : t < 128 ? 9 : 10; }; }); Oe = mt((Ho2) => { "use strict"; var N2 = Ho2; N2.asPromise = Hs(); N2.base64 = Ks(); N2.EventEmitter = Ys(); N2.float = ou(); N2.inquire = iu(); N2.utf8 = su(); N2.pool = lu(); N2.LongBits = cu(); N2.isNode = !!(typeof global < "u" && global && global.process && global.process.versions && global.process.versions.node); N2.global = N2.isNode && global || typeof window < "u" && window || typeof self < "u" && self || Ho2; N2.emptyArray = Object.freeze ? Object.freeze([]) : []; N2.emptyObject = Object.freeze ? Object.freeze({}) : {}; N2.isInteger = Number.isInteger || function(e) { return typeof e == "number" && isFinite(e) && Math.floor(e) === e; }; N2.isString = function(e) { return typeof e == "string" || e instanceof String; }; N2.isObject = function(e) { return e && typeof e == "object"; }; N2.isset = N2.isSet = function(e, o) { var t = e[o]; return t != null && e.hasOwnProperty(o) ? typeof t != "object" || (Array.isArray(t) ? t.length : Object.keys(t).length) > 0 : false; }; N2.Buffer = (function() { try { var i = N2.inquire("buffer").Buffer; return i.prototype.utf8Write ? i : null; } catch { return null; } })(); N2._Buffer_from = null; N2._Buffer_allocUnsafe = null; N2.newBuffer = function(e) { return typeof e == "number" ? N2.Buffer ? N2._Buffer_allocUnsafe(e) : new N2.Array(e) : N2.Buffer ? N2._Buffer_from(e) : typeof Uint8Array > "u" ? e : new Uint8Array(e); }; N2.Array = typeof Uint8Array < "u" ? Uint8Array : Array; N2.Long = N2.global.dcodeIO && N2.global.dcodeIO.Long || N2.global.Long || N2.inquire("long"); N2.key2Re = /^true|false|0|1$/; N2.key32Re = /^-?(?:0|[1-9][0-9]*)$/; N2.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; N2.longToHash = function(e) { return e ? N2.LongBits.from(e).toHash() : N2.LongBits.zeroHash; }; N2.longFromHash = function(e, o) { var t = N2.LongBits.fromHash(e); return N2.Long ? N2.Long.fromBits(t.lo, t.hi, o) : t.toNumber(!!o); }; function pu3(i, e, o) { for (var t = Object.keys(e), r = 0; r < t.length; ++r) (i[t[r]] === void 0 || !o) && (i[t[r]] = e[t[r]]); return i; } N2.merge = pu3; N2.lcFirst = function(e) { return e.charAt(0).toLowerCase() + e.substring(1); }; function du3(i) { function e(o, t) { if (!(this instanceof e)) return new e(o, t); Object.defineProperty(this, "message", { get: function() { return o; } }), Error.captureStackTrace ? Error.captureStackTrace(this, e) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), t && pu3(this, t); } return e.prototype = Object.create(Error.prototype, { constructor: { value: e, writable: true, enumerable: false, configurable: true }, name: { get: function() { return i; }, set: void 0, enumerable: false, configurable: true }, toString: { value: function() { return this.name + ": " + this.message; }, writable: true, enumerable: false, configurable: true } }), e; } N2.newError = du3; N2.ProtocolError = du3("ProtocolError"); N2.oneOfGetter = function(e) { for (var o = {}, t = 0; t < e.length; ++t) o[e[t]] = 1; return function() { for (var r = Object.keys(this), n = r.length - 1; n > -1; --n) if (o[r[n]] === 1 && this[r[n]] !== void 0 && this[r[n]] !== null) return r[n]; }; }; N2.oneOfSetter = function(e) { return function(o) { for (var t = 0; t < e.length; ++t) e[t] !== o && delete this[e[t]]; }; }; N2.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }; N2._configure = function() { var i = N2.Buffer; if (!i) { N2._Buffer_from = N2._Buffer_allocUnsafe = null; return; } N2._Buffer_from = i.from !== Uint8Array.from && i.from || function(o, t) { return new i(o, t); }, N2._Buffer_allocUnsafe = i.allocUnsafe || function(o) { return new i(o); }; }; }); Zo = mt((Ky, gu3) => { "use strict"; gu3.exports = X; var zt2 = Oe(), qo, vn2 = zt2.LongBits, hu3 = zt2.base64, mu3 = zt2.utf8; function Dr3(i, e, o) { this.fn = i, this.len = e, this.next = void 0, this.val = o; } function Xo() { } function ah2(i) { this.head = i.head, this.tail = i.tail, this.len = i.len, this.next = i.states; } function X() { this.len = 0, this.head = new Dr3(Xo, 0, 0), this.tail = this.head, this.states = null; } var bu3 = function() { return zt2.Buffer ? function() { return (X.create = function() { return new qo(); })(); } : function() { return new X(); }; }; X.create = bu3(); X.alloc = function(e) { return new zt2.Array(e); }; zt2.Array !== Array && (X.alloc = zt2.pool(X.alloc, zt2.Array.prototype.subarray)); X.prototype._push = function(e, o, t) { return this.tail = this.tail.next = new Dr3(e, o, t), this.len += o, this; }; function Ko(i, e, o) { e[o] = i & 255; } function sh2(i, e, o) { for (; i > 127; ) e[o++] = i & 127 | 128, i >>>= 7; e[o] = i; } function Jo(i, e) { this.len = i, this.next = void 0, this.val = e; } Jo.prototype = Object.create(Dr3.prototype); Jo.prototype.fn = sh2; X.prototype.uint32 = function(e) { return this.len += (this.tail = this.tail.next = new Jo((e = e >>> 0) < 128 ? 1 : e < 16384 ? 2 : e < 2097152 ? 3 : e < 268435456 ? 4 : 5, e)).len, this; }; X.prototype.int32 = function(e) { return e < 0 ? this._push(Yo2, 10, vn2.fromNumber(e)) : this.uint32(e); }; X.prototype.sint32 = function(e) { return this.uint32((e << 1 ^ e >> 31) >>> 0); }; function Yo2(i, e, o) { for (; i.hi; ) e[o++] = i.lo & 127 | 128, i.lo = (i.lo >>> 7 | i.hi << 25) >>> 0, i.hi >>>= 7; for (; i.lo > 127; ) e[o++] = i.lo & 127 | 128, i.lo = i.lo >>> 7; e[o++] = i.lo; } X.prototype.uint64 = function(e) { var o = vn2.from(e); return this._push(Yo2, o.length(), o); }; X.prototype.int64 = X.prototype.uint64; X.prototype.sint64 = function(e) { var o = vn2.from(e).zzEncode(); return this._push(Yo2, o.length(), o); }; X.prototype.bool = function(e) { return this._push(Ko, 1, e ? 1 : 0); }; function jo(i, e, o) { e[o] = i & 255, e[o + 1] = i >>> 8 & 255, e[o + 2] = i >>> 16 & 255, e[o + 3] = i >>> 24; } X.prototype.fixed32 = function(e) { return this._push(jo, 4, e >>> 0); }; X.prototype.sfixed32 = X.prototype.fixed32; X.prototype.fixed64 = function(e) { var o = vn2.from(e); return this._push(jo, 4, o.lo)._push(jo, 4, o.hi); }; X.prototype.sfixed64 = X.prototype.fixed64; X.prototype.float = function(e) { return this._push(zt2.float.writeFloatLE, 4, e); }; X.prototype.double = function(e) { return this._push(zt2.float.writeDoubleLE, 8, e); }; var uh2 = zt2.Array.prototype.set ? function(e, o, t) { o.set(e, t); } : function(e, o, t) { for (var r = 0; r < e.length; ++r) o[t + r] = e[r]; }; X.prototype.bytes = function(e) { var o = e.length >>> 0; if (!o) return this._push(Ko, 1, 0); if (zt2.isString(e)) { var t = X.alloc(o = hu3.length(e)); hu3.decode(e, t, 0), e = t; } return this.uint32(o)._push(uh2, o, e); }; X.prototype.string = function(e) { var o = mu3.length(e); return o ? this.uint32(o)._push(mu3.write, o, e) : this._push(Ko, 1, 0); }; X.prototype.fork = function() { return this.states = new ah2(this), this.head = this.tail = new Dr3(Xo, 0, 0), this.len = 0, this; }; X.prototype.reset = function() { return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new Dr3(Xo, 0, 0), this.len = 0), this; }; X.prototype.ldelim = function() { var e = this.head, o = this.tail, t = this.len; return this.reset().uint32(t), t && (this.tail.next = e.next, this.tail = o, this.len += t), this; }; X.prototype.finish = function() { for (var e = this.head.next, o = this.constructor.alloc(this.len), t = 0; e; ) e.fn(e.val, o, t), t += e.len, e = e.next; return o; }; X._configure = function(i) { qo = i, X.create = bu3(), qo._configure(); }; }); Tu = mt((Jy, xu3) => { "use strict"; xu3.exports = se2; var yu3 = Zo(); (se2.prototype = Object.create(yu3.prototype)).constructor = se2; var Se2 = Oe(); function se2() { yu3.call(this); } se2._configure = function() { se2.alloc = Se2._Buffer_allocUnsafe, se2.writeBytesBuffer = Se2.Buffer && Se2.Buffer.prototype instanceof Uint8Array && Se2.Buffer.prototype.set.name === "set" ? function(e, o, t) { o.set(e, t); } : function(e, o, t) { if (e.copy) e.copy(o, t, 0, e.length); else for (var r = 0; r < e.length; ) o[t++] = e[r++]; }; }; se2.prototype.bytes = function(e) { Se2.isString(e) && (e = Se2._Buffer_from(e, "base64")); var o = e.length >>> 0; return this.uint32(o), o && this._push(se2.writeBytesBuffer, o, e), this; }; function lh2(i, e, o) { i.length < 40 ? Se2.utf8.write(i, e, o) : e.utf8Write ? e.utf8Write(i, o) : e.write(i, o); } se2.prototype.string = function(e) { var o = Se2.Buffer.byteLength(e); return this.uint32(o), o && this._push(lh2, o, e), this; }; se2._configure(); }); ei = mt((Yy, Ou3) => { "use strict"; Ou3.exports = ct2; var Qt3 = Oe(), ti, Iu3 = Qt3.LongBits, fh2 = Qt3.utf8; function te3(i, e) { return RangeError("index out of range: " + i.pos + " + " + (e || 1) + " > " + i.len); } function ct2(i) { this.buf = i, this.pos = 0, this.len = i.length; } var wu3 = typeof Uint8Array < "u" ? function(e) { if (e instanceof Uint8Array || Array.isArray(e)) return new ct2(e); throw Error("illegal buffer"); } : function(e) { if (Array.isArray(e)) return new ct2(e); throw Error("illegal buffer"); }, _u3 = function() { return Qt3.Buffer ? function(o) { return (ct2.create = function(r) { return Qt3.Buffer.isBuffer(r) ? new ti(r) : wu3(r); })(o); } : wu3; }; ct2.create = _u3(); ct2.prototype._slice = Qt3.Array.prototype.subarray || Qt3.Array.prototype.slice; ct2.prototype.uint32 = /* @__PURE__ */ (function() { var e = 4294967295; return function() { if (e = (this.buf[this.pos] & 127) >>> 0, this.buf[this.pos++] < 128 || (e = (e | (this.buf[this.pos] & 127) << 7) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 127) << 14) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 127) << 21) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 15) << 28) >>> 0, this.buf[this.pos++] < 128)) return e; if ((this.pos += 5) > this.len) throw this.pos = this.len, te3(this, 10); return e; }; })(); ct2.prototype.int32 = function() { return this.uint32() | 0; }; ct2.prototype.sint32 = function() { var e = this.uint32(); return e >>> 1 ^ -(e & 1) | 0; }; function Qo2() { var i = new Iu3(0, 0), e = 0; if (this.len - this.pos > 4) { for (; e < 4; ++e) if (i.lo = (i.lo | (this.buf[this.pos] & 127) << e * 7) >>> 0, this.buf[this.pos++] < 128) return i; if (i.lo = (i.lo | (this.buf[this.pos] & 127) << 28) >>> 0, i.hi = (i.hi | (this.buf[this.pos] & 127) >> 4) >>> 0, this.buf[this.pos++] < 128) return i; e = 0; } else { for (; e < 3; ++e) { if (this.pos >= this.len) throw te3(this); if (i.lo = (i.lo | (this.buf[this.pos] & 127) << e * 7) >>> 0, this.buf[this.pos++] < 128) return i; } return i.lo = (i.lo | (this.buf[this.pos++] & 127) << e * 7) >>> 0, i; } if (this.len - this.pos > 4) { for (; e < 5; ++e) if (i.hi = (i.hi | (this.buf[this.pos] & 127) << e * 7 + 3) >>> 0, this.buf[this.pos++] < 128) return i; } else for (; e < 5; ++e) { if (this.pos >= this.len) throw te3(this); if (i.hi = (i.hi | (this.buf[this.pos] & 127) << e * 7 + 3) >>> 0, this.buf[this.pos++] < 128) return i; } throw Error("invalid varint encoding"); } ct2.prototype.bool = function() { return this.uint32() !== 0; }; function In2(i, e) { return (i[e - 4] | i[e - 3] << 8 | i[e - 2] << 16 | i[e - 1] << 24) >>> 0; } ct2.prototype.fixed32 = function() { if (this.pos + 4 > this.len) throw te3(this, 4); return In2(this.buf, this.pos += 4); }; ct2.prototype.sfixed32 = function() { if (this.pos + 4 > this.len) throw te3(this, 4); return In2(this.buf, this.pos += 4) | 0; }; function vu3() { if (this.pos + 8 > this.len) throw te3(this, 8); return new Iu3(In2(this.buf, this.pos += 4), In2(this.buf, this.pos += 4)); } ct2.prototype.float = function() { if (this.pos + 4 > this.len) throw te3(this, 4); var e = Qt3.float.readFloatLE(this.buf, this.pos); return this.pos += 4, e; }; ct2.prototype.double = function() { if (this.pos + 8 > this.len) throw te3(this, 4); var e = Qt3.float.readDoubleLE(this.buf, this.pos); return this.pos += 8, e; }; ct2.prototype.bytes = function() { var e = this.uint32(), o = this.pos, t = this.pos + e; if (t > this.len) throw te3(this, e); if (this.pos += e, Array.isArray(this.buf)) return this.buf.slice(o, t); if (o === t) { var r = Qt3.Buffer; return r ? r.alloc(0) : new this.buf.constructor(0); } return this._slice.call(this.buf, o, t); }; ct2.prototype.string = function() { var e = this.bytes(); return fh2.read(e, 0, e.length); }; ct2.prototype.skip = function(e) { if (typeof e == "number") { if (this.pos + e > this.len) throw te3(this, e); this.pos += e; } else do if (this.pos >= this.len) throw te3(this); while (this.buf[this.pos++] & 128); return this; }; ct2.prototype.skipType = function(i) { switch (i) { case 0: this.skip(); break; case 1: this.skip(8); break; case 2: this.skip(this.uint32()); break; case 3: for (; (i = this.uint32() & 7) !== 4; ) this.skipType(i); break; case 5: this.skip(4); break; default: throw Error("invalid wire type " + i + " at offset " + this.pos); } return this; }; ct2._configure = function(i) { ti = i, ct2.create = _u3(), ti._configure(); var e = Qt3.Long ? "toLong" : "toNumber"; Qt3.merge(ct2.prototype, { int64: function() { return Qo2.call(this)[e](false); }, uint64: function() { return Qo2.call(this)[e](true); }, sint64: function() { return Qo2.call(this).zzDecode()[e](false); }, fixed64: function() { return vu3.call(this)[e](true); }, sfixed64: function() { return vu3.call(this)[e](false); } }); }; }); Eu = mt((Zy, Pu3) => { "use strict"; Pu3.exports = Re2; var Au3 = ei(); (Re2.prototype = Object.create(Au3.prototype)).constructor = Re2; var Su3 = Oe(); function Re2(i) { Au3.call(this, i); } Re2._configure = function() { Su3.Buffer && (Re2.prototype._slice = Su3.Buffer.prototype.slice); }; Re2.prototype.string = function() { var e = this.uint32(); return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + e, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + e, this.len)); }; Re2._configure(); }); Lu = mt((Qy, Du3) => { "use strict"; Du3.exports = Lr3; var ri = Oe(); (Lr3.prototype = Object.create(ri.EventEmitter.prototype)).constructor = Lr3; function Lr3(i, e, o) { if (typeof i != "function") throw TypeError("rpcImpl must be a function"); ri.EventEmitter.call(this), this.rpcImpl = i, this.requestDelimited = !!e, this.responseDelimited = !!o; } Lr3.prototype.rpcCall = function i(e, o, t, r, n) { if (!r) throw TypeError("request must be specified"); var s = this; if (!n) return ri.asPromise(i, s, e, o, t, r); if (!s.rpcImpl) { setTimeout(function() { n(Error("already ended")); }, 0); return; } try { return s.rpcImpl(e, o[s.requestDelimited ? "encodeDelimited" : "encode"](r).finish(), function(u, l) { if (u) return s.emit("error", u, e), n(u); if (l === null) { s.end(true); return; } if (!(l instanceof t)) try { l = t[s.responseDelimited ? "decodeDelimited" : "decode"](l); } catch (f) { return s.emit("error", f, e), n(f); } return s.emit("data", l, e), n(null, l); }); } catch (a) { s.emit("error", a, e), setTimeout(function() { n(a); }, 0); return; } }; Lr3.prototype.end = function(e) { return this.rpcImpl && (e || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this; }; }); ku = mt(($u3) => { "use strict"; var ch2 = $u3; ch2.Service = Lu(); }); Fu = mt((ex, Bu3) => { "use strict"; Bu3.exports = {}; }); Ru = mt((Nu3) => { "use strict"; var Ct2 = Nu3; Ct2.build = "minimal"; Ct2.Writer = Zo(); Ct2.BufferWriter = Tu(); Ct2.Reader = ei(); Ct2.BufferReader = Eu(); Ct2.util = Oe(); Ct2.rpc = ku(); Ct2.roots = Fu(); Ct2.configure = Cu3; function Cu3() { Ct2.util._configure(), Ct2.Writer._configure(Ct2.BufferWriter), Ct2.Reader._configure(Ct2.BufferReader); } Cu3(); }); Mu = mt((nx, Gu3) => { "use strict"; Gu3.exports = Ru(); }); sr = mt((ox, Uu3) => { "use strict"; var nt3 = Mu(), $2 = nt3.Reader, pt2 = nt3.Writer, b = nt3.util, h = nt3.roots.default || (nt3.roots.default = {}); h.onnx = (function() { var i = {}; return i.Version = (function() { var e = {}, o = Object.create(e); return o[e[0] = "_START_VERSION"] = 0, o[e[1] = "IR_VERSION_2017_10_10"] = 1, o[e[2] = "IR_VERSION_2017_10_30"] = 2, o[e[3] = "IR_VERSION_2017_11_3"] = 3, o[e[4] = "IR_VERSION_2019_1_22"] = 4, o[e[5] = "IR_VERSION_2019_3_18"] = 5, o[e[6] = "IR_VERSION_2019_9_19"] = 6, o[e[7] = "IR_VERSION_2020_5_8"] = 7, o[e[8] = "IR_VERSION_2021_7_30"] = 8, o[e[9] = "IR_VERSION"] = 9, o; })(), i.AttributeProto = (function() { function e(o) { if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], this.sparseTensors = [], this.typeProtos = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.name = "", e.prototype.refAttrName = "", e.prototype.docString = "", e.prototype.type = 0, e.prototype.f = 0, e.prototype.i = b.Long ? b.Long.fromBits(0, 0, false) : 0, e.prototype.s = b.newBuffer([]), e.prototype.t = null, e.prototype.g = null, e.prototype.sparseTensor = null, e.prototype.tp = null, e.prototype.floats = b.emptyArray, e.prototype.ints = b.emptyArray, e.prototype.strings = b.emptyArray, e.prototype.tensors = b.emptyArray, e.prototype.graphs = b.emptyArray, e.prototype.sparseTensors = b.emptyArray, e.prototype.typeProtos = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(10).string(t.name), t.f != null && Object.hasOwnProperty.call(t, "f") && r.uint32(21).float(t.f), t.i != null && Object.hasOwnProperty.call(t, "i") && r.uint32(24).int64(t.i), t.s != null && Object.hasOwnProperty.call(t, "s") && r.uint32(34).bytes(t.s), t.t != null && Object.hasOwnProperty.call(t, "t") && h.onnx.TensorProto.encode(t.t, r.uint32(42).fork()).ldelim(), t.g != null && Object.hasOwnProperty.call(t, "g") && h.onnx.GraphProto.encode(t.g, r.uint32(50).fork()).ldelim(), t.floats != null && t.floats.length) { r.uint32(58).fork(); for (var n = 0; n < t.floats.length; ++n) r.float(t.floats[n]); r.ldelim(); } if (t.ints != null && t.ints.length) { r.uint32(66).fork(); for (var n = 0; n < t.ints.length; ++n) r.int64(t.ints[n]); r.ldelim(); } if (t.strings != null && t.strings.length) for (var n = 0; n < t.strings.length; ++n) r.uint32(74).bytes(t.strings[n]); if (t.tensors != null && t.tensors.length) for (var n = 0; n < t.tensors.length; ++n) h.onnx.TensorProto.encode(t.tensors[n], r.uint32(82).fork()).ldelim(); if (t.graphs != null && t.graphs.length) for (var n = 0; n < t.graphs.length; ++n) h.onnx.GraphProto.encode(t.graphs[n], r.uint32(90).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(106).string(t.docString), t.tp != null && Object.hasOwnProperty.call(t, "tp") && h.onnx.TypeProto.encode(t.tp, r.uint32(114).fork()).ldelim(), t.typeProtos != null && t.typeProtos.length) for (var n = 0; n < t.typeProtos.length; ++n) h.onnx.TypeProto.encode(t.typeProtos[n], r.uint32(122).fork()).ldelim(); if (t.type != null && Object.hasOwnProperty.call(t, "type") && r.uint32(160).int32(t.type), t.refAttrName != null && Object.hasOwnProperty.call(t, "refAttrName") && r.uint32(170).string(t.refAttrName), t.sparseTensor != null && Object.hasOwnProperty.call(t, "sparseTensor") && h.onnx.SparseTensorProto.encode(t.sparseTensor, r.uint32(178).fork()).ldelim(), t.sparseTensors != null && t.sparseTensors.length) for (var n = 0; n < t.sparseTensors.length; ++n) h.onnx.SparseTensorProto.encode(t.sparseTensors[n], r.uint32(186).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.AttributeProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.name = t.string(); break; } case 21: { s.refAttrName = t.string(); break; } case 13: { s.docString = t.string(); break; } case 20: { s.type = t.int32(); break; } case 2: { s.f = t.float(); break; } case 3: { s.i = t.int64(); break; } case 4: { s.s = t.bytes(); break; } case 5: { s.t = h.onnx.TensorProto.decode(t, t.uint32()); break; } case 6: { s.g = h.onnx.GraphProto.decode(t, t.uint32()); break; } case 22: { s.sparseTensor = h.onnx.SparseTensorProto.decode(t, t.uint32()); break; } case 14: { s.tp = h.onnx.TypeProto.decode(t, t.uint32()); break; } case 7: { if (s.floats && s.floats.length || (s.floats = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.floats.push(t.float()); else s.floats.push(t.float()); break; } case 8: { if (s.ints && s.ints.length || (s.ints = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.ints.push(t.int64()); else s.ints.push(t.int64()); break; } case 9: { s.strings && s.strings.length || (s.strings = []), s.strings.push(t.bytes()); break; } case 10: { s.tensors && s.tensors.length || (s.tensors = []), s.tensors.push(h.onnx.TensorProto.decode(t, t.uint32())); break; } case 11: { s.graphs && s.graphs.length || (s.graphs = []), s.graphs.push(h.onnx.GraphProto.decode(t, t.uint32())); break; } case 23: { s.sparseTensors && s.sparseTensors.length || (s.sparseTensors = []), s.sparseTensors.push(h.onnx.SparseTensorProto.decode(t, t.uint32())); break; } case 15: { s.typeProtos && s.typeProtos.length || (s.typeProtos = []), s.typeProtos.push(h.onnx.TypeProto.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.refAttrName != null && t.hasOwnProperty("refAttrName") && !b.isString(t.refAttrName)) return "refAttrName: string expected"; if (t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString)) return "docString: string expected"; if (t.type != null && t.hasOwnProperty("type")) switch (t.type) { default: return "type: enum value expected"; case 0: case 1: case 2: case 3: case 4: case 5: case 11: case 13: case 6: case 7: case 8: case 9: case 10: case 12: case 14: break; } if (t.f != null && t.hasOwnProperty("f") && typeof t.f != "number") return "f: number expected"; if (t.i != null && t.hasOwnProperty("i") && !b.isInteger(t.i) && !(t.i && b.isInteger(t.i.low) && b.isInteger(t.i.high))) return "i: integer|Long expected"; if (t.s != null && t.hasOwnProperty("s") && !(t.s && typeof t.s.length == "number" || b.isString(t.s))) return "s: buffer expected"; if (t.t != null && t.hasOwnProperty("t")) { var r = h.onnx.TensorProto.verify(t.t); if (r) return "t." + r; } if (t.g != null && t.hasOwnProperty("g")) { var r = h.onnx.GraphProto.verify(t.g); if (r) return "g." + r; } if (t.sparseTensor != null && t.hasOwnProperty("sparseTensor")) { var r = h.onnx.SparseTensorProto.verify(t.sparseTensor); if (r) return "sparseTensor." + r; } if (t.tp != null && t.hasOwnProperty("tp")) { var r = h.onnx.TypeProto.verify(t.tp); if (r) return "tp." + r; } if (t.floats != null && t.hasOwnProperty("floats")) { if (!Array.isArray(t.floats)) return "floats: array expected"; for (var n = 0; n < t.floats.length; ++n) if (typeof t.floats[n] != "number") return "floats: number[] expected"; } if (t.ints != null && t.hasOwnProperty("ints")) { if (!Array.isArray(t.ints)) return "ints: array expected"; for (var n = 0; n < t.ints.length; ++n) if (!b.isInteger(t.ints[n]) && !(t.ints[n] && b.isInteger(t.ints[n].low) && b.isInteger(t.ints[n].high))) return "ints: integer|Long[] expected"; } if (t.strings != null && t.hasOwnProperty("strings")) { if (!Array.isArray(t.strings)) return "strings: array expected"; for (var n = 0; n < t.strings.length; ++n) if (!(t.strings[n] && typeof t.strings[n].length == "number" || b.isString(t.strings[n]))) return "strings: buffer[] expected"; } if (t.tensors != null && t.hasOwnProperty("tensors")) { if (!Array.isArray(t.tensors)) return "tensors: array expected"; for (var n = 0; n < t.tensors.length; ++n) { var r = h.onnx.TensorProto.verify(t.tensors[n]); if (r) return "tensors." + r; } } if (t.graphs != null && t.hasOwnProperty("graphs")) { if (!Array.isArray(t.graphs)) return "graphs: array expected"; for (var n = 0; n < t.graphs.length; ++n) { var r = h.onnx.GraphProto.verify(t.graphs[n]); if (r) return "graphs." + r; } } if (t.sparseTensors != null && t.hasOwnProperty("sparseTensors")) { if (!Array.isArray(t.sparseTensors)) return "sparseTensors: array expected"; for (var n = 0; n < t.sparseTensors.length; ++n) { var r = h.onnx.SparseTensorProto.verify(t.sparseTensors[n]); if (r) return "sparseTensors." + r; } } if (t.typeProtos != null && t.hasOwnProperty("typeProtos")) { if (!Array.isArray(t.typeProtos)) return "typeProtos: array expected"; for (var n = 0; n < t.typeProtos.length; ++n) { var r = h.onnx.TypeProto.verify(t.typeProtos[n]); if (r) return "typeProtos." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.AttributeProto) return t; var r = new h.onnx.AttributeProto(); switch (t.name != null && (r.name = String(t.name)), t.refAttrName != null && (r.refAttrName = String(t.refAttrName)), t.docString != null && (r.docString = String(t.docString)), t.type) { default: if (typeof t.type == "number") { r.type = t.type; break; } break; case "UNDEFINED": case 0: r.type = 0; break; case "FLOAT": case 1: r.type = 1; break; case "INT": case 2: r.type = 2; break; case "STRING": case 3: r.type = 3; break; case "TENSOR": case 4: r.type = 4; break; case "GRAPH": case 5: r.type = 5; break; case "SPARSE_TENSOR": case 11: r.type = 11; break; case "TYPE_PROTO": case 13: r.type = 13; break; case "FLOATS": case 6: r.type = 6; break; case "INTS": case 7: r.type = 7; break; case "STRINGS": case 8: r.type = 8; break; case "TENSORS": case 9: r.type = 9; break; case "GRAPHS": case 10: r.type = 10; break; case "SPARSE_TENSORS": case 12: r.type = 12; break; case "TYPE_PROTOS": case 14: r.type = 14; break; } if (t.f != null && (r.f = Number(t.f)), t.i != null && (b.Long ? (r.i = b.Long.fromValue(t.i)).unsigned = false : typeof t.i == "string" ? r.i = parseInt(t.i, 10) : typeof t.i == "number" ? r.i = t.i : typeof t.i == "object" && (r.i = new b.LongBits(t.i.low >>> 0, t.i.high >>> 0).toNumber())), t.s != null && (typeof t.s == "string" ? b.base64.decode(t.s, r.s = b.newBuffer(b.base64.length(t.s)), 0) : t.s.length >= 0 && (r.s = t.s)), t.t != null) { if (typeof t.t != "object") throw TypeError(".onnx.AttributeProto.t: object expected"); r.t = h.onnx.TensorProto.fromObject(t.t); } if (t.g != null) { if (typeof t.g != "object") throw TypeError(".onnx.AttributeProto.g: object expected"); r.g = h.onnx.GraphProto.fromObject(t.g); } if (t.sparseTensor != null) { if (typeof t.sparseTensor != "object") throw TypeError(".onnx.AttributeProto.sparseTensor: object expected"); r.sparseTensor = h.onnx.SparseTensorProto.fromObject(t.sparseTensor); } if (t.tp != null) { if (typeof t.tp != "object") throw TypeError(".onnx.AttributeProto.tp: object expected"); r.tp = h.onnx.TypeProto.fromObject(t.tp); } if (t.floats) { if (!Array.isArray(t.floats)) throw TypeError(".onnx.AttributeProto.floats: array expected"); r.floats = []; for (var n = 0; n < t.floats.length; ++n) r.floats[n] = Number(t.floats[n]); } if (t.ints) { if (!Array.isArray(t.ints)) throw TypeError(".onnx.AttributeProto.ints: array expected"); r.ints = []; for (var n = 0; n < t.ints.length; ++n) b.Long ? (r.ints[n] = b.Long.fromValue(t.ints[n])).unsigned = false : typeof t.ints[n] == "string" ? r.ints[n] = parseInt(t.ints[n], 10) : typeof t.ints[n] == "number" ? r.ints[n] = t.ints[n] : typeof t.ints[n] == "object" && (r.ints[n] = new b.LongBits(t.ints[n].low >>> 0, t.ints[n].high >>> 0).toNumber()); } if (t.strings) { if (!Array.isArray(t.strings)) throw TypeError(".onnx.AttributeProto.strings: array expected"); r.strings = []; for (var n = 0; n < t.strings.length; ++n) typeof t.strings[n] == "string" ? b.base64.decode(t.strings[n], r.strings[n] = b.newBuffer(b.base64.length(t.strings[n])), 0) : t.strings[n].length >= 0 && (r.strings[n] = t.strings[n]); } if (t.tensors) { if (!Array.isArray(t.tensors)) throw TypeError(".onnx.AttributeProto.tensors: array expected"); r.tensors = []; for (var n = 0; n < t.tensors.length; ++n) { if (typeof t.tensors[n] != "object") throw TypeError(".onnx.AttributeProto.tensors: object expected"); r.tensors[n] = h.onnx.TensorProto.fromObject(t.tensors[n]); } } if (t.graphs) { if (!Array.isArray(t.graphs)) throw TypeError(".onnx.AttributeProto.graphs: array expected"); r.graphs = []; for (var n = 0; n < t.graphs.length; ++n) { if (typeof t.graphs[n] != "object") throw TypeError(".onnx.AttributeProto.graphs: object expected"); r.graphs[n] = h.onnx.GraphProto.fromObject(t.graphs[n]); } } if (t.sparseTensors) { if (!Array.isArray(t.sparseTensors)) throw TypeError(".onnx.AttributeProto.sparseTensors: array expected"); r.sparseTensors = []; for (var n = 0; n < t.sparseTensors.length; ++n) { if (typeof t.sparseTensors[n] != "object") throw TypeError(".onnx.AttributeProto.sparseTensors: object expected"); r.sparseTensors[n] = h.onnx.SparseTensorProto.fromObject(t.sparseTensors[n]); } } if (t.typeProtos) { if (!Array.isArray(t.typeProtos)) throw TypeError(".onnx.AttributeProto.typeProtos: array expected"); r.typeProtos = []; for (var n = 0; n < t.typeProtos.length; ++n) { if (typeof t.typeProtos[n] != "object") throw TypeError(".onnx.AttributeProto.typeProtos: object expected"); r.typeProtos[n] = h.onnx.TypeProto.fromObject(t.typeProtos[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.floats = [], n.ints = [], n.strings = [], n.tensors = [], n.graphs = [], n.typeProtos = [], n.sparseTensors = []), r.defaults) { if (n.name = "", n.f = 0, b.Long) { var s = new b.Long(0, 0, false); n.i = r.longs === String ? s.toString() : r.longs === Number ? s.toNumber() : s; } else n.i = r.longs === String ? "0" : 0; r.bytes === String ? n.s = "" : (n.s = [], r.bytes !== Array && (n.s = b.newBuffer(n.s))), n.t = null, n.g = null, n.docString = "", n.tp = null, n.type = r.enums === String ? "UNDEFINED" : 0, n.refAttrName = "", n.sparseTensor = null; } if (t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.f != null && t.hasOwnProperty("f") && (n.f = r.json && !isFinite(t.f) ? String(t.f) : t.f), t.i != null && t.hasOwnProperty("i") && (typeof t.i == "number" ? n.i = r.longs === String ? String(t.i) : t.i : n.i = r.longs === String ? b.Long.prototype.toString.call(t.i) : r.longs === Number ? new b.LongBits(t.i.low >>> 0, t.i.high >>> 0).toNumber() : t.i), t.s != null && t.hasOwnProperty("s") && (n.s = r.bytes === String ? b.base64.encode(t.s, 0, t.s.length) : r.bytes === Array ? Array.prototype.slice.call(t.s) : t.s), t.t != null && t.hasOwnProperty("t") && (n.t = h.onnx.TensorProto.toObject(t.t, r)), t.g != null && t.hasOwnProperty("g") && (n.g = h.onnx.GraphProto.toObject(t.g, r)), t.floats && t.floats.length) { n.floats = []; for (var a = 0; a < t.floats.length; ++a) n.floats[a] = r.json && !isFinite(t.floats[a]) ? String(t.floats[a]) : t.floats[a]; } if (t.ints && t.ints.length) { n.ints = []; for (var a = 0; a < t.ints.length; ++a) typeof t.ints[a] == "number" ? n.ints[a] = r.longs === String ? String(t.ints[a]) : t.ints[a] : n.ints[a] = r.longs === String ? b.Long.prototype.toString.call(t.ints[a]) : r.longs === Number ? new b.LongBits(t.ints[a].low >>> 0, t.ints[a].high >>> 0).toNumber() : t.ints[a]; } if (t.strings && t.strings.length) { n.strings = []; for (var a = 0; a < t.strings.length; ++a) n.strings[a] = r.bytes === String ? b.base64.encode(t.strings[a], 0, t.strings[a].length) : r.bytes === Array ? Array.prototype.slice.call(t.strings[a]) : t.strings[a]; } if (t.tensors && t.tensors.length) { n.tensors = []; for (var a = 0; a < t.tensors.length; ++a) n.tensors[a] = h.onnx.TensorProto.toObject(t.tensors[a], r); } if (t.graphs && t.graphs.length) { n.graphs = []; for (var a = 0; a < t.graphs.length; ++a) n.graphs[a] = h.onnx.GraphProto.toObject(t.graphs[a], r); } if (t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.tp != null && t.hasOwnProperty("tp") && (n.tp = h.onnx.TypeProto.toObject(t.tp, r)), t.typeProtos && t.typeProtos.length) { n.typeProtos = []; for (var a = 0; a < t.typeProtos.length; ++a) n.typeProtos[a] = h.onnx.TypeProto.toObject(t.typeProtos[a], r); } if (t.type != null && t.hasOwnProperty("type") && (n.type = r.enums === String ? h.onnx.AttributeProto.AttributeType[t.type] === void 0 ? t.type : h.onnx.AttributeProto.AttributeType[t.type] : t.type), t.refAttrName != null && t.hasOwnProperty("refAttrName") && (n.refAttrName = t.refAttrName), t.sparseTensor != null && t.hasOwnProperty("sparseTensor") && (n.sparseTensor = h.onnx.SparseTensorProto.toObject(t.sparseTensor, r)), t.sparseTensors && t.sparseTensors.length) { n.sparseTensors = []; for (var a = 0; a < t.sparseTensors.length; ++a) n.sparseTensors[a] = h.onnx.SparseTensorProto.toObject(t.sparseTensors[a], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.AttributeProto"; }, e.AttributeType = (function() { var o = {}, t = Object.create(o); return t[o[0] = "UNDEFINED"] = 0, t[o[1] = "FLOAT"] = 1, t[o[2] = "INT"] = 2, t[o[3] = "STRING"] = 3, t[o[4] = "TENSOR"] = 4, t[o[5] = "GRAPH"] = 5, t[o[11] = "SPARSE_TENSOR"] = 11, t[o[13] = "TYPE_PROTO"] = 13, t[o[6] = "FLOATS"] = 6, t[o[7] = "INTS"] = 7, t[o[8] = "STRINGS"] = 8, t[o[9] = "TENSORS"] = 9, t[o[10] = "GRAPHS"] = 10, t[o[12] = "SPARSE_TENSORS"] = 12, t[o[14] = "TYPE_PROTOS"] = 14, t; })(), e; })(), i.ValueInfoProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.name = "", e.prototype.type = null, e.prototype.docString = "", e.create = function(t) { return new e(t); }, e.encode = function(t, r) { return r || (r = pt2.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(10).string(t.name), t.type != null && Object.hasOwnProperty.call(t, "type") && h.onnx.TypeProto.encode(t.type, r.uint32(18).fork()).ldelim(), t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(26).string(t.docString), r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.ValueInfoProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.name = t.string(); break; } case 2: { s.type = h.onnx.TypeProto.decode(t, t.uint32()); break; } case 3: { s.docString = t.string(); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.type != null && t.hasOwnProperty("type")) { var r = h.onnx.TypeProto.verify(t.type); if (r) return "type." + r; } return t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString) ? "docString: string expected" : null; }, e.fromObject = function(t) { if (t instanceof h.onnx.ValueInfoProto) return t; var r = new h.onnx.ValueInfoProto(); if (t.name != null && (r.name = String(t.name)), t.type != null) { if (typeof t.type != "object") throw TypeError(".onnx.ValueInfoProto.type: object expected"); r.type = h.onnx.TypeProto.fromObject(t.type); } return t.docString != null && (r.docString = String(t.docString)), r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; return r.defaults && (n.name = "", n.type = null, n.docString = ""), t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.type != null && t.hasOwnProperty("type") && (n.type = h.onnx.TypeProto.toObject(t.type, r)), t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.ValueInfoProto"; }, e; })(), i.NodeProto = (function() { function e(o) { if (this.input = [], this.output = [], this.attribute = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.input = b.emptyArray, e.prototype.output = b.emptyArray, e.prototype.name = "", e.prototype.opType = "", e.prototype.domain = "", e.prototype.attribute = b.emptyArray, e.prototype.docString = "", e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.input != null && t.input.length) for (var n = 0; n < t.input.length; ++n) r.uint32(10).string(t.input[n]); if (t.output != null && t.output.length) for (var n = 0; n < t.output.length; ++n) r.uint32(18).string(t.output[n]); if (t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(26).string(t.name), t.opType != null && Object.hasOwnProperty.call(t, "opType") && r.uint32(34).string(t.opType), t.attribute != null && t.attribute.length) for (var n = 0; n < t.attribute.length; ++n) h.onnx.AttributeProto.encode(t.attribute[n], r.uint32(42).fork()).ldelim(); return t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(50).string(t.docString), t.domain != null && Object.hasOwnProperty.call(t, "domain") && r.uint32(58).string(t.domain), r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.NodeProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.input && s.input.length || (s.input = []), s.input.push(t.string()); break; } case 2: { s.output && s.output.length || (s.output = []), s.output.push(t.string()); break; } case 3: { s.name = t.string(); break; } case 4: { s.opType = t.string(); break; } case 7: { s.domain = t.string(); break; } case 5: { s.attribute && s.attribute.length || (s.attribute = []), s.attribute.push(h.onnx.AttributeProto.decode(t, t.uint32())); break; } case 6: { s.docString = t.string(); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var r = 0; r < t.input.length; ++r) if (!b.isString(t.input[r])) return "input: string[] expected"; } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var r = 0; r < t.output.length; ++r) if (!b.isString(t.output[r])) return "output: string[] expected"; } if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.opType != null && t.hasOwnProperty("opType") && !b.isString(t.opType)) return "opType: string expected"; if (t.domain != null && t.hasOwnProperty("domain") && !b.isString(t.domain)) return "domain: string expected"; if (t.attribute != null && t.hasOwnProperty("attribute")) { if (!Array.isArray(t.attribute)) return "attribute: array expected"; for (var r = 0; r < t.attribute.length; ++r) { var n = h.onnx.AttributeProto.verify(t.attribute[r]); if (n) return "attribute." + n; } } return t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString) ? "docString: string expected" : null; }, e.fromObject = function(t) { if (t instanceof h.onnx.NodeProto) return t; var r = new h.onnx.NodeProto(); if (t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.NodeProto.input: array expected"); r.input = []; for (var n = 0; n < t.input.length; ++n) r.input[n] = String(t.input[n]); } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.NodeProto.output: array expected"); r.output = []; for (var n = 0; n < t.output.length; ++n) r.output[n] = String(t.output[n]); } if (t.name != null && (r.name = String(t.name)), t.opType != null && (r.opType = String(t.opType)), t.domain != null && (r.domain = String(t.domain)), t.attribute) { if (!Array.isArray(t.attribute)) throw TypeError(".onnx.NodeProto.attribute: array expected"); r.attribute = []; for (var n = 0; n < t.attribute.length; ++n) { if (typeof t.attribute[n] != "object") throw TypeError(".onnx.NodeProto.attribute: object expected"); r.attribute[n] = h.onnx.AttributeProto.fromObject(t.attribute[n]); } } return t.docString != null && (r.docString = String(t.docString)), r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.input = [], n.output = [], n.attribute = []), r.defaults && (n.name = "", n.opType = "", n.docString = "", n.domain = ""), t.input && t.input.length) { n.input = []; for (var s = 0; s < t.input.length; ++s) n.input[s] = t.input[s]; } if (t.output && t.output.length) { n.output = []; for (var s = 0; s < t.output.length; ++s) n.output[s] = t.output[s]; } if (t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.opType != null && t.hasOwnProperty("opType") && (n.opType = t.opType), t.attribute && t.attribute.length) { n.attribute = []; for (var s = 0; s < t.attribute.length; ++s) n.attribute[s] = h.onnx.AttributeProto.toObject(t.attribute[s], r); } return t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.domain != null && t.hasOwnProperty("domain") && (n.domain = t.domain), n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.NodeProto"; }, e; })(), i.TrainingInfoProto = (function() { function e(o) { if (this.initializationBinding = [], this.updateBinding = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.initialization = null, e.prototype.algorithm = null, e.prototype.initializationBinding = b.emptyArray, e.prototype.updateBinding = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.initialization != null && Object.hasOwnProperty.call(t, "initialization") && h.onnx.GraphProto.encode(t.initialization, r.uint32(10).fork()).ldelim(), t.algorithm != null && Object.hasOwnProperty.call(t, "algorithm") && h.onnx.GraphProto.encode(t.algorithm, r.uint32(18).fork()).ldelim(), t.initializationBinding != null && t.initializationBinding.length) for (var n = 0; n < t.initializationBinding.length; ++n) h.onnx.StringStringEntryProto.encode(t.initializationBinding[n], r.uint32(26).fork()).ldelim(); if (t.updateBinding != null && t.updateBinding.length) for (var n = 0; n < t.updateBinding.length; ++n) h.onnx.StringStringEntryProto.encode(t.updateBinding[n], r.uint32(34).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.TrainingInfoProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.initialization = h.onnx.GraphProto.decode(t, t.uint32()); break; } case 2: { s.algorithm = h.onnx.GraphProto.decode(t, t.uint32()); break; } case 3: { s.initializationBinding && s.initializationBinding.length || (s.initializationBinding = []), s.initializationBinding.push(h.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 4: { s.updateBinding && s.updateBinding.length || (s.updateBinding = []), s.updateBinding.push(h.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.initialization != null && t.hasOwnProperty("initialization")) { var r = h.onnx.GraphProto.verify(t.initialization); if (r) return "initialization." + r; } if (t.algorithm != null && t.hasOwnProperty("algorithm")) { var r = h.onnx.GraphProto.verify(t.algorithm); if (r) return "algorithm." + r; } if (t.initializationBinding != null && t.hasOwnProperty("initializationBinding")) { if (!Array.isArray(t.initializationBinding)) return "initializationBinding: array expected"; for (var n = 0; n < t.initializationBinding.length; ++n) { var r = h.onnx.StringStringEntryProto.verify(t.initializationBinding[n]); if (r) return "initializationBinding." + r; } } if (t.updateBinding != null && t.hasOwnProperty("updateBinding")) { if (!Array.isArray(t.updateBinding)) return "updateBinding: array expected"; for (var n = 0; n < t.updateBinding.length; ++n) { var r = h.onnx.StringStringEntryProto.verify(t.updateBinding[n]); if (r) return "updateBinding." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.TrainingInfoProto) return t; var r = new h.onnx.TrainingInfoProto(); if (t.initialization != null) { if (typeof t.initialization != "object") throw TypeError(".onnx.TrainingInfoProto.initialization: object expected"); r.initialization = h.onnx.GraphProto.fromObject(t.initialization); } if (t.algorithm != null) { if (typeof t.algorithm != "object") throw TypeError(".onnx.TrainingInfoProto.algorithm: object expected"); r.algorithm = h.onnx.GraphProto.fromObject(t.algorithm); } if (t.initializationBinding) { if (!Array.isArray(t.initializationBinding)) throw TypeError(".onnx.TrainingInfoProto.initializationBinding: array expected"); r.initializationBinding = []; for (var n = 0; n < t.initializationBinding.length; ++n) { if (typeof t.initializationBinding[n] != "object") throw TypeError(".onnx.TrainingInfoProto.initializationBinding: object expected"); r.initializationBinding[n] = h.onnx.StringStringEntryProto.fromObject(t.initializationBinding[n]); } } if (t.updateBinding) { if (!Array.isArray(t.updateBinding)) throw TypeError(".onnx.TrainingInfoProto.updateBinding: array expected"); r.updateBinding = []; for (var n = 0; n < t.updateBinding.length; ++n) { if (typeof t.updateBinding[n] != "object") throw TypeError(".onnx.TrainingInfoProto.updateBinding: object expected"); r.updateBinding[n] = h.onnx.StringStringEntryProto.fromObject(t.updateBinding[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.initializationBinding = [], n.updateBinding = []), r.defaults && (n.initialization = null, n.algorithm = null), t.initialization != null && t.hasOwnProperty("initialization") && (n.initialization = h.onnx.GraphProto.toObject(t.initialization, r)), t.algorithm != null && t.hasOwnProperty("algorithm") && (n.algorithm = h.onnx.GraphProto.toObject(t.algorithm, r)), t.initializationBinding && t.initializationBinding.length) { n.initializationBinding = []; for (var s = 0; s < t.initializationBinding.length; ++s) n.initializationBinding[s] = h.onnx.StringStringEntryProto.toObject(t.initializationBinding[s], r); } if (t.updateBinding && t.updateBinding.length) { n.updateBinding = []; for (var s = 0; s < t.updateBinding.length; ++s) n.updateBinding[s] = h.onnx.StringStringEntryProto.toObject(t.updateBinding[s], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TrainingInfoProto"; }, e; })(), i.ModelProto = (function() { function e(o) { if (this.opsetImport = [], this.metadataProps = [], this.trainingInfo = [], this.functions = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.irVersion = b.Long ? b.Long.fromBits(0, 0, false) : 0, e.prototype.opsetImport = b.emptyArray, e.prototype.producerName = "", e.prototype.producerVersion = "", e.prototype.domain = "", e.prototype.modelVersion = b.Long ? b.Long.fromBits(0, 0, false) : 0, e.prototype.docString = "", e.prototype.graph = null, e.prototype.metadataProps = b.emptyArray, e.prototype.trainingInfo = b.emptyArray, e.prototype.functions = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.irVersion != null && Object.hasOwnProperty.call(t, "irVersion") && r.uint32(8).int64(t.irVersion), t.producerName != null && Object.hasOwnProperty.call(t, "producerName") && r.uint32(18).string(t.producerName), t.producerVersion != null && Object.hasOwnProperty.call(t, "producerVersion") && r.uint32(26).string(t.producerVersion), t.domain != null && Object.hasOwnProperty.call(t, "domain") && r.uint32(34).string(t.domain), t.modelVersion != null && Object.hasOwnProperty.call(t, "modelVersion") && r.uint32(40).int64(t.modelVersion), t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(50).string(t.docString), t.graph != null && Object.hasOwnProperty.call(t, "graph") && h.onnx.GraphProto.encode(t.graph, r.uint32(58).fork()).ldelim(), t.opsetImport != null && t.opsetImport.length) for (var n = 0; n < t.opsetImport.length; ++n) h.onnx.OperatorSetIdProto.encode(t.opsetImport[n], r.uint32(66).fork()).ldelim(); if (t.metadataProps != null && t.metadataProps.length) for (var n = 0; n < t.metadataProps.length; ++n) h.onnx.StringStringEntryProto.encode(t.metadataProps[n], r.uint32(114).fork()).ldelim(); if (t.trainingInfo != null && t.trainingInfo.length) for (var n = 0; n < t.trainingInfo.length; ++n) h.onnx.TrainingInfoProto.encode(t.trainingInfo[n], r.uint32(162).fork()).ldelim(); if (t.functions != null && t.functions.length) for (var n = 0; n < t.functions.length; ++n) h.onnx.FunctionProto.encode(t.functions[n], r.uint32(202).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.ModelProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.irVersion = t.int64(); break; } case 8: { s.opsetImport && s.opsetImport.length || (s.opsetImport = []), s.opsetImport.push(h.onnx.OperatorSetIdProto.decode(t, t.uint32())); break; } case 2: { s.producerName = t.string(); break; } case 3: { s.producerVersion = t.string(); break; } case 4: { s.domain = t.string(); break; } case 5: { s.modelVersion = t.int64(); break; } case 6: { s.docString = t.string(); break; } case 7: { s.graph = h.onnx.GraphProto.decode(t, t.uint32()); break; } case 14: { s.metadataProps && s.metadataProps.length || (s.metadataProps = []), s.metadataProps.push(h.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 20: { s.trainingInfo && s.trainingInfo.length || (s.trainingInfo = []), s.trainingInfo.push(h.onnx.TrainingInfoProto.decode(t, t.uint32())); break; } case 25: { s.functions && s.functions.length || (s.functions = []), s.functions.push(h.onnx.FunctionProto.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.irVersion != null && t.hasOwnProperty("irVersion") && !b.isInteger(t.irVersion) && !(t.irVersion && b.isInteger(t.irVersion.low) && b.isInteger(t.irVersion.high))) return "irVersion: integer|Long expected"; if (t.opsetImport != null && t.hasOwnProperty("opsetImport")) { if (!Array.isArray(t.opsetImport)) return "opsetImport: array expected"; for (var r = 0; r < t.opsetImport.length; ++r) { var n = h.onnx.OperatorSetIdProto.verify(t.opsetImport[r]); if (n) return "opsetImport." + n; } } if (t.producerName != null && t.hasOwnProperty("producerName") && !b.isString(t.producerName)) return "producerName: string expected"; if (t.producerVersion != null && t.hasOwnProperty("producerVersion") && !b.isString(t.producerVersion)) return "producerVersion: string expected"; if (t.domain != null && t.hasOwnProperty("domain") && !b.isString(t.domain)) return "domain: string expected"; if (t.modelVersion != null && t.hasOwnProperty("modelVersion") && !b.isInteger(t.modelVersion) && !(t.modelVersion && b.isInteger(t.modelVersion.low) && b.isInteger(t.modelVersion.high))) return "modelVersion: integer|Long expected"; if (t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString)) return "docString: string expected"; if (t.graph != null && t.hasOwnProperty("graph")) { var n = h.onnx.GraphProto.verify(t.graph); if (n) return "graph." + n; } if (t.metadataProps != null && t.hasOwnProperty("metadataProps")) { if (!Array.isArray(t.metadataProps)) return "metadataProps: array expected"; for (var r = 0; r < t.metadataProps.length; ++r) { var n = h.onnx.StringStringEntryProto.verify(t.metadataProps[r]); if (n) return "metadataProps." + n; } } if (t.trainingInfo != null && t.hasOwnProperty("trainingInfo")) { if (!Array.isArray(t.trainingInfo)) return "trainingInfo: array expected"; for (var r = 0; r < t.trainingInfo.length; ++r) { var n = h.onnx.TrainingInfoProto.verify(t.trainingInfo[r]); if (n) return "trainingInfo." + n; } } if (t.functions != null && t.hasOwnProperty("functions")) { if (!Array.isArray(t.functions)) return "functions: array expected"; for (var r = 0; r < t.functions.length; ++r) { var n = h.onnx.FunctionProto.verify(t.functions[r]); if (n) return "functions." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.ModelProto) return t; var r = new h.onnx.ModelProto(); if (t.irVersion != null && (b.Long ? (r.irVersion = b.Long.fromValue(t.irVersion)).unsigned = false : typeof t.irVersion == "string" ? r.irVersion = parseInt(t.irVersion, 10) : typeof t.irVersion == "number" ? r.irVersion = t.irVersion : typeof t.irVersion == "object" && (r.irVersion = new b.LongBits(t.irVersion.low >>> 0, t.irVersion.high >>> 0).toNumber())), t.opsetImport) { if (!Array.isArray(t.opsetImport)) throw TypeError(".onnx.ModelProto.opsetImport: array expected"); r.opsetImport = []; for (var n = 0; n < t.opsetImport.length; ++n) { if (typeof t.opsetImport[n] != "object") throw TypeError(".onnx.ModelProto.opsetImport: object expected"); r.opsetImport[n] = h.onnx.OperatorSetIdProto.fromObject(t.opsetImport[n]); } } if (t.producerName != null && (r.producerName = String(t.producerName)), t.producerVersion != null && (r.producerVersion = String(t.producerVersion)), t.domain != null && (r.domain = String(t.domain)), t.modelVersion != null && (b.Long ? (r.modelVersion = b.Long.fromValue(t.modelVersion)).unsigned = false : typeof t.modelVersion == "string" ? r.modelVersion = parseInt(t.modelVersion, 10) : typeof t.modelVersion == "number" ? r.modelVersion = t.modelVersion : typeof t.modelVersion == "object" && (r.modelVersion = new b.LongBits(t.modelVersion.low >>> 0, t.modelVersion.high >>> 0).toNumber())), t.docString != null && (r.docString = String(t.docString)), t.graph != null) { if (typeof t.graph != "object") throw TypeError(".onnx.ModelProto.graph: object expected"); r.graph = h.onnx.GraphProto.fromObject(t.graph); } if (t.metadataProps) { if (!Array.isArray(t.metadataProps)) throw TypeError(".onnx.ModelProto.metadataProps: array expected"); r.metadataProps = []; for (var n = 0; n < t.metadataProps.length; ++n) { if (typeof t.metadataProps[n] != "object") throw TypeError(".onnx.ModelProto.metadataProps: object expected"); r.metadataProps[n] = h.onnx.StringStringEntryProto.fromObject(t.metadataProps[n]); } } if (t.trainingInfo) { if (!Array.isArray(t.trainingInfo)) throw TypeError(".onnx.ModelProto.trainingInfo: array expected"); r.trainingInfo = []; for (var n = 0; n < t.trainingInfo.length; ++n) { if (typeof t.trainingInfo[n] != "object") throw TypeError(".onnx.ModelProto.trainingInfo: object expected"); r.trainingInfo[n] = h.onnx.TrainingInfoProto.fromObject(t.trainingInfo[n]); } } if (t.functions) { if (!Array.isArray(t.functions)) throw TypeError(".onnx.ModelProto.functions: array expected"); r.functions = []; for (var n = 0; n < t.functions.length; ++n) { if (typeof t.functions[n] != "object") throw TypeError(".onnx.ModelProto.functions: object expected"); r.functions[n] = h.onnx.FunctionProto.fromObject(t.functions[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.opsetImport = [], n.metadataProps = [], n.trainingInfo = [], n.functions = []), r.defaults) { if (b.Long) { var s = new b.Long(0, 0, false); n.irVersion = r.longs === String ? s.toString() : r.longs === Number ? s.toNumber() : s; } else n.irVersion = r.longs === String ? "0" : 0; if (n.producerName = "", n.producerVersion = "", n.domain = "", b.Long) { var s = new b.Long(0, 0, false); n.modelVersion = r.longs === String ? s.toString() : r.longs === Number ? s.toNumber() : s; } else n.modelVersion = r.longs === String ? "0" : 0; n.docString = "", n.graph = null; } if (t.irVersion != null && t.hasOwnProperty("irVersion") && (typeof t.irVersion == "number" ? n.irVersion = r.longs === String ? String(t.irVersion) : t.irVersion : n.irVersion = r.longs === String ? b.Long.prototype.toString.call(t.irVersion) : r.longs === Number ? new b.LongBits(t.irVersion.low >>> 0, t.irVersion.high >>> 0).toNumber() : t.irVersion), t.producerName != null && t.hasOwnProperty("producerName") && (n.producerName = t.producerName), t.producerVersion != null && t.hasOwnProperty("producerVersion") && (n.producerVersion = t.producerVersion), t.domain != null && t.hasOwnProperty("domain") && (n.domain = t.domain), t.modelVersion != null && t.hasOwnProperty("modelVersion") && (typeof t.modelVersion == "number" ? n.modelVersion = r.longs === String ? String(t.modelVersion) : t.modelVersion : n.modelVersion = r.longs === String ? b.Long.prototype.toString.call(t.modelVersion) : r.longs === Number ? new b.LongBits(t.modelVersion.low >>> 0, t.modelVersion.high >>> 0).toNumber() : t.modelVersion), t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.graph != null && t.hasOwnProperty("graph") && (n.graph = h.onnx.GraphProto.toObject(t.graph, r)), t.opsetImport && t.opsetImport.length) { n.opsetImport = []; for (var a = 0; a < t.opsetImport.length; ++a) n.opsetImport[a] = h.onnx.OperatorSetIdProto.toObject(t.opsetImport[a], r); } if (t.metadataProps && t.metadataProps.length) { n.metadataProps = []; for (var a = 0; a < t.metadataProps.length; ++a) n.metadataProps[a] = h.onnx.StringStringEntryProto.toObject(t.metadataProps[a], r); } if (t.trainingInfo && t.trainingInfo.length) { n.trainingInfo = []; for (var a = 0; a < t.trainingInfo.length; ++a) n.trainingInfo[a] = h.onnx.TrainingInfoProto.toObject(t.trainingInfo[a], r); } if (t.functions && t.functions.length) { n.functions = []; for (var a = 0; a < t.functions.length; ++a) n.functions[a] = h.onnx.FunctionProto.toObject(t.functions[a], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.ModelProto"; }, e; })(), i.StringStringEntryProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.key = "", e.prototype.value = "", e.create = function(t) { return new e(t); }, e.encode = function(t, r) { return r || (r = pt2.create()), t.key != null && Object.hasOwnProperty.call(t, "key") && r.uint32(10).string(t.key), t.value != null && Object.hasOwnProperty.call(t, "value") && r.uint32(18).string(t.value), r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.StringStringEntryProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.key = t.string(); break; } case 2: { s.value = t.string(); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { return typeof t != "object" || t === null ? "object expected" : t.key != null && t.hasOwnProperty("key") && !b.isString(t.key) ? "key: string expected" : t.value != null && t.hasOwnProperty("value") && !b.isString(t.value) ? "value: string expected" : null; }, e.fromObject = function(t) { if (t instanceof h.onnx.StringStringEntryProto) return t; var r = new h.onnx.StringStringEntryProto(); return t.key != null && (r.key = String(t.key)), t.value != null && (r.value = String(t.value)), r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; return r.defaults && (n.key = "", n.value = ""), t.key != null && t.hasOwnProperty("key") && (n.key = t.key), t.value != null && t.hasOwnProperty("value") && (n.value = t.value), n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.StringStringEntryProto"; }, e; })(), i.TensorAnnotation = (function() { function e(o) { if (this.quantParameterTensorNames = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.tensorName = "", e.prototype.quantParameterTensorNames = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.tensorName != null && Object.hasOwnProperty.call(t, "tensorName") && r.uint32(10).string(t.tensorName), t.quantParameterTensorNames != null && t.quantParameterTensorNames.length) for (var n = 0; n < t.quantParameterTensorNames.length; ++n) h.onnx.StringStringEntryProto.encode(t.quantParameterTensorNames[n], r.uint32(18).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.TensorAnnotation(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.tensorName = t.string(); break; } case 2: { s.quantParameterTensorNames && s.quantParameterTensorNames.length || (s.quantParameterTensorNames = []), s.quantParameterTensorNames.push(h.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.tensorName != null && t.hasOwnProperty("tensorName") && !b.isString(t.tensorName)) return "tensorName: string expected"; if (t.quantParameterTensorNames != null && t.hasOwnProperty("quantParameterTensorNames")) { if (!Array.isArray(t.quantParameterTensorNames)) return "quantParameterTensorNames: array expected"; for (var r = 0; r < t.quantParameterTensorNames.length; ++r) { var n = h.onnx.StringStringEntryProto.verify(t.quantParameterTensorNames[r]); if (n) return "quantParameterTensorNames." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.TensorAnnotation) return t; var r = new h.onnx.TensorAnnotation(); if (t.tensorName != null && (r.tensorName = String(t.tensorName)), t.quantParameterTensorNames) { if (!Array.isArray(t.quantParameterTensorNames)) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected"); r.quantParameterTensorNames = []; for (var n = 0; n < t.quantParameterTensorNames.length; ++n) { if (typeof t.quantParameterTensorNames[n] != "object") throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected"); r.quantParameterTensorNames[n] = h.onnx.StringStringEntryProto.fromObject(t.quantParameterTensorNames[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.quantParameterTensorNames = []), r.defaults && (n.tensorName = ""), t.tensorName != null && t.hasOwnProperty("tensorName") && (n.tensorName = t.tensorName), t.quantParameterTensorNames && t.quantParameterTensorNames.length) { n.quantParameterTensorNames = []; for (var s = 0; s < t.quantParameterTensorNames.length; ++s) n.quantParameterTensorNames[s] = h.onnx.StringStringEntryProto.toObject(t.quantParameterTensorNames[s], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorAnnotation"; }, e; })(), i.GraphProto = (function() { function e(o) { if (this.node = [], this.initializer = [], this.sparseInitializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.node = b.emptyArray, e.prototype.name = "", e.prototype.initializer = b.emptyArray, e.prototype.sparseInitializer = b.emptyArray, e.prototype.docString = "", e.prototype.input = b.emptyArray, e.prototype.output = b.emptyArray, e.prototype.valueInfo = b.emptyArray, e.prototype.quantizationAnnotation = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.node != null && t.node.length) for (var n = 0; n < t.node.length; ++n) h.onnx.NodeProto.encode(t.node[n], r.uint32(10).fork()).ldelim(); if (t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(18).string(t.name), t.initializer != null && t.initializer.length) for (var n = 0; n < t.initializer.length; ++n) h.onnx.TensorProto.encode(t.initializer[n], r.uint32(42).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(82).string(t.docString), t.input != null && t.input.length) for (var n = 0; n < t.input.length; ++n) h.onnx.ValueInfoProto.encode(t.input[n], r.uint32(90).fork()).ldelim(); if (t.output != null && t.output.length) for (var n = 0; n < t.output.length; ++n) h.onnx.ValueInfoProto.encode(t.output[n], r.uint32(98).fork()).ldelim(); if (t.valueInfo != null && t.valueInfo.length) for (var n = 0; n < t.valueInfo.length; ++n) h.onnx.ValueInfoProto.encode(t.valueInfo[n], r.uint32(106).fork()).ldelim(); if (t.quantizationAnnotation != null && t.quantizationAnnotation.length) for (var n = 0; n < t.quantizationAnnotation.length; ++n) h.onnx.TensorAnnotation.encode(t.quantizationAnnotation[n], r.uint32(114).fork()).ldelim(); if (t.sparseInitializer != null && t.sparseInitializer.length) for (var n = 0; n < t.sparseInitializer.length; ++n) h.onnx.SparseTensorProto.encode(t.sparseInitializer[n], r.uint32(122).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.GraphProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.node && s.node.length || (s.node = []), s.node.push(h.onnx.NodeProto.decode(t, t.uint32())); break; } case 2: { s.name = t.string(); break; } case 5: { s.initializer && s.initializer.length || (s.initializer = []), s.initializer.push(h.onnx.TensorProto.decode(t, t.uint32())); break; } case 15: { s.sparseInitializer && s.sparseInitializer.length || (s.sparseInitializer = []), s.sparseInitializer.push(h.onnx.SparseTensorProto.decode(t, t.uint32())); break; } case 10: { s.docString = t.string(); break; } case 11: { s.input && s.input.length || (s.input = []), s.input.push(h.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 12: { s.output && s.output.length || (s.output = []), s.output.push(h.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 13: { s.valueInfo && s.valueInfo.length || (s.valueInfo = []), s.valueInfo.push(h.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 14: { s.quantizationAnnotation && s.quantizationAnnotation.length || (s.quantizationAnnotation = []), s.quantizationAnnotation.push(h.onnx.TensorAnnotation.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.node != null && t.hasOwnProperty("node")) { if (!Array.isArray(t.node)) return "node: array expected"; for (var r = 0; r < t.node.length; ++r) { var n = h.onnx.NodeProto.verify(t.node[r]); if (n) return "node." + n; } } if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.initializer != null && t.hasOwnProperty("initializer")) { if (!Array.isArray(t.initializer)) return "initializer: array expected"; for (var r = 0; r < t.initializer.length; ++r) { var n = h.onnx.TensorProto.verify(t.initializer[r]); if (n) return "initializer." + n; } } if (t.sparseInitializer != null && t.hasOwnProperty("sparseInitializer")) { if (!Array.isArray(t.sparseInitializer)) return "sparseInitializer: array expected"; for (var r = 0; r < t.sparseInitializer.length; ++r) { var n = h.onnx.SparseTensorProto.verify(t.sparseInitializer[r]); if (n) return "sparseInitializer." + n; } } if (t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString)) return "docString: string expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var r = 0; r < t.input.length; ++r) { var n = h.onnx.ValueInfoProto.verify(t.input[r]); if (n) return "input." + n; } } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var r = 0; r < t.output.length; ++r) { var n = h.onnx.ValueInfoProto.verify(t.output[r]); if (n) return "output." + n; } } if (t.valueInfo != null && t.hasOwnProperty("valueInfo")) { if (!Array.isArray(t.valueInfo)) return "valueInfo: array expected"; for (var r = 0; r < t.valueInfo.length; ++r) { var n = h.onnx.ValueInfoProto.verify(t.valueInfo[r]); if (n) return "valueInfo." + n; } } if (t.quantizationAnnotation != null && t.hasOwnProperty("quantizationAnnotation")) { if (!Array.isArray(t.quantizationAnnotation)) return "quantizationAnnotation: array expected"; for (var r = 0; r < t.quantizationAnnotation.length; ++r) { var n = h.onnx.TensorAnnotation.verify(t.quantizationAnnotation[r]); if (n) return "quantizationAnnotation." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.GraphProto) return t; var r = new h.onnx.GraphProto(); if (t.node) { if (!Array.isArray(t.node)) throw TypeError(".onnx.GraphProto.node: array expected"); r.node = []; for (var n = 0; n < t.node.length; ++n) { if (typeof t.node[n] != "object") throw TypeError(".onnx.GraphProto.node: object expected"); r.node[n] = h.onnx.NodeProto.fromObject(t.node[n]); } } if (t.name != null && (r.name = String(t.name)), t.initializer) { if (!Array.isArray(t.initializer)) throw TypeError(".onnx.GraphProto.initializer: array expected"); r.initializer = []; for (var n = 0; n < t.initializer.length; ++n) { if (typeof t.initializer[n] != "object") throw TypeError(".onnx.GraphProto.initializer: object expected"); r.initializer[n] = h.onnx.TensorProto.fromObject(t.initializer[n]); } } if (t.sparseInitializer) { if (!Array.isArray(t.sparseInitializer)) throw TypeError(".onnx.GraphProto.sparseInitializer: array expected"); r.sparseInitializer = []; for (var n = 0; n < t.sparseInitializer.length; ++n) { if (typeof t.sparseInitializer[n] != "object") throw TypeError(".onnx.GraphProto.sparseInitializer: object expected"); r.sparseInitializer[n] = h.onnx.SparseTensorProto.fromObject(t.sparseInitializer[n]); } } if (t.docString != null && (r.docString = String(t.docString)), t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.GraphProto.input: array expected"); r.input = []; for (var n = 0; n < t.input.length; ++n) { if (typeof t.input[n] != "object") throw TypeError(".onnx.GraphProto.input: object expected"); r.input[n] = h.onnx.ValueInfoProto.fromObject(t.input[n]); } } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.GraphProto.output: array expected"); r.output = []; for (var n = 0; n < t.output.length; ++n) { if (typeof t.output[n] != "object") throw TypeError(".onnx.GraphProto.output: object expected"); r.output[n] = h.onnx.ValueInfoProto.fromObject(t.output[n]); } } if (t.valueInfo) { if (!Array.isArray(t.valueInfo)) throw TypeError(".onnx.GraphProto.valueInfo: array expected"); r.valueInfo = []; for (var n = 0; n < t.valueInfo.length; ++n) { if (typeof t.valueInfo[n] != "object") throw TypeError(".onnx.GraphProto.valueInfo: object expected"); r.valueInfo[n] = h.onnx.ValueInfoProto.fromObject(t.valueInfo[n]); } } if (t.quantizationAnnotation) { if (!Array.isArray(t.quantizationAnnotation)) throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected"); r.quantizationAnnotation = []; for (var n = 0; n < t.quantizationAnnotation.length; ++n) { if (typeof t.quantizationAnnotation[n] != "object") throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected"); r.quantizationAnnotation[n] = h.onnx.TensorAnnotation.fromObject(t.quantizationAnnotation[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.node = [], n.initializer = [], n.input = [], n.output = [], n.valueInfo = [], n.quantizationAnnotation = [], n.sparseInitializer = []), r.defaults && (n.name = "", n.docString = ""), t.node && t.node.length) { n.node = []; for (var s = 0; s < t.node.length; ++s) n.node[s] = h.onnx.NodeProto.toObject(t.node[s], r); } if (t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.initializer && t.initializer.length) { n.initializer = []; for (var s = 0; s < t.initializer.length; ++s) n.initializer[s] = h.onnx.TensorProto.toObject(t.initializer[s], r); } if (t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.input && t.input.length) { n.input = []; for (var s = 0; s < t.input.length; ++s) n.input[s] = h.onnx.ValueInfoProto.toObject(t.input[s], r); } if (t.output && t.output.length) { n.output = []; for (var s = 0; s < t.output.length; ++s) n.output[s] = h.onnx.ValueInfoProto.toObject(t.output[s], r); } if (t.valueInfo && t.valueInfo.length) { n.valueInfo = []; for (var s = 0; s < t.valueInfo.length; ++s) n.valueInfo[s] = h.onnx.ValueInfoProto.toObject(t.valueInfo[s], r); } if (t.quantizationAnnotation && t.quantizationAnnotation.length) { n.quantizationAnnotation = []; for (var s = 0; s < t.quantizationAnnotation.length; ++s) n.quantizationAnnotation[s] = h.onnx.TensorAnnotation.toObject(t.quantizationAnnotation[s], r); } if (t.sparseInitializer && t.sparseInitializer.length) { n.sparseInitializer = []; for (var s = 0; s < t.sparseInitializer.length; ++s) n.sparseInitializer[s] = h.onnx.SparseTensorProto.toObject(t.sparseInitializer[s], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.GraphProto"; }, e; })(), i.TensorProto = (function() { function e(o) { if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.dims = b.emptyArray, e.prototype.dataType = 0, e.prototype.segment = null, e.prototype.floatData = b.emptyArray, e.prototype.int32Data = b.emptyArray, e.prototype.stringData = b.emptyArray, e.prototype.int64Data = b.emptyArray, e.prototype.name = "", e.prototype.docString = "", e.prototype.rawData = b.newBuffer([]), e.prototype.externalData = b.emptyArray, e.prototype.dataLocation = 0, e.prototype.doubleData = b.emptyArray, e.prototype.uint64Data = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.dims != null && t.dims.length) { r.uint32(10).fork(); for (var n = 0; n < t.dims.length; ++n) r.int64(t.dims[n]); r.ldelim(); } if (t.dataType != null && Object.hasOwnProperty.call(t, "dataType") && r.uint32(16).int32(t.dataType), t.segment != null && Object.hasOwnProperty.call(t, "segment") && h.onnx.TensorProto.Segment.encode(t.segment, r.uint32(26).fork()).ldelim(), t.floatData != null && t.floatData.length) { r.uint32(34).fork(); for (var n = 0; n < t.floatData.length; ++n) r.float(t.floatData[n]); r.ldelim(); } if (t.int32Data != null && t.int32Data.length) { r.uint32(42).fork(); for (var n = 0; n < t.int32Data.length; ++n) r.int32(t.int32Data[n]); r.ldelim(); } if (t.stringData != null && t.stringData.length) for (var n = 0; n < t.stringData.length; ++n) r.uint32(50).bytes(t.stringData[n]); if (t.int64Data != null && t.int64Data.length) { r.uint32(58).fork(); for (var n = 0; n < t.int64Data.length; ++n) r.int64(t.int64Data[n]); r.ldelim(); } if (t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(66).string(t.name), t.rawData != null && Object.hasOwnProperty.call(t, "rawData") && r.uint32(74).bytes(t.rawData), t.doubleData != null && t.doubleData.length) { r.uint32(82).fork(); for (var n = 0; n < t.doubleData.length; ++n) r.double(t.doubleData[n]); r.ldelim(); } if (t.uint64Data != null && t.uint64Data.length) { r.uint32(90).fork(); for (var n = 0; n < t.uint64Data.length; ++n) r.uint64(t.uint64Data[n]); r.ldelim(); } if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(98).string(t.docString), t.externalData != null && t.externalData.length) for (var n = 0; n < t.externalData.length; ++n) h.onnx.StringStringEntryProto.encode(t.externalData[n], r.uint32(106).fork()).ldelim(); return t.dataLocation != null && Object.hasOwnProperty.call(t, "dataLocation") && r.uint32(112).int32(t.dataLocation), r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.TensorProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { if (s.dims && s.dims.length || (s.dims = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.dims.push(t.int64()); else s.dims.push(t.int64()); break; } case 2: { s.dataType = t.int32(); break; } case 3: { s.segment = h.onnx.TensorProto.Segment.decode(t, t.uint32()); break; } case 4: { if (s.floatData && s.floatData.length || (s.floatData = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.floatData.push(t.float()); else s.floatData.push(t.float()); break; } case 5: { if (s.int32Data && s.int32Data.length || (s.int32Data = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.int32Data.push(t.int32()); else s.int32Data.push(t.int32()); break; } case 6: { s.stringData && s.stringData.length || (s.stringData = []), s.stringData.push(t.bytes()); break; } case 7: { if (s.int64Data && s.int64Data.length || (s.int64Data = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.int64Data.push(t.int64()); else s.int64Data.push(t.int64()); break; } case 8: { s.name = t.string(); break; } case 12: { s.docString = t.string(); break; } case 9: { s.rawData = t.bytes(); break; } case 13: { s.externalData && s.externalData.length || (s.externalData = []), s.externalData.push(h.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 14: { s.dataLocation = t.int32(); break; } case 10: { if (s.doubleData && s.doubleData.length || (s.doubleData = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.doubleData.push(t.double()); else s.doubleData.push(t.double()); break; } case 11: { if (s.uint64Data && s.uint64Data.length || (s.uint64Data = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.uint64Data.push(t.uint64()); else s.uint64Data.push(t.uint64()); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.dims != null && t.hasOwnProperty("dims")) { if (!Array.isArray(t.dims)) return "dims: array expected"; for (var r = 0; r < t.dims.length; ++r) if (!b.isInteger(t.dims[r]) && !(t.dims[r] && b.isInteger(t.dims[r].low) && b.isInteger(t.dims[r].high))) return "dims: integer|Long[] expected"; } if (t.dataType != null && t.hasOwnProperty("dataType") && !b.isInteger(t.dataType)) return "dataType: integer expected"; if (t.segment != null && t.hasOwnProperty("segment")) { var n = h.onnx.TensorProto.Segment.verify(t.segment); if (n) return "segment." + n; } if (t.floatData != null && t.hasOwnProperty("floatData")) { if (!Array.isArray(t.floatData)) return "floatData: array expected"; for (var r = 0; r < t.floatData.length; ++r) if (typeof t.floatData[r] != "number") return "floatData: number[] expected"; } if (t.int32Data != null && t.hasOwnProperty("int32Data")) { if (!Array.isArray(t.int32Data)) return "int32Data: array expected"; for (var r = 0; r < t.int32Data.length; ++r) if (!b.isInteger(t.int32Data[r])) return "int32Data: integer[] expected"; } if (t.stringData != null && t.hasOwnProperty("stringData")) { if (!Array.isArray(t.stringData)) return "stringData: array expected"; for (var r = 0; r < t.stringData.length; ++r) if (!(t.stringData[r] && typeof t.stringData[r].length == "number" || b.isString(t.stringData[r]))) return "stringData: buffer[] expected"; } if (t.int64Data != null && t.hasOwnProperty("int64Data")) { if (!Array.isArray(t.int64Data)) return "int64Data: array expected"; for (var r = 0; r < t.int64Data.length; ++r) if (!b.isInteger(t.int64Data[r]) && !(t.int64Data[r] && b.isInteger(t.int64Data[r].low) && b.isInteger(t.int64Data[r].high))) return "int64Data: integer|Long[] expected"; } if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString)) return "docString: string expected"; if (t.rawData != null && t.hasOwnProperty("rawData") && !(t.rawData && typeof t.rawData.length == "number" || b.isString(t.rawData))) return "rawData: buffer expected"; if (t.externalData != null && t.hasOwnProperty("externalData")) { if (!Array.isArray(t.externalData)) return "externalData: array expected"; for (var r = 0; r < t.externalData.length; ++r) { var n = h.onnx.StringStringEntryProto.verify(t.externalData[r]); if (n) return "externalData." + n; } } if (t.dataLocation != null && t.hasOwnProperty("dataLocation")) switch (t.dataLocation) { default: return "dataLocation: enum value expected"; case 0: case 1: break; } if (t.doubleData != null && t.hasOwnProperty("doubleData")) { if (!Array.isArray(t.doubleData)) return "doubleData: array expected"; for (var r = 0; r < t.doubleData.length; ++r) if (typeof t.doubleData[r] != "number") return "doubleData: number[] expected"; } if (t.uint64Data != null && t.hasOwnProperty("uint64Data")) { if (!Array.isArray(t.uint64Data)) return "uint64Data: array expected"; for (var r = 0; r < t.uint64Data.length; ++r) if (!b.isInteger(t.uint64Data[r]) && !(t.uint64Data[r] && b.isInteger(t.uint64Data[r].low) && b.isInteger(t.uint64Data[r].high))) return "uint64Data: integer|Long[] expected"; } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.TensorProto) return t; var r = new h.onnx.TensorProto(); if (t.dims) { if (!Array.isArray(t.dims)) throw TypeError(".onnx.TensorProto.dims: array expected"); r.dims = []; for (var n = 0; n < t.dims.length; ++n) b.Long ? (r.dims[n] = b.Long.fromValue(t.dims[n])).unsigned = false : typeof t.dims[n] == "string" ? r.dims[n] = parseInt(t.dims[n], 10) : typeof t.dims[n] == "number" ? r.dims[n] = t.dims[n] : typeof t.dims[n] == "object" && (r.dims[n] = new b.LongBits(t.dims[n].low >>> 0, t.dims[n].high >>> 0).toNumber()); } if (t.dataType != null && (r.dataType = t.dataType | 0), t.segment != null) { if (typeof t.segment != "object") throw TypeError(".onnx.TensorProto.segment: object expected"); r.segment = h.onnx.TensorProto.Segment.fromObject(t.segment); } if (t.floatData) { if (!Array.isArray(t.floatData)) throw TypeError(".onnx.TensorProto.floatData: array expected"); r.floatData = []; for (var n = 0; n < t.floatData.length; ++n) r.floatData[n] = Number(t.floatData[n]); } if (t.int32Data) { if (!Array.isArray(t.int32Data)) throw TypeError(".onnx.TensorProto.int32Data: array expected"); r.int32Data = []; for (var n = 0; n < t.int32Data.length; ++n) r.int32Data[n] = t.int32Data[n] | 0; } if (t.stringData) { if (!Array.isArray(t.stringData)) throw TypeError(".onnx.TensorProto.stringData: array expected"); r.stringData = []; for (var n = 0; n < t.stringData.length; ++n) typeof t.stringData[n] == "string" ? b.base64.decode(t.stringData[n], r.stringData[n] = b.newBuffer(b.base64.length(t.stringData[n])), 0) : t.stringData[n].length >= 0 && (r.stringData[n] = t.stringData[n]); } if (t.int64Data) { if (!Array.isArray(t.int64Data)) throw TypeError(".onnx.TensorProto.int64Data: array expected"); r.int64Data = []; for (var n = 0; n < t.int64Data.length; ++n) b.Long ? (r.int64Data[n] = b.Long.fromValue(t.int64Data[n])).unsigned = false : typeof t.int64Data[n] == "string" ? r.int64Data[n] = parseInt(t.int64Data[n], 10) : typeof t.int64Data[n] == "number" ? r.int64Data[n] = t.int64Data[n] : typeof t.int64Data[n] == "object" && (r.int64Data[n] = new b.LongBits(t.int64Data[n].low >>> 0, t.int64Data[n].high >>> 0).toNumber()); } if (t.name != null && (r.name = String(t.name)), t.docString != null && (r.docString = String(t.docString)), t.rawData != null && (typeof t.rawData == "string" ? b.base64.decode(t.rawData, r.rawData = b.newBuffer(b.base64.length(t.rawData)), 0) : t.rawData.length >= 0 && (r.rawData = t.rawData)), t.externalData) { if (!Array.isArray(t.externalData)) throw TypeError(".onnx.TensorProto.externalData: array expected"); r.externalData = []; for (var n = 0; n < t.externalData.length; ++n) { if (typeof t.externalData[n] != "object") throw TypeError(".onnx.TensorProto.externalData: object expected"); r.externalData[n] = h.onnx.StringStringEntryProto.fromObject(t.externalData[n]); } } switch (t.dataLocation) { default: if (typeof t.dataLocation == "number") { r.dataLocation = t.dataLocation; break; } break; case "DEFAULT": case 0: r.dataLocation = 0; break; case "EXTERNAL": case 1: r.dataLocation = 1; break; } if (t.doubleData) { if (!Array.isArray(t.doubleData)) throw TypeError(".onnx.TensorProto.doubleData: array expected"); r.doubleData = []; for (var n = 0; n < t.doubleData.length; ++n) r.doubleData[n] = Number(t.doubleData[n]); } if (t.uint64Data) { if (!Array.isArray(t.uint64Data)) throw TypeError(".onnx.TensorProto.uint64Data: array expected"); r.uint64Data = []; for (var n = 0; n < t.uint64Data.length; ++n) b.Long ? (r.uint64Data[n] = b.Long.fromValue(t.uint64Data[n])).unsigned = true : typeof t.uint64Data[n] == "string" ? r.uint64Data[n] = parseInt(t.uint64Data[n], 10) : typeof t.uint64Data[n] == "number" ? r.uint64Data[n] = t.uint64Data[n] : typeof t.uint64Data[n] == "object" && (r.uint64Data[n] = new b.LongBits(t.uint64Data[n].low >>> 0, t.uint64Data[n].high >>> 0).toNumber(true)); } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.dims = [], n.floatData = [], n.int32Data = [], n.stringData = [], n.int64Data = [], n.doubleData = [], n.uint64Data = [], n.externalData = []), r.defaults && (n.dataType = 0, n.segment = null, n.name = "", r.bytes === String ? n.rawData = "" : (n.rawData = [], r.bytes !== Array && (n.rawData = b.newBuffer(n.rawData))), n.docString = "", n.dataLocation = r.enums === String ? "DEFAULT" : 0), t.dims && t.dims.length) { n.dims = []; for (var s = 0; s < t.dims.length; ++s) typeof t.dims[s] == "number" ? n.dims[s] = r.longs === String ? String(t.dims[s]) : t.dims[s] : n.dims[s] = r.longs === String ? b.Long.prototype.toString.call(t.dims[s]) : r.longs === Number ? new b.LongBits(t.dims[s].low >>> 0, t.dims[s].high >>> 0).toNumber() : t.dims[s]; } if (t.dataType != null && t.hasOwnProperty("dataType") && (n.dataType = t.dataType), t.segment != null && t.hasOwnProperty("segment") && (n.segment = h.onnx.TensorProto.Segment.toObject(t.segment, r)), t.floatData && t.floatData.length) { n.floatData = []; for (var s = 0; s < t.floatData.length; ++s) n.floatData[s] = r.json && !isFinite(t.floatData[s]) ? String(t.floatData[s]) : t.floatData[s]; } if (t.int32Data && t.int32Data.length) { n.int32Data = []; for (var s = 0; s < t.int32Data.length; ++s) n.int32Data[s] = t.int32Data[s]; } if (t.stringData && t.stringData.length) { n.stringData = []; for (var s = 0; s < t.stringData.length; ++s) n.stringData[s] = r.bytes === String ? b.base64.encode(t.stringData[s], 0, t.stringData[s].length) : r.bytes === Array ? Array.prototype.slice.call(t.stringData[s]) : t.stringData[s]; } if (t.int64Data && t.int64Data.length) { n.int64Data = []; for (var s = 0; s < t.int64Data.length; ++s) typeof t.int64Data[s] == "number" ? n.int64Data[s] = r.longs === String ? String(t.int64Data[s]) : t.int64Data[s] : n.int64Data[s] = r.longs === String ? b.Long.prototype.toString.call(t.int64Data[s]) : r.longs === Number ? new b.LongBits(t.int64Data[s].low >>> 0, t.int64Data[s].high >>> 0).toNumber() : t.int64Data[s]; } if (t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.rawData != null && t.hasOwnProperty("rawData") && (n.rawData = r.bytes === String ? b.base64.encode(t.rawData, 0, t.rawData.length) : r.bytes === Array ? Array.prototype.slice.call(t.rawData) : t.rawData), t.doubleData && t.doubleData.length) { n.doubleData = []; for (var s = 0; s < t.doubleData.length; ++s) n.doubleData[s] = r.json && !isFinite(t.doubleData[s]) ? String(t.doubleData[s]) : t.doubleData[s]; } if (t.uint64Data && t.uint64Data.length) { n.uint64Data = []; for (var s = 0; s < t.uint64Data.length; ++s) typeof t.uint64Data[s] == "number" ? n.uint64Data[s] = r.longs === String ? String(t.uint64Data[s]) : t.uint64Data[s] : n.uint64Data[s] = r.longs === String ? b.Long.prototype.toString.call(t.uint64Data[s]) : r.longs === Number ? new b.LongBits(t.uint64Data[s].low >>> 0, t.uint64Data[s].high >>> 0).toNumber(true) : t.uint64Data[s]; } if (t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.externalData && t.externalData.length) { n.externalData = []; for (var s = 0; s < t.externalData.length; ++s) n.externalData[s] = h.onnx.StringStringEntryProto.toObject(t.externalData[s], r); } return t.dataLocation != null && t.hasOwnProperty("dataLocation") && (n.dataLocation = r.enums === String ? h.onnx.TensorProto.DataLocation[t.dataLocation] === void 0 ? t.dataLocation : h.onnx.TensorProto.DataLocation[t.dataLocation] : t.dataLocation), n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorProto"; }, e.DataType = (function() { var o = {}, t = Object.create(o); return t[o[0] = "UNDEFINED"] = 0, t[o[1] = "FLOAT"] = 1, t[o[2] = "UINT8"] = 2, t[o[3] = "INT8"] = 3, t[o[4] = "UINT16"] = 4, t[o[5] = "INT16"] = 5, t[o[6] = "INT32"] = 6, t[o[7] = "INT64"] = 7, t[o[8] = "STRING"] = 8, t[o[9] = "BOOL"] = 9, t[o[10] = "FLOAT16"] = 10, t[o[11] = "DOUBLE"] = 11, t[o[12] = "UINT32"] = 12, t[o[13] = "UINT64"] = 13, t[o[14] = "COMPLEX64"] = 14, t[o[15] = "COMPLEX128"] = 15, t[o[16] = "BFLOAT16"] = 16, t[o[17] = "FLOAT8E4M3FN"] = 17, t[o[18] = "FLOAT8E4M3FNUZ"] = 18, t[o[19] = "FLOAT8E5M2"] = 19, t[o[20] = "FLOAT8E5M2FNUZ"] = 20, t; })(), e.Segment = (function() { function o(t) { if (t) for (var r = Object.keys(t), n = 0; n < r.length; ++n) t[r[n]] != null && (this[r[n]] = t[r[n]]); } return o.prototype.begin = b.Long ? b.Long.fromBits(0, 0, false) : 0, o.prototype.end = b.Long ? b.Long.fromBits(0, 0, false) : 0, o.create = function(r) { return new o(r); }, o.encode = function(r, n) { return n || (n = pt2.create()), r.begin != null && Object.hasOwnProperty.call(r, "begin") && n.uint32(8).int64(r.begin), r.end != null && Object.hasOwnProperty.call(r, "end") && n.uint32(16).int64(r.end), n; }, o.encodeDelimited = function(r, n) { return this.encode(r, n).ldelim(); }, o.decode = function(r, n) { r instanceof $2 || (r = $2.create(r)); for (var s = n === void 0 ? r.len : r.pos + n, a = new h.onnx.TensorProto.Segment(); r.pos < s; ) { var u = r.uint32(); switch (u >>> 3) { case 1: { a.begin = r.int64(); break; } case 2: { a.end = r.int64(); break; } default: r.skipType(u & 7); break; } } return a; }, o.decodeDelimited = function(r) { return r instanceof $2 || (r = new $2(r)), this.decode(r, r.uint32()); }, o.verify = function(r) { return typeof r != "object" || r === null ? "object expected" : r.begin != null && r.hasOwnProperty("begin") && !b.isInteger(r.begin) && !(r.begin && b.isInteger(r.begin.low) && b.isInteger(r.begin.high)) ? "begin: integer|Long expected" : r.end != null && r.hasOwnProperty("end") && !b.isInteger(r.end) && !(r.end && b.isInteger(r.end.low) && b.isInteger(r.end.high)) ? "end: integer|Long expected" : null; }, o.fromObject = function(r) { if (r instanceof h.onnx.TensorProto.Segment) return r; var n = new h.onnx.TensorProto.Segment(); return r.begin != null && (b.Long ? (n.begin = b.Long.fromValue(r.begin)).unsigned = false : typeof r.begin == "string" ? n.begin = parseInt(r.begin, 10) : typeof r.begin == "number" ? n.begin = r.begin : typeof r.begin == "object" && (n.begin = new b.LongBits(r.begin.low >>> 0, r.begin.high >>> 0).toNumber())), r.end != null && (b.Long ? (n.end = b.Long.fromValue(r.end)).unsigned = false : typeof r.end == "string" ? n.end = parseInt(r.end, 10) : typeof r.end == "number" ? n.end = r.end : typeof r.end == "object" && (n.end = new b.LongBits(r.end.low >>> 0, r.end.high >>> 0).toNumber())), n; }, o.toObject = function(r, n) { n || (n = {}); var s = {}; if (n.defaults) { if (b.Long) { var a = new b.Long(0, 0, false); s.begin = n.longs === String ? a.toString() : n.longs === Number ? a.toNumber() : a; } else s.begin = n.longs === String ? "0" : 0; if (b.Long) { var a = new b.Long(0, 0, false); s.end = n.longs === String ? a.toString() : n.longs === Number ? a.toNumber() : a; } else s.end = n.longs === String ? "0" : 0; } return r.begin != null && r.hasOwnProperty("begin") && (typeof r.begin == "number" ? s.begin = n.longs === String ? String(r.begin) : r.begin : s.begin = n.longs === String ? b.Long.prototype.toString.call(r.begin) : n.longs === Number ? new b.LongBits(r.begin.low >>> 0, r.begin.high >>> 0).toNumber() : r.begin), r.end != null && r.hasOwnProperty("end") && (typeof r.end == "number" ? s.end = n.longs === String ? String(r.end) : r.end : s.end = n.longs === String ? b.Long.prototype.toString.call(r.end) : n.longs === Number ? new b.LongBits(r.end.low >>> 0, r.end.high >>> 0).toNumber() : r.end), s; }, o.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, o.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TensorProto.Segment"; }, o; })(), e.DataLocation = (function() { var o = {}, t = Object.create(o); return t[o[0] = "DEFAULT"] = 0, t[o[1] = "EXTERNAL"] = 1, t; })(), e; })(), i.SparseTensorProto = (function() { function e(o) { if (this.dims = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.values = null, e.prototype.indices = null, e.prototype.dims = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.values != null && Object.hasOwnProperty.call(t, "values") && h.onnx.TensorProto.encode(t.values, r.uint32(10).fork()).ldelim(), t.indices != null && Object.hasOwnProperty.call(t, "indices") && h.onnx.TensorProto.encode(t.indices, r.uint32(18).fork()).ldelim(), t.dims != null && t.dims.length) { r.uint32(26).fork(); for (var n = 0; n < t.dims.length; ++n) r.int64(t.dims[n]); r.ldelim(); } return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.SparseTensorProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.values = h.onnx.TensorProto.decode(t, t.uint32()); break; } case 2: { s.indices = h.onnx.TensorProto.decode(t, t.uint32()); break; } case 3: { if (s.dims && s.dims.length || (s.dims = []), (a & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.dims.push(t.int64()); else s.dims.push(t.int64()); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.values != null && t.hasOwnProperty("values")) { var r = h.onnx.TensorProto.verify(t.values); if (r) return "values." + r; } if (t.indices != null && t.hasOwnProperty("indices")) { var r = h.onnx.TensorProto.verify(t.indices); if (r) return "indices." + r; } if (t.dims != null && t.hasOwnProperty("dims")) { if (!Array.isArray(t.dims)) return "dims: array expected"; for (var n = 0; n < t.dims.length; ++n) if (!b.isInteger(t.dims[n]) && !(t.dims[n] && b.isInteger(t.dims[n].low) && b.isInteger(t.dims[n].high))) return "dims: integer|Long[] expected"; } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.SparseTensorProto) return t; var r = new h.onnx.SparseTensorProto(); if (t.values != null) { if (typeof t.values != "object") throw TypeError(".onnx.SparseTensorProto.values: object expected"); r.values = h.onnx.TensorProto.fromObject(t.values); } if (t.indices != null) { if (typeof t.indices != "object") throw TypeError(".onnx.SparseTensorProto.indices: object expected"); r.indices = h.onnx.TensorProto.fromObject(t.indices); } if (t.dims) { if (!Array.isArray(t.dims)) throw TypeError(".onnx.SparseTensorProto.dims: array expected"); r.dims = []; for (var n = 0; n < t.dims.length; ++n) b.Long ? (r.dims[n] = b.Long.fromValue(t.dims[n])).unsigned = false : typeof t.dims[n] == "string" ? r.dims[n] = parseInt(t.dims[n], 10) : typeof t.dims[n] == "number" ? r.dims[n] = t.dims[n] : typeof t.dims[n] == "object" && (r.dims[n] = new b.LongBits(t.dims[n].low >>> 0, t.dims[n].high >>> 0).toNumber()); } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.dims = []), r.defaults && (n.values = null, n.indices = null), t.values != null && t.hasOwnProperty("values") && (n.values = h.onnx.TensorProto.toObject(t.values, r)), t.indices != null && t.hasOwnProperty("indices") && (n.indices = h.onnx.TensorProto.toObject(t.indices, r)), t.dims && t.dims.length) { n.dims = []; for (var s = 0; s < t.dims.length; ++s) typeof t.dims[s] == "number" ? n.dims[s] = r.longs === String ? String(t.dims[s]) : t.dims[s] : n.dims[s] = r.longs === String ? b.Long.prototype.toString.call(t.dims[s]) : r.longs === Number ? new b.LongBits(t.dims[s].low >>> 0, t.dims[s].high >>> 0).toNumber() : t.dims[s]; } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.SparseTensorProto"; }, e; })(), i.TensorShapeProto = (function() { function e(o) { if (this.dim = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.dim = b.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.dim != null && t.dim.length) for (var n = 0; n < t.dim.length; ++n) h.onnx.TensorShapeProto.Dimension.encode(t.dim[n], r.uint32(10).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.TensorShapeProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.dim && s.dim.length || (s.dim = []), s.dim.push(h.onnx.TensorShapeProto.Dimension.decode(t, t.uint32())); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.dim != null && t.hasOwnProperty("dim")) { if (!Array.isArray(t.dim)) return "dim: array expected"; for (var r = 0; r < t.dim.length; ++r) { var n = h.onnx.TensorShapeProto.Dimension.verify(t.dim[r]); if (n) return "dim." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof h.onnx.TensorShapeProto) return t; var r = new h.onnx.TensorShapeProto(); if (t.dim) { if (!Array.isArray(t.dim)) throw TypeError(".onnx.TensorShapeProto.dim: array expected"); r.dim = []; for (var n = 0; n < t.dim.length; ++n) { if (typeof t.dim[n] != "object") throw TypeError(".onnx.TensorShapeProto.dim: object expected"); r.dim[n] = h.onnx.TensorShapeProto.Dimension.fromObject(t.dim[n]); } } return r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.dim = []), t.dim && t.dim.length) { n.dim = []; for (var s = 0; s < t.dim.length; ++s) n.dim[s] = h.onnx.TensorShapeProto.Dimension.toObject(t.dim[s], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorShapeProto"; }, e.Dimension = (function() { function o(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } o.prototype.dimValue = null, o.prototype.dimParam = null, o.prototype.denotation = ""; var t; return Object.defineProperty(o.prototype, "value", { get: b.oneOfGetter(t = ["dimValue", "dimParam"]), set: b.oneOfSetter(t) }), o.create = function(n) { return new o(n); }, o.encode = function(n, s) { return s || (s = pt2.create()), n.dimValue != null && Object.hasOwnProperty.call(n, "dimValue") && s.uint32(8).int64(n.dimValue), n.dimParam != null && Object.hasOwnProperty.call(n, "dimParam") && s.uint32(18).string(n.dimParam), n.denotation != null && Object.hasOwnProperty.call(n, "denotation") && s.uint32(26).string(n.denotation), s; }, o.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, o.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TensorShapeProto.Dimension(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.dimValue = n.int64(); break; } case 2: { u.dimParam = n.string(); break; } case 3: { u.denotation = n.string(); break; } default: n.skipType(l & 7); break; } } return u; }, o.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, o.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; var s = {}; if (n.dimValue != null && n.hasOwnProperty("dimValue") && (s.value = 1, !b.isInteger(n.dimValue) && !(n.dimValue && b.isInteger(n.dimValue.low) && b.isInteger(n.dimValue.high)))) return "dimValue: integer|Long expected"; if (n.dimParam != null && n.hasOwnProperty("dimParam")) { if (s.value === 1) return "value: multiple values"; if (s.value = 1, !b.isString(n.dimParam)) return "dimParam: string expected"; } return n.denotation != null && n.hasOwnProperty("denotation") && !b.isString(n.denotation) ? "denotation: string expected" : null; }, o.fromObject = function(n) { if (n instanceof h.onnx.TensorShapeProto.Dimension) return n; var s = new h.onnx.TensorShapeProto.Dimension(); return n.dimValue != null && (b.Long ? (s.dimValue = b.Long.fromValue(n.dimValue)).unsigned = false : typeof n.dimValue == "string" ? s.dimValue = parseInt(n.dimValue, 10) : typeof n.dimValue == "number" ? s.dimValue = n.dimValue : typeof n.dimValue == "object" && (s.dimValue = new b.LongBits(n.dimValue.low >>> 0, n.dimValue.high >>> 0).toNumber())), n.dimParam != null && (s.dimParam = String(n.dimParam)), n.denotation != null && (s.denotation = String(n.denotation)), s; }, o.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.denotation = ""), n.dimValue != null && n.hasOwnProperty("dimValue") && (typeof n.dimValue == "number" ? a.dimValue = s.longs === String ? String(n.dimValue) : n.dimValue : a.dimValue = s.longs === String ? b.Long.prototype.toString.call(n.dimValue) : s.longs === Number ? new b.LongBits(n.dimValue.low >>> 0, n.dimValue.high >>> 0).toNumber() : n.dimValue, s.oneofs && (a.value = "dimValue")), n.dimParam != null && n.hasOwnProperty("dimParam") && (a.dimParam = n.dimParam, s.oneofs && (a.value = "dimParam")), n.denotation != null && n.hasOwnProperty("denotation") && (a.denotation = n.denotation), a; }, o.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, o.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TensorShapeProto.Dimension"; }, o; })(), e; })(), i.TypeProto = (function() { function e(t) { if (t) for (var r = Object.keys(t), n = 0; n < r.length; ++n) t[r[n]] != null && (this[r[n]] = t[r[n]]); } e.prototype.tensorType = null, e.prototype.sequenceType = null, e.prototype.mapType = null, e.prototype.optionalType = null, e.prototype.sparseTensorType = null, e.prototype.denotation = ""; var o; return Object.defineProperty(e.prototype, "value", { get: b.oneOfGetter(o = ["tensorType", "sequenceType", "mapType", "optionalType", "sparseTensorType"]), set: b.oneOfSetter(o) }), e.create = function(r) { return new e(r); }, e.encode = function(r, n) { return n || (n = pt2.create()), r.tensorType != null && Object.hasOwnProperty.call(r, "tensorType") && h.onnx.TypeProto.Tensor.encode(r.tensorType, n.uint32(10).fork()).ldelim(), r.sequenceType != null && Object.hasOwnProperty.call(r, "sequenceType") && h.onnx.TypeProto.Sequence.encode(r.sequenceType, n.uint32(34).fork()).ldelim(), r.mapType != null && Object.hasOwnProperty.call(r, "mapType") && h.onnx.TypeProto.Map.encode(r.mapType, n.uint32(42).fork()).ldelim(), r.denotation != null && Object.hasOwnProperty.call(r, "denotation") && n.uint32(50).string(r.denotation), r.sparseTensorType != null && Object.hasOwnProperty.call(r, "sparseTensorType") && h.onnx.TypeProto.SparseTensor.encode(r.sparseTensorType, n.uint32(66).fork()).ldelim(), r.optionalType != null && Object.hasOwnProperty.call(r, "optionalType") && h.onnx.TypeProto.Optional.encode(r.optionalType, n.uint32(74).fork()).ldelim(), n; }, e.encodeDelimited = function(r, n) { return this.encode(r, n).ldelim(); }, e.decode = function(r, n) { r instanceof $2 || (r = $2.create(r)); for (var s = n === void 0 ? r.len : r.pos + n, a = new h.onnx.TypeProto(); r.pos < s; ) { var u = r.uint32(); switch (u >>> 3) { case 1: { a.tensorType = h.onnx.TypeProto.Tensor.decode(r, r.uint32()); break; } case 4: { a.sequenceType = h.onnx.TypeProto.Sequence.decode(r, r.uint32()); break; } case 5: { a.mapType = h.onnx.TypeProto.Map.decode(r, r.uint32()); break; } case 9: { a.optionalType = h.onnx.TypeProto.Optional.decode(r, r.uint32()); break; } case 8: { a.sparseTensorType = h.onnx.TypeProto.SparseTensor.decode(r, r.uint32()); break; } case 6: { a.denotation = r.string(); break; } default: r.skipType(u & 7); break; } } return a; }, e.decodeDelimited = function(r) { return r instanceof $2 || (r = new $2(r)), this.decode(r, r.uint32()); }, e.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; var n = {}; if (r.tensorType != null && r.hasOwnProperty("tensorType")) { n.value = 1; { var s = h.onnx.TypeProto.Tensor.verify(r.tensorType); if (s) return "tensorType." + s; } } if (r.sequenceType != null && r.hasOwnProperty("sequenceType")) { if (n.value === 1) return "value: multiple values"; n.value = 1; { var s = h.onnx.TypeProto.Sequence.verify(r.sequenceType); if (s) return "sequenceType." + s; } } if (r.mapType != null && r.hasOwnProperty("mapType")) { if (n.value === 1) return "value: multiple values"; n.value = 1; { var s = h.onnx.TypeProto.Map.verify(r.mapType); if (s) return "mapType." + s; } } if (r.optionalType != null && r.hasOwnProperty("optionalType")) { if (n.value === 1) return "value: multiple values"; n.value = 1; { var s = h.onnx.TypeProto.Optional.verify(r.optionalType); if (s) return "optionalType." + s; } } if (r.sparseTensorType != null && r.hasOwnProperty("sparseTensorType")) { if (n.value === 1) return "value: multiple values"; n.value = 1; { var s = h.onnx.TypeProto.SparseTensor.verify(r.sparseTensorType); if (s) return "sparseTensorType." + s; } } return r.denotation != null && r.hasOwnProperty("denotation") && !b.isString(r.denotation) ? "denotation: string expected" : null; }, e.fromObject = function(r) { if (r instanceof h.onnx.TypeProto) return r; var n = new h.onnx.TypeProto(); if (r.tensorType != null) { if (typeof r.tensorType != "object") throw TypeError(".onnx.TypeProto.tensorType: object expected"); n.tensorType = h.onnx.TypeProto.Tensor.fromObject(r.tensorType); } if (r.sequenceType != null) { if (typeof r.sequenceType != "object") throw TypeError(".onnx.TypeProto.sequenceType: object expected"); n.sequenceType = h.onnx.TypeProto.Sequence.fromObject(r.sequenceType); } if (r.mapType != null) { if (typeof r.mapType != "object") throw TypeError(".onnx.TypeProto.mapType: object expected"); n.mapType = h.onnx.TypeProto.Map.fromObject(r.mapType); } if (r.optionalType != null) { if (typeof r.optionalType != "object") throw TypeError(".onnx.TypeProto.optionalType: object expected"); n.optionalType = h.onnx.TypeProto.Optional.fromObject(r.optionalType); } if (r.sparseTensorType != null) { if (typeof r.sparseTensorType != "object") throw TypeError(".onnx.TypeProto.sparseTensorType: object expected"); n.sparseTensorType = h.onnx.TypeProto.SparseTensor.fromObject(r.sparseTensorType); } return r.denotation != null && (n.denotation = String(r.denotation)), n; }, e.toObject = function(r, n) { n || (n = {}); var s = {}; return n.defaults && (s.denotation = ""), r.tensorType != null && r.hasOwnProperty("tensorType") && (s.tensorType = h.onnx.TypeProto.Tensor.toObject(r.tensorType, n), n.oneofs && (s.value = "tensorType")), r.sequenceType != null && r.hasOwnProperty("sequenceType") && (s.sequenceType = h.onnx.TypeProto.Sequence.toObject(r.sequenceType, n), n.oneofs && (s.value = "sequenceType")), r.mapType != null && r.hasOwnProperty("mapType") && (s.mapType = h.onnx.TypeProto.Map.toObject(r.mapType, n), n.oneofs && (s.value = "mapType")), r.denotation != null && r.hasOwnProperty("denotation") && (s.denotation = r.denotation), r.sparseTensorType != null && r.hasOwnProperty("sparseTensorType") && (s.sparseTensorType = h.onnx.TypeProto.SparseTensor.toObject(r.sparseTensorType, n), n.oneofs && (s.value = "sparseTensorType")), r.optionalType != null && r.hasOwnProperty("optionalType") && (s.optionalType = h.onnx.TypeProto.Optional.toObject(r.optionalType, n), n.oneofs && (s.value = "optionalType")), s; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto"; }, e.Tensor = (function() { function t(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } return t.prototype.elemType = 0, t.prototype.shape = null, t.create = function(n) { return new t(n); }, t.encode = function(n, s) { return s || (s = pt2.create()), n.elemType != null && Object.hasOwnProperty.call(n, "elemType") && s.uint32(8).int32(n.elemType), n.shape != null && Object.hasOwnProperty.call(n, "shape") && h.onnx.TensorShapeProto.encode(n.shape, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, t.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TypeProto.Tensor(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.elemType = n.int32(); break; } case 2: { u.shape = h.onnx.TensorShapeProto.decode(n, n.uint32()); break; } default: n.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, t.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; if (n.elemType != null && n.hasOwnProperty("elemType") && !b.isInteger(n.elemType)) return "elemType: integer expected"; if (n.shape != null && n.hasOwnProperty("shape")) { var s = h.onnx.TensorShapeProto.verify(n.shape); if (s) return "shape." + s; } return null; }, t.fromObject = function(n) { if (n instanceof h.onnx.TypeProto.Tensor) return n; var s = new h.onnx.TypeProto.Tensor(); if (n.elemType != null && (s.elemType = n.elemType | 0), n.shape != null) { if (typeof n.shape != "object") throw TypeError(".onnx.TypeProto.Tensor.shape: object expected"); s.shape = h.onnx.TensorShapeProto.fromObject(n.shape); } return s; }, t.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.elemType = 0, a.shape = null), n.elemType != null && n.hasOwnProperty("elemType") && (a.elemType = n.elemType), n.shape != null && n.hasOwnProperty("shape") && (a.shape = h.onnx.TensorShapeProto.toObject(n.shape, s)), a; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, t.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto.Tensor"; }, t; })(), e.Sequence = (function() { function t(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } return t.prototype.elemType = null, t.create = function(n) { return new t(n); }, t.encode = function(n, s) { return s || (s = pt2.create()), n.elemType != null && Object.hasOwnProperty.call(n, "elemType") && h.onnx.TypeProto.encode(n.elemType, s.uint32(10).fork()).ldelim(), s; }, t.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, t.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TypeProto.Sequence(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.elemType = h.onnx.TypeProto.decode(n, n.uint32()); break; } default: n.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, t.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; if (n.elemType != null && n.hasOwnProperty("elemType")) { var s = h.onnx.TypeProto.verify(n.elemType); if (s) return "elemType." + s; } return null; }, t.fromObject = function(n) { if (n instanceof h.onnx.TypeProto.Sequence) return n; var s = new h.onnx.TypeProto.Sequence(); if (n.elemType != null) { if (typeof n.elemType != "object") throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected"); s.elemType = h.onnx.TypeProto.fromObject(n.elemType); } return s; }, t.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.elemType = null), n.elemType != null && n.hasOwnProperty("elemType") && (a.elemType = h.onnx.TypeProto.toObject(n.elemType, s)), a; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, t.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto.Sequence"; }, t; })(), e.Map = (function() { function t(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } return t.prototype.keyType = 0, t.prototype.valueType = null, t.create = function(n) { return new t(n); }, t.encode = function(n, s) { return s || (s = pt2.create()), n.keyType != null && Object.hasOwnProperty.call(n, "keyType") && s.uint32(8).int32(n.keyType), n.valueType != null && Object.hasOwnProperty.call(n, "valueType") && h.onnx.TypeProto.encode(n.valueType, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, t.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TypeProto.Map(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.keyType = n.int32(); break; } case 2: { u.valueType = h.onnx.TypeProto.decode(n, n.uint32()); break; } default: n.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, t.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; if (n.keyType != null && n.hasOwnProperty("keyType") && !b.isInteger(n.keyType)) return "keyType: integer expected"; if (n.valueType != null && n.hasOwnProperty("valueType")) { var s = h.onnx.TypeProto.verify(n.valueType); if (s) return "valueType." + s; } return null; }, t.fromObject = function(n) { if (n instanceof h.onnx.TypeProto.Map) return n; var s = new h.onnx.TypeProto.Map(); if (n.keyType != null && (s.keyType = n.keyType | 0), n.valueType != null) { if (typeof n.valueType != "object") throw TypeError(".onnx.TypeProto.Map.valueType: object expected"); s.valueType = h.onnx.TypeProto.fromObject(n.valueType); } return s; }, t.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.keyType = 0, a.valueType = null), n.keyType != null && n.hasOwnProperty("keyType") && (a.keyType = n.keyType), n.valueType != null && n.hasOwnProperty("valueType") && (a.valueType = h.onnx.TypeProto.toObject(n.valueType, s)), a; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, t.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto.Map"; }, t; })(), e.Optional = (function() { function t(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } return t.prototype.elemType = null, t.create = function(n) { return new t(n); }, t.encode = function(n, s) { return s || (s = pt2.create()), n.elemType != null && Object.hasOwnProperty.call(n, "elemType") && h.onnx.TypeProto.encode(n.elemType, s.uint32(10).fork()).ldelim(), s; }, t.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, t.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TypeProto.Optional(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.elemType = h.onnx.TypeProto.decode(n, n.uint32()); break; } default: n.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, t.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; if (n.elemType != null && n.hasOwnProperty("elemType")) { var s = h.onnx.TypeProto.verify(n.elemType); if (s) return "elemType." + s; } return null; }, t.fromObject = function(n) { if (n instanceof h.onnx.TypeProto.Optional) return n; var s = new h.onnx.TypeProto.Optional(); if (n.elemType != null) { if (typeof n.elemType != "object") throw TypeError(".onnx.TypeProto.Optional.elemType: object expected"); s.elemType = h.onnx.TypeProto.fromObject(n.elemType); } return s; }, t.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.elemType = null), n.elemType != null && n.hasOwnProperty("elemType") && (a.elemType = h.onnx.TypeProto.toObject(n.elemType, s)), a; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, t.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto.Optional"; }, t; })(), e.SparseTensor = (function() { function t(r) { if (r) for (var n = Object.keys(r), s = 0; s < n.length; ++s) r[n[s]] != null && (this[n[s]] = r[n[s]]); } return t.prototype.elemType = 0, t.prototype.shape = null, t.create = function(n) { return new t(n); }, t.encode = function(n, s) { return s || (s = pt2.create()), n.elemType != null && Object.hasOwnProperty.call(n, "elemType") && s.uint32(8).int32(n.elemType), n.shape != null && Object.hasOwnProperty.call(n, "shape") && h.onnx.TensorShapeProto.encode(n.shape, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(n, s) { return this.encode(n, s).ldelim(); }, t.decode = function(n, s) { n instanceof $2 || (n = $2.create(n)); for (var a = s === void 0 ? n.len : n.pos + s, u = new h.onnx.TypeProto.SparseTensor(); n.pos < a; ) { var l = n.uint32(); switch (l >>> 3) { case 1: { u.elemType = n.int32(); break; } case 2: { u.shape = h.onnx.TensorShapeProto.decode(n, n.uint32()); break; } default: n.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(n) { return n instanceof $2 || (n = new $2(n)), this.decode(n, n.uint32()); }, t.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; if (n.elemType != null && n.hasOwnProperty("elemType") && !b.isInteger(n.elemType)) return "elemType: integer expected"; if (n.shape != null && n.hasOwnProperty("shape")) { var s = h.onnx.TensorShapeProto.verify(n.shape); if (s) return "shape." + s; } return null; }, t.fromObject = function(n) { if (n instanceof h.onnx.TypeProto.SparseTensor) return n; var s = new h.onnx.TypeProto.SparseTensor(); if (n.elemType != null && (s.elemType = n.elemType | 0), n.shape != null) { if (typeof n.shape != "object") throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected"); s.shape = h.onnx.TensorShapeProto.fromObject(n.shape); } return s; }, t.toObject = function(n, s) { s || (s = {}); var a = {}; return s.defaults && (a.elemType = 0, a.shape = null), n.elemType != null && n.hasOwnProperty("elemType") && (a.elemType = n.elemType), n.shape != null && n.hasOwnProperty("shape") && (a.shape = h.onnx.TensorShapeProto.toObject(n.shape, s)), a; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, t.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto.SparseTensor"; }, t; })(), e; })(), i.OperatorSetIdProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.domain = "", e.prototype.version = b.Long ? b.Long.fromBits(0, 0, false) : 0, e.create = function(t) { return new e(t); }, e.encode = function(t, r) { return r || (r = pt2.create()), t.domain != null && Object.hasOwnProperty.call(t, "domain") && r.uint32(10).string(t.domain), t.version != null && Object.hasOwnProperty.call(t, "version") && r.uint32(16).int64(t.version), r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.OperatorSetIdProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.domain = t.string(); break; } case 2: { s.version = t.int64(); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { return typeof t != "object" || t === null ? "object expected" : t.domain != null && t.hasOwnProperty("domain") && !b.isString(t.domain) ? "domain: string expected" : t.version != null && t.hasOwnProperty("version") && !b.isInteger(t.version) && !(t.version && b.isInteger(t.version.low) && b.isInteger(t.version.high)) ? "version: integer|Long expected" : null; }, e.fromObject = function(t) { if (t instanceof h.onnx.OperatorSetIdProto) return t; var r = new h.onnx.OperatorSetIdProto(); return t.domain != null && (r.domain = String(t.domain)), t.version != null && (b.Long ? (r.version = b.Long.fromValue(t.version)).unsigned = false : typeof t.version == "string" ? r.version = parseInt(t.version, 10) : typeof t.version == "number" ? r.version = t.version : typeof t.version == "object" && (r.version = new b.LongBits(t.version.low >>> 0, t.version.high >>> 0).toNumber())), r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if (r.defaults) if (n.domain = "", b.Long) { var s = new b.Long(0, 0, false); n.version = r.longs === String ? s.toString() : r.longs === Number ? s.toNumber() : s; } else n.version = r.longs === String ? "0" : 0; return t.domain != null && t.hasOwnProperty("domain") && (n.domain = t.domain), t.version != null && t.hasOwnProperty("version") && (typeof t.version == "number" ? n.version = r.longs === String ? String(t.version) : t.version : n.version = r.longs === String ? b.Long.prototype.toString.call(t.version) : r.longs === Number ? new b.LongBits(t.version.low >>> 0, t.version.high >>> 0).toNumber() : t.version), n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.OperatorSetIdProto"; }, e; })(), i.OperatorStatus = (function() { var e = {}, o = Object.create(e); return o[e[0] = "EXPERIMENTAL"] = 0, o[e[1] = "STABLE"] = 1, o; })(), i.FunctionProto = (function() { function e(o) { if (this.input = [], this.output = [], this.attribute = [], this.attributeProto = [], this.node = [], this.opsetImport = [], o) for (var t = Object.keys(o), r = 0; r < t.length; ++r) o[t[r]] != null && (this[t[r]] = o[t[r]]); } return e.prototype.name = "", e.prototype.input = b.emptyArray, e.prototype.output = b.emptyArray, e.prototype.attribute = b.emptyArray, e.prototype.attributeProto = b.emptyArray, e.prototype.node = b.emptyArray, e.prototype.docString = "", e.prototype.opsetImport = b.emptyArray, e.prototype.domain = "", e.create = function(t) { return new e(t); }, e.encode = function(t, r) { if (r || (r = pt2.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && r.uint32(10).string(t.name), t.input != null && t.input.length) for (var n = 0; n < t.input.length; ++n) r.uint32(34).string(t.input[n]); if (t.output != null && t.output.length) for (var n = 0; n < t.output.length; ++n) r.uint32(42).string(t.output[n]); if (t.attribute != null && t.attribute.length) for (var n = 0; n < t.attribute.length; ++n) r.uint32(50).string(t.attribute[n]); if (t.node != null && t.node.length) for (var n = 0; n < t.node.length; ++n) h.onnx.NodeProto.encode(t.node[n], r.uint32(58).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && r.uint32(66).string(t.docString), t.opsetImport != null && t.opsetImport.length) for (var n = 0; n < t.opsetImport.length; ++n) h.onnx.OperatorSetIdProto.encode(t.opsetImport[n], r.uint32(74).fork()).ldelim(); if (t.domain != null && Object.hasOwnProperty.call(t, "domain") && r.uint32(82).string(t.domain), t.attributeProto != null && t.attributeProto.length) for (var n = 0; n < t.attributeProto.length; ++n) h.onnx.AttributeProto.encode(t.attributeProto[n], r.uint32(90).fork()).ldelim(); return r; }, e.encodeDelimited = function(t, r) { return this.encode(t, r).ldelim(); }, e.decode = function(t, r) { t instanceof $2 || (t = $2.create(t)); for (var n = r === void 0 ? t.len : t.pos + r, s = new h.onnx.FunctionProto(); t.pos < n; ) { var a = t.uint32(); switch (a >>> 3) { case 1: { s.name = t.string(); break; } case 4: { s.input && s.input.length || (s.input = []), s.input.push(t.string()); break; } case 5: { s.output && s.output.length || (s.output = []), s.output.push(t.string()); break; } case 6: { s.attribute && s.attribute.length || (s.attribute = []), s.attribute.push(t.string()); break; } case 11: { s.attributeProto && s.attributeProto.length || (s.attributeProto = []), s.attributeProto.push(h.onnx.AttributeProto.decode(t, t.uint32())); break; } case 7: { s.node && s.node.length || (s.node = []), s.node.push(h.onnx.NodeProto.decode(t, t.uint32())); break; } case 8: { s.docString = t.string(); break; } case 9: { s.opsetImport && s.opsetImport.length || (s.opsetImport = []), s.opsetImport.push(h.onnx.OperatorSetIdProto.decode(t, t.uint32())); break; } case 10: { s.domain = t.string(); break; } default: t.skipType(a & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof $2 || (t = new $2(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !b.isString(t.name)) return "name: string expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var r = 0; r < t.input.length; ++r) if (!b.isString(t.input[r])) return "input: string[] expected"; } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var r = 0; r < t.output.length; ++r) if (!b.isString(t.output[r])) return "output: string[] expected"; } if (t.attribute != null && t.hasOwnProperty("attribute")) { if (!Array.isArray(t.attribute)) return "attribute: array expected"; for (var r = 0; r < t.attribute.length; ++r) if (!b.isString(t.attribute[r])) return "attribute: string[] expected"; } if (t.attributeProto != null && t.hasOwnProperty("attributeProto")) { if (!Array.isArray(t.attributeProto)) return "attributeProto: array expected"; for (var r = 0; r < t.attributeProto.length; ++r) { var n = h.onnx.AttributeProto.verify(t.attributeProto[r]); if (n) return "attributeProto." + n; } } if (t.node != null && t.hasOwnProperty("node")) { if (!Array.isArray(t.node)) return "node: array expected"; for (var r = 0; r < t.node.length; ++r) { var n = h.onnx.NodeProto.verify(t.node[r]); if (n) return "node." + n; } } if (t.docString != null && t.hasOwnProperty("docString") && !b.isString(t.docString)) return "docString: string expected"; if (t.opsetImport != null && t.hasOwnProperty("opsetImport")) { if (!Array.isArray(t.opsetImport)) return "opsetImport: array expected"; for (var r = 0; r < t.opsetImport.length; ++r) { var n = h.onnx.OperatorSetIdProto.verify(t.opsetImport[r]); if (n) return "opsetImport." + n; } } return t.domain != null && t.hasOwnProperty("domain") && !b.isString(t.domain) ? "domain: string expected" : null; }, e.fromObject = function(t) { if (t instanceof h.onnx.FunctionProto) return t; var r = new h.onnx.FunctionProto(); if (t.name != null && (r.name = String(t.name)), t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.FunctionProto.input: array expected"); r.input = []; for (var n = 0; n < t.input.length; ++n) r.input[n] = String(t.input[n]); } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.FunctionProto.output: array expected"); r.output = []; for (var n = 0; n < t.output.length; ++n) r.output[n] = String(t.output[n]); } if (t.attribute) { if (!Array.isArray(t.attribute)) throw TypeError(".onnx.FunctionProto.attribute: array expected"); r.attribute = []; for (var n = 0; n < t.attribute.length; ++n) r.attribute[n] = String(t.attribute[n]); } if (t.attributeProto) { if (!Array.isArray(t.attributeProto)) throw TypeError(".onnx.FunctionProto.attributeProto: array expected"); r.attributeProto = []; for (var n = 0; n < t.attributeProto.length; ++n) { if (typeof t.attributeProto[n] != "object") throw TypeError(".onnx.FunctionProto.attributeProto: object expected"); r.attributeProto[n] = h.onnx.AttributeProto.fromObject(t.attributeProto[n]); } } if (t.node) { if (!Array.isArray(t.node)) throw TypeError(".onnx.FunctionProto.node: array expected"); r.node = []; for (var n = 0; n < t.node.length; ++n) { if (typeof t.node[n] != "object") throw TypeError(".onnx.FunctionProto.node: object expected"); r.node[n] = h.onnx.NodeProto.fromObject(t.node[n]); } } if (t.docString != null && (r.docString = String(t.docString)), t.opsetImport) { if (!Array.isArray(t.opsetImport)) throw TypeError(".onnx.FunctionProto.opsetImport: array expected"); r.opsetImport = []; for (var n = 0; n < t.opsetImport.length; ++n) { if (typeof t.opsetImport[n] != "object") throw TypeError(".onnx.FunctionProto.opsetImport: object expected"); r.opsetImport[n] = h.onnx.OperatorSetIdProto.fromObject(t.opsetImport[n]); } } return t.domain != null && (r.domain = String(t.domain)), r; }, e.toObject = function(t, r) { r || (r = {}); var n = {}; if ((r.arrays || r.defaults) && (n.input = [], n.output = [], n.attribute = [], n.node = [], n.opsetImport = [], n.attributeProto = []), r.defaults && (n.name = "", n.docString = "", n.domain = ""), t.name != null && t.hasOwnProperty("name") && (n.name = t.name), t.input && t.input.length) { n.input = []; for (var s = 0; s < t.input.length; ++s) n.input[s] = t.input[s]; } if (t.output && t.output.length) { n.output = []; for (var s = 0; s < t.output.length; ++s) n.output[s] = t.output[s]; } if (t.attribute && t.attribute.length) { n.attribute = []; for (var s = 0; s < t.attribute.length; ++s) n.attribute[s] = t.attribute[s]; } if (t.node && t.node.length) { n.node = []; for (var s = 0; s < t.node.length; ++s) n.node[s] = h.onnx.NodeProto.toObject(t.node[s], r); } if (t.docString != null && t.hasOwnProperty("docString") && (n.docString = t.docString), t.opsetImport && t.opsetImport.length) { n.opsetImport = []; for (var s = 0; s < t.opsetImport.length; ++s) n.opsetImport[s] = h.onnx.OperatorSetIdProto.toObject(t.opsetImport[s], r); } if (t.domain != null && t.hasOwnProperty("domain") && (n.domain = t.domain), t.attributeProto && t.attributeProto.length) { n.attributeProto = []; for (var s = 0; s < t.attributeProto.length; ++s) n.attributeProto[s] = h.onnx.AttributeProto.toObject(t.attributeProto[s], r); } return n; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, nt3.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.FunctionProto"; }, e; })(), i; })(); Uu3.exports = h; }); Y = O(() => { "use strict"; xn(); zo(); ot = rr(sr()); ze(); Ge = class { static arraysEqual(e, o) { if (e.length !== o.length) return false; for (let t = 0; t < e.length; t++) if (e[t] !== o[t]) return false; return true; } }, ni = class { static preprocessInputShapes(e, o) { let t = e.length === 1 ? [1, e[0]] : e, r = o.length === 1 ? [o[0], 1] : o; return [t, r]; } static postprocessOutputShape(e, o, t) { o === 1 && e.splice(e.length - 2, 1), t === 1 && e.pop(); } static calcMatMulShape(e, o) { return e[1] !== o[0] ? void 0 : [e[0], o[1]]; } }, $t = class i { static calcShape(e, o, t = false) { let r = e.length, n = o.length; if (r === 0) return o; if (n === 0) return e; let s = Math.max(e.length, o.length), a = new Array(s); if (t) { if (r < 2 || n < 2) return; let u = ni.calcMatMulShape([e[r - 2], e[r - 1]], [o[n - 2], o[n - 1]]); if (u === void 0) return; [a[s - 2], a[s - 1]] = u; } for (let u = t ? 3 : 1; u <= s; u++) { let l = r - u < 0 ? 1 : e[r - u], f = n - u < 0 ? 1 : o[n - u]; if (l !== f && l > 1 && f > 1) return; a[s - u] = Math.max(l, f); } return a; } static index(e, o) { let t = new Array(o.length); return i.fillIndex(e, o, t), t; } static fillIndex(e, o, t) { let r = e.length - o.length; for (let n = 0; n < o.length; n++) t[n] = e[r + n] % o[n]; } static calc(e, o, t, r, n) { let s = i.calcShape(e.dims, o.dims); if (s) { if (r && !B.areEqual(s, e.dims)) return; let a = B.size(s), u = r ? e : new bt(s, n || e.type); if (s.length === 0) u.set([], t(e.get([]), o.get([]))); else { let l = new Array(s.length), f = new Array(e.dims.length), p = new Array(o.dims.length), d = 0, y = 0, w = false, v = false; e.dims.length === 0 && (d = e.get([]), w = true), o.dims.length === 0 && (y = o.get([]), v = true); let S; for (let L = 0; L < a; L++) { S = L; for (let A2 = s.length - 1; A2 >= 0; A2--) l[A2] = S % s[A2], S = Math.floor(S / s[A2]); w || (i.fillIndex(l, e.dims, f), d = e.get(f)), v || (i.fillIndex(l, o.dims, p), y = o.get(p)), u.set(l, t(d, y)); } } return u; } } static isValidBroadcast(e, o) { let t = e.length, r = o.length; if (t > r) return false; for (let n = 1; n <= t; n++) if (e[t - n] !== 1 && e[t - n] !== o[r - n]) return false; return true; } static getBroadcastDims(e, o) { let t = e.length, r = []; for (let n = 0; n < t; n++) { let s = t - 1 - n, a = e[s] || 1; (o[o.length - 1 - n] || 1) > 1 && a === 1 && r.unshift(s); } return r; } }, _n = class { static getShapeOfGemmResult(e, o, t, r, n) { if (e.length !== 2 || t.length !== 2) throw new Error("shape need to be of size 2"); let s, a, u; o ? (s = e[1], a = e[0]) : (s = e[0], a = e[1]); let l = -1; if (r ? (u = t[0], l = 1) : (u = t[1], l = 0), t[l] !== a) throw new Error("dimension mismatch"); if (s <= 0 || u <= 0 || a <= 0) throw new Error("invalid shape specified"); if (n && !$t.isValidBroadcast(n, [s, u])) throw new Error("gemm: invalid bias shape for broadcast"); return [s, u, a]; } }, _t = class i { static tensorDataTypeFromProto(e) { switch (e) { case ot.onnx.TensorProto.DataType.INT8: return "int8"; case ot.onnx.TensorProto.DataType.UINT8: return "uint8"; case ot.onnx.TensorProto.DataType.BOOL: return "bool"; case ot.onnx.TensorProto.DataType.INT16: return "int16"; case ot.onnx.TensorProto.DataType.UINT16: return "uint16"; case ot.onnx.TensorProto.DataType.INT32: return "int32"; case ot.onnx.TensorProto.DataType.UINT32: return "uint32"; case ot.onnx.TensorProto.DataType.FLOAT: return "float32"; case ot.onnx.TensorProto.DataType.DOUBLE: return "float64"; case ot.onnx.TensorProto.DataType.STRING: return "string"; case ot.onnx.TensorProto.DataType.INT64: return "int32"; case ot.onnx.TensorProto.DataType.UINT64: return "uint32"; default: throw new Error(`unsupported data type: ${ot.onnx.TensorProto.DataType[e]}`); } } static tensorDataTypeStringToEnum(e) { switch (e) { case "int8": return ot.onnx.TensorProto.DataType.INT8; case "uint8": return ot.onnx.TensorProto.DataType.UINT8; case "bool": return ot.onnx.TensorProto.DataType.BOOL; case "int16": return ot.onnx.TensorProto.DataType.INT16; case "uint16": return ot.onnx.TensorProto.DataType.UINT16; case "int32": return ot.onnx.TensorProto.DataType.INT32; case "uint32": return ot.onnx.TensorProto.DataType.UINT32; case "float32": return ot.onnx.TensorProto.DataType.FLOAT; case "float64": return ot.onnx.TensorProto.DataType.DOUBLE; case "string": return ot.onnx.TensorProto.DataType.STRING; case "int64": return ot.onnx.TensorProto.DataType.INT64; case "uint64": return ot.onnx.TensorProto.DataType.UINT64; default: throw new Error(`unsupported data type: ${e}`); } } static tensorDimsFromProto(e) { return e.map((o) => me.isLong(o) ? o.toNumber() : o); } static tensorValueTypeFromProto(e) { return { tensorType: i.tensorDataTypeFromProto(e.elemType), shape: { dims: i.tensorDimsFromProto(e.shape.dim.map((o) => o.dimValue)) } }; } static tensorDimsFromORTFormat(e) { let o = []; for (let t = 0; t < e.dimsLength(); t++) o.push(Nt.longToNumber(e.dims(t))); return o; } static tensorAttributesFromORTFormat(e) { let o = []; for (let t = 0; t < e.attributesLength(); t++) o.push(e.attributes(t)); return o; } }, Nt = class { static longToNumber(e, o) { return me.isLong(e) ? e.toNumber() : e instanceof T.Long ? me.fromValue({ low: e.low, high: e.high, unsigned: o ?? false }).toNumber() : e; } static isLong(e) { return me.isLong(e) || e instanceof T.Long; } }, B = class i { static size(e) { return i.getSizeFromDimensionRange(e, 0, e.length); } static sizeFromDimension(e, o) { if (o < 0 || o > e.length) throw new Error(`invalid dimension of ${o} for sizeFromDimension as Tensor has ${e.length} dimensions.`); return i.getSizeFromDimensionRange(e, o, e.length); } static sizeToDimension(e, o) { if (o < 0 || o > e.length) throw new Error(`invalid dimension of ${o} for sizeToDimension as Tensor has ${e.length} dimensions.`); return i.getSizeFromDimensionRange(e, 0, o); } static getSizeFromDimensionRange(e, o, t) { let r = 1; for (let n = o; n < t; n++) { if (e[n] <= 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them."); r *= e[n]; } return r; } static computeStrides(e) { let o = e.length; if (o === 0) return []; if (o === 1) return [1]; let t = new Array(o); t[o - 1] = 1, t[o - 2] = e[o - 1]; for (let r = o - 3; r >= 0; --r) t[r] = t[r + 1] * e[r + 1]; return t; } static transpose(e) { return e.slice().reverse(); } static indicesToOffset(e, o, t) { t === void 0 && (t = e.length); let r = 0; for (let n = 0; n < t; ++n) r += o[n] * e[n]; return r; } static offsetToIndices(e, o) { let t = o.length; if (t === 0) return []; if (t === 1) return [e * o[0]]; let r = new Array(o.length); for (let n = 0; n < r.length - 1; ++n) r[n] = Math.floor(e / o[n]), e -= r[n] * o[n]; return r[r.length - 1] = e, r; } static normalizeAxis(e, o) { if (e < -o && e >= o) throw new Error("unsupported axis for this operation."); return e < 0 ? e + o : e; } static normalizeAxes(e, o) { return e.map((t) => this.normalizeAxis(t, o)); } static incrementIndex(e, o, t) { if (o.length === 0 || e.length === 0) throw new Error("Index incrementing unsupported for scalar Tensor"); if (t === void 0) t = o.length; else if (t <= 0 || t > o.length) throw new Error("Incorrect axis to increment on"); for (let r = t - 1; r >= 0 && (e[r]++, !(e[r] < o[r])); --r) e[r] = 0; } static calculateReshapedDims(e, o) { if (o.length === 0) { if (e.length === 0 || i.size(e) === 1) return []; throw new Error("cannot reshape to a scalar Tensor"); } let t = o.length, r = new Array(t), n = -1, s = 1; for (let u = 0; u < t; u++) { if (o[u] < -1) throw new Error("a dimension in shape hints cannot be less than -1"); if (o[u] === -1) { if (n !== -1) throw new Error("at most one dimension in shape hints can be -1"); n = u; } else { if (o[u] === 0) { if (u >= e.length) throw new Error("the dimension with value zero exceeds the dimension size of the input tensor"); r[u] = e[u]; } else r[u] = o[u]; s *= r[u]; } } let a = i.size(e); if (n !== -1) { if (a % s !== 0) throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${o}]`); r[n] = a / s; } else if (s !== a) throw new Error("reshapedDims and originalDims don't have matching sizes"); return r; } static sortBasedOnPerm(e, o) { return o ? o.map((t) => e[t]) : e.slice().reverse(); } static padShape(e, o) { let t = e.length; return e.map((r, n) => r + o[n] + o[n + t]); } static areEqual(e, o) { return e.length !== o.length ? false : e.every((t, r) => t === o[r]); } static validateDimsAndCalcSize(e) { if (e.length > 6) throw new TypeError("Only rank 0 to 6 is supported for tensor shape."); let o = 1; for (let t of e) { if (!Number.isInteger(t)) throw new TypeError(`Invalid shape: ${t} is not an integer`); if (t < 0 || t > 2147483647) throw new TypeError(`Invalid shape: length ${t} is not allowed`); o *= t; } return o; } static flattenShape(e, o) { o < 0 && (o += e.length); let t = e.reduce((s, a) => s * a, 1), r = e.slice(o).reduce((s, a) => s * a, 1); return [t / r, r]; } static squeezeShape(e, o) { let t = new Array(); o = i.normalizeAxes(o, e.length); for (let r = 0; r < e.length; r++) { let n = o.indexOf(r) >= 0; if (n && e[r] !== 1) throw new Error("squeeze an axis of size different than 1"); (o.length === 0 && e[r] > 1 || o.length > 0 && !n) && t.push(e[r]); } return t; } static unsqueezeShape(e, o) { let t = new Array(e.length + o.length); t.fill(0); for (let n = 0; n < o.length; n++) { let s = i.normalizeAxis(o[n], t.length); if (s >= t.length) throw new Error("'axes' has an out of range axis"); if (t[s] !== 0) throw new Error("'axes' has a duplicate axis"); t[s] = 1; } let r = 0; for (let n = 0; n < t.length; n++) t[n] === 0 && (t[n] = e[r++]); if (r !== e.length) throw new Error("the unsqueezed dimension could not be established"); return t; } }, $r = class i { static splitShape(e, o, t, r) { if (t.length === 0) { if (!r) throw new Error("need to know number of outputs when the 'split' attribute is not specified"); i.determineSplit(e[o], r, t); } let n = [], s = [0]; for (let a = 0; a < t.length; ++a) { a !== 0 && s.push(s[a - 1] + t[a - 1]); let u = e.slice(); u[o] = t[a], n.push(u); } return [n, s]; } static determineSplit(e, o, t) { if (e % o !== 0) throw new Error("cannot split tensor to equal sized parts"); for (let r = 0; r < o; ++r) t.push(e / o); } }, Me = class i { static adjustPoolAttributes(e, o, t, r, n, s) { if (!e && t.length !== o.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); if (e) for (let a = 0; a < o.length - 2; a++) a >= t.length ? t.push(o[a + 2]) : t[a] = o[a + 2]; for (let a = 0; a < t.length; a++) if (a < r.length) { if (r[a] < 0) throw new Error("strides should be greater than or equal to 1"); } else r.push(1); for (let a = 0; a < t.length; a++) if (a < n.length) { if (n[a] < 0) throw new Error("dilations should be greater than or equal to 1"); } else n.push(1); for (let a = 0; a < t.length * 2; a++) if (a < s.length) { if (s[a] < 0) throw new Error("pad should be greater than or equal to 1"); } else s.push(0); for (let a = 0; a < t.length; a++) { if (t[a] <= 0) throw new Error("kernel shapes need to be greater than 0"); if (s[a] >= t[a] || s[a + t.length] >= t[a]) throw new Error("pads should be smaller than kernel"); } } static adjustPadsBasedOnAutoPad(e, o, t, r, n, s) { if (s) { if (n.length !== 2 * (e.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); if (o.length !== e.length - 2) throw new Error("length of strides should be the length of data dimensions"); if (r.length !== e.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions"); for (let a = 0; a < e.length - 2; a++) i.adjustPadAndReturnShape(e[a + 2], o[a], t[a], r[a], n, a, a + e.length - 2, s); } } static computePoolOutputShape(e, o, t, r, n, s, a) { if (o.length <= 0) throw new Error("input shape must be of size greater than 0"); let u = [o[0], o[1]]; return i.computeShapeHelper(e, o, u, t, r, n, s, a), u; } static computeConvOutputShape(e, o, t, r, n, s, a) { if (e.length <= 0 || o.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); let u = [e[0], o[0]]; return i.computeShapeHelper(false, e, u, t, r, n, s, a), u; } static computeShapeHelper(e, o, t, r, n, s, a, u) { if (e) for (let l = 0; l < o.length - 2; l++) t.push(1); else for (let l = 0; l < o.length - 2; l++) t.push(i.adjustPadAndReturnShape(o[l + 2], r[l], n[l], s[l], a, l, l + o.length - 2, u)); } static adjustPadAndReturnShape(e, o, t, r, n, s, a, u) { let l = t * (r - 1) + 1; if (u && u !== "NOTSET") switch (u) { case "VALID": return n[s] = 0, n[a] = 0, Math.floor((e - l) / o + 1); case "SAME_LOWER": case "SAME_UPPER": if (t !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); { let p = ((e + o - 1) / o - 1) * o + r - e; return n[s] = Math.floor(u === "SAME_LOWER" ? (p + 1) / 2 : p / 2), n[a] = p - n[s], Math.floor((e + p - r) / o + 1); } default: throw new Error("Unsupported AutoPad type"); } else return Math.floor((e + n[s] + n[a] - l) / o + 1); } }, Ue = -34028234663852886e22, Ve = 34028234663852886e22; }); ze = O(() => { "use strict"; Wu = rr(ks()); zo(); Pr(); H = rr(sr()); Y(); oi = F.experimental.fbs, bt = class i { constructor(e, o, t, r, n, s = Wu.Guid.create()) { this.dims = e; this.type = o; this.dataProvider = t; this.asyncDataProvider = r; this.cache = n; this.dataId = s; this.size = B.validateDimsAndCalcSize(e); let a = this.size, u = t === void 0 && r === void 0 && n === void 0; if (n !== void 0 && n.length !== a) throw new RangeError("Input dims doesn't match data length."); if (o === "string") { if (n !== void 0 && (!Array.isArray(n) || !n.every((l) => typeof l == "string"))) throw new TypeError("cache should be a string array"); u && (this.cache = new Array(a)); } else { if (n !== void 0) { let l = Hu(o); if (!(n instanceof l)) throw new TypeError(`cache should be type ${l.name}`); } if (u) { let l = new ArrayBuffer(a * ph(o)); this.cache = dh(l, o); } } } get data() { if (this.cache === void 0) { let e = this.dataProvider(this.dataId); if (e.length !== this.size) throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor."); this.cache = e; } return this.cache; } get stringData() { if (this.type !== "string") throw new TypeError("data type is not string"); return this.data; } get integerData() { switch (this.type) { case "uint8": case "int8": case "uint16": case "int16": case "int32": case "uint32": case "bool": return this.data; default: throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)"); } } get floatData() { switch (this.type) { case "float32": case "float64": return this.data; default: throw new TypeError("data type is not float (float32, float64)"); } } get numberData() { if (this.type !== "string") return this.data; throw new TypeError("type cannot be non-number (string)"); } get(e) { return this.data[B.indicesToOffset(e, this.strides)]; } set(e, o) { this.data[B.indicesToOffset(e, this.strides)] = o; } async getData() { return this.cache === void 0 && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache; } get strides() { return this._strides || (this._strides = B.computeStrides(this.dims)), this._strides; } static fromProto(e) { if (!e) throw new Error("cannot construct Value from an empty tensor"); let o = _t.tensorDataTypeFromProto(e.dataType), t = _t.tensorDimsFromProto(e.dims), r = new i(t, o); if (o === "string") e.stringData.forEach((n, s) => { r.data[s] = kr(n); }); else if (e.rawData && typeof e.rawData.byteLength == "number" && e.rawData.byteLength > 0) { let n = r.data, s = new DataView(e.rawData.buffer, e.rawData.byteOffset, e.rawData.byteLength), a = Vu(e.dataType), u = e.rawData.byteLength / a; if (e.rawData.byteLength % a !== 0) throw new Error("invalid buffer length"); if (n.length !== u) throw new Error("buffer length mismatch"); for (let l = 0; l < u; l++) { let f = zu(s, e.dataType, l * a); n[l] = f; } } else { let n; switch (e.dataType) { case H.onnx.TensorProto.DataType.FLOAT: n = e.floatData; break; case H.onnx.TensorProto.DataType.INT32: case H.onnx.TensorProto.DataType.INT16: case H.onnx.TensorProto.DataType.UINT16: case H.onnx.TensorProto.DataType.INT8: case H.onnx.TensorProto.DataType.UINT8: case H.onnx.TensorProto.DataType.BOOL: n = e.int32Data; break; case H.onnx.TensorProto.DataType.INT64: n = e.int64Data; break; case H.onnx.TensorProto.DataType.DOUBLE: n = e.doubleData; break; case H.onnx.TensorProto.DataType.UINT32: case H.onnx.TensorProto.DataType.UINT64: n = e.uint64Data; break; default: throw new Error("unspecific error"); } if (n == null) throw new Error("failed to populate data from a tensorproto value"); let s = r.data; if (s.length !== n.length) throw new Error("array length mismatch"); for (let a = 0; a < n.length; a++) { let u = n[a]; me.isLong(u) ? s[a] = ii(u, e.dataType) : s[a] = u; } } return r; } static fromData(e, o, t) { return new i(o, t, void 0, void 0, e); } static fromOrtTensor(e) { if (!e) throw new Error("cannot construct Value from an empty tensor"); let o = _t.tensorDimsFromORTFormat(e), t = _t.tensorDataTypeFromProto(e.dataType()), r = new i(o, t); if (t === "string") for (let n = 0; n < e.stringDataLength(); n++) r.data[n] = e.stringData(n); else if (e.rawDataArray() && typeof e.rawDataLength() == "number" && e.rawDataLength() > 0) { let n = r.data, s = new DataView(e.rawDataArray().buffer, e.rawDataArray().byteOffset, e.rawDataLength()), a = Vu(e.dataType()), u = e.rawDataLength() / a; if (e.rawDataLength() % a !== 0) throw new Error("invalid buffer length"); if (n.length !== u) throw new Error("buffer length mismatch"); for (let l = 0; l < u; l++) { let f = zu(s, e.dataType(), l * a); n[l] = f; } } return r; } }; }); st = O(() => { "use strict"; hh = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, mh = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" }; }); j = O(() => { "use strict"; }); ue = O(() => { "use strict"; Y(); }); We = O(() => { "use strict"; ue(); }); Zu = O(() => { "use strict"; st(); j(); ue(); We(); Ju = { name: "pack", inputNames: ["A"], inputTypes: [1] }, gh = (i, e) => { let o = G(i.session.backend.glContext.version), t = e.dims, r = t.length, n = e.dims.length, s = kt(n), a = cr("rc", n), u = Th(n, a, t[t.length - 2], t[t.length - 1]), l; r === 0 ? l = [1, 1] : r === 1 ? l = [t[0], 1] : l = [t[n - 1], t[n - 2]]; let f = yh(n, l, a), p = xh(t, a), d = ` void main() { ${s} rc = getOutputCoords(); if(${f}) { ${o.output} = vec4(0); } else { ${u} ${o.output} = vec4(${p}); } } `; return { ...Ju, hasMain: true, output: { dims: e.dims, type: e.type, textureType: 2 }, shaderSource: d }; }, Yu = (i, e) => ({ ...Ju, get: () => gh(i, e) }); }); el = O(() => { "use strict"; Y(); st(); j(); We(); wh = (i) => ({ name: "Reshape (packed)", inputTypes: [2], inputNames: ["A"], cacheHint: `${i}` }), vh = (i, e, o, t) => { let r = e.dims, n = t, s = ""; for (let l = 0; l < 4; l++) { let f = ""; switch (l) { case 0: f = "outputCoords = rc;"; break; case 1: f = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);"; break; case 2: f = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);"; break; case 3: f = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);"; break; default: throw new Error(); } s += ` ${f} ${l > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""} int flattenedIndex = getFlattenedIndex(outputCoords); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); result[${l}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); ${l > 0 ? "}" : ""} `; } let a = G(i.session.backend.glContext.version), u = ` ${Ih(r)} ${_h(n)} ${le()} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.0); ivec3 outputCoords; int rows = ${n[2]}; int cols = ${n[1]}; ${s} ${a.output} = result; } `; return { ...o, output: { dims: n, type: e.type, textureType: 2 }, shaderSource: u, hasMain: true }; }, Qu = (i, e, o) => { let t = wh(o); return { ...t, get: () => vh(i, e, t, o) }; }; }); rl = O(() => { "use strict"; st(); j(); ui = (i, e) => { let o = e.shape, t = G(i.session.backend.glContext.version), r = ` const float FLOAT_MAX = 1.70141184e38; const float FLOAT_MIN = 1.17549435e-38; bool isNaN(float val) { return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; } highp vec4 encodeAsUint8(highp float v) { if (isNaN(v)) { return vec4(255, 255, 255, 255); } highp float av = abs(v); if(av < FLOAT_MIN) { return vec4(0.0, 0.0, 0.0, 0.0); } else if(v > FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; } else if(v < -FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; } highp vec4 c = vec4(0,0,0,0); highp float e = floor(log2(av)); highp float m = exp2(fract(log2(av))) - 1.0; c[2] = floor(128.0 * m); m -= c[2] / 128.0; c[1] = floor(32768.0 * m); m -= c[1] / 32768.0; c[0] = floor(8388608.0 * m); highp float ebias = e + 127.0; c[3] = floor(ebias / 2.0); ebias -= c[3] * 2.0; c[2] += floor(ebias) * 128.0; c[3] += 128.0 * step(0.0, -v); return c / 255.0; } void main() { float value = ${t.texture2D}(X,TexCoords).r; ${t.output} = encodeAsUint8(value); }`, n = { name: "Uint8Encode", inputTypes: [0], inputNames: ["X"], output: { dims: o, type: e.tensor.type, textureType: 3 }, shaderSource: r, hasMain: true }; return i.executeProgram(n, [e.tensor]); }; }); il = O(() => { "use strict"; st(); j(); ue(); We(); nl = { name: "unpack", inputNames: ["A"], inputTypes: [2] }, Oh = (i, e) => { let o = e.dims.length, t = cr("rc", o), r = t.slice(-2), n = kt(o), s = le(), u = e.dims.length === 0 ? "" : Sh(o, t), l = o <= 1 ? "rc" : `vec2(${r.join(",")})`, f = G(i.session.backend.glContext.version), p = ` ${s} void main() { ${n} rc = getOutputCoords(); // Sample the texture with the coords to get the rgba channel value. vec4 packedInput = getA(${u}); ${f.output} = vec4(getChannel(packedInput, ${l}), 0, 0, 0); } `; return { ...nl, hasMain: true, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: p }; }, ol = (i, e) => ({ ...nl, get: () => Oh(i, e) }); }); Fr = O(() => { "use strict"; Mt(); Sn = class { constructor(e, o = 1) { if (o === 1) this.internalFormat = e.R32F, this.format = e.RED, this.textureType = e.FLOAT, this.channelSize = o; else if (o === 4) this.internalFormat = e.RGBA32F, this.format = e.RGBA, this.textureType = e.FLOAT, this.channelSize = o; else throw new Error(`Invalid number of channels: ${o}`); } encode(e, o) { let t, r; return e.constructor !== Float32Array && (tt.warning("Encoder", "data was not of type Float32; creating new Float32Array"), r = new Float32Array(e)), o * this.channelSize > e.length ? (tt.warning("Encoder", "Source data too small. Allocating larger array"), r = e, t = this.allocate(o * this.channelSize), r.forEach((n, s) => t[s] = n)) : (r = e, t = r), t; } allocate(e) { return new Float32Array(e * 4); } decode(e, o) { return this.channelSize === 1 ? e.filter((r, n) => n % 4 === 0).subarray(0, o) : e.subarray(0, o); } }, Br = class { constructor(e, o = 1, t) { if (o !== 1 && o !== 4) throw new Error(`Invalid number of channels: ${o}`); this.internalFormat = e.RGBA, this.format = e.RGBA, this.channelSize = o, this.textureType = t || e.FLOAT; } encode(e, o) { let t = e; return this.channelSize === 1 && (tt.verbose("Encoder", "Exploding into a larger array"), t = this.allocate(o), e.forEach((r, n) => t[n * 4] = r)), t; } allocate(e) { return new Float32Array(e * 4); } decode(e, o) { return this.channelSize === 1 ? e.filter((r, n) => n % 4 === 0).subarray(0, o) : e.subarray(0, o); } }, An = class { constructor(e, o = 1) { this.channelSize = 4; if (o === 1) this.internalFormat = e.ALPHA, this.format = e.ALPHA, this.textureType = e.UNSIGNED_BYTE, this.channelSize = o; else if (o === 4) this.internalFormat = e.RGBA, this.format = e.RGBA, this.textureType = e.UNSIGNED_BYTE, this.channelSize = o; else throw new Error(`Invalid number of channels: ${o}`); } encode(e, o) { return new Uint8Array(e.buffer, e.byteOffset, e.byteLength); } allocate(e) { return new Uint8Array(e * this.channelSize); } decode(e, o) { if (e instanceof Uint8Array) return e.subarray(0, o); throw new Error(`Invalid array type: ${e.constructor}`); } }; }); sl = O(() => { "use strict"; Y(); j(); Cr = (i, e, o) => { let t = o === 0 || o === 1 ? 1 : 4, r = o === 2, n = o === 1 || o === 2, s = o === 4 ? e.length - 1 : void 0, a = o === 4 ? e.map((u, l) => l === e.length - 1 ? u * 4 : u) : void 0; return li(i, e, t, a, { isPacked: r, reverseWH: n, breakAxis: s }); }, al = (i, e, o) => { let t = Cr(i, e, o); return [t.width, t.height]; }, li = (i, e, o = 1, t, r) => { let n = !!(r && r.isPacked), [s, a] = i.computeTextureWH(n && t || e, r), u = e.length, l = e.slice(0); if (u === 0 && (l = [1]), o === 1) t = e; else if (n) { if (o !== 4) throw new Error("a packed texture must be 4-channel"); t = e, u > 0 && (l[u - 1] = Math.ceil(l[u - 1] / 2)), u > 1 && (l[u - 2] = Math.ceil(l[u - 2] / 2)); } else if (!t) throw new Error("Unpacked shape is needed when using channels > 1"); return { width: s, height: a, channels: o, isPacked: n, shape: l, strides: B.computeStrides(l), unpackedShape: t, reversedWH: r && r.reverseWH }; }; }); ll = O(() => { "use strict"; Mt(); ze(); Y(); Zu(); el(); rl(); il(); Fr(); sl(); j(); Ph = (i, e) => { let o = e.map((r) => `${r.unpackedShape.join(",")};${r.width}x${r.height}`).join("_"), t = i.name; return i.cacheHint && (t += "[" + i.cacheHint + "]"), t += ":" + o, t; }, Pn = class { constructor(e) { this.session = e; this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } calculateTextureWidthAndHeight(e, o) { return al(this.session.layoutStrategy, e, o); } executeProgram(e, o) { if (o.length < e.inputNames.length) throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`); if (e.inputNames.length !== e.inputTypes.length) throw new Error("input names size does not match input types"); let t = []; for (let l = 0; l < e.inputNames.length; ++l) t[l] = this.getOrCreateTextureData(o[l], e.inputTypes[l]); let r = Ph(e, t), n = this.session.programManager.getArtifact(r), s = n ? n.programInfo : typeof e.get == "function" ? e.get() : e, a = Cr(this.session.layoutStrategy, s.output.dims, s.output.textureType), u = this.createTextureData(a, s.output.type); return n || (n = this.session.programManager.build(s, t, u), this.session.programManager.setArtifact(r, n)), this.runProgram(n, t, u), u; } run(e, o) { return this.executeProgram(e, o).tensor; } runProgram(e, o, t) { for (let r = 0; r < o.length; ++r) if (!!o[r].isPacked != (e.programInfo.inputTypes[r] === 2)) throw new Error(`input[${r}] property packed inconsistent`); if (!!t.isPacked != (e.programInfo.output.textureType === 2)) throw new Error("output property packed inconsistent"); this.session.programManager.run(e, o, t); } getOrCreateTextureData(e, o) { let t = this.getTextureData(e.dataId, o === 2); if (!t && (t = this.getTextureData(e.dataId, o !== 2), t)) return o === 2 ? this.pack(t) : this.unpack(t); if (!t) { let r = Cr(this.session.layoutStrategy, e.dims, o); if (o === 4) { let a = e.dims; if (a.length === 4) { let u = [a[0], Math.ceil(a[1] * a[2] * a[3] / 4)], l = Cr(this.session.layoutStrategy, u, o), f = e.numberData; if (a[1] * a[2] * a[3] % 4 !== 0) { let p = a[0], d = a[1] * a[2] * a[3], y = Math.ceil(d * 1 / 4) * 4, w = p * y; f = new Float32Array(w); for (let v = 0; v < p; ++v) { let S = v * d, L = v * y + v % 1 * d; f.set(e.numberData.subarray(S, S + d), L); } } return this.createTextureData(l, e.type, f, e, 1); } } if (o === 2) { let n = li(this.session.layoutStrategy, e.dims, 1, [], { reverseWH: true }), s = this.createTextureData(n, e.type, e.numberData, e, 1); t = this.pack(s); } else t = this.createTextureData(r, e.type, e.numberData, e, 1); } return t; } createTextureDataFromLayoutBindTensor(e, o, t, r) { return this.createTextureData(e, o, t, r, 1); } createTextureData(e, o, t, r, n) { tt.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(e)}]`); let s = this.session.textureManager.createTextureFromLayout(o, e, t, n); return this.createTextureDataFromTexture(e, o, s, r); } reshapeUnpacked(e, o) { let t = this.getOrCreateTextureData(e, 0), r = { channels: t.channels, height: t.height, width: t.width, shape: o.length !== 0 ? o : [1], strides: B.computeStrides(o), unpackedShape: o }; return this.createTextureDataFromTexture(r, e.type, t.texture).tensor; } reshapePacked(e, o) { let t = this.getOrCreateTextureData(e, 2); if (tl(e.dims, o)) { let l = { channels: t.channels, height: t.height, width: t.width, shape: o.length !== 0 ? o : [1], strides: B.computeStrides(o), unpackedShape: o, isPacked: true }; return this.createTextureDataFromTexture(l, e.type, t.texture).tensor; } let r = si(e.dims), n = si(o), s = this.reshapePacked(e, r), a = this.run(Qu(this, s, n), [s]); return this.reshapePacked(a, o); } cast(e, o) { let t = this.getOrCreateTextureData(e, 0); return this.createTextureDataFromTexture(t, o, t.texture).tensor; } createTextureDataFromTexture(e, o, t, r, n) { let s = { ...e, tensor: r || new bt(e.unpackedShape, o, (a) => this.readTexture(s), async (a) => this.readTextureAsync(s), void 0, n), texture: t }; return this.setTextureData(s.tensor.dataId, s, e.isPacked), s; } getTextureData(e, o = false) { return this.session.isInitializer(e) ? this.session.getTextureData(e, o) : o ? this.packedTextureDataCache.get(e) : this.unpackedTextureDataCache.get(e); } setTextureData(e, o, t = false) { this.session.isInitializer(e) ? this.session.setTextureData(e, o, t) : (t ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(e, o); } isTextureLayoutCached(e, o = false) { return !!this.getTextureData(e.dataId, o); } dispose() { this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((e) => this.session.textureManager.releaseTexture(e)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((e) => this.session.textureManager.releaseTexture(e)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } readTexture(e) { return e.isPacked ? this.readTexture(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat(ui(this, e)); } async readTextureAsync(e) { return e.isPacked ? this.readTextureAsync(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat(ui(this, e)); } pack(e) { return this.executeProgram(Yu(this, e.tensor), [e.tensor]); } unpack(e) { return this.executeProgram(ol(this, e.tensor), [e.tensor]); } }; }); vt = O(() => { "use strict"; fi = class { constructor(e) { Object.assign(this, e); } get cacheKey() { return this.key || (this.key = Object.getOwnPropertyNames(this).sort().map((e) => `${this[e]}`).join(";")), this.key; } }, W = (i) => new fi(i); }); dl = O(() => { "use strict"; vt(); st(); j(); fl = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [0, 0, 0, 0, 0] }, cl = (i, e, o) => (Dh(e), [i.run({ ...fl, cacheHint: o.cacheKey, get: () => Eh(i, e, o) }, e)]), pl = (i) => { let e = i.attributes.getFloat("epsilon", 1e-5), o = i.attributes.getFloat("momentum", 0.9), t = i.attributes.getInt("spatial", 1); return W({ epsilon: e, momentum: o, spatial: t }); }, Eh = (i, e, o) => { let t = G(i.session.backend.glContext.version), r = e[0].dims.length, [n, s] = i.calculateTextureWidthAndHeight(e[1].dims, 0), a = ` float process(int[${r}] indices) { vec2 position = offsetToCoords(indices[1], ${n}, ${s}); float scale = getColorAsFloat(${t.texture2D}(Scale, position)); float mean = getColorAsFloat(${t.texture2D}(Mean, position)); float variance = getColorAsFloat(${t.texture2D}(Variance, position)); float b = getColorAsFloat(${t.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${o.epsilon})) ) + b; }`; return { ...fl, output: { dims: e[0].dims, type: e[0].type, textureType: 0 }, shaderSource: a }; }, Dh = (i) => { if (!i || i.length !== 5) throw new Error("BatchNormalization requires 5 inputs."); let e = i[0], o = i[1], t = i[2], r = i[3], n = i[4]; if (e.dims.length < 3 || o.dims.length !== 1 || t.dims.length !== 1 || r.dims.length !== 1 || n.dims.length !== 1) throw new Error("invalid input shape."); if (o.dims[0] !== e.dims[1] || t.dims[0] !== e.dims[1] || r.dims[0] !== e.dims[1] || n.dims[0] !== e.dims[1]) throw new Error("invalid input shape."); if (e.type !== "float32" && e.type !== "float64" || o.type !== "float32" && o.type !== "float64" || t.type !== "float32" && t.type !== "float64" || r.type !== "float32" && r.type !== "float64" || n.type !== "float32" && n.type !== "float64") throw new Error("invalid input tensor types."); }; }); be = O(() => { "use strict"; En = class { constructor(e, o, t, r) { this.glContext = e; this.programInfo = o; this.inputTextureLayouts = t; this.outputTextureLayout = r; } }, Wt = class { constructor(e) { this.context = e; } }, k = class { constructor(e, o) { this.routineBody = e; this.dependencies = o; } }, Nr = class { constructor(e, o, t) { this.name = e; t ? this.dependencies = t : this.dependencies = [], o && (this.routineBody = o); } addDependency(e) { e && this.dependencies.push(e); } }, Dn = class { static returnOrderedNodes(e) { if (!e || e.length === 0) return []; if (e.length === 1) return e; let o = /* @__PURE__ */ new Set(), t = /* @__PURE__ */ new Set(), r = new Array(); return this.createOrderedNodes(e, o, t, r), r; } static createOrderedNodes(e, o, t, r) { for (let n = 0; n < e.length; ++n) this.dfsTraverse(e[n], o, t, r); } static dfsTraverse(e, o, t, r) { if (!e || t.has(e.name)) return; if (o.has(e.name)) throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader."); o.add(e.name); let n = e.dependencies; if (n && n.length > 0) for (let s = 0; s < n.length; ++s) this.dfsTraverse(n[s], o, t, r); r.push(e), t.add(e.name), o.delete(e.name); } }; }); Sl = O(() => { "use strict"; Y(); be(); st(); j(); Ht = (i, e, o, t = e[0].type, r) => { let n = i.session.pack ? 2 : 0; return { name: o.name, inputNames: ["A", "B"], inputTypes: [n, n], cacheHint: r, get: () => Hh(i, e, o, t) }; }, Hh = (i, e, o, t = e[0].type) => { let r = i.session.pack ? 2 : 0, n = !B.areEqual(e[0].dims, e[1].dims), s = e[0].dims, a = i.session.pack; if (n) { let f = $t.calcShape(e[0].dims, e[1].dims, false); if (!f) throw new Error("Can't perform binary op on the given tensors"); s = f; let p = s.length, d = e[0].dims.length !== 0 ? e[0].dims.length : 1, y = e[1].dims.length !== 0 ? e[1].dims.length : 1, w = e[0].dims.length !== 0 ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", v = e[1].dims.length !== 0 ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", S = G(i.session.backend.glContext.version), L = a ? ` ${o.body} void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = ${o.name}(a, b); ${S.output} = result; }` : ` ${o.body} float process(int indices[${p}]) { int aindices[${d}]; int bindices[${y}]; ${w} ${v} return ${o.name}(_A(aindices), _B(bindices)); }`; return { name: o.name, inputNames: ["A", "B"], inputTypes: [r, r], output: { dims: s, type: t, textureType: r }, shaderSource: L, hasMain: a }; } let u = G(i.session.backend.glContext.version), l = ` ${o.body} void main() { vec4 v1 = ${u.texture2D}(A, TexCoords); vec4 v2 = ${u.texture2D}(B, TexCoords); vec4 result = ${o.name}(v1, v2); ${u.output} = result; } `; return { name: o.name, inputNames: ["A", "B"], inputTypes: [r, r], output: { dims: e[0].dims, type: t, textureType: r }, shaderSource: l, hasMain: true }; }, hl = (i, e) => [i.run(Ht(i, e, $h()), e)], ml = (i, e) => [i.run(Ht(i, e, Gh(), "bool"), e)], bl = (i, e) => [i.run(Ht(i, e, kh()), e)], gl = (i, e) => [i.run(Ht(i, e, Ch(), "bool"), e)], yl = (i, e) => [i.run(Ht(i, e, Nh(), "bool"), e)], xl = (i, e) => [i.run(Ht(i, e, Rh(), "bool"), e)], Tl = (i, e) => [i.run(Ht(i, e, Bh()), e)], wl = (i, e) => [i.run(Ht(i, e, Mh(), "bool"), e)], vl = (i, e) => [i.run(Ht(i, e, Vh()), e)], Il = (i, e) => [i.run(Ht(i, e, zh()), e)], _l = (i, e) => [i.run(Ht(i, e, Fh()), e)], Ol = (i, e) => [i.run(Ht(i, e, Uh(), "bool"), e)]; }); El = O(() => { "use strict"; Y(); Al = (i, e, o) => (jh(e), [i.cast(e[0], o)]), Pl = (i) => _t.tensorDataTypeFromProto(i.attributes.getInt("to")), jh = (i) => { if (!i || i.length !== 1) throw new Error("Cast requires 1 input."); if (i[0].type === "string") throw new Error("Invalid input type."); }; }); Ll = O(() => { "use strict"; st(); j(); ue(); We(); Xh = (i, e) => ({ name: "Concat (packed)", inputNames: Array.from({ length: i }, (o, t) => `X${t}`), inputTypes: Array(i).fill(2), cacheHint: e }), Kh = (i, e, o, t) => { let r = o[0].dims.slice(); if (t >= r.length || t < -1 * r.length) throw new Error("axis specified for concat doesn't match input dimensionality"); t < 0 && (t = r.length + t); let n = r.slice(0); for (let V3 = 1; V3 < o.length; V3++) { let ut2 = o[V3].dims.slice(); for (let xt3 = 0; xt3 < r.length; xt3++) if (xt3 === t) n[t] += ut2[xt3]; else if (r[xt3] !== ut2[xt3]) throw new Error("non concat dimensions must match"); } let s = n.length, a = cr("coords", s), u = kt(s), l = le(), f = o.map((V3) => V3.dims), p = ee(s), d = new Array(f.length - 1); d[0] = f[0][t]; for (let V3 = 1; V3 < d.length; V3++) d[V3] = d[V3 - 1] + f[V3][t]; let y = p[t], w = p.slice(-2), v = p.join(), S = `if (${y} < ${d[0]}) { return getChannel( getX0(${v}), vec2(${w.join()})); }`; for (let V3 = 1; V3 < d.length; V3++) { let ut2 = d[V3 - 1]; S += ` if (${y} < ${d[V3]} && ${y} >= ${d[V3 - 1]}) { return getChannel( getX${V3}(${Ln(p, y, ut2)}), vec2(${Ln(w, y, ut2)})); }`; } let L = d.length, A2 = d[d.length - 1]; S += ` return getChannel( getX${L}(${Ln(p, y, A2)}), vec2(${Ln(w, y, A2)}));`; let P2 = G(i.session.backend.glContext.version), M3 = ` ${l} float getValue(${p.map((V3) => "int " + V3)}) { ${S} } void main() { ${u} coords = getOutputCoords(); int lastDim = coords.${p[s - 1]}; coords.${p[s - 1]} = coords.${p[s - 2]}; coords.${p[s - 2]} = lastDim; vec4 result = vec4(getValue(${a}), 0., 0., 0.); ${a[s - 1]} = ${a[s - 1]} + 1; if (${a[s - 1]} < ${n[s - 1]}) { result.g = getValue(${a}); } ${a[s - 2]} = ${a[s - 2]} + 1; if (${a[s - 2]} < ${n[s - 2]}) { result.a = getValue(${a}); } ${a[s - 1]} = ${a[s - 1]} - 1; if (${a[s - 2]} < ${n[s - 2]} && ${a[s - 1]} < ${n[s - 1]}) { result.b = getValue(${a}); } ${P2.output} = result; } `; return { ...e, output: { dims: n, type: o[0].type, textureType: 2 }, shaderSource: M3, hasMain: true }; }, Dl = (i, e, o) => { let t = Xh(e.length, o.cacheKey); return { ...t, get: () => Kh(i, t, e, o.axis) }; }, Ln = (i, e, o) => { let t = i.indexOf(e); return i.map((n, s) => s === t ? `${n} - ${o}` : n).join(); }; }); Fl = O(() => { "use strict"; vt(); j(); Ll(); $l = (i, e, o) => (rm(e), i.session.pack && e[0].dims.length > 1 ? [i.run(Dl(i, e, o), e)] : [i.run(Zh(i, e, o), e)]), Jh = (i, e) => ({ name: "Concat", inputNames: Array.from({ length: i }, (o, t) => `X${t}`), inputTypes: Array(i).fill(0), cacheHint: e }), Yh = (i, e, o, t) => { let r = o[0].dims.slice(); if (t >= r.length || t < -1 * r.length) throw new Error("axis specified for concat doesn't match input dimensionality"); t < 0 && (t = r.length + t); let n = r.slice(0); for (let y = 1; y < o.length; y++) { let w = o[y].dims.slice(); for (let v = 0; v < r.length; v++) if (v === t) n[t] += w[v]; else if (r[v] !== w[v]) throw new Error("non concat dimensions must match"); } let s = n.length, a = new Array(o.length), u = 0; for (let y = 0; y < a.length; ++y) u += o[y].dims[t], a[y] = u; let l = ""; o.length < 5 ? l = kl(a) : l = Qh(a); let f = tm(o.length, s), p = em(a), d = ` ${f} ${p} ${l} float process(int indices[${s}]) { int textureIndex = getTextureWhereDataResides (indices[${t}]); if(textureIndex != 0) { indices[${t}] = indices[${t}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1))); } return fetchDataFromCorrectTexture(textureIndex, indices); }`; return { ...e, output: { dims: n, type: o[0].type, textureType: 0 }, shaderSource: d }; }, Zh = (i, e, o) => { let t = Jh(e.length, o.cacheKey); return { ...t, get: () => Yh(i, t, e, o.axis) }; }, kl = (i) => `int getTextureWhereDataResides(int index) { ${i.map((o, t) => `if(index<${o}) {return ${t};} `).join("")} }`, Qh = (i) => kl(i), tm = (i, e) => { let o = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`]; for (let t = 0; t < i; ++t) t === 0 ? o.push(` if (textureIndex == ${t}) { return _X${t}(indices); }`) : t === i - 1 ? o.push(` else { return _X${t}(indices); }`) : o.push(` else if (textureIndex == ${t}) { return _X${t}(indices); }`); return o.push(" }"), o.join(` `); }, em = (i) => { let e = ["int getSizeInConcatAxisValueFromIndex(int index) {"]; for (let o = 0; o < i.length; ++o) o === 0 ? e.push(` if (index == ${o}) { return ${i[o]}; }`) : o === i.length - 1 ? e.push(` else { return ${i[o]}; }`) : e.push(` else if (index == ${o}) { return ${i[o]}; }`); return e.push(" }"), e.join(` `); }, Bl = (i) => W({ axis: i.attributes.getInt("axis") }), rm = (i) => { if (!i || i.length < 1) throw new Error("too few inputs"); let e = i[0].type, o = i[0].dims.length; if (e === "string") throw new Error("string tensor is not supported yet"); for (let t of i) { if (t.type !== e) throw new Error("input tensors should be one type"); if (t.dims.length !== o) throw new Error("input tensors should have the same shape"); } }; }); bi = O(() => { "use strict"; vt(); Y(); be(); st(); j(); wm = (i, e, o, t) => { let r = i.session.pack ? 2 : 0, n = G(i.session.backend.glContext.version); return { ...e, output: { dims: o.dims, type: o.type, textureType: r }, shaderSource: ` ${t.body} void main() { vec4 v = ${n.texture2D}(A, TexCoords); v = ${t.name}_(v); ${n.output} = v; } `, hasMain: true }; }, dt = (i, e, o, t) => { let r = i.session.pack ? 2 : 0, n = { name: o.name, inputTypes: [r], inputNames: ["A"], cacheHint: t }; return { ...n, get: () => wm(i, n, e, o) }; }, Cl = (i, e) => [i.run(dt(i, e[0], nm()), e)], Nl = (i, e) => [i.run(dt(i, e[0], om()), e)], Rl = (i, e) => [i.run(dt(i, e[0], im()), e)], Gl = (i, e) => [i.run(dt(i, e[0], am()), e)], hi = (i, e, o) => [i.run(dt(i, e[0], ci(o.min, o.max), o.cacheKey), e)], Ml = (i) => W({ min: i.attributes.getFloat("min", Ue), max: i.attributes.getFloat("max", Ve) }), Ul = (i, e) => { let o = vm(i, e); return hi(i, [e[0]], o); }, vm = (i, e) => { if (e.length >= 3 && (!i.session.isInitializer(e[1].dataId) || !i.session.isInitializer(e[2].dataId))) throw new Error("dynamic clip attributes are not allowed"); let o = e.length >= 3 ? e[1].numberData[0] : Ue, t = e.length >= 3 ? e[2].numberData[0] : Ve; return W({ min: o, max: t }); }, Vl = (i, e) => [i.run(dt(i, e[0], sm()), e)], zl = (i, e) => [i.run(dt(i, e[0], um()), e)], Wl = (i, e, o) => [i.run(dt(i, e[0], lm(o.alpha), o.cacheKey), e)], Hl = (i) => W({ alpha: i.attributes.getFloat("alpha", 1) }), ql = (i, e) => [i.run(dt(i, e[0], fm()), e)], jl = (i, e) => [i.run(dt(i, e[0], cm()), e)], mi = (i, e) => [i.run(dt(i, e[0], pm()), e)], Xl = (i, e, o) => [i.run(dt(i, e[0], dm(o.alpha), o.cacheKey), e)], Kl = (i) => W({ alpha: i.attributes.getFloat("alpha", 0.01) }), Jl = (i, e) => [i.run(dt(i, e[0], hm()), e)], Yl = (i, e) => [i.run(dt(i, e[0], mm()), e)], Zl = (i, e) => [i.run(dt(i, e[0], bm()), e)], Ql = (i, e) => [i.run(dt(i, e[0], pi()), e)], tf = (i, e) => [i.run(dt(i, e[0], di()), e)], ef = (i, e) => [i.run(dt(i, e[0], gm()), e)], rf = (i, e) => [i.run(dt(i, e[0], ym()), e)], nf = (i, e) => [i.run(dt(i, e[0], xm()), e)], of = (i, e) => [i.run(dt(i, e[0], Tm()), e)]; }); He = O(() => { "use strict"; Y(); bi(); pr = (i) => { let e = i.getString("activation", ""); if (e === "Clip") { let [o, t] = i.getFloats("activation_params", [Ue, Ve]); return { activation: e, clipMax: t, clipMin: o, activationCacheKey: `${e}:${o},${t}` }; } return { activation: e, activationCacheKey: e }; }; }); sf = O(() => { "use strict"; Mt(); st(); j(); $n(); He(); _m = (i, e) => ({ name: "GroupedConv", inputNames: i ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: i ? [0, 0, 0] : [0, 0], cacheHint: e }), Om = (i, e, o, t) => { let n = e.length > 2 ? "value += getBias(output_channel);" : "", s = e[0].dims.slice(), a = e[1].dims.slice(), u = a[0] / t.group; tt.verbose("GroupedConv", `autpPad:${t.autoPad}, dilations:${t.dilations}, group:${t.group}, kernelShape:${t.kernelShape}, pads:${t.pads}, strides:${t.strides}`); let l = dr(s, a, t.dilations, t.pads, t.strides), f = G(i.session.backend.glContext.version), { activationFunction: p, applyActivation: d } = fe(t), y = ` const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); ${p} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 xRCCorner = coords.zw * strides - pads; int group_id = output_channel / ${u}; float value = 0.0; for (int wInChannel = 0; wInChannel < ${a[1]}; wInChannel++) { int input_channel = group_id * ${a[1]} + wInChannel; for (int wHeight = 0; wHeight < ${a[2]}; wHeight++) { int xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}; if (xHeight < 0 || xHeight >= ${s[2]}) { continue; } for (int wWidth = 0; wWidth < ${a[3]}; wWidth++) { int xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}; if (xWidth < 0 || xWidth >= ${s[3]}) { continue; } float xVal = getX(batch, input_channel, xWidth, xHeight); float wVal = getW(output_channel, wInChannel, wWidth, wHeight); value += xVal*wVal; } } } ${n} ${d} ${f.output} = vec4(value, .0, .0, .0); } `; return { ...o, output: { dims: l, type: e[0].type, textureType: 0 }, shaderSource: y, hasMain: true }; }, af = (i, e, o) => { let t = _m(e.length > 2, o.cacheKey); return { ...t, get: () => Om(i, e, t, o) }; }; }); lf = O(() => { "use strict"; st(); j(); We(); Sm = (i) => ({ name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [2], cacheHint: i }), Am = (i, e, o, t, r, n) => { let s = o.dims, a = t.dims, u = 2, l = 3, f = r.length, p = [a[1] * a[2] * a[3], r[2] * r[3]], d = a[2] * a[3], y = le(), w = G(i.session.backend.glContext.version), v = ""; for (let L = 0; L <= 1; L++) for (let A2 = 0; A2 <= 1; A2++) v += ` blockIndex = rc.x + ${A2}; pos = rc.y + ${L}; if(blockIndex < ${p[1]} && pos < ${p[0]}) { offsetY = int(blockIndex / (${r[f - 1]})) * ${n.strides[0]} - ${n.pads[0]}; d0 = offsetY + ${n.dilations[0]} * (imod(pos, ${d}) / ${a[2]}); if(d0 < ${s[u]} && d0 >= 0) { offsetX = imod(blockIndex, ${r[f - 1]}) * ${n.strides[1]} - ${n.pads[1]}; d1 = offsetX + ${n.dilations[1]} * imod(imod(pos, ${d}), ${a[2]}); if(d1 < ${s[l]} && d1 >= 0) { ch = int(float(pos)/ ${d}.); innerDims = vec2(d0, d1); result[${L * 2 + A2}] = getChannel( getA(0, ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } `; let S = ` ${y} void main() { ivec2 rc = getOutputCoords(); vec4 result = vec4(0.0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${v} ${w.output} = result; } `; return { ...e, output: { dims: p, type: o.type, textureType: 2 }, shaderSource: S, hasMain: true }; }, uf = (i, e, o, t, r) => { let n = Sm(r.cacheKey); return { ...n, get: () => Am(i, n, e, o, t, r) }; }; }); kn = O(() => { "use strict"; Y(); j(); ue(); He(); xi(); ff = (i, e, o) => (Dm(e), i.session.pack ? [i.run(Bn(i, e, o), e)] : [i.run(gi(e, o), e)]), cf = (i) => pr(i.attributes), Pm = (i, e) => ({ name: "MatMul", inputNames: i ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: i ? [0, 0, 0] : [0, 0], cacheHint: e }); Dm = (i) => { if (!i || i.length !== 2) throw new Error("MatMul requires 2 inputs."); if (i[0].dims[i[0].dims.length - 1] !== i[1].dims[i[1].dims.length - 2]) throw new Error("shared dimension does not match."); if (i[0].type !== "float32" && i[0].type !== "float64" || i[1].type !== "float32" && i[1].type !== "float64") throw new Error("inputs should be float type"); if (i[0].type !== i[1].type) throw new Error("inputs types should match"); }; }); xi = O(() => { "use strict"; Y(); st(); j(); ue(); He(); kn(); Lm = (i, e) => ({ name: "MatMul (packed)", inputNames: i ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: i ? [2, 2, 2] : [2, 2], cacheHint: e }), $m = (i, e, o, t) => { let r = o.length > 2, n = r ? "value += getBiasForMatmul();" : "", s = o[0].dims, a = o[1].dims, u = $t.calcShape(s, a, true), l = !B.areEqual(o[0].dims, o[1].dims); if (!u) throw new Error("Can't use matmul on the given tensors"); let f = s[s.length - 1], p = Math.ceil(f / 2), d = s.length, y = a.length, w = G(i.session.backend.glContext.version), v = kt(u.length), S = u.length, L = ee(), { activationFunction: A2, applyActivation: P2 } = fe(t), M3 = r ? `${yi(v, L, o[2].dims, u, true)}` : "", V3 = l ? `${km(v, L, o, u)}` : "", ut2 = l ? "getAAtOutCoordsMatmul(i)" : `getA(${Bm(L, d)})`, xt3 = l ? "getBAtOutCoordsMatmul(i)" : `getB(${Fm(L, y)})`, et2 = l ? "" : `${v} rc = getOutputCoords(); int lastDim = rc.${L[S - 1]}; rc.${L[S - 1]} = rc.${L[S - 2]}; rc.${L[S - 2]} = lastDim; `, Et3 = ` ${V3} ${M3} ${A2} void main() { ${et2} vec4 value = vec4(0); for (int i = 0; i < ${p}; i++) { vec4 a = ${ut2}; vec4 b = ${xt3}; value += (a.rrbb * b.rgrg); value += (a.ggaa * b.baba); } ${n} ${P2} ${w.output} = value; }`; return { ...e, output: { dims: u, type: o[0].type, textureType: 2 }, shaderSource: Et3, hasMain: true }; }, Bn = (i, e, o) => { let t = Lm(e.length > 2, o.activationCacheKey); return { ...t, get: () => $m(i, t, e, o) }; }; }); df = O(() => { "use strict"; $n(); lf(); xi(); pf = (i, e, o) => { let t = e[0].dims, r = e[1].dims, n = dr(t, r, o.dilations, o.pads, o.strides), s = i.run(uf(i, e[0], e[1], n, o), [e[0]]), a = i.reshapePacked(e[1], [r[0], r[1] * r[2] * r[3]]), u = e.length === 3 ? [a, s, e[2]] : [a, s], l = i.run(Bn(i, u, o), u); return i.reshapePacked(l, n); }; }); wi = O(() => { "use strict"; j(); Cm = (i) => ({ name: "Im2Col", inputNames: ["X"], inputTypes: [0], cacheHint: i }), Nm = (i, e, o, t, r, n) => { let s = o.dims, a = t.dims, u = r.length, l = Ti(s, a, r, 4), f = ` const int XC = ${s[1]}; const int XH = ${s[2]}; const int XW = ${s[3]}; const int KH = ${n.kernelShape[0]}; const int KW = ${n.kernelShape[1]}; const int dilationH = ${n.dilations[0]}; const int dilationW = ${n.dilations[1]}; const int strideH = ${n.strides[0]}; const int strideW = ${n.strides[1]}; const int padH = ${n.pads[0]}; const int padW = ${n.pads[1]}; const int KHKW = KH*KW; const int XCKHKW = XC * KHKW; const int outputChannels = 4; vec4 process(int indices[${u}]) { int b = indices[0]; // batch size int oh = indices[1] * strideH - padH; //output height int ow = indices[2] * strideW - padW; //output width int p = indices[3] * outputChannels; //patch vec4 value = vec4(0.0); for(int i=0; i < outputChannels; ++i) { if(p < XCKHKW) { int patchC = p / KHKW; int patchH = (p - patchC*KHKW) / KW; int patchW = (p - patchC*KHKW) - patchH * KW; int xh2 = oh + patchH * dilationH; int xw2 = ow + patchW * dilationW; int x[${s.length}]; x[0] = b; x[1] = patchC; x[2] = xh2; x[3] = xw2; if(xh2 >= 0 && xh2 < XH && xw2 >= 0 && xw2 < XW) { value[i] = _X(x); } } ++p; } return value; } `; return { ...e, output: { dims: l, type: o.type, textureType: 4 }, shaderSource: f }; }, hf = (i, e, o, t, r) => { let n = Cm(r.cacheKey); return { ...n, get: () => Nm(i, n, e, o, t, r) }; }, Ti = (i, e, o, t = 4) => [o[0], o[2], o[3], Math.ceil(i[1] * e[2] * e[3] / t)]; }); bf = O(() => { "use strict"; Y(); st(); j(); He(); wi(); Rm = (i, e) => ({ name: "ConvDotProduct", inputNames: i ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: i ? [0, 4, 0] : [0, 4], cacheKey: e.activationCacheKey }), Gm = (i, e, o, t, r) => { let n = o[0].dims, s = o[1].dims, a = [s[0], Math.ceil(n[1] * s[2] * s[3] / 4)], u = Ti(n, s, t), [l, f] = i.calculateTextureWidthAndHeight(a, 4), p = B.computeStrides(u), [d, y] = i.calculateTextureWidthAndHeight(u, 4), w = t.length, v = o.length < 3 ? "0.0" : "_B(b)", S = Math.ceil(n[1] * s[2] * s[3] / 4), { activationFunction: L, applyActivation: A2 } = fe(r), P2 = G(i.session.backend.glContext.version), M3 = ` ${L} float process(int indices[${w}]) { int b[1]; b[0] = indices[1]; int im2col[4]; im2col[0] = indices[0]; im2col[1] = indices[2]; im2col[2] = indices[3]; int im2colOffset = im2col[0] * ${p[0]} + im2col[1] * ${p[1]} + im2col[2] * ${p[2]}; int kernelOffset = indices[1] * ${a[1]}; float value = ${v}; for (int i = 0; i < ${S}; ++i) { vec2 im2colCoords = offsetToCoords(im2colOffset, ${d}, ${y}); vec2 kernelCoords = offsetToCoords(kernelOffset, ${l}, ${f}); value += dot(${P2.texture2D}(Im2Col, im2colCoords), ${P2.texture2D}(K, kernelCoords)); ++im2colOffset; ++kernelOffset; } ${A2} return value; }`; return { ...e, output: { dims: t, type: o[0].type, textureType: 0 }, shaderSource: M3 }; }, mf = (i, e, o, t) => { let r = Rm(e.length > 2, t); return { ...r, get: () => Gm(i, r, e, o, t) }; }; }); $n = O(() => { "use strict"; vt(); Y(); sf(); df(); bf(); He(); wi(); kn(); dr = (i, e, o, t, r) => { let n = i[0], s = i.slice(2), a = s.length, u = e[0], f = e.slice(2).map((w, v) => w + (w - 1) * (o[v] - 1)), d = s.map((w, v) => w + t[v] + t[v + a]).map((w, v) => Math.floor((w - f[v] + r[v]) / r[v])); return [n, u].concat(...d); }, vi = (i, e, o) => (Wm(e, o), Mm(i, e, o)), Mm = (i, e, o) => { let t = zm(o, e), r = i.session.pack, n = t.kernelShape[0] === 1 && t.kernelShape[1] === 1; return t.group > 1 ? [i.run(af(i, e, t), e)] : n && r ? [Um(i, e, t)] : r && e[0].dims.length === 4 && e[0].dims[0] === 1 && !n ? [pf(i, e, t)] : [Vm(i, e, t)]; }, Um = (i, e, o) => { let t = e[0].dims, r = e[1].dims, n = dr(t, r, o.dilations, o.pads, o.strides), s = i.reshapeUnpacked(e[0], [t[1], t[2] * t[3]]), a = i.reshapeUnpacked(e[1], [r[0], r[1]]), u = e.length > 2 ? [a, s, e[2]] : [a, s], l = i.run(gi(u, o), u); return i.reshapeUnpacked(l, n); }, Vm = (i, e, o) => { let t = e[0].dims, r = e[1].dims, n = dr(t, r, o.dilations, o.pads, o.strides), s = i.run(hf(i, e[0], e[1], n, o), [e[0]]), a = e.length === 3 ? [s, e[1], e[2]] : [s, e[1]]; return i.run(mf(i, e, n, o), a); }, zm = (i, e) => { let o = i.kernelShape.slice(); if (i.kernelShape.length === 0) for (let n = 2; n < e[1].dims.length; ++n) o.push(e[1].dims[n]); let t = i.pads.slice(); Me.adjustPadsBasedOnAutoPad(e[0].dims, i.strides, i.dilations, o, t, i.autoPad); let r = Object.assign({}, i); return Object.assign(r, { kernelShape: o, pads: t, cacheKey: i.cacheKey }), r; }, Ii = (i) => { let e = i.attributes, o = pr(e), t = e.getString("auto_pad", "NOTSET"), r = e.getInts("dilations", [1, 1]), n = e.getInt("group", 1), s = e.getInts("kernel_shape", []), a = e.getInts("pads", [0, 0, 0, 0]), u = e.getInts("strides", [1, 1]); return W({ autoPad: t, dilations: r, group: n, kernelShape: s, pads: a, strides: u, ...o }); }, Wm = (i, e) => { if (!i || i.length !== 2 && i.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (i[0].dims.length !== 4 || i[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv"); let o = i[0].dims[1], t = i[1].dims[1] * e.group; if (o !== t) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); if (i.length === 3 && (i[2].dims.length !== 1 || i[1].dims[0] !== i[2].dims[0])) throw new Error("invalid bias"); let r = i[0].dims.length - 2; if (e.dilations.length !== r) throw new Error(`dilations should be ${r}D`); if (e.strides.length !== r) throw new Error(`strides should be ${r}D`); if (e.pads.length !== r * 2) throw new Error(`pads should be ${r * 2}D`); if (e.kernelShape.length !== 0 && e.kernelShape.length !== i[1].dims.length - 2) throw new Error("invalid kernel shape"); if (i[0].type !== "float32" || i[1].type !== "float32") throw new Error("Conv input(X,W) should be float tensor"); if (i.length === 3 && i[2].type !== "float32") throw new Error("Conv input(bias) should be float tensor"); }; }); xf = O(() => { "use strict"; vt(); st(); j(); He(); Hm = (i, e, o, t, r, n) => (i - 1) * e + o + (t - 1) * r + 1 - n, qm = (i, e, o, t, r) => { let n = Math.floor(i / 2); e === "SAME_UPPER" ? (o[t] = n, o[r] = i - n) : e === "SAME_LOWER" && (o[t] = i - n, o[r] = n); }, jm = (i, e, o, t, r, n, s, a) => { let u = i.length - 2, l = a.length === 0; for (let f = 0; f < u; ++f) { let p = l ? i[f + 2] * n[f] : a[f], d = Hm(i[f + 2], n[f], r[f], e[f], o[f], p); qm(d, t, r, f, f + u), l && a.push(n[f] * (i[f + 2] - 1) + s[f] + (e[f] - 1) * o[f] + 1 - r[f] - r[f + u]); } }, gf = (i, e, o) => (tb(e, o), Xm(i, e, o)), Xm = (i, e, o) => { let t = Qm(o, e); return [Zm(i, e, t)]; }, Km = (i, e) => ({ name: "ConvTranspose", inputNames: i ? ["X", "W", "B"] : ["X", "W"], inputTypes: i ? [0, 0, 0] : [0, 0], cacheHint: e }), Jm = (i, e, o, t) => { let n = e.length > 2 ? "getB(output_channel)" : "0.0", s = e[0].dims, a = e[1].dims, u = a[1], l = a[0] / t.group, f = [e[0].dims[0], e[1].dims[1] * t.group, ...t.outputShape], p = G(i.session.backend.glContext.version), { activationFunction: d, applyActivation: y } = fe(t), w = ` const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); ${d} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 loc = coords.zw + pads; int group_id = output_channel / ${u}; int wOutChannel = output_channel - group_id * ${u}; float value = ${n}; for (int inChannelOffset = 0; inChannelOffset < ${l}; inChannelOffset++) { int input_channel = group_id * ${l} + inChannelOffset; for (int wWOff = 0; wWOff < ${a[2]}; wWOff++) { for (int wHOff = 0; wHOff < ${a[3]}; wHOff++) { ivec2 wOff = ivec2(wWOff * ${t.dilations[0]}, wHOff * ${t.dilations[1]}); ivec2 wLoc = loc - wOff; ivec2 wLocIn = wLoc / strides; if ( wLocIn * strides == wLoc && wLocIn.x >= 0 && wLocIn.x < ${s[2]} && wLocIn.y >= 0 && wLocIn.y < ${s[3]} ) { float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); value += xVal * wVal; } } } } ${y} ${p.output} = vec4(value, .0, .0, .0); } `; return { ...o, output: { dims: f, type: e[0].type, textureType: 0 }, shaderSource: w, hasMain: true }; }, Ym = (i, e, o) => { let t = Km(e.length > 2, o.cacheKey); return { ...t, get: () => Jm(i, e, t, o) }; }, Zm = (i, e, o) => i.run(Ym(i, e, o), e), Qm = (i, e) => { let o = i.kernelShape.slice(); if (i.kernelShape.length === 0) for (let a = 2; a < e[1].dims.length; ++a) o.push(e[1].dims[a]); let t = i.pads.slice(), r = i.outputShape.slice(), n = e[0].dims; jm(n, o, i.dilations, i.autoPad, t, i.strides, i.outputPadding, r); let s = Object.assign({}, i); return Object.assign(s, { kernelShape: o, pads: t, outputShape: r, cacheKey: i.cacheKey }), s; }, yf = (i) => { let e = i.attributes, o = pr(e), t = e.getString("auto_pad", "NOTSET"), r = e.getInts("dilations", [1, 1]), n = e.getInt("group", 1), s = e.getInts("kernel_shape", []), a = e.getInts("output_padding", [0, 0]), u = e.getInts("output_shape", []), l = e.getInts("pads", [0, 0, 0, 0]), f = e.getInts("strides", [1, 1]); return W({ autoPad: t, dilations: r, group: n, kernelShape: s, outputPadding: a, outputShape: u, pads: l, strides: f, ...o }); }, tb = (i, e) => { if (!i || i.length !== 2 && i.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (i[0].dims.length !== 4 || i[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv"); let o = i[0].dims[1], t = i[1].dims[0]; if (o !== t) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); let r = i[1].dims[1] * e.group; if (i.length === 3 && (i[2].dims.length !== 1 || i[2].dims[0] !== r)) throw new Error("invalid bias"); let n = i[0].dims.length - 2; if (e.dilations.length !== n) throw new Error(`dilations should be ${n}D`); if (e.strides.length !== n) throw new Error(`strides should be ${n}D`); if (e.pads.length !== n * 2) throw new Error(`pads should be ${n * 2}D`); if (e.outputPadding.length !== n) throw new Error(`output_padding should be ${n}D`); if (e.kernelShape.length !== 0 && e.kernelShape.length !== i[1].dims.length - 2) throw new Error("invalid kernel shape"); if (e.outputShape.length !== 0 && e.outputShape.length !== i[0].dims.length - 2) throw new Error("invalid output shape"); if (i[0].type !== "float32" || i[1].type !== "float32") throw new Error("ConvTranspose input(X,W) should be float tensor"); if (i.length === 3 && i[2].type !== "float32") throw new Error("ConvTranspose input(bias) should be float tensor"); }; }); Fn = O(() => { "use strict"; vt(); Y(); j(); Tf = { name: "Transpose", inputNames: ["A"], inputTypes: [0] }, qe = (i, e, o) => (ob(e), [i.run({ ...Tf, cacheHint: o.cacheKey, get: () => eb(i, e[0], o.perm) }, e)]), wf = (i) => W({ perm: i.attributes.getInts("perm", []) }), eb = (i, e, o) => { let t = e.dims; o = vf(t, o); let r = rb(t, o), n = t.length, s = ` ${nb("perm", o, n)} float process(int indices[${n}]) { int a[${n}]; perm(a, indices); return _A(a); }`; return { ...Tf, output: { dims: r, type: e.type, textureType: 0 }, shaderSource: s }; }, vf = (i, e) => (e && e.length !== i.length && (e = [...i.keys()].reverse()), e), rb = (i, e) => (e = vf(i, e), B.sortBasedOnPerm(i, e)), nb = (i, e, o) => { let t = []; t.push(`void ${i}(out int a[${o}], int src[${o}]) {`); for (let r = 0; r < o; ++r) t.push(` a[${e[r]}]=src[${r}];`); return t.push(" }"), t.join(` `); }, ob = (i) => { if (!i || i.length !== 1) throw new Error("Transpose requires 1 input."); if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("input should be float tensor"); }; }); Of = O(() => { "use strict"; Fn(); If2 = (i, e, o) => { ib(e); let t = o.blocksize, r = t * t, n = o.mode === "DCR" ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], s = o.mode === "DCR" ? [e[0].dims[0], t, t, e[0].dims[1] / r, e[0].dims[2], e[0].dims[3]] : [e[0].dims[0], e[0].dims[1] / r, t, t, e[0].dims[2], e[0].dims[3]], a = i.reshapeUnpacked(e[0], s), u = { perm: n, cacheKey: `${n}` }, [l] = qe(i, [a], u), f = [e[0].dims[0], e[0].dims[1] / r, e[0].dims[2] * t, e[0].dims[3] * t]; return [i.reshapeUnpacked(l, f)]; }, _f = (i) => { let e = i.attributes.getInt("blocksize"); if (e < 1) throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`); let o = i.attributes.getString("mode", "DCR"); if (o !== "DCR" && o !== "CRD") throw new Error(`unrecognized mode: ${o} for DepthToSpace`); return { mode: o, blocksize: e }; }, ib = (i) => { if (i.length !== 1) throw new Error(`DepthToSpace expect 1 inputs, but got ${i.length}`); if (i[0].type === "string" || i[0].dims.length !== 4) throw new TypeError("DepthToSpace input should be a 4-D numeric tensor"); }; }); Pf = O(() => { "use strict"; Y(); Sf = (i, e, o) => { ab(e, o); let t = B.flattenShape(e[0].dims, o); return [i.reshapeUnpacked(e[0], t)]; }, Af = (i) => i.attributes.getInt("axis", 1), ab = (i, e) => { if (!i || i.length !== 1) throw new Error("Flatten requires 1 input."); let o = i[0].dims.length; if (o === 0) throw new Error("scalar tensor is not supported."); if (e < -o || e > o) throw new Error("Invalid axis"); if (i[0].type === "string") throw new Error("string tensor is not supported."); }; }); Rr = O(() => { "use strict"; Ae = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"]; }); Lf = O(() => { "use strict"; vt(); Rr(); Y(); j(); Ef = (i, e, o) => (fb(e, o.axis), [i.run(lb(i, e, o), e)]), Df = (i) => W({ axis: i.attributes.getInt("axis", 0) }), sb = { name: "Gather", inputNames: ["A", "B"], inputTypes: [0, 0] }, ub = (i, e, o, t) => { let r = o[0].dims.slice(), n = o[1].dims.slice(), s = new Array(r.length + n.length - 1); t = B.normalizeAxis(t, r.length); let a = []; for (let d = 0; d < s.length; d++) d < t ? (s[d] = r[d], a.push(`inputIdx[${d}] = outputIdx[${d}];`)) : d < t + n.length ? (s[d] = n[d - t], a.push(`indexDataIdx[${d - t}] = outputIdx[${d}];`)) : (s[d] = r[d - n.length + 1], a.push(`inputIdx[${d - n.length + 1}] = outputIdx[${d}];`)); let u = s.length || 1, l = r.length, f = n.length || 1, p = ` float process(int outputIdx[${u}]) { int inputIdx[${l}]; int indexDataIdx[${f}]; indexDataIdx[0] = 0; ${a.join(` `)} int idx = int(_B(indexDataIdx)); inputIdx[${t}] = idx < 0 ? idx + ${r[t]} : idx; return _A(inputIdx); }`; return { ...e, output: { dims: s, type: o[0].type, textureType: 0 }, shaderSource: p }; }, lb = (i, e, o) => { let t = { ...sb, cacheHint: o.cacheKey }; return { ...t, get: () => ub(i, t, e, o.axis) }; }, fb = (i, e) => { if (!i || i.length !== 2) throw new Error("Gather requires 2 inputs."); let o = i[0].dims.length; if (o < 1) throw new Error("Invalid input shape."); if (e < -o || e > o - 1) throw new Error("Invalid axis."); if (Ae.indexOf(i[0].type) === -1) throw new Error("Invaid input type."); if (i[1].type !== "int32" && i[1].type !== "int16") throw new Error("Invaid input type."); }; }); Ff = O(() => { "use strict"; vt(); Y(); j(); _i = (i, e, o) => (db(e, o), [i.run(cb(e, o), e)]), $f = (i, e) => { let o = i.attributes.getInt("transA", 0) !== 0, t = i.attributes.getInt("transB", 0) !== 0, r = i.attributes.getFloat("alpha", 1), n = i.attributes.getFloat("beta", 1); return W({ transA: o, transB: t, alpha: r, beta: n, isOptionalC: e }); }, kf = (i) => $f(i, false), Bf = (i) => $f(i, true), cb = (i, e) => { let o = { name: "Gemm", inputNames: i.length === 3 ? ["A", "B", "C"] : ["A", "B"], inputTypes: i.length === 3 ? [0, 0, 0] : [0, 0], key: e.cacheKey }; return { ...o, get: () => pb(o, i, e) }; }, pb = (i, e, o) => { let t = e[0].dims.slice(), r = e[1].dims.slice(), [n, s] = _n.getShapeOfGemmResult(t, o.transA, r, o.transB, e.length === 3 ? e[2].dims : void 0), a = [n, s]; if (!a) throw new Error("Can't use gemm on the given tensors"); let u = t[t.length - 1], l = ""; o.transA && (u = t[0]), o.transA && o.transB ? l = "value += _A_T(a) * _B_T(b);" : o.transA && !o.transB ? l = "value += _A_T(a) * _B(b);" : !o.transA && o.transB ? l = "value += _A(a) * _B_T(b);" : !o.transA && !o.transB && (l = "value += _A(a) * _B(b);"); let f = a.length, p = e.length === 3 ? `int c[${e[2].dims.length}];` : "", d = e.length === 3 ? "bcastIndices_C(indices, c);" : "", y = e.length === 3 ? "value += beta * _C(c);" : "", w = ` float process(int indices[${f}]) { int a[${f}]; int b[${f}]; ${p} copyVec(indices, a); copyVec(indices, b); ${d} float value = 0.0; for (int k=0; k<${u}; ++k) { a[${f - 1}] = k; b[${f - 2}] = k; ${l} } value = value * alpha; ${y} return value; }`; return { ...i, output: { dims: a, type: e[0].type, textureType: 0 }, variables: [{ name: "alpha", type: "float", data: o.alpha }, { name: "beta", type: "float", data: o.beta }], shaderSource: w }; }, db = (i, e) => { if (!i) throw new Error("Input is missing"); if (e.isOptionalC && (i.length < 2 || i.length > 3)) throw new Error("Invaid input shape."); if (!e.isOptionalC && i.length !== 3) throw new Error("Gemm requires 3 inputs"); if (i.length === 3 && i[2].dims.length !== 1 && i[2].dims.length !== 2) throw new Error("Invalid input shape of C"); if (i[0].type !== "float32" && i[0].type !== "float64" || i[1].type !== "float32" && i[1].type !== "float64" || i.length === 3 && i[2].type !== "float32" && i[2].type !== "float64") throw new Error("Invalid input type."); if (i[0].type !== i[1].type || i.length === 3 && i[0].type !== i[2].type) throw new Error("Input types are mismatched"); }; }); Rf = O(() => { "use strict"; vt(); j(); Cf = (i, e, o) => (yb(e), [i.run(bb(i, e, o), e)]), Nf = (i) => { let e = i.attributes.getFloat("scale"), o = i.attributes.getFloats("bias"); return W({ scale: e, bias: o }); }, hb = { name: "ImageScaler", inputNames: ["X"], inputTypes: [0] }, mb = (i, e, o, t) => { let r = o[0].dims.slice(), n = r.length, a = ` ${gb(t.bias.length)} float process(int indices[${n}]) { return _X(indices) * scale + getBias(bias, indices[1]); }`; return { ...e, output: { dims: r, type: o[0].type, textureType: 0 }, variables: [{ name: "bias", type: "float", arrayLength: t.bias.length, data: t.bias }, { name: "scale", type: "float", data: t.scale }], shaderSource: a }; }, bb = (i, e, o) => { let t = { ...hb, cacheHint: o.cacheKey }; return { ...t, get: () => mb(i, t, e, o) }; }, gb = (i) => { let e = [`float getBias(float bias[${i}], int channel) {`]; for (let o = 0; o < i; ++o) o === 0 ? e.push(` if (channel == ${o}) { return bias[${o}]; }`) : o === i - 1 ? e.push(` else { return bias[${o}]; }`) : e.push(` else if (channel == ${o}) { return bias[${o}]; }`); return e.push(" }"), e.join(` `); }, yb = (i) => { if (!i || i.length !== 1) throw new Error("ImageScaler requires 1 input."); if (i[0].dims.length !== 4) throw new Error("Invalid input shape."); if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("Invalid input type."); }; }); Vf = O(() => { "use strict"; st(); j(); Mf = (i, e, o) => { _b(e); let t = i.run(Tb(e[0]), e); return [i.run(Ib(i, e[0], o, t.dims), [e[0], t, e[1], e[2]])]; }, Uf = (i) => i.attributes.getFloat("epsilon", 1e-5), Gf = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [0] }, xb = (i, e) => { let o = e.dims.slice(), t = o[1], r = o[2] * o[3], n = [o[0], t], s = ` vec4 process(int[2] indices) { vec4 v = vec4(0.0); int a[4]; a[0] = indices[0]; a[1] = indices[1]; float temp = 0.0; for(int a2=0; a2<${o[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${o[3]}; a3++) { a[3] = a3; float x = _X(a); temp += x; } } float mean = temp / float(${r}); temp = 0.0; for(int a2=0; a2<${o[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${o[3]}; a3++) { a[3] = a3; float x = _X(a); temp += (x - mean) * (x - mean); } } v.r = mean; v.g = temp / float(${r}); return v; }`; return { ...i, output: { dims: n, type: e.type, textureType: 4 }, shaderSource: s }; }, Tb = (i) => ({ ...Gf, get: () => xb(Gf, i) }), wb = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [0, 4, 0, 0] }, vb = (i, e, o, t, r) => { let n = G(i.session.backend.glContext.version), [s, a] = i.calculateTextureWidthAndHeight(r, 4), [u, l] = [s / 4, a], f = ` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); vec2 coords = offsetToCoords(offset, ${u}, ${l}); return ${n.texture2D}(MeanAndVariance, coords); } float process(int[4] indices) { int mv[2]; mv[0] = indices[0]; mv[1] = indices[1]; vec4 mean_and_variance = get_MeanAndVariance(mv); float mean = mean_and_variance.r; float variance = mean_and_variance.g; int sb[1]; sb[0] = indices[1]; float scale = _Scale(sb); float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; }`; return { ...e, output: { dims: o.dims, type: o.type, textureType: 0 }, variables: [{ name: "epsilon", type: "float", data: t }], shaderSource: f }; }, Ib = (i, e, o, t) => { let r = { ...wb, cacheHint: `${o}` }; return { ...r, get: () => vb(i, r, e, o, t) }; }, _b = (i) => { if (!i || i.length !== 3) throw new Error("InstanceNormalization requires 3 inputs."); let e = i[0], o = i[1], t = i[2]; if (e.dims.length < 3 || o.dims.length !== 1 || t.dims.length !== 1) throw new Error("Invalid input shape."); if (o.dims[0] !== e.dims[1] || t.dims[0] !== e.dims[1]) throw new Error("Input shapes are mismatched."); if (e.type !== "float32" && e.type !== "float64" || o.type !== "float32" && o.type !== "float64" || t.type !== "float32" && t.type !== "float64") throw new Error("Invalid input type."); if (i[0].dims.length !== 4) throw new Error("Only support 4-D input shape."); }; }); qf = O(() => { "use strict"; vt(); j(); zf = (i, e, o) => (Ab(e), [i.run(Sb(e, o), e)]), Wf = (i) => { let e = i.attributes.getFloat("alpha", 1e-4), o = i.attributes.getFloat("beta", 0.75), t = i.attributes.getFloat("bias", 1), r = i.attributes.getInt("size"); return W({ alpha: e, beta: o, bias: t, size: r }); }, Hf = { name: "LRN", inputNames: ["X"], inputTypes: [0] }; Ab = (i) => { if (!i || i.length !== 1) throw new Error("LRN requires 1 input."); if (i[0].dims.length !== 4) throw new Error('currently only support LRN for input with "NCHW" format'); if (i[0].type !== "float32") throw new Error("input should be float type"); }; }); Jf = O(() => { "use strict"; vt(); Y(); st(); j(); Pb = { name: "Pad", inputNames: ["A"], inputTypes: [0] }, Oi = (i, e, o) => (Lb(e), [i.run({ ...Pb, cacheHint: o.cacheKey, get: () => Db(i, e[0], o) }, e)]), jf = (i) => { let e = i.attributes.getString("mode", "constant"), o = i.attributes.getFloat("value", 0), t = i.attributes.getInts("pads"); return W({ mode: e, value: o, pads: t }); }, Xf = (i, e, o) => { $b(e); let t = Eb(i, e, o); return Oi(i, [e[0]], t); }, Kf = (i) => i.attributes.getString("mode", "constant"), Eb = (i, e, o) => { if (!i.session.isInitializer(e[1].dataId) || e.length >= 3 && !i.session.isInitializer(e[2].dataId)) throw new Error("dynamic pad attributes are not allowed"); let t = Array.from(e[1].integerData), r = e.length >= 3 ? e[2].floatData[0] : 0; return W({ mode: o, pads: t, value: r }); }, Db = (i, e, o) => { let t = B.padShape(e.dims.slice(), o.pads), r = t.length, s = ` ${kb(i, e, o)} float process(int[${r}] indices) { return padA(indices); }`; return { name: "Pad", inputNames: ["A"], inputTypes: [0], output: { dims: t, type: e.type, textureType: 0 }, shaderSource: s }; }, Lb = (i) => { if (!i || i.length !== 1) throw new Error("Pad requires 1 input"); if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("Invalid input type."); }, $b = (i) => { if (!i || i.length !== 2 && i.length !== 3) throw new Error("Pad requires 2 or 3 inputs"); if (i[1].type !== "int32") throw new Error("Invalid input type."); if (i.length >= 3 && i[2].type === "string") throw new Error("Invalid input type."); }, kb = (i, e, o) => { let t = G(i.session.backend.glContext.version), [r, n] = i.calculateTextureWidthAndHeight(e.dims, 0), s = B.computeStrides(e.dims); switch (o.mode) { case "constant": return Bb(t, e.dims, s, r, n, o.pads, o.value); case "reflect": return Fb(t, e.dims, s, r, n, o.pads); case "edge": return Cb(t, e.dims, s, r, n, o.pads); default: throw new Error("Invalid mode"); } }, Bb = (i, e, o, t, r, n, s) => { let a = e.length, u = ""; for (let l = a - 1; l >= 0; --l) u += ` k = m[${l}] - ${n[l]}; if (k < 0) return constant; if (k >= ${e[l]}) return constant; offset += k * ${o[l]}; `; return ` float padA(int m[${a}]) { const float constant = float(${s}); int offset = 0; int k = 0; ${u} vec2 coords = offsetToCoords(offset, ${t}, ${r}); float value = getColorAsFloat(${i.texture2D}(A, coords)); return value; } `; }, Fb = (i, e, o, t, r, n) => { let s = e.length, a = ""; for (let u = s - 1; u >= 0; --u) a += ` k = m[${u}] - ${n[u]}; if (k < 0) { k = -k; } { const int _2n_1 = ${2 * (e[u] - 1)}; k = int( mod( float(k), float(_2n_1) ) ) ; if(k >= ${e[u]}) { k = _2n_1 - k; } } offset += k * ${o[u]}; `; return ` float padA(int m[${s}]) { int offset = 0; int k = 0; ${a} vec2 coords = offsetToCoords(offset, ${t}, ${r}); float value = getColorAsFloat(${i.texture2D}(A, coords)); return value; } `; }, Cb = (i, e, o, t, r, n) => { let s = e.length, a = ""; for (let u = s - 1; u >= 0; --u) a += ` k = m[${u}] - ${n[u]}; if (k < 0) k = 0; if (k >= ${e[u]}) k = ${e[u] - 1}; offset += k * ${o[u]}; `; return ` float padA(int m[${s}]) { int offset = 0; int k = 0; ${a} vec2 coords = offsetToCoords(offset, ${t}, ${r}); float value = getColorAsFloat(${i.texture2D}(A, coords)); return value; } `; }; }); lc = O(() => { "use strict"; vt(); Y(); j(); Zf = (i, e, o) => { Nn(e); let t = { name: "AveragePool", inputNames: ["X"], inputTypes: [0], cacheHint: o.cacheKey }; return [i.run({ ...t, get: () => tc(e, t, false, o) }, e)]; }, Qf = (i) => { let e = i.attributes.getString("auto_pad", "NOTSET"), o = i.attributes.getInt("ceil_mode", 0), t = i.attributes.getInt("count_include_pad", 0) !== 0, r = i.attributes.getInts("kernel_shape"), n = i.attributes.getInts("strides", []), s = i.attributes.getInts("pads", []); if (o !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); return W({ autoPad: e, ceilMode: o, countIncludePad: t, kernelShape: r, strides: n, pads: s }); }, tc = (i, e, o, t) => { let [r, n] = ac(i, t, o), s = B.size(r.kernelShape), a = "value += _X(x);", u = ""; r.countIncludePad ? u += `value /= float(${s});` : u += `value /= float(${s} - pad);`; let f = ` ${uc(i[0].dims, r, a, u, "0.0")} `; return { ...e, output: { dims: n, type: i[0].type, textureType: 0 }, shaderSource: f }; }, ec = (i, e, o) => { Nn(e); let t = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [0], cacheHint: `${o.countIncludePad}` }; return [i.run({ ...t, get: () => tc(e, t, true, o) }, e)]; }, rc = (i) => { let e = i.attributes.getInt("count_include_pad", 0) !== 0; return W({ autoPad: "", ceilMode: 0, countIncludePad: e, kernelShape: [], strides: [], pads: [] }); }, nc = (i, e, o) => { Nn(e); let t = { name: "MaxPool", inputNames: ["X"], inputTypes: [0], cacheHint: o.cacheKey }; return [i.run({ ...t, get: () => ic(e, t, false, o) }, e)]; }, oc = (i) => { let e = i.attributes.getString("auto_pad", "NOTSET"), o = i.attributes.getInt("ceil_mode", 0), t = i.attributes.getInts("kernel_shape"), r = i.attributes.getInts("strides", []), n = i.attributes.getInts("pads", []), s = i.attributes.getInt("storage_order", 0), a = i.attributes.getInts("dilations", []); if (s !== 0) throw new Error("column major storage order is not yet supported for MaxPool"); if (o !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); return W({ autoPad: e, ceilMode: o, countIncludePad: false, kernelShape: t, strides: r, pads: n, storageOrder: s, dilations: a }); }, ic = (i, e, o, t) => { let [r, n] = ac(i, t, o), s = ` value = max(_X(x), value); `, a = "", l = ` ${uc(i[0].dims, r, s, a, "-1e5")} `; return { ...e, output: { dims: n, type: i[0].type, textureType: 0 }, shaderSource: l }; }, ac = (i, e, o) => { let t = i[0].dims.slice(), r = Object.hasOwnProperty.call(e, "dilations"), n = e.kernelShape.slice(), s = e.strides.slice(), a = r ? e.dilations.slice() : [], u = e.pads.slice(); Me.adjustPoolAttributes(o, t, n, s, a, u); let l = Me.computePoolOutputShape(o, t, s, a, n, u, e.autoPad), f = Object.assign({}, e); return r ? Object.assign(f, { kernelShape: n, strides: s, pads: u, dilations: a, cacheKey: e.cacheKey }) : Object.assign(f, { kernelShape: n, strides: s, pads: u, cacheKey: e.cacheKey }), [f, l]; }, Nb = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, Yf = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [0] }, sc = (i, e) => (Nn(e), [i.run({ ...Yf, get: () => ic(e, Yf, true, Nb) }, e)]), Nn = (i) => { if (!i || i.length !== 1) throw new Error("Pool ops requires 1 input."); if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("Invalid input type."); }, uc = (i, e, o, t, r) => { let n = i.length; if (e.kernelShape.length <= 2) { let s = e.kernelShape[e.kernelShape.length - 1], a = e.strides[e.strides.length - 1], u = e.pads[e.pads.length / 2 - 1], l = e.pads[e.pads.length - 1], f = i[n - 1], p = "", d = "", y = ""; if (u + l !== 0 ? p = ` for (int i = 0; i < ${s}; i++) { x[${n} - 1] = indices[${n} - 1] * ${a} - ${u} + i; if (x[${n} - 1] < 0 || x[${n} - 1] >= ${f}) { pad++; continue; } ${o} }` : p = ` for (int i = 0; i < ${s}; i++) { x[${n} - 1] = indices[${n} - 1] * ${a} - ${u} + i; ${o} }`, e.kernelShape.length === 2) { let v = e.kernelShape[e.kernelShape.length - 2], S = e.strides[e.strides.length - 2], L = e.pads[e.pads.length / 2 - 2], A2 = e.pads[e.pads.length - 2], P2 = i[n - 2]; L + A2 !== 0 ? d = ` for (int j = 0; j < ${v}; j++) { x[${n} - 2] = indices[${n} - 2] * ${S} - ${L} + j; if (x[${n} - 2] < 0 || x[${n} - 2] >= ${P2}) { pad+= ${s}; continue; } ` : d = ` for (int j = 0; j < ${v}; j++) { x[${n} - 2] = indices[${n} - 2] * ${S} - ${L} + j; `, y = ` } `; } return ` float process(int indices[${n}]) { int x[${n}]; copyVec(indices, x); float value = ${r}; int pad = 0; ${d} ${p} ${y} ${t} return value; } `; } else { let s = B.size(e.kernelShape), a = B.computeStrides(e.kernelShape), u = a.length, l = e.pads.length, f = Rb(u), p = Cn(i, "inputDims"), d = Cn(e.pads, "pads"), y = Cn(a, "kernelStrides"), w = Cn(e.strides, "strides"), v = e.pads.reduce((A2, P2) => A2 + P2), S = ""; return v ? S = ` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; break; } } if (!isPad) { ${o} }` : S = ` } ${o} `, ` ${f} float process(int indices[${n}]) { int x[${n}]; copyVec(indices, x); int offset[${u}]; int pads[${l}]; int inputDims[${n}]; int kernelStrides[${u}]; int strides[${u}]; ${d} ${p} ${w} ${y} float value = ${r}; int pad = 0; bool isPad = false; for (int i = 0; i < ${s}; i++) { offsetToIndices(i, kernelStrides, offset); isPad = false; for (int j = ${n} - ${u}; j < ${n}; j++) { x[j] = indices[j] * strides[j - ${n} + ${u}] + offset[j - ${n} + ${u}] - pads[j - 2]; ${S} } ${t} return value; } `; } }, Cn = (i, e) => { let o = ""; for (let t = 0; t < i.length; t++) o += ` ${e}[${t}] = ${i[t]}; `; return o; }, Rb = (i) => ` void offsetToIndices(int offset, int[${i}] strides, out int[${i}] indices) { if (${i} == 0) { return; } for (int i = 0; i < ${i} - 1; ++i) { indices[i] = offset / strides[i]; offset -= indices[i] * strides[i]; } indices[${i} - 1] = offset; }`; }); gc = O(() => { "use strict"; vt(); Rr(); Y(); j(); je = (i, e, o, t, r) => { Mb(e); let n = { name: t, inputNames: ["A"], inputTypes: [0] }; return [i.run({ ...n, cacheHint: o.cacheKey, get: () => Gb(i, e, o, t, r, n) }, e)]; }, Pe = (i) => { let e = i.attributes.getInts("axes", []), o = i.attributes.getInt("keepdims", 1) === 1; return W({ axes: e, keepDims: o }); }, Gb = (i, e, o, t, r, n) => { let s = [], a = e[0].dims.length || 1, u = [], l = B.normalizeAxes(o.axes, e[0].dims.length), f = r(e, l), p = f[1]; for (let w = 0; w < e[0].dims.length; w++) l.indexOf(w) >= 0 || l.length === 0 ? (o.keepDims && s.push(1), p = ` for(int j${w} = 0; j${w} < ${e[0].dims[w]}; j${w}++) { inputIdx[${w}] = j${w}; ${p} }`) : (u.push(`inputIdx[${w}] = outputIdx[${s.length}];`), s.push(e[0].dims[w])); let y = ` float process(int outputIdx[${s.length || 1}]) { float value; // final result int inputIdx[${a}]; // addressing input data ${u.join(` `)} ${f[0]} // init ops for reduce max/min ${p} ${f[2]} // final computation for reduce mean return value; }`; return { ...n, output: { dims: s, type: e[0].type, textureType: 0 }, shaderSource: y }; }, Mb = (i) => { if (!i || i.length !== 1) throw new Error("Reduce op requires 1 input."); if (Ae.indexOf(i[0].type) === -1) throw new Error("Invalid input type."); }, fc = (i, e, o) => je(i, e, o, "ReduceSum", () => ["value = 0.0;", "value += _A(inputIdx);", ""]), cc = (i, e, o) => je(i, e, o, "ReduceMean", (r, n) => { let s = 1; for (let a = 0; a < r[0].dims.length; a++) (n.indexOf(a) >= 0 || n.length === 0) && (s *= r[0].dims[a]); return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${s}.;`]; }), pc = (i, e, o) => je(i, e, o, "ReduceMax", (r, n) => { let s = []; for (let a = 0; a < r[0].dims.length; a++) (n.indexOf(a) >= 0 || n.length === 0) && s.push(`inputIdx[${a}] = 0;`); return [`${s.join(` `)} value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""]; }), dc = (i, e, o) => je(i, e, o, "ReduceMin", (r, n) => { let s = []; for (let a = 0; a < r[0].dims.length; a++) (n.indexOf(a) >= 0 || n.length === 0) && s.push(`inputIdx[${a}] = 0;`); return [`${s.join(` `)} value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""]; }), hc = (i, e, o) => je(i, e, o, "ReduceProd", () => ["value = 1.0;", "value *= _A(inputIdx);", ""]), mc = (i, e, o) => je(i, e, o, "ReduceLogSum", () => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"]), bc = (i, e, o) => je(i, e, o, "ReduceLogSumSquare", () => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]); }); xc = O(() => { "use strict"; Y(); yc = (i, e) => { let o = B.calculateReshapedDims(e[0].dims, e[1].integerData); return i.session.pack ? [i.reshapePacked(e[0], o)] : [i.reshapeUnpacked(e[0], o)]; }; }); Pi = O(() => { "use strict"; vt(); st(); j(); Tc = { name: "Upsample", inputNames: ["X"], inputTypes: [0] }, Si = (i, e, o) => (Ai(e, o), [i.run({ ...Tc, cacheHint: o.cacheKey, get: () => Ub(i, e, o) }, e)]), wc = (i) => Gr(i, 7), vc = (i) => Gr(i, 9), Gr = (i, e) => { let o = e >= 10, t = i.attributes.getString("mode", "nearest"); if (t !== "nearest" && t !== "linear" && (e < 11 || t !== "cubic")) throw new Error(`unrecognized mode: ${t}`); let r = []; e < 9 && (r = i.attributes.getFloats("scales"), Rn(r, t, o)); let n = i.attributes.getFloat("extrapolation_value", 0), s = e > 10 ? i.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric"; if (["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(s) === -1) throw new Error(`coordinate_transform_mode '${s}' is not supported`); let a = s === "tf_crop_and_resize", u = a, l = t === "nearest" && e >= 11 ? i.attributes.getString("nearest_mode", "round_prefer_floor") : ""; if (["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(l) === -1) throw new Error(`nearest_mode '${l}' is not supported`); let f = i.attributes.getFloat("cubic_coeff_a", -0.75), p = i.attributes.getInt("exclude_outside", 0) !== 0; if (p && t !== "cubic") throw new Error("exclude_outside can be set to 1 only when mode is CUBIC."); let d = e < 11 ? true : t === "nearest" && s === "asymmetric" && l === "floor", y = 0, w = 0, v = 0; return e > 10 ? i.inputs.length > 2 ? (y = 1, w = 2, v = 3) : (w = 1, v = 2) : e === 9 && (w = 1), W({ opset: e, isResize: o, mode: t, scales: r, extrapolationValue: n, coordinateTransformMode: s, useExtrapolation: u, needRoiInput: a, nearestMode: l, cubicCoefficientA: f, excludeOutside: p, useNearest2xOptimization: d, roiInputIdx: y, scalesInputIdx: w, sizesInputIdx: v }); }, Ub = (i, e, o) => { let t = G(i.session.backend.glContext.version), [r, n] = i.calculateTextureWidthAndHeight(e[0].dims, 0), s = e[0].dims.map((v, S) => Math.floor(v * o.scales[S])), [a, u] = i.calculateTextureWidthAndHeight(s, 0), l = s.length, f = new Array(l), p = new Array(l), d = ` int output_pitches[${l}]; int input_pitches[${l}]; `; for (let v = l - 1; v >= 0; v--) f[v] = v === l - 1 ? 1 : f[v + 1] * s[v + 1], p[v] = v === l - 1 ? 1 : p[v + 1] * e[0].dims[v + 1], d += ` output_pitches[${v}] = ${f[v]}; input_pitches[${v}] = ${p[v]}; `; let y = ` float getInputFloat(int index) { vec2 coords = offsetToCoords(index, ${r}, ${n}); float value = getColorAsFloat(${t.texture2D}(X, coords)); return value; } `, w = o.mode === "nearest" ? ` ${y} float process(int indices[${l}]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${u}); ${d} int d, m; for (int dim = 0; dim < ${l}; ++dim) { d = output_index / output_pitches[dim]; m = output_index - d * output_pitches[dim]; output_index = m; if (scales[dim] != 1 && d > 0) { int d2 = d / scales[dim]; m = d - d2 * scales[dim]; d = d2; } input_index += input_pitches[dim] * d; } return getInputFloat(input_index); }` : l === 4 ? ` ${y} float process(int indices[4]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${u}); ${d} int m; int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m / output_pitches[1]; m = m - index_of_dim1 * output_pitches[1]; index_of_dim2 = m / output_pitches[2]; m = m - index_of_dim2 * output_pitches[2]; index_of_dim3 = m; int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; index_of_input_dim2 = index_of_dim2 / scales[2]; y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; index_of_input_dim3 = index_of_dim3 / scales[3]; x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; input_index = index_of_dim0 * input_pitches[0] + index_of_dim1 * input_pitches[1] + index_of_input_dim2 * input_pitches[2] + index_of_input_dim3; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim2 = false; if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) { // It's the end in dimension 2 x01 = x00; end_of_dim2 = true; } else { x01 = getInputFloat(input_index + input_pitches[2]); } if (index_of_input_dim3 == (input_pitches[2] - 1)) { // It's the end in dimension 3 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); }` : ` ${y} float process(int indices[2]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${u}); ${d} int m; int index_of_dim0, index_of_dim1; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m; int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; index_of_input_dim0 = index_of_dim0 / scales[0]; y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; index_of_input_dim1 = index_of_dim1 / scales[1]; x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim0 = false; if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) { // It's the end in dimension 0 x01 = x00; end_of_dim0 = true; } else { x01 = getInputFloat(input_index + input_pitches[0]); } if (index_of_input_dim1 == (input_pitches[0] - 1)) { // It's the end in dimension 1 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); }`; return { ...Tc, output: { dims: s, type: e[0].type, textureType: 0 }, shaderSource: w, variables: [{ name: "scales", type: "int", arrayLength: o.scales.length, data: o.scales.map((v) => Math.ceil(v)) }] }; }, Ai = (i, e) => { if (!i || e.opset < 9 && i.length !== 1 || e.opset >= 9 && e.opset < 11 && i.length !== 2 || e.opset >= 11 && i.length < 2) throw new Error("invalid inputs."); if (e.scales.length > 0 && i[0].dims.length !== e.scales.length) throw new Error("Invalid input shape."); if (i[0].type === "string") throw new Error("Invalid input tensor types."); }, Rn = (i, e, o) => { if (o) { for (let t of i) if (t <= 0) throw new Error("Scale value should be greater than 0."); } else for (let t of i) if (t < 1) throw new Error("Scale value should be greater than or equal to 1."); if ((e === "linear" || e === "cubic") && i.length !== 2 && (i.length !== 4 || i[0] !== 1 || i[1] !== 1)) throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${o ? "Resize" : "Upsample"} opeartor.`); }; }); Oc = O(() => { "use strict"; st(); j(); ue(); We(); Pi(); Ei = { name: "Resize", inputNames: ["A"], inputTypes: [2] }, Di = (i, e, o) => (Ai(e, o), [i.run({ ...Ei, cacheHint: o.cacheKey, get: () => Vb(i, e, o) }, e)]), Ic = (i) => Gr(i, 10), _c = (i) => Gr(i, 11), Vb = (i, e, o) => { let t = G(i.session.backend.glContext.version), [r, n] = zb(e, o); if (r.every((P2) => P2 === 1) && o.coordinateTransformMode !== "tf_crop_and_resize") return { ...Ei, output: { dims: n, type: e[0].type, textureType: 2 }, hasMain: true, shaderSource: `void main() { vec4 v = ${t.texture2D}(X, TexCoords); ${t.output} = v; }` }; let a = n.length; if (a < 2) throw new Error(`output dimension should be at least 2, but got ${a}`); let u = n[a - 2], l = n[a - 1], f = e[0].dims; if (a !== f.length) throw new Error(`output dimension should match input ${f.length}, but got ${a}`); let p = f[a - 2], d = f[a - 1], y = r[a - 2], w = r[a - 1], v = ""; if (o.mode !== "linear") throw new Error(`resize (packed) does not support mode: '${o.mode}'`); switch (o.coordinateTransformMode) { case "asymmetric": v = ` vec4 getSourceFracIndex(ivec4 coords) { return vec4(coords) / scaleWHWH; } `; break; case "half_pixel": v = ` vec4 getSourceFracIndex(ivec4 coords) { return (vec4(coords) + 0.5) / scaleWHWH - 0.5; } `; break; case "pytorch_half_pixel": v = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 fcoords = vec4(coords); return vec4( ${l}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, ${u}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, ${l}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, ${u}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 ); } `; break; case "align_corners": v = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 resized = vec4(${l}.0 - 1.0, ${u}.0 - 1.0, ${l}.0 - 1.0, ${u}.0 - 1.0); vec4 original = vec4(${d}.0 - 1.0, ${p}.0 - 1.0, ${d}.0 - 1.0, ${p}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `; break; default: throw new Error(`resize (packed) does not support coordinateTransformMode: '${o.coordinateTransformMode}'`); } let S = kt(a), L = le(), A2 = ` const vec2 inputWH = vec2(${p}.0, ${d}.0); const vec4 scaleWHWH = vec4(float(${y}), float(${w}), float(${y}), float(${w})); ${L} ${v} float getAValue(int x10, int r, int c, int d) { return getChannel(getA(x10, r, c, d), vec2(c, d)); } void main() { ${S} rc = getOutputCoords(); int batch = rc[0]; int depth = rc[1]; // retrieve the 4 coordinates that is used in the 4 packed output values. ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); // calculate the source index in fraction vec4 sourceFrac = getSourceFracIndex(coords); // get the lower and upper bound of the 4 values that will be packed into one texel. ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); bool hasNextRow = rc.w < ${u - 1}; bool hasNextCol = rc.z < ${l - 1}; // pack x00, x01, x10, x11's top-left corner into one vec4 structure vec4 topLeft = vec4( getAValue(batch, depth, x00.x, x00.y), hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); // pack x00, x01, x10, x11's top-right corner into one vec4 structure vec4 topRight = vec4( getAValue(batch, depth, x00.x, x00.w), hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure vec4 bottomLeft = vec4( getAValue(batch, depth, x00.z, x00.y), hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure vec4 bottomRight = vec4( getAValue(batch, depth, x00.z, x00.w), hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); // calculate the interpolation fraction on u and v direction vec4 frac = vec4(sourceFrac) - floor(sourceFrac); vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); vec4 top = mix(topLeft, topRight, clampFrac.ywyw); vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); vec4 newValue = mix(top, bottom, clampFrac.xxzz); ${t.output} = vec4(newValue); } `; return { ...Ei, output: { dims: n, type: e[0].type, textureType: 2 }, hasMain: true, shaderSource: A2 }; }, zb = (i, e) => { let t = i[0].dims, r = e.scales, n; if (r.length === 0) { let a = i[e.scalesInputIdx]; if (a && a.size !== 0) { if (i[e.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); r = Wb(a, e.mode, e.isResize); } else { let u = i[e.sizesInputIdx]; if (!u || u.size === 0) throw new Error("Either scales or sizes MUST be provided as input."); n = Array.from(u.integerData), r = Hb(n, t, e.mode, e.isResize); } } else if (i[e.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); let s = n || t.map((a, u) => Math.floor(a * r[u])); return [r, s]; }, Wb = (i, e, o) => { let t = Array.from(i.floatData); return Rn(t, e, o), t; }, Hb = (i, e, o, t) => { let r = e.length, n = new Array(r); for (let s = 0, a = r; s < a; s++) if (e[s] === 0) { if (i[s] !== 0) throw new Error("Input dim is zero but required output dim is non-zero."); n[s] = 1; } else n[s] = i[s] / e[s]; return Rn(n, o, t), n; }; }); Ac = O(() => { "use strict"; ze(); Sc = (i, e) => (qb(e), [new bt([e[0].dims.length], "int32", void 0, void 0, new Int32Array(e[0].dims))]), qb = (i) => { if (!i || i.length !== 1) throw new Error("Shape requires 1 input."); }; }); $c = O(() => { "use strict"; vt(); Rr(); Y(); j(); Li = { name: "Slice", inputNames: ["A"], inputTypes: [0] }, Pc = (i, e, o) => (jb(e), [i.run({ ...Li, cacheHint: o.cacheKey, get: () => Dc(i, e[0], o) }, e)]), Ec = (i) => { let e = i.attributes.getInts("starts"), o = i.attributes.getInts("ends"), t = i.attributes.getInts("axes", []); return W({ starts: e, ends: o, axes: t }); }, Dc = (i, e, o) => { let t = o.axes.length === 0 ? e.dims.slice(0).map((p, d) => d) : o.axes, r = B.normalizeAxes(t, e.dims.length), n = o.starts.map((p, d) => p > e.dims[r[d]] - 1 ? e.dims[r[d]] : B.normalizeAxis(p, e.dims[r[d]])), s = o.ends.map((p, d) => p > e.dims[r[d]] - 1 ? e.dims[r[d]] : B.normalizeAxis(p, e.dims[r[d]])), a = e.dims.slice(), u = []; for (let p = 0; p < r.length; p++) a[r[p]] = s[p] - n[p], n[p] > 0 && u.push(`outputIdx[${r[p]}] += ${n[p]};`); let f = ` float process(int outputIdx[${a.length}]) { ${u.join(` `)} return _A(outputIdx); }`; return { ...Li, output: { dims: a, type: e.type, textureType: 0 }, shaderSource: f }; }, jb = (i) => { if (!i || i.length !== 1) throw new Error("Slice requires 1 input."); if (Ae.indexOf(i[0].type) === -1) throw new Error("Invalid input type."); }, Lc = (i, e) => { Kb(e); let o = Xb(i, e); return [i.run({ ...Li, cacheHint: o.cacheKey, get: () => Dc(i, e[0], o) }, [e[0]])]; }, Xb = (i, e) => { if (!i.session.isInitializer(e[1].dataId) || !i.session.isInitializer(e[2].dataId) || e.length >= 4 && !i.session.isInitializer(e[3].dataId) || e.length >= 5 && !i.session.isInitializer(e[4].dataId)) throw new Error("dynamic slice attributes are not allowed"); if (e.length >= 5 && e[4].integerData.some((s) => s !== 1)) throw new Error("currently non-1 steps is not supported for Slice"); let o = Array.from(e[1].integerData), t = Array.from(e[2].integerData), r = e.length >= 4 ? Array.from(e[3].integerData) : [], n = `${r};${o};${t}`; return { starts: o, ends: t, axes: r, cacheKey: n }; }, Kb = (i) => { if (!i || i.length < 3 || i.length > 5) throw new Error("Invalid input number."); if (i[1].type !== "int32" || i[1].dims.length !== 1) throw new Error("Invalid input type."); if (i[2].type !== "int32" || i[2].dims.length !== 1) throw new Error("Invalid input type."); if (i.length >= 4 && (i[3].type !== "int32" || i[3].dims.length !== 1)) throw new Error("Invalid input type."); if (i.length >= 5 && (i[4].type !== "int32" || i[4].dims.length !== 1)) throw new Error("Invalid input type."); }; }); Vc = O(() => { "use strict"; vt(); Y(); st(); j(); Fn(); kc = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [0] }, Bc = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [0, 0] }, Fc = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [0, 0, 0] }, Cc = (i, e, o) => { Uc(e); let t = e[0].dims.slice(), r = B.normalizeAxis(o.axis, t.length), n = B.sizeToDimension(t, r), s = B.sizeFromDimension(t, r); return Mc(i, e, o, n, s); }, Nc = (i) => W({ axis: i.attributes.getInt("axis", 1) }), Rc = (i) => W({ axis: i.attributes.getInt("axis", -1) }), Gc = (i, e, o) => { Uc(e); let t = e[0].dims.slice(), r = B.normalizeAxis(o.axis, t.length), n = t.length, s = r !== n - 1, a = [], u = [], l = [], f; s && (u = Array.from({ length: n }).map((w, v) => v), u[r] = n - 1, u[n - 1] = r, u.map((w) => a.push(t[w])), f = W({ perm: u }), l = qe(i, e, f)); let p = s ? B.sizeToDimension(a, n - 1) : B.sizeToDimension(t, n - 1), d = s ? B.sizeFromDimension(a, n - 1) : B.sizeFromDimension(t, n - 1), y = Mc(i, s ? l : e, o, p, d); return s ? qe(i, y, f) : y; }, Mc = (i, e, o, t, r) => { let n = Jb(i, e[0], t, r, [t]), s = i.run({ ...kc, cacheHint: o.cacheKey, get: () => n }, e), a = Yb(i, e[0], t, r, n.output.dims, [t]), u = i.run({ ...Bc, cacheHint: o.cacheKey, get: () => a }, [e[0], s]), l = Zb(i, e[0], t, r, n.output.dims, a.output.dims); return [i.run({ ...Fc, cacheHint: o.cacheKey, get: () => l }, [e[0], s, u])]; }, Jb = (i, e, o, t, r) => { let [n, s] = i.calculateTextureWidthAndHeight(e.dims, 0), a = r.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (r.length !== 1) throw new Error("Dimensionality of the output should be 1"); if (r[0] !== o) throw new Error("Shape of the output should be equal to logical row count"); let u = G(i.session.backend.glContext.version), l = ` float process(int[${a}] indices) { int logical_row_start_offset = indices[0] * ${t}; float max = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset, ${n}, ${s} ))); for(int i=1; i<${t}; ++i) { float current = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${n}, ${s}))); if(current > max) max = current; } return max; }`; return { ...kc, output: { dims: r, type: e.type, textureType: 0 }, shaderSource: l }; }, Yb = (i, e, o, t, r, n) => { let [s, a] = i.calculateTextureWidthAndHeight(e.dims, 0), u = n.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (n.length !== 1) throw new Error("Dimensionality of the output should be 1"); if (n[0] !== o) throw new Error("Shape of the output should be equal to logical row count"); if (r.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1"); if (r[0] !== o) throw new Error("Shape of the intermediate results should be equal to logical row count"); let l = G(i.session.backend.glContext.version), f = ` float process(int[${u}] indices) { int logical_row_start_offset = indices[0] * ${t}; float norm_factor = 0.0; float max = _Max(indices); for(int i=0; i<${t}; ++i) { norm_factor += exp(getColorAsFloat(${l.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${s}, ${a}))) - max); } return norm_factor; }`; return { ...Bc, output: { dims: n, type: e.type, textureType: 0 }, shaderSource: f }; }, Zb = (i, e, o, t, r, n) => { let [s, a] = i.calculateTextureWidthAndHeight(e.dims, 0), u = e.dims.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (r.length !== 1 || n.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1"); if (r[0] !== o || n[0] !== o) throw new Error("Shape of the intermediate results should be equal to logical row count"); let l = ` float process(int[${u}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) int offset = coordsToOffset(TexCoords, ${s}, ${a}); //determine the logical row for this index int logical_row_index[1]; logical_row_index[0] = offset / ${t}; float norm_factor = _Norm(logical_row_index); // avoid possible division by 0 // if norm_facor is 0, all elements are zero // if so, return 0 if(norm_factor == 0.0) return 0.0; return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; }`; return { ...Fc, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: l }; }, Uc = (i) => { if (!i || i.length !== 1) throw new Error("Softmax requires 1 input."); if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("Invalid input type"); }; }); qc = O(() => { "use strict"; vt(); Y(); j(); zc = { name: "Split", inputNames: ["A"], inputTypes: [0] }, Wc = (i, e, o) => { eg(e); let t = B.normalizeAxis(o.axis, e[0].dims.length), r = Qb(i, e, t, o), n = []; for (let s = 0; s < r; ++s) n.push(i.run({ ...zc, cacheHint: `${o.cacheKey};${s}`, get: () => tg(i, e[0], o, t, s) }, e)); return n; }, Hc = (i) => { let e = i.attributes.getInt("axis", 0), o = i.attributes.getInts("split", []), t = i.outputs.length; return W({ axis: e, split: o, numOutputs: t }); }, Qb = (i, e, o, t) => { let [, r] = $r.splitShape(e[0].dims, o, t.split, t.numOutputs); return r.length; }, tg = (i, e, o, t, r) => { let [n, s] = $r.splitShape(e.dims, t, o.split, o.numOutputs), a = s[r], u = n[r], f = ` float process(int indices[${u.length}]) { indices[${t}] += ${a}; return _A(indices); } `; return { ...zc, cacheHint: `${o.cacheKey}:${r}`, output: { dims: u, type: e.type, textureType: 0 }, shaderSource: f }; }, eg = (i) => { if (!i || i.length !== 1) throw new Error("Split requires one input."); if (i[0].type !== "int8" && i[0].type !== "uint8" && i[0].type !== "int16" && i[0].type !== "uint16" && i[0].type !== "int32" && i[0].type !== "uint32" && i[0].type !== "float32" && i[0].type !== "float64" && i[0].type !== "bool") throw new Error("Invalid input type."); }; }); Kc = O(() => { "use strict"; Y(); $i = (i, e, o) => { rg(e); let t = B.squeezeShape(e[0].dims, o); return [i.reshapeUnpacked(e[0], t)]; }, jc = (i, e) => (ng(e), $i(i, [e[0]], Array.from(e[1].integerData))), Xc = (i) => i.attributes.getInts("axes"), rg = (i) => { if (!i || i.length !== 1) throw new Error("Squeeze requires 1 input."); if (i[0].type === "string") throw new Error("invalid input tensor types."); }, ng = (i) => { if (!i || i.length !== 2) throw new Error("Squeeze requires 2 inputs."); if (i[1].type !== "int32") throw new Error("Invalid input type."); }; }); Yc = O(() => { "use strict"; st(); j(); Jc = (i, e) => { ig(e); let o = { name: "Sum", inputNames: e.map((r, n) => `X${n}`), inputTypes: new Array(e.length).fill(0) }; return [i.run({ ...o, get: () => og(i, e, o) }, e)]; }, og = (i, e, o) => { let t = G(i.session.backend.glContext.version), r = e[0].dims.slice(), s = ` void main() { vec4 result = ${e.map((a, u) => `${t.texture2D}(X${u},TexCoords)`).join(" + ")}; ${t.output} = result; } `; return { ...o, output: { dims: r, type: e[0].type, textureType: 0 }, hasMain: true, shaderSource: s }; }, ig = (i) => { if (!i || i.length === 0) throw new Error("Sum requires inputs."); let e = i[0].dims.length; for (let o = 1; o < i.length; o++) { if (e !== i[o].dims.length) throw new Error("Input shapes are mismatched."); for (let t = 0; t < e; t++) if (i[0].dims[t] !== i[o].dims[t]) throw new Error("Input shapes are not matched."); } if (i[0].type !== "float32" && i[0].type !== "float64") throw new Error("Invalid input type."); for (let o = 1; o < i.length; o++) if (i[0].type !== i[o].type) throw new Error("Input types are not matched."); }; }); Qc = O(() => { "use strict"; Rr(); j(); Zc = (i, e) => { sg(e); let o = { name: "Tile", inputNames: ["A"], inputTypes: [0] }; return [i.run({ ...o, get: () => ag(i, e, o) }, e)]; }, ag = (i, e, o) => { let t = e[0].dims.slice(), r = new Array(t.length), n = []; for (let u = 0; u < t.length; u++) r[u] = t[u] * e[1].numberData[u], n.push(`inputIdx[${u}] = int(mod(float(outputIdx[${u}]), ${t[u]}.));`); let s = r.length, a = ` float process(int outputIdx[${s}]) { int inputIdx[${s}]; ${n.join(` `)} return _A(inputIdx); } `; return { ...o, output: { dims: r, type: e[0].type, textureType: 0 }, shaderSource: a }; }, sg = (i) => { if (!i || i.length !== 2) throw new Error("Tile requires 2 input."); if (i[1].dims.length !== 1) throw new Error("The second input shape must 1 dimension."); if (i[1].dims[0] !== i[0].dims.length) throw new Error("Invalid input shape."); if (Ae.indexOf(i[0].type) === -1) throw new Error("Invalid input type."); if (i[1].type !== "int32" && i[1].type !== "int16") throw new Error("Invalid repeat type."); }; }); rp = O(() => { "use strict"; Y(); ki = (i, e, o) => { ug(e); let t = B.unsqueezeShape(e[0].dims, o); return [i.reshapeUnpacked(e[0], t)]; }, tp = (i, e) => (lg(e), ki(i, [e[0]], Array.from(e[1].integerData))), ep = (i) => i.attributes.getInts("axes"), ug = (i) => { if (!i || i.length !== 1) throw new Error("Unsqueeze requires 1 input."); if (i[0].type === "string") throw new Error("invalid input tensor types."); }, lg = (i) => { if (!i || i.length !== 2) throw new Error("Unsqueeze requires 2 inputs."); if (i[1].type !== "int32") throw new Error("Invalid input type."); }; }); op = O(() => { "use strict"; dl(); Sl(); El(); Fl(); $n(); xf(); Of(); Pf(); Lf(); Ff(); Rf(); Vf(); qf(); kn(); Jf(); lc(); gc(); xc(); Oc(); Ac(); $c(); Vc(); qc(); Kc(); Yc(); Qc(); Fn(); bi(); rp(); Pi(); np = [["Abs", "", "6+", Cl], ["Acos", "", "7+", Nl], ["Add", "", "7+", hl], ["And", "", "7+", ml], ["Asin", "", "7+", Rl], ["Atan", "", "7+", Gl], ["AveragePool", "", "7+", Zf, Qf], ["BatchNormalization", "", "7+", cl, pl], ["Cast", "", "6+", Al, Pl], ["Ceil", "", "6+", Vl], ["Clip", "", "6-10", hi, Ml], ["Clip", "", "11+", Ul], ["Concat", "", "4+", $l, Bl], ["Conv", "", "1+", vi, Ii], ["ConvTranspose", "", "1+", gf, yf], ["Cos", "", "7+", zl], ["Div", "", "7+", bl], ["Dropout", "", "7+", mi], ["DepthToSpace", "", "1+", If2, _f], ["Equal", "", "7+", gl], ["Elu", "", "6+", Wl, Hl], ["Exp", "", "6+", ql], ["Flatten", "", "1+", Sf, Af], ["Floor", "", "6+", jl], ["FusedConv", "com.microsoft", "1+", vi, Ii], ["Gather", "", "1+", Ef, Df], ["Gemm", "", "7-10", _i, kf], ["Gemm", "", "11+", _i, Bf], ["GlobalAveragePool", "", "1+", ec, rc], ["GlobalMaxPool", "", "1+", sc], ["Greater", "", "7+", yl], ["Identity", "", "1+", mi], ["ImageScaler", "", "1+", Cf, Nf], ["InstanceNormalization", "", "6+", Mf, Uf], ["LeakyRelu", "", "6+", Xl, Kl], ["Less", "", "7+", xl], ["LRN", "", "1+", zf, Wf], ["Log", "", "6+", Jl], ["MatMul", "", "1+", ff, cf], ["MaxPool", "", "1+", nc, oc], ["Mul", "", "7+", Tl], ["Neg", "", "6+", Yl], ["Not", "", "1+", Zl], ["Or", "", "7+", wl], ["Pad", "", "2-10", Oi, jf], ["Pad", "", "11+", Xf, Kf], ["Pow", "", "7+", vl], ["PRelu", "", "7+", Il], ["ReduceLogSum", "", "1+", mc, Pe], ["ReduceMax", "", "1+", pc, Pe], ["ReduceMean", "", "1+", cc, Pe], ["ReduceMin", "", "1+", dc, Pe], ["ReduceProd", "", "1+", hc, Pe], ["ReduceSum", "", "1-12", fc, Pe], ["ReduceSumSquare", "", "1+", bc, Pe], ["Relu", "", "6+", Ql], ["Reshape", "", "5+", yc], ["Resize", "", "10", Di, Ic], ["Resize", "", "11+", Di, _c], ["Shape", "", "1+", Sc], ["Sigmoid", "", "6+", tf], ["Sin", "", "7+", ef], ["Slice", "", "10+", Lc], ["Slice", "", "1-9", Pc, Ec], ["Softmax", "", "1-12", Cc, Nc], ["Softmax", "", "13+", Gc, Rc], ["Split", "", "2-12", Wc, Hc], ["Sqrt", "", "6+", rf], ["Squeeze", "", "1-12", $i, Xc], ["Squeeze", "", "13+", jc], ["Sub", "", "7+", _l], ["Sum", "", "6+", Jc], ["Tan", "", "7+", nf], ["Tanh", "", "6+", of], ["Tile", "", "6+", Zc], ["Transpose", "", "1+", qe, wf], ["Upsample", "", "7-8", Si, wc], ["Upsample", "", "9", Si, vc], ["Unsqueeze", "", "1-12", ki, ep], ["Unsqueeze", "", "13+", tp], ["Xor", "", "7+", Ol]]; }); sp = O(() => { "use strict"; ip = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm, fg = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"; }); Bi = O(() => { "use strict"; Mt(); Y(); Gn = class { constructor(e) { this.maxTextureSize = e; } computeTextureWH(e, o) { let t = this.computeTexture(e, o); return o && o.isPacked && (t[0] /= 2, t[1] /= 2), o && o.reverseWH ? [t[1], t[0]] : t; } computeTexture(e, o) { let t = o && o.isPacked; if (e.length === 0) return t ? [2, 2] : [1, 1]; let r = this.maxTextureSize; if (o && o.breakAxis !== void 0) { let a = o.breakAxis >= e.length ? 1 : e.slice(o.breakAxis).reduce((l, f) => l * f), u = o.breakAxis <= 0 ? 1 : e.slice(0, o.breakAxis).reduce((l, f) => l * f); if (a > r || u > r) tt.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${e}, breakAxis:${o.breakAxis}`); else return [a, u]; } let n = e.slice(0); t && (r = r * 2, n = n.map((a, u) => u >= n.length - 2 ? n[u] % 2 === 0 ? n[u] : n[u] + 1 : n[u]), n.length === 1 && (n = [2, n[0]])), n.length !== 2 && (n = hr(n).newShape); let s = dg(n); return n.length <= 1 && s <= r ? [1, s] : n.length === 2 && n[0] <= r && n[1] <= r ? n : n.length === 3 && n[0] * n[1] <= r && n[2] <= r ? [n[0] * n[1], n[2]] : n.length === 3 && n[0] <= r && n[1] * n[2] <= r ? [n[0], n[1] * n[2]] : n.length === 4 && n[0] * n[1] * n[2] <= r && n[3] <= r ? [n[0] * n[1] * n[2], n[3]] : n.length === 4 && n[0] <= r && n[1] * n[2] * n[3] <= r ? [n[0], n[1] * n[2] * n[3]] : t ? up(s / 4).map((a) => a * 2) : up(s); } }; }); lp = O(() => { "use strict"; Y(); be(); st(); Bi(); ue(); Mn = class extends Wt { constructor(o) { super(o); } getFunctions() { return { ...this.offsetToCoords(), ...this.coordsToOffset(), ...this.toVec(), ...this.valueFrom(), ...this.getCommonUtilFuncs(), ...this.getInputsSamplingSnippets(), ...this.getOutputSamplingSnippet() }; } getCustomTypes() { return {}; } offsetToCoords() { let o = "offsetToCoords"; return { offsetToCoords: new k(` vec2 ${o}(int offset, int width, int height) { int t = offset / width; int s = offset - t*width; vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); return coords; } `) }; } coordsToOffset() { let o = "coordsToOffset"; return { coordsToOffset: new k(` int ${o}(vec2 coords, int width, int height) { float s = coords.s * float(width); float t = coords.t * float(height); int offset = int(t) * width + int(s); return offset; } `) }; } getOutputSamplingSnippet() { let o = this.context.outputTextureLayout; return o.isPacked ? this.getPackedOutputSamplingSnippet(o) : this.getUnpackedOutputSamplingSnippet(o); } getPackedOutputSamplingSnippet(o) { let t = o.unpackedShape, r = [o.width, o.height], n = {}, s = "getOutputCoords"; switch (t.length) { case 0: n[s] = this.getOutputScalarCoords(); break; case 1: n[s] = this.getOutputPacked1DCoords(t, r); break; case 2: n[s] = this.getOutputPacked2DCoords(t, r); break; case 3: n[s] = this.getOutputPacked3DCoords(t, r); break; default: n[s] = this.getOutputPackedNDCoords(t, r); } let u = ` void setOutput(vec4 val) { ${G(this.context.glContext.version).output} = val; } `, l = "floatTextureSetRGBA"; return n[l] = new k(u), n; } getUnpackedOutputSamplingSnippet(o) { let t = o.unpackedShape, r = [o.width, o.height], n = {}, s = "getOutputCoords"; switch (t.length) { case 0: n[s] = this.getOutputScalarCoords(); break; case 1: n[s] = this.getOutputUnpacked1DCoords(t, r); break; case 2: n[s] = this.getOutputUnpacked2DCoords(t, r); break; case 3: n[s] = this.getOutputUnpacked3DCoords(t, r); break; case 4: n[s] = this.getOutputUnpacked4DCoords(t, r); break; case 5: n[s] = this.getOutputUnpacked5DCoords(t, r); break; case 6: n[s] = this.getOutputUnpacked6DCoords(t, r); break; default: throw new Error(`Unsupported output dimensionality: ${t.length}`); } let u = ` void setOutput(float val) { ${G(this.context.glContext.version).output} = vec4(val, 0, 0, 0); } `, l = "floatTextureSetR"; return n[l] = new k(u), n; } getOutputScalarCoords() { return new k(` int getOutputCoords() { return 0; } `); } getOutputPacked1DCoords(o, t) { let r = t, n = ""; return r[0] === 1 ? (n = ` int getOutputCoords() { return 2 * int(TexCoords.y * ${r[1]}.0); } `, new k(n)) : r[1] === 1 ? (n = ` int getOutputCoords() { return 2 * int(TexCoords.x * ${r[0]}.0); } `, new k(n)) : (n = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${r[0]}, ${r[1]})); return 2 * (resTexRC.y * ${r[0]} + resTexRC.x); } `, new k(n)); } getOutputPacked2DCoords(o, t) { let r = ""; if (Ge.arraysEqual(o, t)) return r = ` ivec2 getOutputCoords() { return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); } `, new k(r); let n = t, s = Math.ceil(o[1] / 2); return r = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; // reverse r and c order for packed texture int r = imod(index, ${s}) * 2; int c = 2 * (index / ${s}); return ivec2(r, c); } `, new k(r); } getOutputPacked3DCoords(o, t) { let r = [t[0], t[1]], n = Math.ceil(o[2] / 2), s = n * Math.ceil(o[1] / 2), a = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${r[0]}, ${r[1]})); int index = resTexRC.y * ${r[0]} + resTexRC.x; int b = index / ${s}; index -= b * ${s}; // reverse r and c order for packed texture int r = imod(index, ${n}) * 2; int c = 2 * (index / ${n}); return ivec3(b, r, c); } `; return new k(a); } getOutputPackedNDCoords(o, t) { let r = [t[0], t[1]], n = Math.ceil(o[o.length - 1] / 2), s = n * Math.ceil(o[o.length - 2] / 2), a = s, u = "", l = "b, r, c"; for (let p = 2; p < o.length - 1; p++) a *= o[o.length - p - 1], u = ` int b${p} = index / ${a}; index -= b${p} * ${a}; ` + u, l = `b${p}, ` + l; let f = ` ivec${o.length} getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${r[0]}, ${r[1]})); int index = resTexRC.y * ${r[0]} + resTexRC.x; ${u} int b = index / ${s}; index -= b * ${s}; // reverse r and c order for packed texture int r = imod(index, ${n}) * 2; int c = 2 * (index / ${n}); return ivec${o.length}(${l}); } `; return new k(f); } getOutputUnpacked1DCoords(o, t) { let r = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); return resTexRC.y * ${t[0]} + resTexRC.x; } `; return new k(r); } getOutputUnpacked2DCoords(o, t) { let r = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; int r = index / ${o[1]}; int c = index - r * ${o[1]}; return ivec2(r, c); } `; return new k(r); } getOutputUnpacked3DCoords(o, t) { let r = "", n = o.length, s = null; n < 2 && (s = []), s = new Array(n - 1), s[n - 2] = o[n - 1]; for (let l = n - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let a = ["r", "c", "d"], u = s.map((l, f) => { let p = `int ${a[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${a[f + 1]} = index - ${a[f]} * ${l}` : `index -= ${a[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return r = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec3(r, c, d); } `, new k(r); } getOutputUnpacked4DCoords(o, t) { let r = "", n = o.length, s = null; n < 2 && (s = []), s = new Array(n - 1), s[n - 2] = o[n - 1]; for (let l = n - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let a = ["r", "c", "d", "d2"], u = s.map((l, f) => { let p = `int ${a[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${a[f + 1]} = index - ${a[f]} * ${l}` : `index -= ${a[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return r = ` ivec4 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec4(r, c, d, d2); } `, new k(r); } getOutputUnpacked5DCoords(o, t) { let r = "", n = o.length, s = null; n < 2 && (s = []), s = new Array(n - 1), s[n - 2] = o[n - 1]; for (let l = n - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let a = ["r", "c", "d", "d2", "d3"], u = s.map((l, f) => { let p = `int ${a[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${a[f + 1]} = index - ${a[f]} * ${l}` : `index -= ${a[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return r = ` ivec5 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec5(r, c, d, d2, d3); } `, new k(r); } getOutputUnpacked6DCoords(o, t) { let r = "", n = o.length, s = null; n < 2 && (s = []), s = new Array(n - 1), s[n - 2] = o[n - 1]; for (let l = n - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let a = ["r", "c", "d", "d2", "d3", "d4"], u = s.map((l, f) => { let p = `int ${a[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${a[f + 1]} = index - ${a[f]} * ${l}` : `index -= ${a[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return r = ` ivec6 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec6(r, c, d, d2, d3, d4); } `, new k(r); } getCommonUtilFuncs() { let o = {}, t = "uvFromFlat"; o[t] = new k(` vec2 uvFromFlat(int texNumR, int texNumC, int index) { int texC = index / texNumR; int texR = index - texC * texNumR; // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to // v. return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); } `), t = "packedUVfrom1D", o[t] = new k(` vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { int texelIndex = index / 2; int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "packedUVfrom2D", o[t] = new k(` vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "packedUVfrom3D", o[t] = new k(` vec2 packedUVfrom3D(int texNumR, int texNumC, int texelsInBatch, int texelsInLogicalRow, int b, int row, int col) { int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); int texR = index / texNumC; int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "sampleTexture"; let r = G(this.context.glContext.version); return o[t] = new k(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${r.texture2D}(textureSampler, uv).r; }`), o; } getInputsSamplingSnippets() { let o = {}, t = this.context.outputTextureLayout; return this.context.programInfo.inputNames.forEach((r, n) => { let s = this.context.inputTextureLayouts[n], a = On(r); s.isPacked ? o[a] = this.getPackedSamplerFromInput(a, r, s) : o[a] = this.getUnpackedSamplerFromInput(a, r, s); let u = Ku(r); s.unpackedShape.length <= t.unpackedShape.length && (s.isPacked ? o[u] = this.getPackedSamplerAtOutputCoords(u, s, t, r) : o[u] = this.getUnpackedSamplerAtOutputCoords(u, s, t, r)); }), o; } getPackedSamplerAtOutputCoords(o, t, r, n) { let s = t.unpackedShape, a = r.unpackedShape, l = On(n), f = s.length, p = a.length, d = $t.getBroadcastDims(s, a), y = kt(p), w = p - f, v, S = ee(); f === 0 ? v = "" : p < 2 && d.length >= 1 ? v = "coords = 0;" : v = d.map((Et3) => `coords.${S[Et3 + w]} = 0;`).join(` `); let L = ""; p < 2 && f > 0 ? L = "coords" : L = s.map((Et3, It2) => `coords.${S[It2 + w]}`).join(", "); let A2 = "return outputValue;", M3 = B.size(s) === 1, ut2 = B.size(a) === 1; if (f === 1 && !M3 && !ut2) A2 = ` return vec4(outputValue.xy, outputValue.xy); `; else if (M3 && !ut2) p === 1 ? A2 = ` return vec4(outputValue.x, outputValue.x, 0., 0.); ` : A2 = ` return vec4(outputValue.x); `; else if (d.length) { let Et3 = f - 2, It2 = f - 1; d.indexOf(Et3) > -1 && d.indexOf(It2) > -1 ? A2 = "return vec4(outputValue.x);" : d.indexOf(Et3) > -1 ? A2 = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf(It2) > -1 && (A2 = "return vec4(outputValue.xx, outputValue.zz);"); } let xt3 = ` int lastDim = coords.${S[p - 1]}; coords.${S[p - 1]} = coords.${S[p - 2]}; coords.${S[p - 2]} = lastDim; `, et2 = ` vec4 ${o}() { ${y} coords = getOutputCoords(); ${xt3} ${v} vec4 outputValue = ${l}(${L}); ${A2} } `; return new k(et2, ["coordinates.getOutputCoords"]); } getUnpackedSamplerAtOutputCoords(o, t, r, n) { let s = [r.width, r.height], a = [t.width, t.height], u = t.unpackedShape.length, l = r.unpackedShape.length, f = t.unpackedShape, p = r.unpackedShape, d = On(n); if (u === l && Ge.arraysEqual(a, s)) { let M3 = ` float ${o}() { return sampleTexture(${n}, TexCoords); } `; return new k(M3, ["coordinates.sampleTexture"]); } let y = kt(l), w = $t.getBroadcastDims(f, p), v = l - u, S, L = ee(); u === 0 ? S = "" : l < 2 && w.length >= 1 ? S = "coords = 0;" : S = w.map((M3) => `coords.${L[M3 + v]} = 0;`).join(` `); let A2 = ""; l < 2 && u > 0 ? A2 = "coords" : A2 = t.unpackedShape.map((M3, V3) => `coords.${L[V3 + v]}`).join(", "); let P2 = ` float ${o}() { ${y} coords = getOutputCoords(); ${S} return ${d}(${A2}); } `; return new k(P2, ["coordinates.getOutputCoords"]); } getPackedSamplerFromInput(o, t, r) { switch (r.unpackedShape.length) { case 0: return this.getPackedSamplerScalar(o, t); case 1: return this.getPackedSampler1D(o, t, r); case 2: return this.getPackedSampler2D(o, t, r); case 3: return this.getPackedSampler3D(o, t, r); default: return this.getPackedSamplerND(o, t, r); } } getUnpackedSamplerFromInput(o, t, r) { let n = r.unpackedShape; switch (n.length) { case 0: return this.getUnpackedSamplerScalar(o, t, r); case 1: return this.getUnpackedSampler1D(o, t, r); case 2: return this.getUnpackedSampler2D(o, t, r); case 3: return this.getUnpackedSampler3D(o, t, r); case 4: return this.getUnpackedSampler4D(o, t, r); case 5: return this.getUnpackedSampler5D(o, t, r); case 6: return this.getUnpackedSampler6D(o, t, r); default: throw new Error(`Unsupported dimension ${n.length}-D`); } } getPackedSamplerScalar(o, t) { let r = G(this.context.glContext.version), n = ` vec4 ${o}() { return ${r.texture2D}(${t}, halfCR); } `; return new k(n); } getPackedSampler1D(o, t, r) { let n = [r.width, r.height], s = [n[1], n[0]], a = G(this.context.glContext.version), l = `vec4 ${o}(int index) { vec2 uv = packedUVfrom1D( ${s[0]}, ${s[1]}, index); return ${a.texture2D}(${t}, uv); }`; return new k(l, ["coordinates.packedUVfrom1D"]); } getPackedSampler2D(o, t, r) { let n = r.unpackedShape, s = [r.width, r.height], a = G(this.context.glContext.version), u = s[0], l = s[1]; if (s != null && Ge.arraysEqual(n, s)) { let w = `vec4 ${o}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${u}.0); return ${a.texture2D}(${t}, uv); }`; return new k(w); } let f = s, p = Math.ceil(n[1] / 2), y = `vec4 ${o}(int row, int col) { vec2 uv = packedUVfrom2D(${f[1]}, ${f[0]}, ${p}, row, col); return ${a.texture2D}(${t}, uv); }`; return new k(y, ["coordinates.packedUVfrom2D"]); } getPackedSampler3D(o, t, r) { let n = r.unpackedShape, s = [r.width, r.height], a = [s[0], s[1]], u = G(this.context.glContext.version); if (n[0] === 1) { let v = n.slice(1), S = [1, 2], L = lr(n, v), A2 = ["b", "row", "col"], P2 = JSON.parse(JSON.stringify(r)); P2.unpackedShape = L; let M3 = this.getPackedSamplerFromInput(o, t, P2), ut2 = `${M3.routineBody} vec4 ${o}(int b, int row, int col) { return ${o}(${fr(A2, S)}); } `; return new k(ut2, M3.dependencies); } let l = a[0], f = a[1], p = Math.ceil(n[2] / 2), d = p * Math.ceil(n[1] / 2), w = `vec4 ${o}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${f}, ${l}, ${d}, ${p}, b, row, col); return ${u.texture2D}(${t}, uv);}`; return new k(w, ["coordinates.packedUVfrom3D"]); } getPackedSamplerND(o, t, r) { let n = r.unpackedShape, s = n.length, a = [r.width, r.height], u = G(this.context.glContext.version), l = [a[0], a[1]], f = l[1], p = l[0], d = Math.ceil(n[s - 1] / 2), y = d * Math.ceil(n[s - 2] / 2), w = "int b, int row, int col", v = `b * ${y} + (row / 2) * ${d} + (col / 2)`; for (let A2 = 2; A2 < s - 1; A2++) w = `int b${A2}, ` + w, y *= n[s - A2 - 1], v = `b${A2} * ${y} + ` + v; let L = `vec4 ${o}(${w}) { int index = ${v}; int texR = index / ${p}; int texC = index - texR * ${p}; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${f}); return ${u.texture2D}(${t}, uv); }`; return new k(L); } getUnpackedSamplerScalar(o, t, r) { let [n, s] = [r.width, r.height]; if (n === 1 && s === 1) { let u = ` float ${o}() { return sampleTexture(${t}, halfCR); } `; return new k(u, ["coordinates.sampleTexture"]); } let a = ` float ${o}() { int offset_${t} = coordsToOffset(TexCoords, ${n}, ${s}); vec2 uv = uvFromFlat(${n}, ${s}, offset_${t}); return sampleTexture(${t}, uv); } `; return new k(a, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler1D(o, t, r) { let n = r.width, s = r.height; if (s === 1 && n === 1) { let u = ` float ${o}(int index) { return sampleTexture(${t}, halfCR); } `; return new k(u, ["coordinates.sampleTexture"]); } if (s === 1) { let u = ` float ${o}(int index) { vec2 uv = vec2((float(index) + 0.5) / ${n}.0, 0.5); return sampleTexture(${t}, uv); } `; return new k(u, ["coordinates.sampleTexture"]); } if (n === 1) { let u = ` float ${o}(int index) { vec2 uv = vec2(0.5, (float(index) + 0.5) / ${s}.0); return sampleTexture(${t}, uv); } `; return new k(u, ["coordinates.sampleTexture"]); } let a = ` float ${o}(int index) { vec2 uv = uvFromFlat(${n}, ${s}, index); return sampleTexture(${t}, uv); } `; return new k(a, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler2D(o, t, r) { let n = r.unpackedShape, s = [r.height, r.width]; if (s != null && Ge.arraysEqual(n, s)) { let y = s[1], w = s[0], v = ` float ${o}(int row, int col) { vec2 uv = (vec2(row, col) + halfCR) / vec2(${y}.0, ${w}.0); return sampleTexture(${t}, uv); } `; return new k(v, ["coordinates.sampleTexture"]); } let { newShape: a, keptDims: u } = hr(n), l = a; if (l.length < n.length) { let y = lr(n, l), w = JSON.parse(JSON.stringify(r)); w.unpackedShape = y; let v = ["col", "row"], S = ` ${this.getUnpackedSamplerFromInput(o, t, w).routineBody} float ${o}(int row, int col) { return ${o}(${fr(v, u)}); } `; return new k(S, ["coordinates.sampleTexture"]); } let f = s[1], p = s[0]; if (p === 1) { let y = ` float ${o}(int row, int col) { int offset_${t} = coordsToOffset(TexCoords, ${f}, ${p}); float index = dot(vec3(row, col, offset_${t}), vec3(${n[1]}, 1, 1)); vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0); return sampleTexture(${t}, uv); } `; return new k(y, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } if (f === 1) { let y = ` float ${o}(int row, int col) { int offset_${t} = coordsToOffset(TexCoords, ${f}, ${p}); float index = dot(vec3(row, col, offset_${t}), vec3(${n[1]}, 1, 1)); vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5); return sampleTexture(${t}, uv); } `; return new k(y, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } let d = ` float ${o}(int row, int col) { int index = col * ${n[1]} + row; vec2 uv = uvFromFlat(${f}, ${p}, index); return sampleTexture(${t}, uv); } `; return new k(d, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler3D(o, t, r) { let n = r.unpackedShape, s = n[1] * n[2], a = n[2], { newShape: u, keptDims: l } = hr(n), f = u; if (f.length < n.length) { let w = lr(n, f), v = ["batch", "col", "row"], S = JSON.parse(JSON.stringify(r)); S.unpackedShape = w; let L = this.getUnpackedSamplerFromInput(o, t, S), A2 = l.reverse(), P2 = ` ${L.routineBody} float ${o}(int batch, int row, int col) { return ${o}(${fr(v, A2)}); } `; return new k(P2, L.dependencies); } let p = r.width, d = r.height, y = ` float ${o}(int depth, int row, int col) { // Explicitly use integer operations as dot() only works on floats. int index = depth * ${s} + col * ${a} + row; vec2 uv = uvFromFlat(${p}, ${d}, index); return sampleTexture(${t}, uv); } `; return new k(y, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler4D(o, t, r) { let n = r.unpackedShape, s = n[3], a = n[2] * s, u = n[1] * a, l = r.width, f = r.height, p = ` float ${o}(int row, int col, int depth, int depth2) { int index = row * ${u} + col * ${a} + depth2 * ${s} + depth; vec2 uv = uvFromFlat(${l}, ${f}, index); return sampleTexture(${t}, uv); } `; return new k(p, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler5D(o, t, r) { let n = r.unpackedShape, s = n[4], a = n[3] * s, u = n[2] * a, l = n[1] * u, { newShape: f, keptDims: p } = hr(n); if (f.length < n.length) { let v = lr(n, f), S = ["row", "col", "depth", "depth2", "depth3"], L = JSON.parse(JSON.stringify(r)); L.unpackedShape = v; let A2 = ` ${this.getUnpackedSamplerFromInput(o, t, L).routineBody} float ${o}(int row, int col, int depth, int depth2, int depth3) { return ${o}(${fr(S, p)}); } `; return new k(A2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } let d = r.width, y = r.height, w = ` float ${o}(int row, int col, int depth, int depth2, int depth3) { int index = row * ${l} + col * ${u} + depth * ${a} + depth3 * ${s} + depth2; vec2 uv = uvFromFlat(${d}, ${y}, index); return sampleTexture(${t}, uv); } `; return new k(w, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } getUnpackedSampler6D(o, t, r) { let n = r.unpackedShape, s = n[5], a = n[4] * s, u = n[3] * a, l = n[2] * u, f = n[1] * l, { newShape: p, keptDims: d } = hr(n); if (p.length < n.length) { let S = lr(n, p), L = ["row", "col", "depth", "depth2", "depth3", "depth4"], A2 = JSON.parse(JSON.stringify(r)); A2.unpackedShape = S; let P2 = ` ${this.getUnpackedSamplerFromInput(o, t, A2).routineBody} float ${o}(int row, int col, int depth, int depth2, int depth3, int depth4) { return ${o}(${fr(L, d)}); } `; return new k(P2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } let y = r.width, w = r.height, v = ` float ${o}(int row, int col, int depth, int depth2, int depth3, int depth4) { int index = row * ${f} + col * ${l} + depth * ${u} + depth2 * ${a} + depth3 * ${s} + depth4; vec2 uv = uvFromFlat(${y}, ${w}, index); return sampleTexture(${t}, uv); } `; return new k(v, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } toVec() { let o = this.context.outputTextureLayout, t = o.shape.length, r = o.strides, n = o.width, s = o.height, a = []; for (let l = 0; l < t - 1; ++l) a.push(` c[${l}] = offset / ${r[l]};`), a.push(` offset -= c[${l}] * ${r[l]};`); a.push(` c[${t - 1}] = offset;`); let u = ` void toVec(vec2 texCoords, out int c[${t}]) { int offset = coordsToOffset(texCoords, ${n}, ${s}); ${a.join("")} } void toVec(int offset, out int c[${t}]) { ${a.join("")} } `; return { toVec: new k(u, ["coordinates.coordsToOffset"]) }; } valueFrom() { let o = {}; return this.context.programInfo.inputNames.forEach((t, r) => { let n = this.context.inputTextureLayouts[r], a = (n.unpackedShape.length > 0 ? n.unpackedShape : n.shape).length, u = `_${t}`; o[u] = new k(this.getValueFromSingle(t, a, n.width, n.height, false), [`shapeUtils.indicesToOffset${u}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), u = u + "_T", o[u] = new k(this.getValueFromSingle(t, a, n.width, n.height, true), [`shapeUtils.indicesToOffset${u}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]); }), o; } getValueFromSingle(o, t, r, n, s) { let a = `_${o}`; s && (a = a + "_T"); let u = G(this.context.glContext.version); return ` float ${a}(int m[${t}]) { int offset = indicesToOffset${a}(m); vec2 coords = offsetToCoords(offset, ${r}, ${n}); float value = getColorAsFloat(${u.texture2D}(${o}, coords)); return value; } `; } getPackedValueFrom(o, t, r, n, s) { let a = `_${o}_Pack`; s && (a = a + "_T"); let u = G(this.context.glContext.version); return ` vec4 ${a}(int m[${t}]) { int offset = indicesToOffset_${o}(m); vec2 coords = offsetToCoords(offset, ${r}, ${n}); return ${u.texture2D}(${o}, coords); } `; } }; }); fp = O(() => { "use strict"; be(); Un = class i extends Wt { constructor(e) { super(e); } getFunctions() { return { ...this.encodeFloat32(), ...this.decodeFloat32() }; } getCustomTypes() { return {}; } encodeFloat32() { return { encode: new k(`highp vec4 encode(highp float f) { return vec4(f, 0.0, 0.0, 0.0); } `) }; } decodeFloat32() { return { decode: new k(`highp float decode(highp vec4 rgba) { return rgba.r; } `) }; } encodeUint8() { let e = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { encode: new k(` highp vec4 encode(highp float f) { highp float F = abs(f); highp float Sign = step(0.0,-f); highp float Exponent = floor(log2(F)); highp float Mantissa = (exp2(- Exponent) * F); Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); highp vec4 rgba; rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); ${e} rgba = rgba / 255.0; // values need to be normalized to [0,1] return rgba; } `) }; } decodeUint8() { let e = i.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { decode: new k(` highp float decode(highp vec4 rgba) { rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] ${e} highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); return Result; } `) }; } static isLittleEndian() { let e = new ArrayBuffer(4), o = new Uint32Array(e), t = new Uint8Array(e); if (o[0] = 3735928559, t[0] === 239) return true; if (t[0] === 222) return false; throw new Error("unknown endianness"); } }; }); cp = O(() => { "use strict"; be(); st(); Vn = class extends Wt { constructor(e) { super(e); } getFunctions() { return { ...this.setFragColor(), ...this.getColorAsFloat() }; } getCustomTypes() { return {}; } setFragColor() { let e = G(this.context.glContext.version); return { setFragColor: new k(` void setFragColor(float value) { ${e.output} = encode(value); } `, ["encoding.encode"]) }; } getColorAsFloat() { return { getColorAsFloat: new k(` float getColorAsFloat(vec4 color) { return decode(color); } `, ["encoding.decode"]) }; } }; }); pp = O(() => { "use strict"; be(); zn = class i extends Wt { constructor(e) { super(e); } getFunctions() { return { ...this.bcastIndex(), ...this.bcastMatmulIndex(), ...this.offsetToIndices(), ...this.indicesToOffset(), ...this.incrementIndices() }; } getCustomTypes() { return {}; } bcastIndex() { let e = this.context.outputTextureLayout.shape.length, o = {}; return this.context.programInfo.inputNames.forEach((t, r) => { let n = this.context.inputTextureLayouts[r].unpackedShape; if (n.length <= e) { let s = n.length, a = e - s, u = `bcastIndices_${t}`, l = ""; for (let p = 0; p < s; ++p) l += ` realIndices[${p}] = int( mod(float(bcastedIndices[${a + p}]), ${n[p]}.0) ); `; let f = ` void ${u} (int bcastedIndices[${e}], out int realIndices[${s}]) { ${l} } `; o[u] = new k(f); } }), o; } bcastMatmulIndex() { let e = this.context.outputTextureLayout.shape.length, o = {}; return this.context.programInfo.inputNames.forEach((t, r) => { let n = this.context.inputTextureLayouts[r].shape; if (!(n.length < 2 || n.length > e)) { let s = n.length, a = e - s, u = `bcastMatmulIndices_${t}`, l = ""; for (let p = 0; p < s - 2; ++p) l += ` realIndices[${p}] = int( mod(float(bcastedIndices[${a + p}]), ${n[p]}.0) ); `; let f = ` void ${u}(int bcastedIndices[${e}], out int realIndices[${s}]) { ${l} realIndices[${s - 1}] = bcastedIndices[${e - 1}]; realIndices[${s - 2}] = bcastedIndices[${e - 2}]; } `; o[u] = new k(f); } }), o; } indicesToOffset() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let r = this.context.inputTextureLayouts[t].shape, n = this.context.inputTextureLayouts[t].strides, s = r.length, a = `indicesToOffset_${o}`; e[a] = new k(i.indexToOffsetSingle(a, s, n)), a = `indicesToOffset_${o}_T`, e[a] = new k(i.indexToOffsetSingle(a, s, n.slice().reverse())); }), e; } static indexToOffsetSingle(e, o, t) { let r = ""; for (let n = o - 1; n >= 0; --n) r += ` offset += indices[${n}] * ${t[n]}; `; return ` int ${e}(int indices[${o}]) { int offset = 0; ${r} return offset; } `; } offsetToIndices() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let r = this.context.inputTextureLayouts[t].shape, n = this.context.inputTextureLayouts[t].strides, s = r.length, a = `offsetToIndices_${o}`; e[a] = new k(i.offsetToIndicesSingle(a, s, n)), a = `offsetToIndices_${o}_T`, e[a] = new k(i.offsetToIndicesSingle(a, s, n.slice().reverse())); }), e; } static offsetToIndicesSingle(e, o, t) { let r = []; for (let n = 0; n < o - 1; ++n) r.push(` indices[${n}] = offset / ${t[n]};`), r.push(` offset -= indices[${n}] * ${t[n]};`); return r.push(` indices[${o - 1}] = offset;`), ` void ${e}(int offset, out int indices[${o}]) { ${r.join("")} } `; } incrementIndices() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let r = this.context.inputTextureLayouts[t].shape, n = r.length, s = `incrementIndices_${o}`, a = ""; for (let l = 0; l < n; ++l) a += ` shape[${l}] = ${r[l]};`; let u = ` void ${s}(int axis, out int indices[${n}]) { int shape[${n}]; ${a}; for(int i = ${n} -1 ; i >= 0; --i) { if(i > axis) continue; indices[i] += 1; if(indices[i] < shape[i]) { break; } indices[i] = 0; } } `; e[s] = new k(u); }), e; } }; }); dp = O(() => { "use strict"; be(); Wn = class extends Wt { constructor(e) { super(e); } getCustomTypes() { return {}; } getFunctions() { return { ...this.binaryVecFunctions(), ...this.copyVec(), ...this.setVecItem(), ...this.getVecItem() }; } binaryVecFunctions() { let o = this.context.outputTextureLayout.shape.length, t = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, r = {}; for (let n in t) { let s = `${n}Vec`, a = ""; for (let l = 0; l < o; ++l) a += ` dest[${l}] ${t[n]} src[${l}]; `; let u = ` void ${s}(int src[${o}], out int dest[${o}]) { ${a} } `; r[s] = new k(u); } return r; } copyVec() { let o = this.context.outputTextureLayout.shape.length, t = ""; for (let n = 0; n < o; ++n) t += ` dest[${n}] = src[${n}]; `; let r = ` void copyVec(int src[${o}], out int dest[${o}]) { ${t} } `; return { copyVec: new k(r) }; } setVecItem() { let o = this.context.outputTextureLayout.shape.length, t = ` if(index < 0) index =${o} + index; if (index == 0) m[0] = value; `; for (let n = 1; n < o - 1; ++n) t += ` else if (index == ${n}) m[${n}] = value; `; t += ` else m[${o - 1}] = value; `; let r = ` void setVecItem(out int m[${o}], int index, int value) { ${t} } `; return { setVecItem: new k(r) }; } getVecItem() { let o = this.context.outputTextureLayout.shape.length, t = ` if(index < 0) index = ${o} + index; if (index == 0) return m[0]; `; for (let n = 1; n < o - 1; ++n) t += ` else if (index == ${n}) return m[${n}]; `; t += ` else return m[${o - 1}]; `; let r = ` int getVecItem(int m[${o}], int index) { ${t} } `; return { getVecItem: new k(r) }; } }; }); hp = O(() => { "use strict"; lp(); fp(); cp(); pp(); dp(); Fi = { encoding: Un, fragcolor: Vn, vec: Wn, shapeUtils: zn, coordinates: Mn }; }); mp = O(() => { "use strict"; be(); sp(); hp(); st(); Hn = class { constructor(e, o, t, r) { this.libs = {}; this.glslLibRoutineDependencyGraph = {}; this.context = new En(e, o, t, r), Object.keys(Fi).forEach((s) => { let a = new Fi[s](this.context); this.libs[s] = a; }); let n = this.glslLibRoutineDependencyGraph; for (let s in this.libs) { let u = this.libs[s].getFunctions(); for (let l in u) { let f = s + "." + l, p; n[f] ? (p = n[f], p.routineBody = u[l].routineBody) : (p = new Nr(f, u[l].routineBody), n[f] = p); let d = u[l].dependencies; if (d) for (let y = 0; y < d.length; ++y) if (n[d[y]]) p.addDependency(n[d[y]]); else { let w = new Nr(d[y]); n[d[y]] = w, p.addDependency(w); } } } } preprocess() { let e = this.context.programInfo, o = e.shaderSource; return this.context.programInfo.hasMain || (o = `${o} ${Xu(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), o = ap(o), `${ju(this.context.glContext.version)} ${this.getUniforms(e.inputNames, e.variables)} ${this.getImports(o)} ${o}`; } getImports(e) { let o = this.selectGlslLibRoutinesToBeIncluded(e); if (o.length === 0) return ""; let t = ""; for (let r = 0; r < o.length; ++r) if (o[r].routineBody) t += o[r].routineBody + ` `; else throw new Error(`Missing body for the Glsl Library routine: ${o[r].name}`); return t; } selectGlslLibRoutinesToBeIncluded(e) { let o = []; return Object.keys(this.glslLibRoutineDependencyGraph).forEach((t) => { let r = t.split(".")[1]; e.indexOf(r) !== -1 && o.push(this.glslLibRoutineDependencyGraph[t]); }), Dn.returnOrderedNodes(o); } getUniforms(e, o) { let t = []; if (e) for (let r of e) t.push(`uniform sampler2D ${r};`); if (o) for (let r of o) t.push(`uniform ${r.type} ${r.name}${r.arrayLength ? `[${r.arrayLength}]` : ""};`); return t.join(` `); } }; }); bp = O(() => { "use strict"; Kt(); Mt(); mp(); st(); qn = class { constructor(e, o, t) { this.profiler = e; this.glContext = o; this.textureLayoutStrategy = t; this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; } getArtifact(e) { return this.repo.get(e); } setArtifact(e, o) { this.repo.set(e, o); } run(e, o, t) { this.profiler.event("op", `ProgramManager.run ${e.programInfo.name ?? "unknown kernel"}`, () => { let r = this.glContext.gl, n = e.program; r.useProgram(n); try { this.bindOutput(t), this.attributesBound || this.bindAttributes(e.attribLocations), this.bindUniforms(e.uniformLocations, e.programInfo.variables ?? [], o); } catch (s) { throw tt.error("ProgramManager", e.programInfo.shaderSource), s; } this.profiler.event("backend", "GlContext.draw()", () => { this.glContext.draw(); }); }, this.glContext); } dispose() { this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach((e) => this.glContext.deleteProgram(e.program)); } build(e, o, t) { return this.profiler.event("backend", "ProgramManager.build", () => { let r = new Hn(this.glContext, e, o, t), n = r.preprocess(), s = this.compile(n); return { programInfo: e, program: s, uniformLocations: this.getUniformLocations(s, r.context.programInfo.inputNames, r.context.programInfo.variables), attribLocations: this.getAttribLocations(s) }; }); } compile(e) { if (!this.vertexShader) { tt.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time"); let r = qu(this.glContext.version); this.vertexShader = this.glContext.compileShader(r, this.glContext.gl.VERTEX_SHADER); } z.debug && tt.verbose("ProrgramManager", `FragShader: ${e} `); let o = this.glContext.compileShader(e, this.glContext.gl.FRAGMENT_SHADER), t = this.glContext.createProgram(this.vertexShader, o); return this.glContext.deleteShader(o), t; } bindOutput(e) { let o = e.width, t = e.height; tt.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${o}/${t}, shape=${e.shape}, type=${e.tensor.type}`), this.glContext.attachFramebuffer(e.texture, o, t); } bindAttributes(e) { let o = e.position, t = e.textureCoord; this.glContext.setVertexAttributes(o, t), this.attributesBound = true; } bindUniforms(e, o, t) { let r = this.glContext.gl, n = 0; for (let { name: s, type: a, location: u, arrayLength: l } of e) { let f = o.find((p) => p.name === s)?.data; if (a !== "sampler2D" && !f) throw new Error(`variable '${s}' does not have data defined in program info`); switch (a) { case "sampler2D": this.bindTexture(t[n], u, n), n++; break; case "float": l ? r.uniform1fv(u, f) : r.uniform1f(u, f); break; case "int": l ? r.uniform1iv(u, f) : r.uniform1i(u, f); break; default: throw new Error(`Uniform not implemented: ${a}`); } } } bindTexture(e, o, t) { this.glContext.bindTextureToUniform(e.texture, t, o); } getAttribLocations(e) { return { position: this.getAttribLocation(e, "position"), textureCoord: this.getAttribLocation(e, "textureCoord") }; } getUniformLocations(e, o, t) { let r = []; if (o) for (let n of o) r.push({ name: n, type: "sampler2D", location: this.getUniformLocation(e, n) }); if (t) for (let n of t) r.push({ ...n, location: this.getUniformLocation(e, n.name) }); return r; } getUniformLocation(e, o) { let r = this.glContext.gl.getUniformLocation(e, o); if (r === null) throw new Error(`Uniform ${o} not found.`); return r; } getAttribLocation(e, o) { return this.glContext.gl.getAttribLocation(e, o); } }; }); gp = O(() => { "use strict"; Mt(); Fr(); jn = class { constructor(e, o, t, r) { this.glContext = e; this.layoutStrategy = o; this.profiler = t; this.config = r; this.pendingRead = /* @__PURE__ */ new Map(); r.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map()); } createTextureFromLayout(e, o, t, r) { let n = this.toEncoderType(e), s = this.glContext.getEncoder(n, o.channels || 1, r); if (o.isPacked && r === 1) throw new Error("not implemented"); let a = o.width, u = o.height, l, f; if (this.config.reuseTextures) { l = `${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`, f = this.inUseTextures.get(l), f || (f = [], this.inUseTextures.set(l, f)); let d = this.idleTextures.get(l); if (d && d.length > 0) { let y = d.pop(); return f.push(y), r === 1 && this.glContext.updateTexture(y, a, u, s, this.toTextureData(e, t)), y; } } tt.verbose("TextureManager", `Creating new texture of size ${o.width}x${o.height}`); let p = this.glContext.allocateTexture(a, u, s, this.toTextureData(e, t)); return this.config.reuseTextures && (f.push(p), this.textureLookup.set(p, l)), p; } readTexture(e, o, t) { return t || (t = 1), this.profiler.event("backend", "TextureManager.readTexture", () => { let r = e.shape.reduce((s, a) => s * a) * t, n = this.glContext.readTexture(e.texture, e.width, e.height, r, this.toEncoderType(o), t); return this.toTensorData(o, n); }); } async readTextureAsync(e, o, t) { let r = e.tensor.dataId; if (t || (t = 1), this.pendingRead.has(r)) { let n = this.pendingRead.get(r); return new Promise((s) => n?.push(s)); } return this.profiler.event("backend", "TextureManager.readTextureAsync", async () => { this.pendingRead.set(r, []); let n = e.shape.reduce((l, f) => l * f) * t; await this.glContext.createAndWaitForFence(); let s = this.glContext.readTexture(e.texture, e.width, e.height, n, this.toEncoderType(o), t), a = this.toTensorData(o, s), u = this.pendingRead.get(r); return this.pendingRead.delete(r), u?.forEach((l) => l(a)), a; }); } readUint8TextureAsFloat(e) { return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", () => { let o = e.shape.reduce((r, n) => r * n), t = this.glContext.readTexture(e.texture, e.width, e.height, o * 4, "byte", 4); return new Float32Array(t.buffer, t.byteOffset, o); }); } releaseTexture(e, o) { let t; if (this.config.reuseTextures && (t = this.textureLookup.get(e.texture), t)) { o && this.textureLookup.delete(t); let r = this.inUseTextures.get(t); if (r) { let n = r.indexOf(e.texture); if (n !== -1) { r.splice(n, 1); let s = this.idleTextures.get(t); s || (s = [], this.idleTextures.set(t, s)), s.push(e.texture); } } } (!t || o) && (tt.verbose("TextureManager", `Deleting texture of size ${e.width}x${e.height}`), this.glContext.deleteTexture(e.texture)); } toTensorData(e, o) { switch (e) { case "int16": return o instanceof Int16Array ? o : Int16Array.from(o); case "int32": return o instanceof Int32Array ? o : Int32Array.from(o); case "int8": return o instanceof Int8Array ? o : Int8Array.from(o); case "uint16": return o instanceof Uint16Array ? o : Uint16Array.from(o); case "uint32": return o instanceof Uint32Array ? o : Uint32Array.from(o); case "uint8": case "bool": return o instanceof Uint8Array ? o : Uint8Array.from(o); case "float32": return o instanceof Float32Array ? o : Float32Array.from(o); case "float64": return o instanceof Float64Array ? o : Float64Array.from(o); default: throw new Error(`TensorData type ${e} is not supported`); } } toTextureData(e, o) { if (o) return o instanceof Float32Array ? o : new Float32Array(o); } toEncoderType(e) { return "float"; } clearActiveTextures() { this.glContext.clearActiveTextures(); } }; }); yp = O(() => { "use strict"; Mt(); $s(); ll(); op(); bp(); Bi(); gp(); Xn = class { constructor(e, o) { this.backend = e; this.context = o; this.layoutStrategy = new Gn(e.glContext.maxTextureSize), this.programManager = new qn(this.context.profiler, e.glContext, this.layoutStrategy), this.textureManager = new jn(e.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: e.textureCacheMode === "full" }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = e.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map(); } createInferenceHandler() { return new Pn(this); } onGraphInitialized(e) { let o = e.getValues().filter((t) => t.from === -1 && t.tensor).map((t) => t.tensor.dataId); this.initializers = new Set(o); } isInitializer(e) { return this.initializers ? this.initializers.has(e) : false; } addInitializer(e) { this.initializers.add(e); } getTextureData(e, o) { return o ? this.packedTextureDataCache.get(e) : this.unpackedTextureDataCache.get(e); } setTextureData(e, o, t = false) { tt.verbose("WebGLSessionHandler", "Storing Texture data in cache"), t ? this.packedTextureDataCache.set(e, o) : this.unpackedTextureDataCache.set(e, o); } dispose() { this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((e) => this.textureManager.releaseTexture(e, true)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((e) => this.textureManager.releaseTexture(e, true)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } resolve(e, o, t) { let r = Ls(e, o, np); return { impl: r.opImpl, context: r.opInit ? r.opInit(e, t) : e }; } }; }); xp = O(() => { "use strict"; Kt(); Fr(); Fr(); ue(); Mr = class { constructor(e, o) { this.frameBufferBound = false; this.itemsToPoll = []; this.gl = e, this.version = o, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters(); } allocateTexture(e, o, t, r) { let n = this.gl, s = n.createTexture(); n.bindTexture(n.TEXTURE_2D, s), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_MIN_FILTER, n.NEAREST), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_MAG_FILTER, n.NEAREST), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_WRAP_S, n.CLAMP_TO_EDGE), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_WRAP_T, n.CLAMP_TO_EDGE); let a = r ? t.encode(r, e * o) : null; return n.texImage2D(n.TEXTURE_2D, 0, t.internalFormat, e, o, 0, t.format, t.textureType, a), this.checkError(), s; } updateTexture(e, o, t, r, n) { let s = this.gl; s.bindTexture(s.TEXTURE_2D, e); let a = r.encode(n, o * t); s.texSubImage2D(s.TEXTURE_2D, 0, 0, 0, o, t, r.format, r.textureType, a), this.checkError(); } attachFramebuffer(e, o, t) { let r = this.gl; r.bindTexture(r.TEXTURE_2D, e), r.bindFramebuffer(r.FRAMEBUFFER, this.framebuffer), r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, e, 0), this.checkError(), r.viewport(0, 0, o, t), r.scissor(0, 0, o, t); } readTexture(e, o, t, r, n, s) { let a = this.gl; s || (s = 1), this.frameBufferBound || this.attachFramebuffer(e, o, t); let u = this.getEncoder(n, s), l = u.allocate(o * t); return a.bindTexture(a.TEXTURE_2D, e), a.framebufferTexture2D(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0, a.TEXTURE_2D, e, 0), a.readPixels(0, 0, o, t, a.RGBA, u.textureType, l), this.checkError(), u.decode(l, r); } isFramebufferReady() { return true; } getActiveTexture() { let e = this.gl; return `TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE) - e.TEXTURE0}`; } getTextureBinding() { return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); } getFramebufferBinding() { return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); } setVertexAttributes(e, o) { let t = this.gl; t.vertexAttribPointer(e, 3, t.FLOAT, false, 20, 0), t.enableVertexAttribArray(e), o !== -1 && (t.vertexAttribPointer(o, 2, t.FLOAT, false, 20, 12), t.enableVertexAttribArray(o)), this.checkError(); } createProgram(e, o) { let t = this.gl, r = t.createProgram(); return t.attachShader(r, e), t.attachShader(r, o), t.linkProgram(r), r; } compileShader(e, o) { let t = this.gl, r = t.createShader(o); if (!r) throw new Error(`createShader() returned null with type ${o}`); if (t.shaderSource(r, e), t.compileShader(r), t.getShaderParameter(r, t.COMPILE_STATUS) === false) throw new Error(`Failed to compile shader: ${t.getShaderInfoLog(r)} Shader source: ${e}`); return r; } deleteShader(e) { this.gl.deleteShader(e); } bindTextureToUniform(e, o, t) { let r = this.gl; r.activeTexture(r.TEXTURE0 + o), this.checkError(), r.bindTexture(r.TEXTURE_2D, e), this.checkError(), r.uniform1i(t, o), this.checkError(); } draw() { this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError(); } checkError() { if (z.debug) { let e = this.gl, o = e.getError(), t = ""; switch (o) { case e.NO_ERROR: return; case e.INVALID_ENUM: t = "INVALID_ENUM"; break; case e.INVALID_VALUE: t = "INVALID_VALUE"; break; case e.INVALID_OPERATION: t = "INVALID_OPERATION"; break; case e.INVALID_FRAMEBUFFER_OPERATION: t = "INVALID_FRAMEBUFFER_OPERATION"; break; case e.OUT_OF_MEMORY: t = "OUT_OF_MEMORY"; break; case e.CONTEXT_LOST_WEBGL: t = "CONTEXT_LOST_WEBGL"; break; default: t = `Unknown WebGL Error: ${o.toString(16)}`; } throw new Error(t); } } deleteTexture(e) { this.gl.deleteTexture(e); } deleteProgram(e) { this.gl.deleteProgram(e); } getEncoder(e, o, t = 0) { if (this.version === 2) return new Sn(this.gl, o); switch (e) { case "float": return t === 1 || this.isRenderFloat32Supported ? new Br(this.gl, o) : new Br(this.gl, o, this.textureHalfFloatExtension.HALF_FLOAT_OES); case "int": throw new Error("not implemented"); case "byte": return new An(this.gl, o); default: throw new Error(`Invalid dataType: ${e}`); } } clearActiveTextures() { let e = this.gl; for (let o = 0; o < this.maxTextureImageUnits; ++o) e.activeTexture(e.TEXTURE0 + o), e.bindTexture(e.TEXTURE_2D, null); } dispose() { if (this.disposed) return; let e = this.gl; e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteFramebuffer(this.framebuffer), e.bindBuffer(e.ARRAY_BUFFER, null), e.deleteBuffer(this.vertexbuffer), e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, null), e.finish(), this.disposed = true; } createDefaultGeometry() { return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]); } createVertexbuffer() { let e = this.gl, o = e.createBuffer(); if (!o) throw new Error("createBuffer() returned null"); let t = this.createDefaultGeometry(); return e.bindBuffer(e.ARRAY_BUFFER, o), e.bufferData(e.ARRAY_BUFFER, t, e.STATIC_DRAW), this.checkError(), o; } createFramebuffer() { let e = this.gl.createFramebuffer(); if (!e) throw new Error("createFramebuffer returned null"); return e; } queryVitalParameters() { let e = this.gl; if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) throw new Error("both float32 and float16 TextureType are not supported"); this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = e.getParameter(e.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS), this.version; } getExtensions() { this.version === 2 ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float")); } checkFloatTextureAttachableToFrameBuffer() { let e = this.gl, o = e.createTexture(); e.bindTexture(e.TEXTURE_2D, o); let t = this.version === 2 ? e.RGBA32F : e.RGBA; e.texImage2D(e.TEXTURE_2D, 0, t, 1, 1, 0, e.RGBA, e.FLOAT, null); let r = e.createFramebuffer(); e.bindFramebuffer(e.FRAMEBUFFER, r), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, o, 0); let n = e.checkFramebufferStatus(e.FRAMEBUFFER) === e.FRAMEBUFFER_COMPLETE; return e.bindTexture(e.TEXTURE_2D, null), e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteTexture(o), e.deleteFramebuffer(r), n; } checkRenderFloat32() { if (this.version === 2) { if (!this.colorBufferFloatExtension) return false; } else if (!this.textureFloatExtension) return false; return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Download() { if (this.version === 2) { if (!this.colorBufferFloatExtension) return false; } else if (!this.textureFloatExtension || !this.gl.getExtension("WEBGL_color_buffer_float")) return false; return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Blend() { let e = this.gl, o, t, r, n, s; try { o = e.createTexture(), t = e.createFramebuffer(), e.bindTexture(e.TEXTURE_2D, o); let a = this.version === 2 ? e.RGBA32F : e.RGBA; return e.texImage2D(e.TEXTURE_2D, 0, a, 1, 1, 0, e.RGBA, e.FLOAT, null), e.bindFramebuffer(e.FRAMEBUFFER, t), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, o, 0), e.enable(e.BLEND), r = e.createShader(e.VERTEX_SHADER), !r || (e.shaderSource(r, "void main(){}"), e.compileShader(r), n = e.createShader(e.FRAGMENT_SHADER), !n) || (e.shaderSource(n, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), e.compileShader(n), s = e.createProgram(), !s) ? false : (e.attachShader(s, r), e.attachShader(s, n), e.linkProgram(s), e.useProgram(s), e.drawArrays(e.POINTS, 0, 1), e.getError() === e.NO_ERROR); } finally { e.disable(e.BLEND), s && e.deleteProgram(s), r && e.deleteShader(r), n && e.deleteShader(n), t && (e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteFramebuffer(t)), o && (e.bindTexture(e.TEXTURE_2D, null), e.deleteTexture(o)); } } beginTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let e = this.gl, o = this.disjointTimerQueryWebgl2Extension, t = e.createQuery(); return e.beginQuery(o.TIME_ELAPSED_EXT, t), t; } else throw new Error("WebGL1 profiling currently not supported."); } endTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let e = this.gl, o = this.disjointTimerQueryWebgl2Extension; e.endQuery(o.TIME_ELAPSED_EXT); return; } else throw new Error("WebGL1 profiling currently not supported"); } isTimerResultAvailable(e) { let o = false, t = false; if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let r = this.gl, n = this.disjointTimerQueryWebgl2Extension; o = r.getQueryParameter(e, r.QUERY_RESULT_AVAILABLE), t = r.getParameter(n.GPU_DISJOINT_EXT); } else throw new Error("WebGL1 profiling currently not supported"); return o && !t; } getTimerResult(e) { let o = 0; if (this.version === 2) { let t = this.gl; o = t.getQueryParameter(e, t.QUERY_RESULT), t.deleteQuery(e); } else throw new Error("WebGL1 profiling currently not supported"); return o / 1e6; } async waitForQueryAndGetTime(e) { return await ai(() => this.isTimerResultAvailable(e)), this.getTimerResult(e); } async createAndWaitForFence() { let e = this.createFence(this.gl); return this.pollFence(e); } createFence(e) { let o, t = e, r = t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE, 0); return e.flush(), r === null ? o = () => true : o = () => { let n = t.clientWaitSync(r, 0, 0); return n === t.ALREADY_SIGNALED || n === t.CONDITION_SATISFIED; }, { query: r, isFencePassed: o }; } async pollFence(e) { return new Promise((o) => { this.addItemToPoll(() => e.isFencePassed(), () => o()); }); } pollItems() { let e = hg(this.itemsToPoll.map((o) => o.isDoneFn)); for (let o = 0; o <= e; ++o) { let { resolveFn: t } = this.itemsToPoll[o]; t(); } this.itemsToPoll = this.itemsToPoll.slice(e + 1); } async addItemToPoll(e, o) { this.itemsToPoll.push({ isDoneFn: e, resolveFn: o }), !(this.itemsToPoll.length > 1) && await ai(() => (this.pollItems(), this.itemsToPoll.length === 0)); } }; }); wp = O(() => { "use strict"; Mt(); xp(); mr = {}; }); vp = O(() => { "use strict"; Kt(); Mt(); yp(); wp(); Kn = class { get contextId() { return z.webgl.contextId; } set contextId(e) { z.webgl.contextId = e; } get matmulMaxBatchSize() { return z.webgl.matmulMaxBatchSize; } set matmulMaxBatchSize(e) { z.webgl.matmulMaxBatchSize = e; } get textureCacheMode() { return z.webgl.textureCacheMode; } set textureCacheMode(e) { z.webgl.textureCacheMode = e; } get pack() { return z.webgl.pack; } set pack(e) { z.webgl.pack = e; } get async() { return z.webgl.async; } set async(e) { z.webgl.async = e; } initialize() { try { return this.glContext = Ci(this.contextId), typeof this.matmulMaxBatchSize != "number" && (this.matmulMaxBatchSize = 16), typeof this.textureCacheMode != "string" && (this.textureCacheMode = "full"), typeof this.pack != "boolean" && (this.pack = false), typeof this.async != "boolean" && (this.async = false), tt.setWithEnv(z), z.webgl.context || Object.defineProperty(z.webgl, "context", { value: this.glContext.gl }), tt.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), true; } catch (e) { return tt.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${e}`), false; } } createSessionHandler(e) { return new Xn(this, e); } dispose() { this.glContext.dispose(); } }; }); _p = O(() => { "use strict"; vp(); Ip = /* @__PURE__ */ new Map(), gg = { webgl: new Kn() }; }); Op = O(() => { "use strict"; Mt(); Ri = class { constructor(e, o) { this.op = e; this.node = o; } }, Jn = class { constructor(e, o, t) { this.graph = e; this.profiler = t; this.initialize(o); } initialize(e) { this.profiler.event("session", "ExecutionPlan.initialize", () => { let o = this.graph.getNodes(); if (o.length !== e.length) throw new Error("The size of nodes and OPs do not match."); this._ops = e.map((t, r) => new Ri(t, o[r])), this.reset(), this._starter = [], this._ops.forEach((t, r) => { let n = true; for (let s of t.node.inputs) if (!this._values[s] && this.graph.getInputIndices().indexOf(s) === -1) { n = false; break; } n && this._starter.push(r); }); }); } reset() { this._values = this.graph.getValues().map((e) => e.tensor); } async execute(e, o) { return this.profiler.event("session", "ExecutionPlan.execute", async () => { this.reset(); let t = e.createInferenceHandler(), r = this.graph.getInputIndices(); if (o.length !== r.length) throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${o.length} expected: ${r.length}`); o.forEach((f, p) => { let d = r[p]; this._values[d] = f; }); let n = this._starter.slice(0), s = this.graph.getValues(), a = this.graph.getNodes(), u = 0; for (; u < n.length; ) { let f = n[u++], p = this._ops[f], d = p.node.inputs.map((S) => this._values[S]); if (d.indexOf(void 0) !== -1) throw new Error(`unresolved input detected: op: ${p.node}`); let y = d; tt.verbose("ExecPlan", `Running op:${p.node.name} (${y.map((S, L) => `'${p.node.inputs[L]}': ${S.type}[${S.dims.join(",")}]`).join(", ")})`); let w = await this.profiler.event("node", p.node.name, async () => p.op.impl(t, y, p.op.context)); if (w.length !== p.node.outputs.length) throw new Error("the size of output does not match model definition."); w.forEach((S, L) => { let A2 = p.node.outputs[L]; if (this._values[A2]) throw new Error(`output [${A2}] already has value: op:${p.node.name}`); this._values[A2] = S; }); let v = /* @__PURE__ */ new Set(); w.forEach((S, L) => { let A2 = p.node.outputs[L]; for (let P2 of s[A2].to) { let M3 = a[P2], V3 = true; for (let ut2 of M3.inputs) if (!this._values[ut2]) { V3 = false; break; } V3 && v.add(P2); } }), n.push(...v); } let l = []; for (let f = 0; f < this.graph.getOutputIndices().length; f++) { let p = this.graph.getOutputIndices()[f], d = this._values[p]; if (d === void 0) throw new Error(`required output [${p}] does not have value`); p === 0 ? await d.getData() : d.data, l.push(d); } return tt.verbose("ExecPlan", "disposing of inferenceHandler"), t.dispose(), l; }); } }; }); Sp = O(() => { "use strict"; Pr(); q = rr(sr()); ze(); Y(); jt = F.experimental.fbs, Ur = class i { constructor(e) { if (this._attributes = /* @__PURE__ */ new Map(), e != null) { for (let o of e) o instanceof q.onnx.AttributeProto ? this._attributes.set(o.name, [i.getValue(o), i.getType(o)]) : o instanceof jt.Attribute && this._attributes.set(o.name(), [i.getValue(o), i.getType(o)]); if (this._attributes.size < e.length) throw new Error("duplicated attribute names"); } } set(e, o, t) { this._attributes.set(e, [t, o]); } delete(e) { this._attributes.delete(e); } getFloat(e, o) { return this.get(e, "float", o); } getInt(e, o) { return this.get(e, "int", o); } getString(e, o) { return this.get(e, "string", o); } getTensor(e, o) { return this.get(e, "tensor", o); } getFloats(e, o) { return this.get(e, "floats", o); } getInts(e, o) { return this.get(e, "ints", o); } getStrings(e, o) { return this.get(e, "strings", o); } getTensors(e, o) { return this.get(e, "tensors", o); } get(e, o, t) { let r = this._attributes.get(e); if (r === void 0) { if (t !== void 0) return t; throw new Error(`required attribute not found: ${e}`); } if (r[1] !== o) throw new Error(`type mismatch: expected ${o} but got ${r[1]}`); return r[0]; } static getType(e) { let o = e instanceof q.onnx.AttributeProto ? e.type : e.type(); switch (o) { case q.onnx.AttributeProto.AttributeType.FLOAT: return "float"; case q.onnx.AttributeProto.AttributeType.INT: return "int"; case q.onnx.AttributeProto.AttributeType.STRING: return "string"; case q.onnx.AttributeProto.AttributeType.TENSOR: return "tensor"; case q.onnx.AttributeProto.AttributeType.FLOATS: return "floats"; case q.onnx.AttributeProto.AttributeType.INTS: return "ints"; case q.onnx.AttributeProto.AttributeType.STRINGS: return "strings"; case q.onnx.AttributeProto.AttributeType.TENSORS: return "tensors"; default: throw new Error(`attribute type is not supported yet: ${q.onnx.AttributeProto.AttributeType[o]}`); } } static getValue(e) { let o = e instanceof q.onnx.AttributeProto ? e.type : e.type(); if (o === q.onnx.AttributeProto.AttributeType.GRAPH || o === q.onnx.AttributeProto.AttributeType.GRAPHS) throw new Error("graph attribute is not supported yet"); let t = this.getValueNoCheck(e); if (o === q.onnx.AttributeProto.AttributeType.INT && Nt.isLong(t)) return Nt.longToNumber(t); if (o === q.onnx.AttributeProto.AttributeType.INTS) { let r = t, n = new Array(r.length); for (let s = 0; s < r.length; s++) { let a = r[s]; n[s] = Nt.longToNumber(a); } return n; } if (o === q.onnx.AttributeProto.AttributeType.TENSOR) return e instanceof q.onnx.AttributeProto ? bt.fromProto(t) : bt.fromOrtTensor(t); if (o === q.onnx.AttributeProto.AttributeType.TENSORS) { if (e instanceof q.onnx.AttributeProto) return t.map((n) => bt.fromProto(n)); if (e instanceof jt.Attribute) return t.map((n) => bt.fromOrtTensor(n)); } return o === q.onnx.AttributeProto.AttributeType.STRING && e instanceof q.onnx.AttributeProto ? kr(t) : o === q.onnx.AttributeProto.AttributeType.STRINGS && e instanceof q.onnx.AttributeProto ? t.map(kr) : t; } static getValueNoCheck(e) { return e instanceof q.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(e) : this.getValueNoCheckFromOrtFormat(e); } static getValueNoCheckFromOnnxFormat(e) { switch (e.type) { case q.onnx.AttributeProto.AttributeType.FLOAT: return e.f; case q.onnx.AttributeProto.AttributeType.INT: return e.i; case q.onnx.AttributeProto.AttributeType.STRING: return e.s; case q.onnx.AttributeProto.AttributeType.TENSOR: return e.t; case q.onnx.AttributeProto.AttributeType.GRAPH: return e.g; case q.onnx.AttributeProto.AttributeType.FLOATS: return e.floats; case q.onnx.AttributeProto.AttributeType.INTS: return e.ints; case q.onnx.AttributeProto.AttributeType.STRINGS: return e.strings; case q.onnx.AttributeProto.AttributeType.TENSORS: return e.tensors; case q.onnx.AttributeProto.AttributeType.GRAPHS: return e.graphs; default: throw new Error(`unsupported attribute type: ${q.onnx.AttributeProto.AttributeType[e.type]}`); } } static getValueNoCheckFromOrtFormat(e) { switch (e.type()) { case jt.AttributeType.FLOAT: return e.f(); case jt.AttributeType.INT: return e.i(); case jt.AttributeType.STRING: return e.s(); case jt.AttributeType.TENSOR: return e.t(); case jt.AttributeType.GRAPH: return e.g(); case jt.AttributeType.FLOATS: return e.floatsArray(); case jt.AttributeType.INTS: { let o = []; for (let t = 0; t < e.intsLength(); t++) o.push(e.ints(t)); return o; } case jt.AttributeType.STRINGS: { let o = []; for (let t = 0; t < e.stringsLength(); t++) o.push(e.strings(t)); return o; } case jt.AttributeType.TENSORS: { let o = []; for (let t = 0; t < e.tensorsLength(); t++) o.push(e.tensors(t)); return o; } default: throw new Error(`unsupported attribute type: ${jt.AttributeType[e.type()]}`); } } }; }); Ap = O(() => { "use strict"; Sp(); Pr(); Mi = rr(sr()); ze(); Y(); Yn = F.experimental.fbs, Ui = { from: (i, e) => new Gi(i, e) }, ce = class { constructor(e) { this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, e && (this.type = _t.tensorValueTypeFromProto(e.type.tensorType)); } get from() { return this._from; } get to() { return this._to; } }, Zn = class { constructor(e, o) { e instanceof Mi.onnx.NodeProto ? (this.name = e.name, this.opType = e.opType, this.attributes = new Ur(e.attribute)) : e instanceof Yn.Node && (this.name = o ?? e.name(), this.opType = e.opType(), this.attributes = new Ur(_t.tensorAttributesFromORTFormat(e))), this.inputs = [], this.outputs = [], this.executeNode = true; } }, Gi = class { constructor(e, o) { if (!e) throw new TypeError("graph is empty"); this.buildGraph(e), this.transformGraph(o), this.checkIsAcyclic(); } getInputIndices() { return this._allInputIndices; } getInputNames() { return this._allInputNames; } getOutputIndices() { return this._allOutputIndices; } getOutputNames() { return this._allOutputNames; } getValues() { return this._allData; } getNodes() { return this._nodes; } buildGraph(e) { if (e instanceof Mi.onnx.GraphProto) this.buildGraphFromOnnxFormat(e); else if (e instanceof Yn.Graph) this.buildGraphFromOrtFormat(e); else throw new TypeError("Graph type is not supported."); } buildGraphFromOnnxFormat(e) { let o = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; let t = /* @__PURE__ */ new Map(); if (!e.input) throw new Error("missing information in graph: input"); let r = []; for (let n of e.input) { if (o.has(n.name)) throw new Error(`duplicated input name: ${n.name}`); let s = this._allData.push(new ce(n)) - 1; o.set(n.name, s), r.push(n.name); } if (!e.initializer) throw new Error("missing information in graph: initializer"); for (let n of e.initializer) { let s = o.get(n.name); if (s === void 0) { let a = new ce(); a.type = { shape: { dims: _t.tensorDimsFromProto(n.dims) }, tensorType: _t.tensorDataTypeFromProto(n.dataType) }, s = this._allData.push(a) - 1, o.set(n.name, s); } this._allData[s]._from = -1, this._allData[s].tensor = bt.fromProto(n); } for (let n = 0; n < this._allData.length; n++) this._allData[n].tensor || (this._allInputIndices.push(n), this._allInputNames.push(r[n])); if (!e.output) throw new Error("missing information in graph: output"); for (let n of e.output) { if (o.has(n.name)) throw new Error(`duplicated output name: ${n.name}`); let s = this._allData.push(new ce(n)) - 1; o.set(n.name, s), this._allOutputIndices.push(s), this._allOutputNames.push(n.name); } if (!e.node) throw new Error("missing information in graph: node"); for (let n of e.node) { if (!n.name) for (let a = 0; ; a++) { let u = `unnamed_${n.opType}_${a}`; if (!t.has(u)) { n.name = u; break; } } if (t.has(n.name)) throw new Error(`duplicated node name: ${n.name}`); let s = this._nodes.push(new Zn(n)) - 1; t.set(n.name, s); } for (let n = 0; n < this._nodes.length; n++) { let s = this._nodes[n], a = e.node[n]; if (!a.output) throw new Error(`missing output for node: ${a.name}`); for (let u of a.output) { let l = o.get(u); if (typeof l > "u" && (l = this._allData.push(new ce()) - 1, o.set(u, l)), s.outputs.push(l), this._allData[l]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${l}`); if (this._allData[l]._from = n, a.opType === "Constant") { if (!a.attribute || a.attribute.length !== 1 || !a.attribute[0].t) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (!a.output || a.output.length !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator"); s.outputs.pop(), s.executeNode = false, this._allData[l]._from = -1, this._allData[l].tensor = bt.fromProto(a.attribute[0].t); } } } for (let n = 0; n < this._nodes.length; n++) { let s = this._nodes[n], a = e.node[n]; if (!a.input) throw new Error(`missing input for node: ${a.name}`); for (let u of a.input) { let l = o.get(u); if (typeof l > "u") { if (u === "" && (a.input.length === 3 || a.input.length === 4) && a.opType === "Resize") continue; throw new Error(`unrecognized input '${u}' for node: ${a.name}`); } s.inputs.push(l), this._allData[l]._to.push(n); } } return true; } buildGraphFromOrtFormat(e) { let o = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; let t = /* @__PURE__ */ new Map(), r = []; for (let n = 0; n < e.inputsLength(); n++) { let s = e.inputs(n); if (o.has(s)) throw new Error(`duplicated input name: ${s}`); for (let a = 0; a < e.nodeArgsLength(); a++) if (e.nodeArgs(a)?.name() === s) { let u = new ce(); if (e.nodeArgs(a)?.type()?.valueType() !== Yn.TypeInfoValue.tensor_type) throw new Error("Unexpected value type for the nodeArg."); let f = e.nodeArgs(a).type().value(new Yn.TensorTypeAndShape()), p = _t.tensorDataTypeFromProto(f.elemType()), d = f.shape(), y = []; for (let v = 0; v < d.dimLength(); v++) y.push(Nt.longToNumber(d.dim(v).value().dimValue())); u.type = { shape: { dims: y }, tensorType: p }; let w = this._allData.push(u) - 1; o.set(s, w), r.push(s); } } for (let n = 0; n < e.initializersLength(); n++) { let s = e.initializers(n), a = o.get(s.name()); if (a === void 0) { let u = new ce(), l = _t.tensorDimsFromORTFormat(s), f = _t.tensorDataTypeFromProto(s.dataType()); u.type = { shape: { dims: l }, tensorType: f }, a = this._allData.push(u) - 1, o.set(s.name(), a); } this._allData[a]._from = -1, this._allData[a].tensor = bt.fromOrtTensor(s); } for (let n = 0; n < this._allData.length; n++) this._allData[n].tensor || (this._allInputIndices.push(n), this._allInputNames.push(r[n])); for (let n = 0; n < e.outputsLength(); n++) { let s = e.outputs(n); if (o.has(s)) throw new Error(`duplicated output name: ${s}`); let a = this._allData.push(new ce()) - 1; o.set(s, a), this._allOutputIndices.push(a), this._allOutputNames.push(s); } if (!e.nodes) throw new Error("missing information in graph: node"); for (let n = 0; n < e.nodesLength(); n++) { let s = e.nodes(n), a = s.name(); if (!a) for (let l = 0; a = `unnamed_${s.opType()}_${l}`, !!t.has(a); l++) ; if (t.has(a)) throw new Error(`duplicated node name: ${a}`); let u = this._nodes.push(new Zn(s, a)) - 1; t.set(a, u); } for (let n = 0; n < this._nodes.length; n++) { let s = this._nodes[n], a = e.nodes(n); if (a == null) throw new Error(`No node exists at index ${n}`); if (a?.outputsLength() === 0) throw new Error(`missing output for node: ${a.name}`); for (let u = 0; u < a?.outputsLength(); u++) { let l = a?.outputs(u), f = o.get(l); if (typeof f > "u" && (f = this._allData.push(new ce()) - 1, o.set(l, f)), s.outputs.push(f), this._allData[f]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${f}`); if (this._allData[f]._from = n, a.opType() === "Constant") { if (a.attributesLength() !== 1 || !a.attributes(0).t()) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (a.outputsLength() !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator"); s.outputs.pop(), s.executeNode = false, this._allData[f]._from = -1, this._allData[f].tensor = bt.fromOrtTensor(a.attributes(0).t()); } } } for (let n = 0; n < this._nodes.length; n++) { let s = this._nodes[n], a = e.nodes(n); if (a.inputsLength() === 0) throw new Error(`missing input for node: ${a.name}`); for (let u = 0; u < a.inputsLength(); u++) { let l = a.inputs(u), f = o.get(l); if (typeof f > "u") throw new Error(`unrecognized input '${l}' for node: ${a.name()}`); s.inputs.push(f), this._allData[f]._to.push(n); } } } checkIsAcyclic() { let e = /* @__PURE__ */ new Set(); this._allInputIndices.forEach((r) => { this._allData[r]._to.forEach((s) => { e.add(s); }); }); let o = Array.from(e), t = new Array(this._nodes.length).fill("white"); for (; o.length > 0; ) { let r = o.pop(); t[r] === "gray" ? t[r] = "black" : (o.push(r), t[r] = "gray", this._nodes[r].outputs.forEach((n) => { let s = this._allData[n]; if (typeof s.tensor < "u") throw new Error("node outputs should not be initialized"); if (s._from !== r) throw new Error("from property of the Value object doesn't match index of Node being processed"); s._to.forEach((a) => { if (t[a] === "gray") throw new Error("model graph is cyclic"); t[a] === "white" && o.push(a); }); })); } } transformGraph(e) { this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), e && e.transformGraph(this), this.finalizeGraph(); } finalizeGraph() { let e = 0, o = new Array(this._nodes.length, 0), t = 0; for (let r = 0; r < this._nodes.length; r++) o[r] = t, this._nodes[r].executeNode ? (t !== r && (this._nodes[t] = this._nodes[r]), t++) : this._nodes[r].outputs.forEach((n) => { this._allData[n]._from = -2; }); this._nodes.splice(t, this._nodes.length - t); for (let r = 0; r < this._allData.length; r++) { let n = this._allData[r]; n._from !== void 0 && n._from !== -1 && n._from !== -2 && (n._from = o[n._from]); for (let s = 0; s < n._to.length; s++) if (n._to[s] >= 0) n._to[s] = o[n._to[s]]; else throw new Error("Trying to update a removed node"); } e = 0; for (let r = 0; r < this._allData.length; r++) { if (this._allData[r].from === -2 && this._allOutputIndices.indexOf(r + e) === -1) { e++, this._allData.splice(r, 1), r--; continue; } if (e > 0) { let n = -1; this._allData[r].from !== void 0 && this._allData[r].from !== -1 ? (n = this._nodes[this._allData[r].from].outputs.indexOf(r + e), n !== -1 && (this._nodes[this._allData[r].from].outputs[n] = r)) : (n = this._allInputIndices.indexOf(r + e), n !== -1 && (this._allInputIndices[n] = r)), this._allData[r].to.forEach((s) => { n = this._nodes[s].inputs.indexOf(r + e), n !== -1 && (this._nodes[s].inputs[n] = r); }), this._allData[r].to.length === 0 && (n = this._allOutputIndices.indexOf(r + e), n !== -1 && (this._allOutputIndices[n] = r)); } } } deleteNode(e) { let o = this._nodes[e]; if (o.outputs.length > 1) { for (let a = 1; a < o.outputs.length; a++) if (this._allData[o.outputs[a]].to.length > 0) throw new Error("Node deletion with more than one output connected to other nodes is not supported. "); } o.executeNode = false; let t = o.inputs[0], r = o.outputs[0], n = this._allData[r].to; for (let a = 0; a < o.inputs.length; a++) { let u = this._allData[o.inputs[a]].to.indexOf(e); if (u === -1) throw new Error("The Value object doesn't have the current Node in it's 'to' property "); this._allData[o.inputs[a]].to.splice(u, 1); } this._allData[r]._to = []; let s = this._allOutputIndices.indexOf(r); if (s !== -1 && (this._allOutputIndices[s] = t), n && n.length > 0) for (let a of n) { let u = this._nodes[a].inputs.indexOf(r); if (u === -1) throw new Error("The Node object doesn't have the output Value in it's 'inputs' property "); this._nodes[a].inputs[u] = t, this._allData[t].to.push(a); } } removeAllDropoutNodes() { let e = 0; for (let o of this._nodes) { if (o.opType === "Dropout") { if (o.inputs.length !== 1) throw new Error("Dropout nodes should only contain one input. "); if (o.outputs.length !== 1 && o.outputs.length !== 2) throw new Error("Dropout nodes should contain either 1 or 2 output(s)"); if (o.outputs.length === 2 && this._allData[o.outputs[1]]._to.length !== 0) throw new Error("Dropout nodes's second output should not be referenced by other nodes"); this.deleteNode(e); } e++; } } removeAllIdentityNodes() { let e = 0; for (let o of this._nodes) o.opType === "Identity" && this.deleteNode(e), e++; } isActivation(e) { switch (e.opType) { case "Relu": case "Sigmoid": case "Clip": return true; default: return false; } } fuseConvActivationNodes() { for (let e of this._nodes) if (e.opType === "Conv") { let o = this._allData[e.outputs[0]]._to; if (o.length === 1 && this.isActivation(this._nodes[o[0]])) { let t = this._nodes[o[0]]; if (t.opType === "Clip") if (t.inputs.length === 1) try { e.attributes.set("activation_params", "floats", [t.attributes.getFloat("min"), t.attributes.getFloat("max")]); } catch { e.attributes.set("activation_params", "floats", [Ue, Ve]); } else if (t.inputs.length >= 3 && this._allData[t.inputs[1]].tensor !== void 0 && this._allData[t.inputs[2]].tensor !== void 0) e.attributes.set("activation_params", "floats", [this._allData[t.inputs[1]].tensor.floatData[0], this._allData[t.inputs[2]].tensor.floatData[0]]); else continue; e.attributes.set("activation", "string", t.opType), this.deleteNode(o[0]); } } } }; }); Ep = O(() => { "use strict"; xn(); Ap(); Pr(); Pp = rr(sr()); Y(); Tg = F.experimental.fbs, Qn = class { constructor() { } load(e, o, t) { let r; if (!t) try { this.loadFromOnnxFormat(e, o); return; } catch (n) { if (t !== void 0) throw n; r = n; } try { this.loadFromOrtFormat(e, o); } catch (n) { throw t !== void 0 ? n : new Error(`Failed to load model as ONNX format: ${r} as ORT format: ${n}`); } } loadFromOnnxFormat(e, o) { let t = Pp.onnx.ModelProto.decode(e); if (Nt.longToNumber(t.irVersion) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = t.opsetImport.map((n) => ({ domain: n.domain, version: Nt.longToNumber(n.version) })), this._graph = Ui.from(t.graph, o); } loadFromOrtFormat(e, o) { let t = new T.ByteBuffer(e), r = Tg.InferenceSession.getRootAsInferenceSession(t).model(); if (Nt.longToNumber(r.irVersion()) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = []; for (let s = 0; s < r.opsetImportLength(); s++) { let a = r.opsetImport(s); this._opsets.push({ domain: a?.domain(), version: Nt.longToNumber(a.version()) }); } this._graph = Ui.from(r.graph(), o); } get graph() { return this._graph; } get opsets() { return this._opsets; } }; }); Dp = O(() => { "use strict"; _p(); Op(); Mt(); Ep(); to = class { constructor(e = {}) { this._initialized = false, this.backendHint = e.backendHint, this.profiler = gn.create(e.profiler), this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] }; } get inputNames() { return this._model.graph.getInputNames(); } get outputNames() { return this._model.graph.getOutputNames(); } startProfiling() { this.profiler.start(); } endProfiling() { this.profiler.stop(); } async loadModel(e, o, t) { await this.profiler.event("session", "Session.loadModel", async () => { let r = await Ni(this.backendHint); if (this.sessionHandler = r.createSessionHandler(this.context), this._model = new Qn(), typeof e == "string") { let n = e.endsWith(".ort"); { let a = await (await fetch(e)).arrayBuffer(); this.initialize(new Uint8Array(a), n); } } else if (ArrayBuffer.isView(e)) this.initialize(e); else { let n = new Uint8Array(e, o || 0, t || e.byteLength); this.initialize(n); } }); } initialize(e, o) { if (this._initialized) throw new Error("already initialized"); this.profiler.event("session", "Session.initialize", () => { let t = this.sessionHandler.transformGraph ? this.sessionHandler : void 0; this._model.load(e, t, o), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new Jn(this._model.graph, this._ops, this.profiler); }), this._initialized = true; } async run(e) { if (!this._initialized) throw new Error("session not initialized yet"); return this.profiler.event("session", "Session.run", async () => { let o = this.normalizeAndValidateInputs(e), t = await this._executionPlan.execute(this.sessionHandler, o); return this.createOutput(t); }); } normalizeAndValidateInputs(e) { let o = this._model.graph.getInputNames(); if (Array.isArray(e)) { if (e.length !== o.length) throw new Error(`incorrect input array length: expected ${o.length} but got ${e.length}`); } else { if (e.size !== o.length) throw new Error(`incorrect input map size: expected ${o.length} but got ${e.size}`); let t = new Array(e.size), r = 0; for (let n = 0; n < o.length; ++n) { let s = e.get(o[n]); if (!s) throw new Error(`missing input tensor for: '${name}'`); t[r++] = s; } e = t; } if (!this.context.graphInputTypes || this.context.graphInputTypes.length === 0 || !this.context.graphInputDims || this.context.graphInputDims.length === 0) { let t = this._model.graph.getInputIndices(), r = this._model.graph.getValues(), n = new Array(t.length); for (let s = 0; s < t.length; ++s) { let a = r[t[s]]; n[s] = a.type.shape.dims, this.context.graphInputTypes.push(a.type.tensorType), this.context.graphInputDims.push(e[s].dims); } this.validateInputTensorDims(n, e, true); } else this.validateInputTensorDims(this.context.graphInputDims, e, false); return this.validateInputTensorTypes(this.context.graphInputTypes, e), e; } validateInputTensorTypes(e, o) { for (let t = 0; t < o.length; t++) { let r = e[t], n = o[t].type; if (r !== n) throw new Error(`input tensor[${t}] check failed: expected type '${r}' but got ${n}`); } } validateInputTensorDims(e, o, t) { for (let r = 0; r < o.length; r++) { let n = e[r], s = o[r].dims; if (!this.compareTensorDims(n, s, t)) throw new Error(`input tensor[${r}] check failed: expected shape '[${n.join(",")}]' but got [${s.join(",")}]`); } } compareTensorDims(e, o, t) { if (e.length !== o.length) return false; for (let r = 0; r < e.length; ++r) if (e[r] !== o[r] && (!t || e[r] !== 0)) return false; return true; } createOutput(e) { let o = this._model.graph.getOutputNames(); if (e.length !== o.length) throw new Error("expected number of outputs do not match number of generated outputs"); let t = /* @__PURE__ */ new Map(); for (let r = 0; r < o.length; ++r) t.set(o[r], e[r]); return t; } initializeOps(e) { let o = e.getNodes(); this._ops = new Array(o.length); for (let t = 0; t < o.length; t++) this._ops[t] = this.sessionHandler.resolve(o[t], this._model.opsets, e); } }; }); Lp = O(() => { "use strict"; Kt(); ze(); eo = class { constructor(e) { this.session = e; this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames; } async dispose() { } async run(e, o, t) { let r = /* @__PURE__ */ new Map(); for (let a in e) if (Object.hasOwnProperty.call(e, a)) { let u = e[a]; r.set(a, new bt(u.dims, u.type, void 0, void 0, u.data)); } let n = await this.session.run(r), s = {}; return n.forEach((a, u) => { s[u] = new Tt(a.type, a.data, a.dims); }), s; } startProfiling() { this.session.startProfiling(); } endProfiling() { this.session.endProfiling(); } }; }); $p = {}; Or($p, { onnxjsBackend: () => wg }); kp = O(() => { "use strict"; Dp(); Lp(); Vi = class { async init() { } async createInferenceSessionHandler(e, o) { let t = new to(o); return typeof e == "string" ? await t.loadModel(e) : await t.loadModel(e), new eo(t); } }, wg = new Vi(); }); ro = O(() => { "use strict"; }); Cp = {}; Or(Cp, { default: () => vg }); Np = O(() => { "use strict"; zi(); Xe(); Vr(); Bp = "ort-wasm-proxy-worker", Fp = globalThis.self?.name === Bp; Fp && (self.onmessage = (i) => { let { type: e, in: o } = i.data; try { switch (e) { case "init-wasm": no(o.wasm).then(() => { oo(o).then(() => { postMessage({ type: e }); }, (t) => { postMessage({ type: e, err: t }); }); }, (t) => { postMessage({ type: e, err: t }); }); break; case "init-ep": { let { epName: t, env: r } = o; io(r, t).then(() => { postMessage({ type: e }); }, (n) => { postMessage({ type: e, err: n }); }); break; } case "copy-from": { let { buffer: t } = o, r = zr(t); postMessage({ type: e, out: r }); break; } case "create": { let { model: t, options: r } = o; ao(t, r).then((n) => { postMessage({ type: e, out: n }); }, (n) => { postMessage({ type: e, err: n }); }); break; } case "release": so(o), postMessage({ type: e }); break; case "run": { let { sessionId: t, inputIndices: r, inputs: n, outputIndices: s, options: a } = o; uo(t, r, n, s, new Array(s.length).fill(null), a).then((u) => { u.some((l) => l[3] !== "cpu") ? postMessage({ type: e, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: e, out: u }, fo([...n, ...u])); }, (u) => { postMessage({ type: e, err: u }); }); break; } case "end-profiling": lo(o), postMessage({ type: e }); break; default: } } catch (t) { postMessage({ type: e, err: t }); } }); vg = Fp ? null : (i) => new Worker(i ?? br, { type: "module", name: Bp }); }); Gp = {}; Or(Gp, { default: () => Ig }); Mp = O(() => { "use strict"; Rp = (Wi = import.meta.url, async function(i = {}) { function e() { return C.buffer != re2.buffer && lt2(), re2; } function o() { return C.buffer != re2.buffer && lt2(), ye2; } function t() { return C.buffer != re2.buffer && lt2(), Z2; } function r() { return C.buffer != re2.buffer && lt2(), xe; } function n() { return C.buffer != re2.buffer && lt2(), oe2; } var s, a, u = Object.assign({}, i), l = new Promise((c, m2) => { s = c, a = m2; }), f = typeof window == "object", p = typeof importScripts == "function", d = p && self.name == "em-pthread"; u.mountExternalData = (c, m2) => { (u.Ua || (u.Ua = /* @__PURE__ */ new Map())).set(c, m2); }, u.unmountExternalData = () => { delete u.Ua; }; var y, w, v = globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, shared: true }).buffer.constructor, S = Object.assign({}, u), L = "./this.program", A2 = (c, m2) => { throw m2; }, P2 = ""; (f || p) && (p ? P2 = self.location.href : typeof document < "u" && document.currentScript && (P2 = document.currentScript.src), Wi && (P2 = Wi), P2 = P2.startsWith("blob:") ? "" : P2.substr(0, P2.replace(/[?#].*/, "").lastIndexOf("/") + 1), p && (w = (c) => { var m2 = new XMLHttpRequest(); return m2.open("GET", c, false), m2.responseType = "arraybuffer", m2.send(null), new Uint8Array(m2.response); }), y = (c, m2, g) => { var x2 = new XMLHttpRequest(); x2.open("GET", c, true), x2.responseType = "arraybuffer", x2.onload = () => { x2.status == 200 || x2.status == 0 && x2.response ? m2(x2.response) : g(); }, x2.onerror = g, x2.send(null); }); var M3, V3 = console.log.bind(console), ut2 = console.error.bind(console), xt3 = V3, et2 = ut2; if (Object.assign(u, S), S = null, d) { let c = function(m2) { try { var g = m2.data, x2 = g.cmd; if (x2 === "load") { let I2 = []; self.onmessage = (E2) => I2.push(E2), self.startWorker = () => { postMessage({ cmd: "loaded" }); for (let E2 of I2) c(E2); self.onmessage = c; }; for (let E2 of g.handlers) u[E2] && !u[E2].proxy || (u[E2] = (...R) => { postMessage({ Za: "callHandler", kb: E2, args: R }); }, E2 == "print" && (xt3 = u[E2]), E2 == "printErr" && (et2 = u[E2])); C = g.wasmMemory, lt2(), Et3(g.wasmModule); } else if (x2 === "run") { Eo3(g.pthread_ptr, 0, 0, 1, 0, 0), _o3(g.pthread_ptr), dd2(), ia3(), It2 ||= true; try { hd2(g.start_routine, g.arg); } catch (I2) { if (I2 != "unwind") throw I2; } } else x2 === "cancel" ? er3() && en3(-1) : g.target !== "setimmediate" && (x2 === "checkMailbox" ? It2 && Zr2() : x2 && (et2(`worker: received unknown command ${x2}`), et2(g))); } catch (I2) { throw Wa3(), I2; } }; var Ug = c, Et3, It2 = false; et2 = function(...m2) { m2 = m2.join(" "), console.error(m2); }, self.alert = function(...m2) { postMessage({ Za: "alert", text: m2.join(" "), mb: er3() }); }, u.instantiateWasm = (m2, g) => new Promise((x2) => { Et3 = (I2) => { I2 = new WebAssembly.Instance(I2, Kr2()), g(I2), x2(); }; }), self.onunhandledrejection = (m2) => { throw m2.reason || m2; }, self.onmessage = c; } u.wasmBinary && (M3 = u.wasmBinary); var C, jr2, ge3, re2, ye2, Z2, xe, ne2, oe2, pe2 = false; function lt2() { var c = C.buffer; u.HEAP8 = re2 = new Int8Array(c), u.HEAP16 = new Int16Array(c), u.HEAPU8 = ye2 = new Uint8Array(c), u.HEAPU16 = new Uint16Array(c), u.HEAP32 = Z2 = new Int32Array(c), u.HEAPU32 = xe = new Uint32Array(c), u.HEAPF32 = new Float32Array(c), u.HEAPF64 = oe2 = new Float64Array(c), u.HEAP64 = ne2 = new BigInt64Array(c), u.HEAPU64 = new BigUint64Array(c); } if (!d) { if (!((C = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: true })).buffer instanceof v)) throw et2("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), Error("bad memory"); lt2(); } var Gt3 = [], Xr2 = [], Je2 = [], Te2 = 0, Ye2 = null, Ee3 = null; function we2() { if (--Te2 == 0 && (Ye2 !== null && (clearInterval(Ye2), Ye2 = null), Ee3)) { var c = Ee3; Ee3 = null, c(); } } function ie3(c) { throw et2(c = "Aborted(" + c + ")"), pe2 = true, ge3 = 1, c = new WebAssembly.RuntimeError(c + ". Build with -sASSERTIONS for more info."), a(c), c; } var Ze, Ot = (c) => c.startsWith("data:application/octet-stream;base64,"), St3 = (c) => c.startsWith("file://"); function de2(c) { if (c == Ze && M3) return new Uint8Array(M3); if (w) return w(c); throw "both async and sync fetching of the wasm failed"; } function wr3(c, m2, g) { return (function(x2) { if (!M3 && (f || p)) { if (typeof fetch == "function" && !St3(x2)) return fetch(x2, { credentials: "same-origin" }).then((I2) => { if (!I2.ok) throw `failed to load wasm binary file at '${x2}'`; return I2.arrayBuffer(); }).catch(() => de2(x2)); if (y) return new Promise((I2, E2) => { y(x2, (R) => I2(new Uint8Array(R)), E2); }); } return Promise.resolve().then(() => de2(x2)); })(c).then((x2) => WebAssembly.instantiate(x2, m2)).then(g, (x2) => { et2(`failed to asynchronously prepare wasm: ${x2}`), ie3(x2); }); } function Kr2() { return { a: { j: pd2, b: bd2, E: fa3, g: da3, V: ha3, A: ga3, C: ya3, W: xa3, T: Ta3, L: wa3, S: va3, o: Ia3, B: _a3, y: Oa3, U: Sa3, z: Aa3, _: gd2, Z: yd2, P: xd2, w: Td2, F: wd2, k: vd2, O: _o3, Y: Id2, I: _d2, J: Od2, K: Sd2, G: Da3, H: La3, v: Ad2, q: Pd2, l: Ed2, p: Dd2, e: Ld2, X: $d2, x: kd2, d: $a3, f: Bd2, i: Fd2, u: Cd2, t: Nd2, s: Rd2, Q: Fa3, R: Ca3, D: Io3, h: Na3, n: Ra3, M: Ga3, m: Ma3, a: C, r: vo3, N: za3, c: Ud2 } }; } var ta3 = { 822132: (c, m2, g, x2) => { if (u === void 0 || !u.Ua) return 1; if ((c = Ir3(c >>> 0)).startsWith("./") && (c = c.substring(2)), !(c = u.Ua.get(c))) return 2; if (x2 >>>= 0, (m2 >>>= 0) + (g >>>= 0) > c.byteLength) return 3; try { return o().set(c.subarray(m2, m2 + g), x2 >>> 0), 0; } catch { return 4; } }, 822633: () => typeof wasmOffsetConverter < "u" }; function pd2() { return typeof wasmOffsetConverter < "u"; } function To3(c) { this.name = "ExitStatus", this.message = `Program terminated with exit(${c})`, this.status = c; } var wo3 = (c) => { c.terminate(), c.onmessage = () => { }; }, ea3 = (c) => { ve2.length == 0 && (sa3(), aa3(ve2[0])); var m2 = ve2.pop(); if (!m2) return 6; De3.push(m2), ae2[c.Ra] = m2, m2.Ra = c.Ra; var g = { cmd: "run", start_routine: c.cb, arg: c.ab, pthread_ptr: c.Ra }; return m2.postMessage(g, c.ib), 0; }, vr3 = 0, at3 = (c, m2, ...g) => { for (var x2 = 2 * g.length, I2 = $o3(), E2 = Lo2(8 * x2), R = E2 >>> 3, it3 = 0; it3 < g.length; it3++) { var At2 = g[it3]; typeof At2 == "bigint" ? (ne2[R + 2 * it3] = 1n, ne2[R + 2 * it3 + 1] = At2) : (ne2[R + 2 * it3] = 0n, n()[R + 2 * it3 + 1 >>> 0] = At2); } return c = Ha3(c, 0, x2, E2, m2), rn2(I2), c; }; function vo3(c) { if (d) return at3(0, 1, c); if (ge3 = c, !(0 < vr3)) { for (var m2 of De3) wo3(m2); for (m2 of ve2) wo3(m2); ve2 = [], De3 = [], ae2 = [], pe2 = true; } A2(c, new To3(c)); } function ra2(c) { if (d) return at3(1, 0, c); Io3(c); } var Io3 = (c) => { if (ge3 = c, d) throw ra2(c), "unwind"; vo3(c); }, ve2 = [], De3 = [], na3 = [], ae2 = {}, oa3 = (c) => { var m2 = c.Ra; delete ae2[m2], ve2.push(c), De3.splice(De3.indexOf(c), 1), c.Ra = 0, Do2(m2); }; function ia3() { na3.forEach((c) => c()); } var aa3 = (c) => new Promise((m2) => { c.onmessage = (I2) => { var E2 = (I2 = I2.data).cmd; if (I2.targetThread && I2.targetThread != er3()) { var R = ae2[I2.targetThread]; R ? R.postMessage(I2, I2.transferList) : et2(`Internal error! Worker sent a message "${E2}" to target pthread ${I2.targetThread}, but that thread no longer exists!`); } else E2 === "checkMailbox" ? Zr2() : E2 === "spawnThread" ? ea3(I2) : E2 === "cleanupThread" ? oa3(ae2[I2.thread]) : E2 === "killThread" ? (I2 = I2.thread, E2 = ae2[I2], delete ae2[I2], wo3(E2), Do2(I2), De3.splice(De3.indexOf(E2), 1), E2.Ra = 0) : E2 === "cancelThread" ? ae2[I2.thread].postMessage({ cmd: "cancel" }) : E2 === "loaded" ? (c.loaded = true, m2(c)) : E2 === "alert" ? alert(`Thread ${I2.threadId}: ${I2.text}`) : I2.target === "setimmediate" ? c.postMessage(I2) : E2 === "callHandler" ? u[I2.handler](...I2.args) : E2 && et2(`worker sent an unknown command ${E2}`); }, c.onerror = (I2) => { throw et2(`worker sent an error! ${I2.filename}:${I2.lineno}: ${I2.message}`), I2; }; var g, x2 = []; for (g of []) u.hasOwnProperty(g) && x2.push(g); c.postMessage({ cmd: "load", handlers: x2, wasmMemory: C, wasmModule: jr2 }); }); function sa3() { var c = new Worker(new URL(import.meta.url), { type: "module", workerData: "em-pthread", name: "em-pthread" }); ve2.push(c); } var ua3, Jr2 = (c) => { for (; 0 < c.length; ) c.shift()(u); }, dd2 = () => { var c = er3(), m2 = r()[c + 52 >>> 2 >>> 0]; c = r()[c + 56 >>> 2 >>> 0], ja3(m2, m2 - c), rn2(m2); }, Yr3 = [], hd2 = (c, m2) => { vr3 = 0; var g = Yr3[c]; g || (c >= Yr3.length && (Yr3.length = c + 1), Yr3[c] = g = ua3.get(c)), c = g(m2), 0 < vr3 ? ge3 = c : en3(c); }; class md2 { constructor(m2) { this.Xa = m2 - 24; } } function bd2(c, m2, g) { var x2 = new md2(c >>>= 0); throw m2 >>>= 0, g >>>= 0, r()[x2.Xa + 16 >>> 2 >>> 0] = 0, r()[x2.Xa + 4 >>> 2 >>> 0] = m2, r()[x2.Xa + 8 >>> 2 >>> 0] = g, c; } function la3(c, m2, g, x2) { return d ? at3(2, 1, c, m2, g, x2) : fa3(c, m2, g, x2); } function fa3(c, m2, g, x2) { if (c >>>= 0, m2 >>>= 0, g >>>= 0, x2 >>>= 0, v === void 0) return et2("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; var I2 = []; return d && I2.length === 0 ? la3(c, m2, g, x2) : (c = { cb: g, Ra: c, ab: x2, ib: I2 }, d ? (c.Za = "spawnThread", postMessage(c, I2), 0) : ea3(c)); } var ca3 = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0, pa3 = (c, m2, g) => { var x2 = (m2 >>>= 0) + g; for (g = m2; c[g] && !(g >= x2); ) ++g; if (16 < g - m2 && c.buffer && ca3) return ca3.decode(c.buffer instanceof v ? c.slice(m2, g) : c.subarray(m2, g)); for (x2 = ""; m2 < g; ) { var I2 = c[m2++]; if (128 & I2) { var E2 = 63 & c[m2++]; if ((224 & I2) == 192) x2 += String.fromCharCode((31 & I2) << 6 | E2); else { var R = 63 & c[m2++]; 65536 > (I2 = (240 & I2) == 224 ? (15 & I2) << 12 | E2 << 6 | R : (7 & I2) << 18 | E2 << 12 | R << 6 | 63 & c[m2++]) ? x2 += String.fromCharCode(I2) : (I2 -= 65536, x2 += String.fromCharCode(55296 | I2 >> 10, 56320 | 1023 & I2)); } } else x2 += String.fromCharCode(I2); } return x2; }, Ir3 = (c, m2) => (c >>>= 0) ? pa3(o(), c, m2) : ""; function da3(c, m2, g) { return d ? at3(3, 1, c, m2, g) : 0; } function ha3(c, m2) { if (d) return at3(4, 1, c, m2); } var ma3 = (c) => { for (var m2 = 0, g = 0; g < c.length; ++g) { var x2 = c.charCodeAt(g); 127 >= x2 ? m2++ : 2047 >= x2 ? m2 += 2 : 55296 <= x2 && 57343 >= x2 ? (m2 += 4, ++g) : m2 += 3; } return m2; }, ba3 = (c, m2, g, x2) => { if (!(0 < x2)) return 0; var I2 = g >>>= 0; x2 = g + x2 - 1; for (var E2 = 0; E2 < c.length; ++E2) { var R = c.charCodeAt(E2); if (55296 <= R && 57343 >= R && (R = 65536 + ((1023 & R) << 10) | 1023 & c.charCodeAt(++E2)), 127 >= R) { if (g >= x2) break; m2[g++ >>> 0] = R; } else { if (2047 >= R) { if (g + 1 >= x2) break; m2[g++ >>> 0] = 192 | R >> 6; } else { if (65535 >= R) { if (g + 2 >= x2) break; m2[g++ >>> 0] = 224 | R >> 12; } else { if (g + 3 >= x2) break; m2[g++ >>> 0] = 240 | R >> 18, m2[g++ >>> 0] = 128 | R >> 12 & 63; } m2[g++ >>> 0] = 128 | R >> 6 & 63; } m2[g++ >>> 0] = 128 | 63 & R; } } return m2[g >>> 0] = 0, g - I2; }, _r3 = (c, m2, g) => ba3(c, o(), m2, g); function ga3(c, m2) { if (d) return at3(5, 1, c, m2); } function ya3(c, m2, g) { if (d) return at3(6, 1, c, m2, g); } function xa3(c, m2, g) { return d ? at3(7, 1, c, m2, g) : 0; } function Ta3(c, m2) { if (d) return at3(8, 1, c, m2); } function wa3(c, m2, g) { if (d) return at3(9, 1, c, m2, g); } function va3(c, m2, g, x2) { if (d) return at3(10, 1, c, m2, g, x2); } function Ia3(c, m2, g, x2) { if (d) return at3(11, 1, c, m2, g, x2); } function _a3(c, m2, g, x2) { if (d) return at3(12, 1, c, m2, g, x2); } function Oa3(c) { if (d) return at3(13, 1, c); } function Sa3(c, m2) { if (d) return at3(14, 1, c, m2); } function Aa3(c, m2, g) { if (d) return at3(15, 1, c, m2, g); } var gd2 = () => { ie3(""); }, yd2 = () => 1; function xd2(c) { Eo3(c >>> 0, !p, 1, !f, 131072, false), ia3(); } function _o3(c) { c >>>= 0, typeof Atomics.jb == "function" && (Atomics.jb(t(), c >>> 2, c).value.then(Zr2), c += 128, Atomics.store(t(), c >>> 2, 1)); } var Zr2 = () => { var c = er3(); if (c && (_o3(c), c = qa2, !pe2)) try { if (c(), !(0 < vr3)) try { d ? en3(ge3) : Io3(ge3); } catch (m2) { m2 instanceof To3 || m2 == "unwind" || A2(1, m2); } } catch (m2) { m2 instanceof To3 || m2 == "unwind" || A2(1, m2); } }; function Td2(c, m2) { (c >>>= 0) == m2 >>> 0 ? setTimeout(Zr2) : d ? postMessage({ targetThread: c, cmd: "checkMailbox" }) : (c = ae2[c]) && c.postMessage({ cmd: "checkMailbox" }); } var Oo2 = []; function wd2(c, m2, g, x2, I2) { for (m2 >>>= 0, x2 /= 2, Oo2.length = x2, g = I2 >>> 0 >>> 3, I2 = 0; I2 < x2; I2++) Oo2[I2] = ne2[g + 2 * I2] ? ne2[g + 2 * I2 + 1] : n()[g + 2 * I2 + 1 >>> 0]; return (m2 ? ta3[m2] : Vd2[c])(...Oo2); } function vd2(c) { c >>>= 0, d ? postMessage({ cmd: "cleanupThread", thread: c }) : oa3(ae2[c]); } function Id2(c) { } function _d2(c, m2) { c = -9007199254740992 > c || 9007199254740992 < c ? NaN : Number(c), m2 >>>= 0, c = new Date(1e3 * c), t()[m2 >>> 2 >>> 0] = c.getUTCSeconds(), t()[m2 + 4 >>> 2 >>> 0] = c.getUTCMinutes(), t()[m2 + 8 >>> 2 >>> 0] = c.getUTCHours(), t()[m2 + 12 >>> 2 >>> 0] = c.getUTCDate(), t()[m2 + 16 >>> 2 >>> 0] = c.getUTCMonth(), t()[m2 + 20 >>> 2 >>> 0] = c.getUTCFullYear() - 1900, t()[m2 + 24 >>> 2 >>> 0] = c.getUTCDay(), c = (c.getTime() - Date.UTC(c.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, t()[m2 + 28 >>> 2 >>> 0] = c; } var Qe = (c) => c % 4 == 0 && (c % 100 != 0 || c % 400 == 0), Pa3 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Ea3 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; function Od2(c, m2) { c = -9007199254740992 > c || 9007199254740992 < c ? NaN : Number(c), m2 >>>= 0, c = new Date(1e3 * c), t()[m2 >>> 2 >>> 0] = c.getSeconds(), t()[m2 + 4 >>> 2 >>> 0] = c.getMinutes(), t()[m2 + 8 >>> 2 >>> 0] = c.getHours(), t()[m2 + 12 >>> 2 >>> 0] = c.getDate(), t()[m2 + 16 >>> 2 >>> 0] = c.getMonth(), t()[m2 + 20 >>> 2 >>> 0] = c.getFullYear() - 1900, t()[m2 + 24 >>> 2 >>> 0] = c.getDay(); var g = (Qe(c.getFullYear()) ? Pa3 : Ea3)[c.getMonth()] + c.getDate() - 1 | 0; t()[m2 + 28 >>> 2 >>> 0] = g, t()[m2 + 36 >>> 2 >>> 0] = -60 * c.getTimezoneOffset(), g = new Date(c.getFullYear(), 6, 1).getTimezoneOffset(); var x2 = new Date(c.getFullYear(), 0, 1).getTimezoneOffset(); c = 0 | (g != x2 && c.getTimezoneOffset() == Math.min(x2, g)), t()[m2 + 32 >>> 2 >>> 0] = c; } function Sd2(c) { c >>>= 0; var m2 = new Date(t()[c + 20 >>> 2 >>> 0] + 1900, t()[c + 16 >>> 2 >>> 0], t()[c + 12 >>> 2 >>> 0], t()[c + 8 >>> 2 >>> 0], t()[c + 4 >>> 2 >>> 0], t()[c >>> 2 >>> 0], 0), g = t()[c + 32 >>> 2 >>> 0], x2 = m2.getTimezoneOffset(), I2 = new Date(m2.getFullYear(), 6, 1).getTimezoneOffset(), E2 = new Date(m2.getFullYear(), 0, 1).getTimezoneOffset(), R = Math.min(E2, I2); return 0 > g ? t()[c + 32 >>> 2 >>> 0] = +(I2 != E2 && R == x2) : 0 < g != (R == x2) && (I2 = Math.max(E2, I2), m2.setTime(m2.getTime() + 6e4 * ((0 < g ? R : I2) - x2))), t()[c + 24 >>> 2 >>> 0] = m2.getDay(), g = (Qe(m2.getFullYear()) ? Pa3 : Ea3)[m2.getMonth()] + m2.getDate() - 1 | 0, t()[c + 28 >>> 2 >>> 0] = g, t()[c >>> 2 >>> 0] = m2.getSeconds(), t()[c + 4 >>> 2 >>> 0] = m2.getMinutes(), t()[c + 8 >>> 2 >>> 0] = m2.getHours(), t()[c + 12 >>> 2 >>> 0] = m2.getDate(), t()[c + 16 >>> 2 >>> 0] = m2.getMonth(), t()[c + 20 >>> 2 >>> 0] = m2.getYear(), c = m2.getTime(), BigInt(isNaN(c) ? -1 : c / 1e3); } function Da3(c, m2, g, x2, I2, E2, R) { return d ? at3(16, 1, c, m2, g, x2, I2, E2, R) : -52; } function La3(c, m2, g, x2, I2, E2) { if (d) return at3(17, 1, c, m2, g, x2, I2, E2); } function Ad2(c, m2, g, x2) { c >>>= 0, m2 >>>= 0, g >>>= 0, x2 >>>= 0; var I2 = (/* @__PURE__ */ new Date()).getFullYear(), E2 = new Date(I2, 0, 1), R = new Date(I2, 6, 1); I2 = E2.getTimezoneOffset(); var it3 = R.getTimezoneOffset(), At2 = Math.max(I2, it3); r()[c >>> 2 >>> 0] = 60 * At2, t()[m2 >>> 2 >>> 0] = +(I2 != it3), E2 = (c = (Dt2) => Dt2.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1])(E2), R = c(R), it3 < I2 ? (_r3(E2, g, 17), _r3(R, x2, 17)) : (_r3(E2, x2, 17), _r3(R, g, 17)); } var So3 = []; function Pd2(c, m2, g) { c >>>= 0, m2 >>>= 0, g >>>= 0, So3.length = 0; for (var x2; x2 = o()[m2++ >>> 0]; ) { var I2 = x2 != 105; g += (I2 &= x2 != 112) && g % 8 ? 4 : 0, So3.push(x2 == 112 ? r()[g >>> 2 >>> 0] : x2 == 106 ? ne2[g >>> 3] : x2 == 105 ? t()[g >>> 2 >>> 0] : n()[g >>> 3 >>> 0]), g += I2 ? 8 : 4; } return ta3[c](...So3); } var Ed2 = () => { }, Dd2 = () => Date.now(); function Ld2(c, m2) { return et2(Ir3(c >>> 0, m2 >>> 0)); } var $a3, $d2 = () => { throw vr3 += 1, "unwind"; }; function kd2() { return 4294901760; } $a3 = () => performance.timeOrigin + performance.now(); var Bd2 = () => navigator.hardwareConcurrency; function Fd2() { return ie3("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"), 0; } function Cd2(c) { c >>>= 0; var m2 = o().length; if (c <= m2 || 4294901760 < c) return false; for (var g = 1; 4 >= g; g *= 2) { var x2 = m2 * (1 + 0.2 / g); x2 = Math.min(x2, c + 100663296); var I2 = Math; x2 = Math.max(c, x2); t: { I2 = (I2.min.call(I2, 4294901760, x2 + (65536 - x2 % 65536) % 65536) - C.buffer.byteLength + 65535) / 65536; try { C.grow(I2), lt2(); var E2 = 1; break t; } catch { } E2 = void 0; } if (E2) return true; } return false; } var Qr2 = () => (ie3("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"), 0), tr2 = {}, ka3 = (c) => { c.forEach((m2) => { var g = Qr2(); g && (tr2[g] = m2); }); }; function Nd2() { var c = Error().stack.toString().split(` `); return c[0] == "Error" && c.shift(), ka3(c), tr2.$a = Qr2(), tr2.bb = c, tr2.$a; } function Rd2(c, m2, g) { if (c >>>= 0, m2 >>>= 0, tr2.$a == c) var x2 = tr2.bb; else (x2 = Error().stack.toString().split(` `))[0] == "Error" && x2.shift(), ka3(x2); for (var I2 = 3; x2[I2] && Qr2() != c; ) ++I2; for (c = 0; c < g && x2[c + I2]; ++c) t()[m2 + 4 * c >>> 2 >>> 0] = Qr2(); return c; } var Ao3, Po2 = {}, Ba3 = () => { if (!Ao3) { var c, m2 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: L || "./this.program" }; for (c in Po2) Po2[c] === void 0 ? delete m2[c] : m2[c] = Po2[c]; var g = []; for (c in m2) g.push(`${c}=${m2[c]}`); Ao3 = g; } return Ao3; }; function Fa3(c, m2) { if (d) return at3(18, 1, c, m2); c >>>= 0, m2 >>>= 0; var g = 0; return Ba3().forEach((x2, I2) => { var E2 = m2 + g; for (I2 = r()[c + 4 * I2 >>> 2 >>> 0] = E2, E2 = 0; E2 < x2.length; ++E2) e()[I2++ >>> 0] = x2.charCodeAt(E2); e()[I2 >>> 0] = 0, g += x2.length + 1; }), 0; } function Ca3(c, m2) { if (d) return at3(19, 1, c, m2); c >>>= 0, m2 >>>= 0; var g = Ba3(); r()[c >>> 2 >>> 0] = g.length; var x2 = 0; return g.forEach((I2) => x2 += I2.length + 1), r()[m2 >>> 2 >>> 0] = x2, 0; } function Na3(c) { return d ? at3(20, 1, c) : 52; } function Ra3(c, m2, g, x2) { return d ? at3(21, 1, c, m2, g, x2) : 52; } function Ga3(c, m2, g, x2) { return d ? at3(22, 1, c, m2, g, x2) : 70; } var Gd2 = [null, [], []]; function Ma3(c, m2, g, x2) { if (d) return at3(23, 1, c, m2, g, x2); m2 >>>= 0, g >>>= 0, x2 >>>= 0; for (var I2 = 0, E2 = 0; E2 < g; E2++) { var R = r()[m2 >>> 2 >>> 0], it3 = r()[m2 + 4 >>> 2 >>> 0]; m2 += 8; for (var At2 = 0; At2 < it3; At2++) { var Dt2 = o()[R + At2 >>> 0], Bt2 = Gd2[c]; Dt2 === 0 || Dt2 === 10 ? ((c === 1 ? xt3 : et2)(pa3(Bt2, 0)), Bt2.length = 0) : Bt2.push(Dt2); } I2 += it3; } return r()[x2 >>> 2 >>> 0] = I2, 0; } var Ua3 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Va3 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Md2 = (c, m2) => { e().set(c, m2 >>> 0); }; function za3(c, m2, g, x2) { function I2(_, Q2, ft2) { for (_ = typeof _ == "number" ? _.toString() : _ || ""; _.length < Q2; ) _ = ft2[0] + _; return _; } function E2(_, Q2) { return I2(_, Q2, "0"); } function R(_, Q2) { function ft2(Ya3) { return 0 > Ya3 ? -1 : 0 < Ya3 ? 1 : 0; } var Le3; return (Le3 = ft2(_.getFullYear() - Q2.getFullYear())) === 0 && (Le3 = ft2(_.getMonth() - Q2.getMonth())) === 0 && (Le3 = ft2(_.getDate() - Q2.getDate())), Le3; } function it3(_) { switch (_.getDay()) { case 0: return new Date(_.getFullYear() - 1, 11, 29); case 1: return _; case 2: return new Date(_.getFullYear(), 0, 3); case 3: return new Date(_.getFullYear(), 0, 2); case 4: return new Date(_.getFullYear(), 0, 1); case 5: return new Date(_.getFullYear() - 1, 11, 31); case 6: return new Date(_.getFullYear() - 1, 11, 30); } } function At2(_) { var Q2 = _.Sa; for (_ = new Date(new Date(_.Ta + 1900, 0, 1).getTime()); 0 < Q2; ) { var ft2 = _.getMonth(), Le3 = (Qe(_.getFullYear()) ? Ua3 : Va3)[ft2]; if (!(Q2 > Le3 - _.getDate())) { _.setDate(_.getDate() + Q2); break; } Q2 -= Le3 - _.getDate() + 1, _.setDate(1), 11 > ft2 ? _.setMonth(ft2 + 1) : (_.setMonth(0), _.setFullYear(_.getFullYear() + 1)); } return ft2 = new Date(_.getFullYear() + 1, 0, 4), Q2 = it3(new Date(_.getFullYear(), 0, 4)), ft2 = it3(ft2), 0 >= R(Q2, _) ? 0 >= R(ft2, _) ? _.getFullYear() + 1 : _.getFullYear() : _.getFullYear() - 1; } c >>>= 0, m2 >>>= 0, g >>>= 0, x2 >>>= 0; var Dt2 = r()[x2 + 40 >>> 2 >>> 0]; for (var Bt2 in x2 = { gb: t()[x2 >>> 2 >>> 0], fb: t()[x2 + 4 >>> 2 >>> 0], Va: t()[x2 + 8 >>> 2 >>> 0], Ya: t()[x2 + 12 >>> 2 >>> 0], Wa: t()[x2 + 16 >>> 2 >>> 0], Ta: t()[x2 + 20 >>> 2 >>> 0], Qa: t()[x2 + 24 >>> 2 >>> 0], Sa: t()[x2 + 28 >>> 2 >>> 0], nb: t()[x2 + 32 >>> 2 >>> 0], eb: t()[x2 + 36 >>> 2 >>> 0], hb: Dt2 ? Ir3(Dt2) : "" }, g = Ir3(g), Dt2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) g = g.replace(new RegExp(Bt2, "g"), Dt2[Bt2]); var Ka3 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), Ja3 = "January February March April May June July August September October November December".split(" "); for (Bt2 in Dt2 = { "%a": (_) => Ka3[_.Qa].substring(0, 3), "%A": (_) => Ka3[_.Qa], "%b": (_) => Ja3[_.Wa].substring(0, 3), "%B": (_) => Ja3[_.Wa], "%C": (_) => E2((_.Ta + 1900) / 100 | 0, 2), "%d": (_) => E2(_.Ya, 2), "%e": (_) => I2(_.Ya, 2, " "), "%g": (_) => At2(_).toString().substring(2), "%G": At2, "%H": (_) => E2(_.Va, 2), "%I": (_) => ((_ = _.Va) == 0 ? _ = 12 : 12 < _ && (_ -= 12), E2(_, 2)), "%j": (_) => { for (var Q2 = 0, ft2 = 0; ft2 <= _.Wa - 1; Q2 += (Qe(_.Ta + 1900) ? Ua3 : Va3)[ft2++]) ; return E2(_.Ya + Q2, 3); }, "%m": (_) => E2(_.Wa + 1, 2), "%M": (_) => E2(_.fb, 2), "%n": () => ` `, "%p": (_) => 0 <= _.Va && 12 > _.Va ? "AM" : "PM", "%S": (_) => E2(_.gb, 2), "%t": () => " ", "%u": (_) => _.Qa || 7, "%U": (_) => E2(Math.floor((_.Sa + 7 - _.Qa) / 7), 2), "%V": (_) => { var Q2 = Math.floor((_.Sa + 7 - (_.Qa + 6) % 7) / 7); if (2 >= (_.Qa + 371 - _.Sa - 2) % 7 && Q2++, Q2) Q2 == 53 && ((ft2 = (_.Qa + 371 - _.Sa) % 7) == 4 || ft2 == 3 && Qe(_.Ta) || (Q2 = 1)); else { Q2 = 52; var ft2 = (_.Qa + 7 - _.Sa - 1) % 7; (ft2 == 4 || ft2 == 5 && Qe(_.Ta % 400 - 1)) && Q2++; } return E2(Q2, 2); }, "%w": (_) => _.Qa, "%W": (_) => E2(Math.floor((_.Sa + 7 - (_.Qa + 6) % 7) / 7), 2), "%y": (_) => (_.Ta + 1900).toString().substring(2), "%Y": (_) => _.Ta + 1900, "%z": (_) => { var Q2 = 0 <= (_ = _.eb); return _ = Math.abs(_) / 60, (Q2 ? "+" : "-") + ("0000" + (_ / 60 * 100 + _ % 60)).slice(-4); }, "%Z": (_) => _.hb, "%%": () => "%" }, g = g.replace(/%%/g, "\0\0"), Dt2) g.includes(Bt2) && (g = g.replace(new RegExp(Bt2, "g"), Dt2[Bt2](x2))); return Bt2 = (function(_) { var Q2 = Array(ma3(_) + 1); return ba3(_, Q2, 0, Q2.length), Q2; })(g = g.replace(/\0\0/g, "%")), Bt2.length > m2 ? 0 : (Md2(Bt2, c), Bt2.length - 1); } function Ud2(c, m2, g, x2) { return za3(c >>> 0, m2 >>> 0, g >>> 0, x2 >>> 0); } d || (function() { for (var c = u.numThreads - 1; c--; ) sa3(); Gt3.unshift(() => { Te2++, (function(m2) { d ? m2() : Promise.all(ve2.map(aa3)).then(m2); })(() => we2()); }); })(); var Vd2 = [vo3, ra2, la3, da3, ha3, ga3, ya3, xa3, Ta3, wa3, va3, Ia3, _a3, Oa3, Sa3, Aa3, Da3, La3, Fa3, Ca3, Na3, Ra3, Ga3, Ma3], U3 = (function() { function c(g, x2) { return U3 = g.exports, U3 = (function() { var I2 = U3, E2 = (it3) => () => it3() >>> 0, R = (it3) => (At2) => it3(At2) >>> 0; return (I2 = Object.assign({}, I2)).Ba = E2(I2.Ba), I2.Ca = R(I2.Ca), I2.emscripten_main_runtime_thread_id = E2(I2.emscripten_main_runtime_thread_id), I2.Oa = R(I2.Oa), I2.Pa = E2(I2.Pa), I2; })(), na3.push(U3.Ea), ua3 = U3.Fa, Xr2.unshift(U3.$), jr2 = x2, we2(), U3; } var m2 = Kr2(); if (Te2++, u.instantiateWasm) try { return u.instantiateWasm(m2, c); } catch (g) { et2(`Module.instantiateWasm callback failed with error: ${g}`), a(g); } return Ze ||= u.locateFile ? Ot("ort-wasm-simd-threaded.wasm") ? "ort-wasm-simd-threaded.wasm" : u.locateFile ? u.locateFile("ort-wasm-simd-threaded.wasm", P2) : P2 + "ort-wasm-simd-threaded.wasm" : new URL("ort-wasm-simd-threaded.wasm", import.meta.url).href, (function(g, x2) { var I2 = Ze; return M3 || typeof WebAssembly.instantiateStreaming != "function" || Ot(I2) || St3(I2) || typeof fetch != "function" ? wr3(I2, g, x2) : fetch(I2, { credentials: "same-origin" }).then((E2) => WebAssembly.instantiateStreaming(E2, g).then(x2, function(R) { return et2(`wasm streaming compile failed: ${R}`), et2("falling back to ArrayBuffer instantiation"), wr3(I2, g, x2); })); })(m2, function(g) { c(g.instance, g.module); }).catch(a), {}; })(); u._OrtInit = (c, m2) => (u._OrtInit = U3.aa)(c, m2), u._OrtGetLastError = (c, m2) => (u._OrtGetLastError = U3.ba)(c, m2), u._OrtCreateSessionOptions = (c, m2, g, x2, I2, E2, R, it3, At2, Dt2) => (u._OrtCreateSessionOptions = U3.ca)(c, m2, g, x2, I2, E2, R, it3, At2, Dt2), u._OrtAppendExecutionProvider = (c, m2) => (u._OrtAppendExecutionProvider = U3.da)(c, m2), u._OrtAddFreeDimensionOverride = (c, m2, g) => (u._OrtAddFreeDimensionOverride = U3.ea)(c, m2, g), u._OrtAddSessionConfigEntry = (c, m2, g) => (u._OrtAddSessionConfigEntry = U3.fa)(c, m2, g), u._OrtReleaseSessionOptions = (c) => (u._OrtReleaseSessionOptions = U3.ga)(c), u._OrtCreateSession = (c, m2, g) => (u._OrtCreateSession = U3.ha)(c, m2, g), u._OrtReleaseSession = (c) => (u._OrtReleaseSession = U3.ia)(c), u._OrtGetInputOutputCount = (c, m2, g) => (u._OrtGetInputOutputCount = U3.ja)(c, m2, g), u._OrtGetInputName = (c, m2) => (u._OrtGetInputName = U3.ka)(c, m2), u._OrtGetOutputName = (c, m2) => (u._OrtGetOutputName = U3.la)(c, m2), u._OrtFree = (c) => (u._OrtFree = U3.ma)(c), u._OrtCreateTensor = (c, m2, g, x2, I2, E2) => (u._OrtCreateTensor = U3.na)(c, m2, g, x2, I2, E2), u._OrtGetTensorData = (c, m2, g, x2, I2) => (u._OrtGetTensorData = U3.oa)(c, m2, g, x2, I2), u._OrtReleaseTensor = (c) => (u._OrtReleaseTensor = U3.pa)(c), u._OrtCreateRunOptions = (c, m2, g, x2) => (u._OrtCreateRunOptions = U3.qa)(c, m2, g, x2), u._OrtAddRunConfigEntry = (c, m2, g) => (u._OrtAddRunConfigEntry = U3.ra)(c, m2, g), u._OrtReleaseRunOptions = (c) => (u._OrtReleaseRunOptions = U3.sa)(c), u._OrtCreateBinding = (c) => (u._OrtCreateBinding = U3.ta)(c), u._OrtBindInput = (c, m2, g) => (u._OrtBindInput = U3.ua)(c, m2, g), u._OrtBindOutput = (c, m2, g, x2) => (u._OrtBindOutput = U3.va)(c, m2, g, x2), u._OrtClearBoundOutputs = (c) => (u._OrtClearBoundOutputs = U3.wa)(c), u._OrtReleaseBinding = (c) => (u._OrtReleaseBinding = U3.xa)(c), u._OrtRunWithBinding = (c, m2, g, x2, I2) => (u._OrtRunWithBinding = U3.ya)(c, m2, g, x2, I2), u._OrtRun = (c, m2, g, x2, I2, E2, R, it3) => (u._OrtRun = U3.za)(c, m2, g, x2, I2, E2, R, it3), u._OrtEndProfiling = (c) => (u._OrtEndProfiling = U3.Aa)(c); var er3 = () => (er3 = U3.Ba)(); u._malloc = (c) => (u._malloc = U3.Ca)(c), u._free = (c) => (u._free = U3.Da)(c); var tn2, Eo3 = (c, m2, g, x2, I2, E2) => (Eo3 = U3.Ga)(c, m2, g, x2, I2, E2), Wa3 = () => (Wa3 = U3.Ha)(), Ha3 = (c, m2, g, x2, I2) => (Ha3 = U3.Ia)(c, m2, g, x2, I2), Do2 = (c) => (Do2 = U3.Ja)(c), en3 = (c) => (en3 = U3.Ka)(c), qa2 = () => (qa2 = U3.La)(), ja3 = (c, m2) => (ja3 = U3.Ma)(c, m2), rn2 = (c) => (rn2 = U3.Na)(c), Lo2 = (c) => (Lo2 = U3.Oa)(c), $o3 = () => ($o3 = U3.Pa)(); function Xa3() { 0 < Te2 || (d ? (s(u), d || Jr2(Xr2), startWorker(u)) : (Jr2(Gt3), 0 < Te2 || tn2 || (tn2 = true, u.calledRun = true, pe2 || (d || Jr2(Xr2), s(u), d || Jr2(Je2))))); } return u.___start_em_js = 822690, u.___stop_em_js = 822751, u.stackSave = () => $o3(), u.stackRestore = (c) => rn2(c), u.stackAlloc = (c) => Lo2(c), u.UTF8ToString = Ir3, u.stringToUTF8 = _r3, u.lengthBytesUTF8 = ma3, Ee3 = function c() { tn2 || Xa3(), tn2 || (Ee3 = c); }, Xa3(), l; }), Ig = Rp; globalThis.self?.name === "em-pthread" && Rp(); }); Vr = O(() => { "use strict"; ro(); br = false ? void 0 : import.meta.url ?? (typeof document < "u" ? document.currentScript?.src : typeof self < "u" ? self.location?.href : void 0), _g = typeof location > "u" ? void 0 : location.origin, Og = (i, e) => { try { let o = e ?? br; return (o ? new URL(i, o) : new URL(i)).origin === _g; } catch { return false; } }, Sg = async (i) => { let o = await (await fetch(i, { credentials: "same-origin" })).blob(); return URL.createObjectURL(o); }, Up = (Np(), on(Cp)).default, Vp = async () => { if (!br) throw new Error("Failed to load proxy worker: cannot determine the script source URL."); if (Og(br)) return [void 0, Up()]; let i = await Sg(br); return [i, Up(i)]; }, Ag = (Mp(), on(Gp)).default, zp = async (i, e, o) => [void 0, Ag]; }); Xe = O(() => { "use strict"; Vr(); qi = false, co = false, Wp = false, Pg = () => { if (typeof SharedArrayBuffer > "u") return false; try { return typeof MessageChannel < "u" && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11])); } catch { return false; } }, Eg = () => { try { return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11])); } catch { return false; } }, no = async (i) => { if (qi) return Promise.resolve(); if (co) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); if (Wp) throw new Error("previous call to 'initializeWebAssembly()' failed."); co = true; let e = i.initTimeout, o = i.numThreads; if (!Eg()) throw new Error("WebAssembly SIMD is not supported in the current environment."); let t = Pg(); o > 1 && !t && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + o + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."), console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."), i.numThreads = o = 1); let r = i.wasmPaths, n = typeof r == "string" ? r : void 0, s = r?.mjs, a = s?.href ?? s, u = r?.wasm, l = u?.href ?? u, f = i.wasmBinary, [p, d] = await zp(a, n, o > 1), y = false, w = []; if (e > 0 && w.push(new Promise((v) => { setTimeout(() => { y = true, v(); }, e); })), w.push(new Promise((v, S) => { let L = { numThreads: o }; f ? L.wasmBinary = f : (l || n) && (L.locateFile = (A2, P2) => l ?? (n ?? P2) + A2), d(L).then((A2) => { co = false, qi = true, Hi = A2, v(), p && URL.revokeObjectURL(p); }, (A2) => { co = false, Wp = true, S(A2); }); })), await Promise.race(w), y) throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`); }, gt = () => { if (qi && Hi) return Hi; throw new Error("WebAssembly is not initialized yet."); }; }); po = O(() => { "use strict"; Xe(); yt = (i, e) => { let o = gt(), t = o.lengthBytesUTF8(i) + 1, r = o._malloc(t); return o.stringToUTF8(i, r, t), e.push(r), r; }, Wr = (i, e, o, t) => { if (typeof i == "object" && i !== null) { if (o.has(i)) throw new Error("Circular reference in options"); o.add(i); } Object.entries(i).forEach(([r, n]) => { let s = e ? e + r : r; if (typeof n == "object") Wr(n, s + ".", o, t); else if (typeof n == "string" || typeof n == "number") t(s, n.toString()); else if (typeof n == "boolean") t(s, n ? "1" : "0"); else throw new Error(`Can't handle extra config type: ${typeof n}`); }); }, ht = (i) => { let e = gt(), o = e.stackSave(); try { let t = e.stackAlloc(8); e._OrtGetLastError(t, t + 4); let r = e.HEAP32[t / 4], n = e.HEAPU32[t / 4 + 1], s = n ? e.UTF8ToString(n) : ""; throw new Error(`${i} ERROR_CODE: ${r}, ERROR_MESSAGE: ${s}`); } finally { e.stackRestore(o); } }; }); qp = O(() => { "use strict"; Xe(); po(); Hp = (i) => { let e = gt(), o = 0, t = [], r = i || {}; try { if (i?.logSeverityLevel === void 0) r.logSeverityLevel = 2; else if (typeof i.logSeverityLevel != "number" || !Number.isInteger(i.logSeverityLevel) || i.logSeverityLevel < 0 || i.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${i.logSeverityLevel}`); if (i?.logVerbosityLevel === void 0) r.logVerbosityLevel = 0; else if (typeof i.logVerbosityLevel != "number" || !Number.isInteger(i.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${i.logVerbosityLevel}`); i?.terminate === void 0 && (r.terminate = false); let n = 0; return i?.tag !== void 0 && (n = yt(i.tag, t)), o = e._OrtCreateRunOptions(r.logSeverityLevel, r.logVerbosityLevel, !!r.terminate, n), o === 0 && ht("Can't create run options."), i?.extra !== void 0 && Wr(i.extra, "", /* @__PURE__ */ new WeakSet(), (s, a) => { let u = yt(s, t), l = yt(a, t); e._OrtAddRunConfigEntry(o, u, l) !== 0 && ht(`Can't set a run config entry: ${s} - ${a}.`); }), [o, t]; } catch (n) { throw o !== 0 && e._OrtReleaseRunOptions(o), t.forEach((s) => e._free(s)), n; } }; }); Xp = O(() => { "use strict"; Xe(); po(); Dg = (i) => { switch (i) { case "disabled": return 0; case "basic": return 1; case "extended": return 2; case "all": return 99; default: throw new Error(`unsupported graph optimization level: ${i}`); } }, Lg = (i) => { switch (i) { case "sequential": return 0; case "parallel": return 1; default: throw new Error(`unsupported execution mode: ${i}`); } }, $g = (i) => { i.extra || (i.extra = {}), i.extra.session || (i.extra.session = {}); let e = i.extra.session; e.use_ort_model_bytes_directly || (e.use_ort_model_bytes_directly = "1"), i.executionProviders && i.executionProviders.some((o) => (typeof o == "string" ? o : o.name) === "webgpu") && (i.enableMemPattern = false); }, kg = (i, e, o) => { for (let t of e) { let r = typeof t == "string" ? t : t.name; switch (r) { case "webnn": if (r = "WEBNN", typeof t != "string") { let a = t?.deviceType; if (a) { let u = yt("deviceType", o), l = yt(a, o); gt()._OrtAddSessionConfigEntry(i, u, l) !== 0 && ht(`Can't set a session config entry: 'deviceType' - ${a}.`); } } break; case "webgpu": if (r = "JS", typeof t != "string") { let s = t; if (s?.preferredLayout) { if (s.preferredLayout !== "NCHW" && s.preferredLayout !== "NHWC") throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`); let a = yt("preferredLayout", o), u = yt(s.preferredLayout, o); gt()._OrtAddSessionConfigEntry(i, a, u) !== 0 && ht(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`); } } break; case "wasm": case "cpu": continue; default: throw new Error(`not supported execution provider: ${r}`); } let n = yt(r, o); gt()._OrtAppendExecutionProvider(i, n) !== 0 && ht(`Can't append execution provider: ${r}.`); } }, jp = (i) => { let e = gt(), o = 0, t = [], r = i || {}; $g(r); try { let n = Dg(r.graphOptimizationLevel ?? "all"), s = Lg(r.executionMode ?? "sequential"), a = typeof r.logId == "string" ? yt(r.logId, t) : 0, u = r.logSeverityLevel ?? 2; if (!Number.isInteger(u) || u < 0 || u > 4) throw new Error(`log serverity level is not valid: ${u}`); let l = r.logVerbosityLevel ?? 0; if (!Number.isInteger(l) || l < 0 || l > 4) throw new Error(`log verbosity level is not valid: ${l}`); let f = typeof r.optimizedModelFilePath == "string" ? yt(r.optimizedModelFilePath, t) : 0; if (o = e._OrtCreateSessionOptions(n, !!r.enableCpuMemArena, !!r.enableMemPattern, s, !!r.enableProfiling, 0, a, u, l, f), o === 0 && ht("Can't create session options."), r.executionProviders && kg(o, r.executionProviders, t), r.enableGraphCapture !== void 0) { if (typeof r.enableGraphCapture != "boolean") throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`); let p = yt("enableGraphCapture", t), d = yt(r.enableGraphCapture.toString(), t); e._OrtAddSessionConfigEntry(o, p, d) !== 0 && ht(`Can't set a session config entry: 'enableGraphCapture' - ${r.enableGraphCapture}.`); } if (r.freeDimensionOverrides) for (let [p, d] of Object.entries(r.freeDimensionOverrides)) { if (typeof p != "string") throw new Error(`free dimension override name must be a string: ${p}`); if (typeof d != "number" || !Number.isInteger(d) || d < 0) throw new Error(`free dimension override value must be a non-negative integer: ${d}`); let y = yt(p, t); e._OrtAddFreeDimensionOverride(o, y, d) !== 0 && ht(`Can't set a free dimension override: ${p} - ${d}.`); } return r.extra !== void 0 && Wr(r.extra, "", /* @__PURE__ */ new WeakSet(), (p, d) => { let y = yt(p, t), w = yt(d, t); e._OrtAddSessionConfigEntry(o, y, w) !== 0 && ht(`Can't set a session config entry: ${p} - ${d}.`); }), [o, t]; } catch (n) { throw o !== 0 && e._OrtReleaseSessionOptions(o), t.forEach((s) => e._free(s)), n; } }; }); Ki = O(() => { "use strict"; ji = (i) => { switch (i) { case "int8": return 3; case "uint8": return 2; case "bool": return 9; case "int16": return 5; case "uint16": return 4; case "int32": return 6; case "uint32": return 12; case "float16": return 10; case "float32": return 1; case "float64": return 11; case "string": return 8; case "int64": return 7; case "uint64": return 13; default: throw new Error(`unsupported data type: ${i}`); } }, Kp = (i) => { switch (i) { case 3: return "int8"; case 2: return "uint8"; case 9: return "bool"; case 5: return "int16"; case 4: return "uint16"; case 6: return "int32"; case 12: return "uint32"; case 10: return "float16"; case 1: return "float32"; case 11: return "float64"; case 8: return "string"; case 7: return "int64"; case 13: return "uint64"; default: throw new Error(`unsupported data type: ${i}`); } }, Xi = (i) => [void 0, 4, 1, 1, 2, 2, 4, 8, void 0, 1, 2, 8, 4, 8, void 0, void 0, void 0][i], Jp = (i) => { switch (i) { case "float16": return typeof Float16Array < "u" && Float16Array.from ? Float16Array : Uint16Array; case "float32": return Float32Array; case "uint8": return Uint8Array; case "int8": return Int8Array; case "uint16": return Uint16Array; case "int16": return Int16Array; case "int32": return Int32Array; case "bool": return Uint8Array; case "float64": return Float64Array; case "uint32": return Uint32Array; case "int64": return BigInt64Array; case "uint64": return BigUint64Array; default: throw new Error(`unsupported type: ${i}`); } }, Yp = (i) => { switch (i) { case "verbose": return 0; case "info": return 1; case "warning": return 2; case "error": return 3; case "fatal": return 4; default: throw new Error(`unsupported logging level: ${i}`); } }, ho = (i) => i === "float32" || i === "float16" || i === "int32" || i === "int64" || i === "uint32" || i === "uint8" || i === "bool", Zp = (i) => { switch (i) { case "none": return 0; case "cpu": return 1; case "cpu-pinned": return 2; case "texture": return 3; case "gpu-buffer": return 4; default: throw new Error(`unsupported data location: ${i}`); } }; }); Ji = O(() => { "use strict"; ro(); Hr = async (i) => { if (typeof i == "string") if (false) try { let { readFile: e } = ko("node:fs/promises"); return new Uint8Array(await e(i)); } catch (e) { if (e.code === "ERR_FS_FILE_TOO_LARGE") { let { createReadStream: o } = ko("node:fs"), t = o(i), r = []; for await (let n of t) r.push(n); return new Uint8Array(Buffer.concat(r)); } throw e; } else { let e = await fetch(i); if (!e.ok) throw new Error(`failed to load external data file: ${i}`); let o = e.headers.get("Content-Length"), t = o ? parseInt(o, 10) : 0; if (t < 1073741824) return new Uint8Array(await e.arrayBuffer()); { if (!e.body) throw new Error(`failed to load external data file: ${i}, no response body.`); let r = e.body.getReader(), n; try { n = new ArrayBuffer(t); } catch (a) { if (a instanceof RangeError) { let u = Math.ceil(t / 65536); n = new WebAssembly.Memory({ initial: u, maximum: u }).buffer; } else throw a; } let s = 0; for (; ; ) { let { done: a, value: u } = await r.read(); if (a) break; let l = u.byteLength; new Uint8Array(n, s, l).set(u), s += l; } return new Uint8Array(n, 0, t); } } else return i instanceof Blob ? new Uint8Array(await i.arrayBuffer()) : i instanceof Uint8Array ? i : new Uint8Array(i); }; }); zi = O(() => { "use strict"; qp(); Xp(); Ki(); Xe(); po(); Ji(); Bg = (i, e) => { gt()._OrtInit(i, e) !== 0 && ht("Can't initialize onnxruntime."); }, oo = async (i) => { Bg(i.wasm.numThreads, Yp(i.logLevel)); }, io = async (i, e) => { }, yr = /* @__PURE__ */ new Map(), Fg = (i) => { let e = gt(), o = e.stackSave(); try { let t = e.stackAlloc(8); return e._OrtGetInputOutputCount(i, t, t + 4) !== 0 && ht("Can't get session input/output count."), [e.HEAP32[t / 4], e.HEAP32[t / 4 + 1]]; } finally { e.stackRestore(o); } }, zr = (i) => { let e = gt(), o = e._malloc(i.byteLength); if (o === 0) throw new Error(`Can't create a session. failed to allocate a buffer of size ${i.byteLength}.`); return e.HEAPU8.set(i, o), [o, i.byteLength]; }, ao = async (i, e) => { let o, t, r = gt(); Array.isArray(i) ? [o, t] = i : i.buffer === r.HEAPU8.buffer ? [o, t] = [i.byteOffset, i.byteLength] : [o, t] = zr(i); let n = 0, s = 0, a = 0, u = [], l = [], f = []; try { if ([s, u] = jp(e), e?.externalData && r.mountExternalData) { let A2 = []; for (let P2 of e.externalData) { let M3 = typeof P2 == "string" ? P2 : P2.path; A2.push(Hr(typeof P2 == "string" ? P2 : P2.data).then((V3) => { r.mountExternalData(M3, V3); })); } await Promise.all(A2); } for (let A2 of e?.executionProviders ?? []) if ((typeof A2 == "string" ? A2 : A2.name) === "webnn") { if (r.currentContext) throw new Error("WebNN execution provider is already set."); if (typeof A2 != "string") { let M3 = A2, V3 = M3?.context, ut2 = M3?.gpuDevice, xt3 = M3?.deviceType, et2 = M3?.numThreads, Et3 = M3?.powerPreference; V3 ? r.currentContext = V3 : ut2 ? r.currentContext = await navigator.ml.createContext(ut2) : r.currentContext = await navigator.ml.createContext({ deviceType: xt3, numThreads: et2, powerPreference: Et3 }); } else r.currentContext = await navigator.ml.createContext(); break; } n = await r._OrtCreateSession(o, t, s), n === 0 && ht("Can't create a session."), r.currentContext && (r.currentContext = void 0); let [p, d] = Fg(n), y = !!e?.enableGraphCapture, w = [], v = [], S = []; for (let A2 = 0; A2 < p; A2++) { let P2 = r._OrtGetInputName(n, A2); P2 === 0 && ht("Can't get an input name."), l.push(P2), w.push(r.UTF8ToString(P2)); } for (let A2 = 0; A2 < d; A2++) { let P2 = r._OrtGetOutputName(n, A2); P2 === 0 && ht("Can't get an output name."), f.push(P2); let M3 = r.UTF8ToString(P2); v.push(M3); } let L = null; return yr.set(n, [n, l, f, L, y, false]), [n, w, v]; } catch (p) { throw l.forEach((d) => r._OrtFree(d)), f.forEach((d) => r._OrtFree(d)), a !== 0 && r._OrtReleaseBinding(a), n !== 0 && r._OrtReleaseSession(n), p; } finally { r._free(o), s !== 0 && r._OrtReleaseSessionOptions(s), u.forEach((p) => r._free(p)), r.unmountExternalData?.(); } }, so = (i) => { let e = gt(), o = yr.get(i); if (!o) throw new Error(`cannot release session. invalid session id: ${i}`); let [t, r, n, s, a] = o; s && (a && e._OrtClearBoundOutputs(s.handle), e._OrtReleaseBinding(s.handle)), e.jsepOnReleaseSession?.(i), r.forEach((u) => e._OrtFree(u)), n.forEach((u) => e._OrtFree(u)), e._OrtReleaseSession(t), yr.delete(i); }, Qp = (i, e, o, t, r, n = false) => { if (!i) { e.push(0); return; } let s = gt(), a = i[0], u = i[1], l = i[3], f, p; if (a === "string" && l === "gpu-buffer") throw new Error("String tensor is not supported on GPU."); if (n && l !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${r} when enableGraphCapture is true.`); if (l === "gpu-buffer") { let w = i[2].gpuBuffer, v = Xi(ji(a)); p = u.reduce((L, A2) => L * A2, 1) * v; let S = s.jsepRegisterBuffer; if (!S) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.'); f = S(t, r, w, p); } else { let w = i[2]; if (Array.isArray(w)) { p = 4 * w.length, f = s._malloc(p), o.push(f); let v = f / 4; for (let S = 0; S < w.length; S++) { if (typeof w[S] != "string") throw new TypeError(`tensor data at index ${S} is not a string`); s.HEAPU32[v++] = yt(w[S], o); } } else p = w.byteLength, f = s._malloc(p), o.push(f), s.HEAPU8.set(new Uint8Array(w.buffer, w.byteOffset, p), f); } let d = s.stackSave(), y = s.stackAlloc(4 * u.length); try { let w = y / 4; u.forEach((S) => s.HEAP32[w++] = S); let v = s._OrtCreateTensor(ji(a), f, p, y, u.length, Zp(l)); v === 0 && ht(`Can't create tensor for input/output. session=${t}, index=${r}.`), e.push(v); } finally { s.stackRestore(d); } }, uo = async (i, e, o, t, r, n) => { let s = gt(), a = yr.get(i); if (!a) throw new Error(`cannot run inference. invalid session id: ${i}`); let u = a[0], l = a[1], f = a[2], p = a[3], d = a[4], y = a[5], w = e.length, v = t.length, S = 0, L = [], A2 = [], P2 = [], M3 = [], V3 = s.stackSave(), ut2 = s.stackAlloc(w * 4), xt3 = s.stackAlloc(w * 4), et2 = s.stackAlloc(v * 4), Et3 = s.stackAlloc(v * 4); try { [S, L] = Hp(n); for (let Z2 = 0; Z2 < w; Z2++) Qp(o[Z2], A2, M3, i, e[Z2], d); for (let Z2 = 0; Z2 < v; Z2++) Qp(r[Z2], P2, M3, i, w + t[Z2], d); let It2 = ut2 / 4, C = xt3 / 4, jr2 = et2 / 4, ge3 = Et3 / 4; for (let Z2 = 0; Z2 < w; Z2++) s.HEAPU32[It2++] = A2[Z2], s.HEAPU32[C++] = l[e[Z2]]; for (let Z2 = 0; Z2 < v; Z2++) s.HEAPU32[jr2++] = P2[Z2], s.HEAPU32[ge3++] = f[t[Z2]]; s.jsepOnRunStart?.(u); let re2; re2 = await s._OrtRun(u, xt3, ut2, w, Et3, v, et2, S), re2 !== 0 && ht("failed to call OrtRun()."); let ye2 = []; for (let Z2 = 0; Z2 < v; Z2++) { let xe = s.HEAPU32[et2 / 4 + Z2]; if (xe === P2[Z2]) { ye2.push(r[Z2]); continue; } let ne2 = s.stackSave(), oe2 = s.stackAlloc(4 * 4), pe2 = false, lt2, Gt3 = 0; try { s._OrtGetTensorData(xe, oe2, oe2 + 4, oe2 + 8, oe2 + 12) !== 0 && ht(`Can't access output tensor data on index ${Z2}.`); let Je2 = oe2 / 4, Te2 = s.HEAPU32[Je2++]; Gt3 = s.HEAPU32[Je2++]; let Ye2 = s.HEAPU32[Je2++], Ee3 = s.HEAPU32[Je2++], we2 = []; for (let Ot = 0; Ot < Ee3; Ot++) we2.push(s.HEAPU32[Ye2 / 4 + Ot]); s._OrtFree(Ye2); let ie3 = we2.reduce((Ot, St3) => Ot * St3, 1); lt2 = Kp(Te2); let Ze = p?.outputPreferredLocations[t[Z2]]; if (lt2 === "string") { if (Ze === "gpu-buffer") throw new Error("String tensor is not supported on GPU."); let Ot = [], St3 = Gt3 / 4; for (let de2 = 0; de2 < ie3; de2++) { let wr3 = s.HEAPU32[St3++], Kr2 = de2 === ie3 - 1 ? void 0 : s.HEAPU32[St3] - wr3; Ot.push(s.UTF8ToString(wr3, Kr2)); } ye2.push([lt2, we2, Ot, "cpu"]); } else if (Ze === "gpu-buffer" && ie3 > 0) { let Ot = s.jsepGetBuffer; if (!Ot) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.'); let St3 = Ot(Gt3), de2 = Xi(Te2); if (de2 === void 0 || !ho(lt2)) throw new Error(`Unsupported data type: ${lt2}`); pe2 = true, ye2.push([lt2, we2, { gpuBuffer: St3, download: s.jsepCreateDownloader(St3, ie3 * de2, lt2), dispose: () => { s._OrtReleaseTensor(xe); } }, "gpu-buffer"]); } else { let Ot = Jp(lt2), St3 = new Ot(ie3); new Uint8Array(St3.buffer, St3.byteOffset, St3.byteLength).set(s.HEAPU8.subarray(Gt3, Gt3 + St3.byteLength)), ye2.push([lt2, we2, St3, "cpu"]); } } finally { s.stackRestore(ne2), lt2 === "string" && Gt3 && s._free(Gt3), pe2 || s._OrtReleaseTensor(xe); } } return p && !d && (s._OrtClearBoundOutputs(p.handle), yr.set(i, [u, l, f, p, d, false])), ye2; } finally { s.stackRestore(V3), A2.forEach((It2) => s._OrtReleaseTensor(It2)), P2.forEach((It2) => s._OrtReleaseTensor(It2)), M3.forEach((It2) => s._free(It2)), S !== 0 && s._OrtReleaseRunOptions(S), L.forEach((It2) => s._free(It2)); } }, lo = (i) => { let e = gt(), o = yr.get(i); if (!o) throw new Error("invalid session id"); let t = o[0], r = e._OrtEndProfiling(t); r === 0 && ht("Can't get an profile file name."), e._OrtFree(r); }, fo = (i) => { let e = []; for (let o of i) { let t = o[2]; !Array.isArray(t) && "buffer" in t && e.push(t.buffer); } return e; }; }); Qi = O(() => { "use strict"; Kt(); zi(); Xe(); Vr(); Ke = () => !!z.wasm.proxy && typeof document < "u", qr = false, bo = false, go = false, Zi = /* @__PURE__ */ new Map(), xr = (i, e) => { let o = Zi.get(i); o ? o.push(e) : Zi.set(i, [e]); }, Tr = () => { if (qr || !bo || go || !Xt) throw new Error("worker not ready"); }, Ng = (i) => { switch (i.data.type) { case "init-wasm": qr = false, i.data.err ? (go = true, Yi[1](i.data.err)) : (bo = true, Yi[0]()), mo && (URL.revokeObjectURL(mo), mo = void 0); break; case "init-ep": case "copy-from": case "create": case "release": case "run": case "end-profiling": { let e = Zi.get(i.data.type); i.data.err ? e.shift()[1](i.data.err) : e.shift()[0](i.data.out); break; } default: } }, td = async () => { if (!bo) { if (qr) throw new Error("multiple calls to 'initWasm()' detected."); if (go) throw new Error("previous call to 'initWasm()' failed."); if (qr = true, Ke()) return new Promise((i, e) => { Xt?.terminate(), Vp().then(([o, t]) => { try { Xt = t, Xt.onerror = (n) => e(n), Xt.onmessage = Ng, Yi = [i, e]; let r = { type: "init-wasm", in: z }; Xt.postMessage(r), mo = o; } catch (r) { e(r); } }, e); }); try { await no(z.wasm), await oo(z), bo = true; } catch (i) { throw go = true, i; } finally { qr = false; } } }, ed = async (i) => { if (Ke()) return Tr(), new Promise((e, o) => { xr("init-ep", [e, o]); let t = { type: "init-ep", in: { epName: i, env: z } }; Xt.postMessage(t); }); await io(z, i); }, rd = async (i) => Ke() ? (Tr(), new Promise((e, o) => { xr("copy-from", [e, o]); let t = { type: "copy-from", in: { buffer: i } }; Xt.postMessage(t, [i.buffer]); })) : zr(i), nd = async (i, e) => { if (Ke()) { if (e?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); return Tr(), new Promise((o, t) => { xr("create", [o, t]); let r = { type: "create", in: { model: i, options: { ...e } } }, n = []; i instanceof Uint8Array && n.push(i.buffer), Xt.postMessage(r, n); }); } else return ao(i, e); }, od = async (i) => { if (Ke()) return Tr(), new Promise((e, o) => { xr("release", [e, o]); let t = { type: "release", in: i }; Xt.postMessage(t); }); so(i); }, id = async (i, e, o, t, r, n) => { if (Ke()) { if (o.some((s) => s[3] !== "cpu")) throw new Error("input tensor on GPU is not supported for proxy."); if (r.some((s) => s)) throw new Error("pre-allocated output tensor is not supported for proxy."); return Tr(), new Promise((s, a) => { xr("run", [s, a]); let u = o, l = { type: "run", in: { sessionId: i, inputIndices: e, inputs: u, outputIndices: t, options: n } }; Xt.postMessage(l, fo(u)); }); } else return uo(i, e, o, t, r, n); }, ad = async (i) => { if (Ke()) return Tr(), new Promise((e, o) => { xr("end-profiling", [e, o]); let t = { type: "end-profiling", in: i }; Xt.postMessage(t); }); lo(i); }; }); ud = O(() => { "use strict"; Kt(); Qi(); Ki(); ro(); Ji(); sd = (i, e) => { switch (i.location) { case "cpu": return [i.type, i.dims, i.data, "cpu"]; case "gpu-buffer": return [i.type, i.dims, { gpuBuffer: i.gpuBuffer }, "gpu-buffer"]; default: throw new Error(`invalid data location: ${i.location} for ${e()}`); } }, Rg = (i) => { switch (i[3]) { case "cpu": return new Tt(i[0], i[2], i[1]); case "gpu-buffer": { let e = i[0]; if (!ho(e)) throw new Error(`not supported data type: ${e} for deserializing GPU tensor`); let { gpuBuffer: o, download: t, dispose: r } = i[2]; return Tt.fromGpuBuffer(o, { dataType: e, dims: i[1], download: t, dispose: r }); } default: throw new Error(`invalid data location: ${i[3]}`); } }, yo = class { async fetchModelAndCopyToWasmMemory(e) { return rd(await Hr(e)); } async loadModel(e, o) { Be(); let t; typeof e == "string" ? false ? t = await Hr(e) : t = await this.fetchModelAndCopyToWasmMemory(e) : t = e, [this.sessionId, this.inputNames, this.outputNames] = await nd(t, o), Fe(); } async dispose() { return od(this.sessionId); } async run(e, o, t) { Be(); let r = [], n = []; Object.entries(e).forEach((d) => { let y = d[0], w = d[1], v = this.inputNames.indexOf(y); if (v === -1) throw new Error(`invalid input '${y}'`); r.push(w), n.push(v); }); let s = [], a = []; Object.entries(o).forEach((d) => { let y = d[0], w = d[1], v = this.outputNames.indexOf(y); if (v === -1) throw new Error(`invalid output '${y}'`); s.push(w), a.push(v); }); let u = r.map((d, y) => sd(d, () => `input "${this.inputNames[n[y]]}"`)), l = s.map((d, y) => d ? sd(d, () => `output "${this.outputNames[a[y]]}"`) : null), f = await id(this.sessionId, n, u, a, l, t), p = {}; for (let d = 0; d < f.length; d++) p[this.outputNames[a[d]]] = s[d] ?? Rg(f[d]); return Fe(), p; } startProfiling() { } endProfiling() { ad(this.sessionId); } }; }); ld = O(() => { "use strict"; Kt(); Qi(); ud(); Vr(); Gg = () => { if ((typeof z.wasm.initTimeout != "number" || z.wasm.initTimeout < 0) && (z.wasm.initTimeout = 0), z.wasm.simd === false && console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'), typeof z.wasm.proxy != "boolean" && (z.wasm.proxy = false), typeof z.wasm.trace != "boolean" && (z.wasm.trace = false), typeof z.wasm.numThreads != "number" || !Number.isInteger(z.wasm.numThreads) || z.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) z.wasm.numThreads = 1; else { let i = typeof navigator > "u" ? ko("node:os").cpus().length : navigator.hardwareConcurrency; z.wasm.numThreads = Math.min(4, Math.ceil((i || 1) / 2)); } }, xo = class { async init(e) { Gg(), await td(), await ed(e); } async createInferenceSessionHandler(e, o) { let t = new yo(); return await t.loadModel(e, o), Promise.resolve(t); } }; }); fd = {}; Or(fd, { wasmBackend: () => Mg }); cd = O(() => { "use strict"; ld(); Mg = new xo(); }); Kt(); Kt(); Kt(); Ps = "1.19.2"; bO = No; { let i = (kp(), on($p)).onnxjsBackend; nr("webgl", i, -10); } { let i = (cd(), on(fd)).wasmBackend; nr("cpu", i, 10), nr("wasm", i, 10); } Object.defineProperty(z.versions, "web", { value: Ps, enumerable: true }); } }); // node_modules/gliner/node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs var Rn2, op2, ip2, ap2, Mn2, U, Ft2, sp2, br2, wr, $t2, _t2, up2, vr, $r2, Yi2, Xi2, Zi2, Qi2, Ne, Un2, be2, Ji2, ea, ta, ra, Vn2, na, oa, ia, aa, sa, xt, qt2, ua, da, la, ca, pa, ma, Be2, _r, De, xr2, Sr2, fa, We2, Me2, Nn2, Ir, ha, dp2, ga, ya, ba, wa, va, lp2, Cr2, $a, cp2, _a, Wn2, Ke2, Tr2, Ca, Sa, Ia, pp2, Ta, Ea, Gn2, Aa, mp2, ka, Ut2, fp2, hp2, gp2, Pa, Oa, yp2, Da, jt2, Ln2, Fn2, Rr2, za, bp2, wp2, Ar2, Ie2, St, Te, Yt2, _e, Mr2, Ba, Ra, vp2, $p2, _p2, xp2, Ma, Ua, qn2, ht2, It, Ur2, Xt2, Vr2, jn2, Q, Zt, Kn2, Sp2, Ip2, Va, Na, Wa, Cp2, ve, dt2, Ha, Ga, Nr2, La, Yn2, Xn2, Tp2, Ap2, Fa, Qn2, Zn2, ja, Ka, Jn2, te, Ce2, eo2, tt2, k2, Ct, Wr2, Hr2, Gr2, ae, Tt2, ro2, ge, Oe2, V, $e2, gt2, At, Xe2, G2, no2, E, M, Lr, to2, Ya, Nt2, ie, Ep2, Xa, kp2, Pp2, Ue2, Za2, Qa2, Et, Op2, Dp2, zp2, Bp2, Rp2, Mp2, Up2, Vp2, Np2, Wp2, rt2, Ja, es2, ts2, rs2, ns2, os2, is2, as2, ss2, us2, ds2, nt, Hp2, qr2, oo2, ot2, Gp2, Lp2, Fp2, qp2, jp2, Kp2, Yp2, Xp2, Zp2, Qp2, it, ls2, cs2, ps2, ms2, fs4, hs2, gs2, ys2, bs2, ws2, Fr2, vs2, $s2, _s2, io2, xs2, Jp2, em2, tm2, rm2, Wt2, nm2, Ss2, jr, om2, im2, am2, Is2, Cs2, sm2, um2, Ts2, As2, dm2, fe2, Es2, ks2, Ps2, Os2, Ds2, zs2, Bs2, Rs2, Ms2, lm2, Us2, Vs2, Ns2, Ws, Qt, Hs2, Kr, Gs2, Ls2, Fs2, qs, js, Ks2, Ys2, Xs, Zs, Qs, Js, eu, tu, ru, nu, ou2, iu2, au, ao2, so2, su2, uu, du, cm2, pm2, lu2, Yr, mm2, fm2, pu, mu, hm2, gm2, at, fu, hu, gu, yu, bu, wu, vu, $u, _u, xu, Su, bm2, wm2, vm2, $m2, Iu, Cu, Tu2, He2, Ge2, Le, Xr, lt, Ee, Zr, Jt2, Qr, uo2, _m2, xm2, er, Au, Sm2, tr, Im, Jr, rr2, Cm2, Eu2, ku2, Tm2, Pu, en, Am2, Ou, Em2, Du, zu2, Bu, lo2, Ru2, Mu2, po2, km2, Uu, mo2, tn, fo2, Pm2, ho2, go2, Om2, Dm2, zm2, yo2, co2, Bm2, Vu2, Nu, Rm2, bo2, Wu2, Mm2, Um2, Vm2, Hu2, Gu, Nm2, Wm2, Hm2, Gm2, Lu2, Fu2, Lm2, qu2, ju2, Ku2, Fm2, qm2, jm2, Yu2, Xu2, Zu2, wo, rn, Qu2, Km2, Ym2, vo, $o, Ju2, Xm2, ed2, td2, rd2, Zm2, nd2, Qm2, Jm2, od2, id2, ef2, ad2, sd2, tf2, rf2, ud2, dd, ld2, nf2, of2, cd2, pd, md, af2, sf2, fd2, hd, gd, Ve2, lf2, bd, yd, cf2, nr2, wd, _o, vd, pf2, mf2, xo2, $d, So, ff2, _d, Sd, hf2, xd, Id, Cd, gf2, yf2, bf2, Td, Ad, wf2, vf2, Ed, kd, $f2, _f2, Pd, Od, Dd, xf2, Sf2, If3, Cf2, Tf2, Af2, Ef2, kf2, zd2, Bd, nn2, Rd, Md, Ud, Vd, Pf2, Of2, Nd, Wd2, Hd2, Gd, Ld, Fd, qd2, jd2, Kd2, Yd2, Xd2, Zd2, Qd2, zf2, Bf2, Jd2, el2, Rf2, Mf2, Uf2, Vf2, Nf2, Wf2, Hf2, Gf2, Lf2, Ff2, qf2, tl2, jf2, Kf2, Yf2, Xf2, Zf2, rl2, nl2, ol2, Qf2, Jf2, il2, al2, eh, th2, sl2, ul, rh2, on2, nh, dl2, oh, ih, ll2, cl2, pl2, ah, sh, ml2, fl2, hl2, uh, dh2, lh, ch, ph2, gl2, yl2, bl2, mh2, fh, wl2, vl2, $l2, _l2, an2, xl2, hh2, gh2, Io, sn2, Sl2, Il2, or2, Co2, yh2, Cl2, bh2, Er, kr2, kt2, wh2, Kt2, Pr2, Or2, Tl2, Dr, zr2, Br2, Hn2, Pt2, Ye, ir2, dn2, ln2, un2, To, Ao, Ht2, Gt, $h2, Al2, El2, kl2, Pl2, Ol2, Dl2, zl2, Eo, Bl2, _h2, cn2, Rl2, xh2, pn2, Ml2, Ul2, Sh2, Vl2, xa, K_; var init_ort_webgpu_bundle_min = __esm({ "node_modules/gliner/node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"() { Rn2 = Object.defineProperty; op2 = Object.getOwnPropertyDescriptor; ip2 = Object.getOwnPropertyNames; ap2 = Object.prototype.hasOwnProperty; Mn2 = ((e) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(e, { get: (t, r) => (typeof __require < "u" ? __require : t)[r] }) : e)(function(e) { if (typeof __require < "u") return __require.apply(this, arguments); throw Error('Dynamic require of "' + e + '" is not supported'); }); U = (e, t) => () => (e && (t = e(e = 0)), t); Ft2 = (e, t) => { for (var r in t) Rn2(e, r, { get: t[r], enumerable: true }); }; sp2 = (e, t, r, n) => { if (t && typeof t == "object" || typeof t == "function") for (let o of ip2(t)) !ap2.call(e, o) && o !== r && Rn2(e, o, { get: () => t[o], enumerable: !(n = op2(t, o)) || n.enumerable }); return e; }; br2 = (e) => sp2(Rn2({}, "__esModule", { value: true }), e); $r2 = U(() => { "use strict"; wr = /* @__PURE__ */ new Map(), $t2 = [], _t2 = (e, t, r) => { if (t && typeof t.init == "function" && typeof t.createInferenceSessionHandler == "function") { let n = wr.get(e); if (n === void 0) wr.set(e, { backend: t, priority: r }); else { if (n.priority > r) return; if (n.priority === r && n.backend !== t) throw new Error(`cannot register backend "${e}" using priority ${r}`); } if (r >= 0) { let o = $t2.indexOf(e); o !== -1 && $t2.splice(o, 1); for (let i = 0; i < $t2.length; i++) if (wr.get($t2[i]).priority <= r) { $t2.splice(i, 0, e); return; } $t2.push(e); } return; } throw new TypeError("not a valid backend"); }, up2 = async (e) => { let t = wr.get(e); if (!t) return "backend not found."; if (t.initialized) return t.backend; if (t.aborted) return t.error; { let r = !!t.initPromise; try { return r || (t.initPromise = t.backend.init(e)), await t.initPromise, t.initialized = true, t.backend; } catch (n) { return r || (t.error = `${n}`, t.aborted = true), t.error; } finally { delete t.initPromise; } } }, vr = async (e) => { let t = e.executionProviders || [], r = t.map((d) => typeof d == "string" ? d : d.name), n = r.length === 0 ? $t2 : r, o, i = [], a = /* @__PURE__ */ new Set(); for (let d of n) { let p = await up2(d); typeof p == "string" ? i.push({ name: d, err: p }) : (o || (o = p), o === p && a.add(d)); } if (!o) throw new Error(`no available backend found. ERR: ${i.map((d) => `[${d.name}] ${d.err}`).join(", ")}`); for (let { name: d, err: p } of i) r.includes(d) && console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`); let l = t.filter((d) => a.has(typeof d == "string" ? d : d.name)); return [o, new Proxy(e, { get: (d, p) => p === "executionProviders" ? l : Reflect.get(d, p) })]; }; }); Yi2 = U(() => { "use strict"; $r2(); }); Zi2 = U(() => { "use strict"; Xi2 = "1.19.2"; }); Un2 = U(() => { "use strict"; Zi2(); Qi2 = "warning", Ne = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: Xi2 }, set logLevel(e) { if (e !== void 0) { if (typeof e != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(e) === -1) throw new Error(`Unsupported logging level: ${e}`); Qi2 = e; } }, get logLevel() { return Qi2; } }; Object.defineProperty(Ne, "logLevel", { enumerable: true }); }); Ji2 = U(() => { "use strict"; Un2(); be2 = Ne; }); ra = U(() => { "use strict"; ea = (e, t) => { let r = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); r.width = e.dims[3], r.height = e.dims[2]; let n = r.getContext("2d"); if (n != null) { let o, i; t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[3]) : (o = e.dims[3], i = e.dims[2]); let a = t?.format !== void 0 ? t.format : "RGB", l = t?.norm, d, p; l === void 0 || l.mean === void 0 ? d = [255, 255, 255, 255] : typeof l.mean == "number" ? d = [l.mean, l.mean, l.mean, l.mean] : (d = [l.mean[0], l.mean[1], l.mean[2], 0], l.mean[3] !== void 0 && (d[3] = l.mean[3])), l === void 0 || l.bias === void 0 ? p = [0, 0, 0, 0] : typeof l.bias == "number" ? p = [l.bias, l.bias, l.bias, l.bias] : (p = [l.bias[0], l.bias[1], l.bias[2], 0], l.bias[3] !== void 0 && (p[3] = l.bias[3])); let m2 = i * o, u = 0, h = m2, w = m2 * 2, g = -1; a === "RGBA" ? (u = 0, h = m2, w = m2 * 2, g = m2 * 3) : a === "RGB" ? (u = 0, h = m2, w = m2 * 2) : a === "RBG" && (u = 0, w = m2, h = m2 * 2); for (let b = 0; b < i; b++) for (let x2 = 0; x2 < o; x2++) { let _ = (e.data[u++] - p[0]) * d[0], $2 = (e.data[h++] - p[1]) * d[1], S = (e.data[w++] - p[2]) * d[2], I2 = g === -1 ? 255 : (e.data[g++] - p[3]) * d[3]; n.fillStyle = "rgba(" + _ + "," + $2 + "," + S + "," + I2 + ")", n.fillRect(x2, b, 1, 1); } if ("toDataURL" in r) return r.toDataURL(); throw new Error("toDataURL is not supported"); } else throw new Error("Can not access image data"); }, ta = (e, t) => { let r = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), n; if (r != null) { let o, i, a; t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[1], a = e.dims[3]) : (o = e.dims[3], i = e.dims[2], a = e.dims[1]); let l = t !== void 0 && t.format !== void 0 ? t.format : "RGB", d = t?.norm, p, m2; d === void 0 || d.mean === void 0 ? p = [255, 255, 255, 255] : typeof d.mean == "number" ? p = [d.mean, d.mean, d.mean, d.mean] : (p = [d.mean[0], d.mean[1], d.mean[2], 255], d.mean[3] !== void 0 && (p[3] = d.mean[3])), d === void 0 || d.bias === void 0 ? m2 = [0, 0, 0, 0] : typeof d.bias == "number" ? m2 = [d.bias, d.bias, d.bias, d.bias] : (m2 = [d.bias[0], d.bias[1], d.bias[2], 0], d.bias[3] !== void 0 && (m2[3] = d.bias[3])); let u = i * o; if (t !== void 0 && (t.format !== void 0 && a === 4 && t.format !== "RGBA" || a === 3 && t.format !== "RGB" && t.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); let h = 4, w = 0, g = 1, b = 2, x2 = 3, _ = 0, $2 = u, S = u * 2, I2 = -1; l === "RGBA" ? (_ = 0, $2 = u, S = u * 2, I2 = u * 3) : l === "RGB" ? (_ = 0, $2 = u, S = u * 2) : l === "RBG" && (_ = 0, S = u, $2 = u * 2), n = r.createImageData(o, i); for (let T3 = 0; T3 < i * o; w += h, g += h, b += h, x2 += h, T3++) n.data[w] = (e.data[_++] - m2[0]) * p[0], n.data[g] = (e.data[$2++] - m2[1]) * p[1], n.data[b] = (e.data[S++] - m2[2]) * p[2], n.data[x2] = I2 === -1 ? 255 : (e.data[I2++] - m2[3]) * p[3]; } else throw new Error("Can not access image data"); return n; }; }); sa = U(() => { "use strict"; _r(); Vn2 = (e, t) => { if (e === void 0) throw new Error("Image buffer must be defined"); if (t.height === void 0 || t.width === void 0) throw new Error("Image height and width must be defined"); if (t.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet"); let { height: r, width: n } = t, o = t.norm ?? { mean: 255, bias: 0 }, i, a; typeof o.mean == "number" ? i = [o.mean, o.mean, o.mean, o.mean] : i = [o.mean[0], o.mean[1], o.mean[2], o.mean[3] ?? 255], typeof o.bias == "number" ? a = [o.bias, o.bias, o.bias, o.bias] : a = [o.bias[0], o.bias[1], o.bias[2], o.bias[3] ?? 0]; let l = t.format !== void 0 ? t.format : "RGBA", d = t.tensorFormat !== void 0 && t.tensorFormat !== void 0 ? t.tensorFormat : "RGB", p = r * n, m2 = d === "RGBA" ? new Float32Array(p * 4) : new Float32Array(p * 3), u = 4, h = 0, w = 1, g = 2, b = 3, x2 = 0, _ = p, $2 = p * 2, S = -1; l === "RGB" && (u = 3, h = 0, w = 1, g = 2, b = -1), d === "RGBA" ? S = p * 3 : d === "RBG" ? (x2 = 0, $2 = p, _ = p * 2) : d === "BGR" && ($2 = 0, _ = p, x2 = p * 2); for (let T3 = 0; T3 < p; T3++, h += u, g += u, w += u, b += u) m2[x2++] = (e[h] + a[0]) / i[0], m2[_++] = (e[w] + a[1]) / i[1], m2[$2++] = (e[g] + a[2]) / i[2], S !== -1 && b !== -1 && (m2[S++] = (e[b] + a[3]) / i[3]); return d === "RGBA" ? new Be2("float32", m2, [1, 4, r, n]) : new Be2("float32", m2, [1, 3, r, n]); }, na = async (e, t) => { let r = typeof HTMLImageElement < "u" && e instanceof HTMLImageElement, n = typeof ImageData < "u" && e instanceof ImageData, o = typeof ImageBitmap < "u" && e instanceof ImageBitmap, i = typeof e == "string", a, l = t ?? {}, d = () => { if (typeof document < "u") return document.createElement("canvas"); if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); throw new Error("Canvas is not supported"); }, p = (m2) => m2 instanceof HTMLCanvasElement || m2 instanceof OffscreenCanvas ? m2.getContext("2d") : null; if (r) { let m2 = d(); m2.width = e.width, m2.height = e.height; let u = p(m2); if (u != null) { let h = e.height, w = e.width; if (t !== void 0 && t.resizedHeight !== void 0 && t.resizedWidth !== void 0 && (h = t.resizedHeight, w = t.resizedWidth), t !== void 0) { if (l = t, t.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); l.tensorFormat = "RGBA", l.height = h, l.width = w; } else l.tensorFormat = "RGBA", l.height = h, l.width = w; u.drawImage(e, 0, 0), a = u.getImageData(0, 0, w, h).data; } else throw new Error("Can not access image data"); } else if (n) { let m2, u; if (t !== void 0 && t.resizedWidth !== void 0 && t.resizedHeight !== void 0 ? (m2 = t.resizedHeight, u = t.resizedWidth) : (m2 = e.height, u = e.width), t !== void 0 && (l = t), l.format = "RGBA", l.height = m2, l.width = u, t !== void 0) { let h = d(); h.width = u, h.height = m2; let w = p(h); if (w != null) w.putImageData(e, 0, 0), a = w.getImageData(0, 0, u, m2).data; else throw new Error("Can not access image data"); } else a = e.data; } else if (o) { if (t === void 0) throw new Error("Please provide image config with format for Imagebitmap"); let m2 = d(); m2.width = e.width, m2.height = e.height; let u = p(m2); if (u != null) { let h = e.height, w = e.width; return u.drawImage(e, 0, 0, w, h), a = u.getImageData(0, 0, w, h).data, l.height = h, l.width = w, Vn2(a, l); } else throw new Error("Can not access image data"); } else { if (i) return new Promise((m2, u) => { let h = d(), w = p(h); if (!e || !w) return u(); let g = new Image(); g.crossOrigin = "Anonymous", g.src = e, g.onload = () => { h.width = g.width, h.height = g.height, w.drawImage(g, 0, 0, h.width, h.height); let b = w.getImageData(0, 0, h.width, h.height); l.height = h.height, l.width = h.width, m2(Vn2(b.data, l)); }; }); throw new Error("Input data provided is not supported - aborted tensor creation"); } if (a !== void 0) return Vn2(a, l); throw new Error("Input data provided is not supported - aborted tensor creation"); }, oa = (e, t) => { let { width: r, height: n, download: o, dispose: i } = t, a = [1, n, r, 4]; return new Be2({ location: "texture", type: "float32", texture: e, dims: a, download: o, dispose: i }); }, ia = (e, t) => { let { dataType: r, dims: n, download: o, dispose: i } = t; return new Be2({ location: "gpu-buffer", type: r ?? "float32", gpuBuffer: e, dims: n, download: o, dispose: i }); }, aa = (e, t, r) => new Be2({ location: "cpu-pinned", type: e, data: t, dims: r ?? [t.length] }); }); la = U(() => { "use strict"; xt = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), qt2 = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), ua = false, da = () => { if (!ua) { ua = true; let e = typeof BigInt64Array < "u" && BigInt64Array.from, t = typeof BigUint64Array < "u" && BigUint64Array.from, r = typeof Float16Array < "u" && Float16Array.from; e && (xt.set("int64", BigInt64Array), qt2.set(BigInt64Array, "int64")), t && (xt.set("uint64", BigUint64Array), qt2.set(BigUint64Array, "uint64")), r ? (xt.set("float16", Float16Array), qt2.set(Float16Array, "float16")) : xt.set("float16", Uint16Array); } }; }); ma = U(() => { "use strict"; _r(); ca = (e) => { let t = 1; for (let r = 0; r < e.length; r++) { let n = e[r]; if (typeof n != "number" || !Number.isSafeInteger(n)) throw new TypeError(`dims[${r}] must be an integer, got: ${n}`); if (n < 0) throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`); t *= n; } return t; }, pa = (e, t) => { switch (e.location) { case "cpu": return new Be2(e.type, e.data, t); case "cpu-pinned": return new Be2({ location: "cpu-pinned", data: e.data, type: e.type, dims: t }); case "texture": return new Be2({ location: "texture", texture: e.texture, type: e.type, dims: t }); case "gpu-buffer": return new Be2({ location: "gpu-buffer", gpuBuffer: e.gpuBuffer, type: e.type, dims: t }); default: throw new Error(`tensorReshape: tensor location ${e.location} is not supported`); } }; }); _r = U(() => { "use strict"; ra(); sa(); la(); ma(); Be2 = class { constructor(t, r, n) { da(); let o, i; if (typeof t == "object" && "location" in t) switch (this.dataLocation = t.location, o = t.type, i = t.dims, t.location) { case "cpu-pinned": { let l = xt.get(o); if (!l) throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`); if (!(t.data instanceof l)) throw new TypeError(`buffer should be of type ${l.name}`); this.cpuData = t.data; break; } case "texture": { if (o !== "float32") throw new TypeError(`unsupported type "${o}" to create tensor from texture`); this.gpuTextureData = t.texture, this.downloader = t.download, this.disposer = t.dispose; break; } case "gpu-buffer": { if (o !== "float32" && o !== "float16" && o !== "int32" && o !== "int64" && o !== "uint32" && o !== "uint8" && o !== "bool") throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`); this.gpuBufferData = t.gpuBuffer, this.downloader = t.download, this.disposer = t.dispose; break; } default: throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); } else { let l, d; if (typeof t == "string") if (o = t, d = n, t === "string") { if (!Array.isArray(r)) throw new TypeError("A string tensor's data must be a string array."); l = r; } else { let p = xt.get(t); if (p === void 0) throw new TypeError(`Unsupported tensor type: ${t}.`); if (Array.isArray(r)) { if (t === "float16" && p === Uint16Array) throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data."); t === "uint64" || t === "int64" ? l = p.from(r, BigInt) : l = p.from(r); } else if (r instanceof p) l = r; else throw new TypeError(`A ${o} tensor's data must be type of ${p}`); } else if (d = r, Array.isArray(t)) { if (t.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); let p = typeof t[0]; if (p === "string") o = "string", l = t; else if (p === "boolean") o = "bool", l = Uint8Array.from(t); else throw new TypeError(`Invalid element type of data array: ${p}.`); } else { let p = qt2.get(t.constructor); if (p === void 0) throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`); o = p, l = t; } if (d === void 0) d = [l.length]; else if (!Array.isArray(d)) throw new TypeError("A tensor's dims must be a number array"); i = d, this.cpuData = l, this.dataLocation = "cpu"; } let a = ca(i); if (this.cpuData && a !== this.cpuData.length) throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`); this.type = o, this.dims = i, this.size = a; } static async fromImage(t, r) { return na(t, r); } static fromTexture(t, r) { return oa(t, r); } static fromGpuBuffer(t, r) { return ia(t, r); } static fromPinnedBuffer(t, r, n) { return aa(t, r, n); } toDataURL(t) { return ea(this, t); } toImageData(t) { return ta(this, t); } get data() { if (this.ensureValid(), !this.cpuData) throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly."); return this.cpuData; } get location() { return this.dataLocation; } get texture() { if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture."); return this.gpuTextureData; } get gpuBuffer() { if (this.ensureValid(), !this.gpuBufferData) throw new Error("The data is not stored as a WebGPU buffer."); return this.gpuBufferData; } async getData(t) { switch (this.ensureValid(), this.dataLocation) { case "cpu": case "cpu-pinned": return this.data; case "texture": case "gpu-buffer": { if (!this.downloader) throw new Error("The current tensor is not created with a specified data downloader."); if (this.isDownloading) throw new Error("The current tensor is being downloaded."); try { this.isDownloading = true; let r = await this.downloader(); return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = r, t && this.disposer && (this.disposer(), this.disposer = void 0), r; } finally { this.isDownloading = false; } } default: throw new Error(`cannot get data from location: ${this.dataLocation}`); } } dispose() { if (this.isDownloading) throw new Error("The current tensor is being downloaded."); this.disposer && (this.disposer(), this.disposer = void 0), this.cpuData = void 0, this.gpuTextureData = void 0, this.gpuBufferData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none"; } ensureValid() { if (this.dataLocation === "none") throw new Error("The tensor is disposed."); } reshape(t) { if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource."); return pa(this, t); } }; }); xr2 = U(() => { "use strict"; _r(); De = Be2; }); Nn2 = U(() => { "use strict"; Un2(); Sr2 = (e, t) => { (typeof Ne.trace > "u" ? !Ne.wasm.trace : !Ne.trace) || console.timeStamp(`${e}::ORT::${t}`); }, fa = (e, t) => { let r = new Error().stack?.split(/\r\n|\r|\n/g) || [], n = false; for (let o = 0; o < r.length; o++) { if (n && !r[o].includes("TRACE_FUNC")) { let i = `FUNC_${e}::${r[o].trim().split(" ")[1]}`; t && (i += `::${t}`), Sr2("CPU", i); return; } r[o].includes("TRACE_FUNC") && (n = true); } }, We2 = (e) => { (typeof Ne.trace > "u" ? !Ne.wasm.trace : !Ne.trace) || fa("BEGIN", e); }, Me2 = (e) => { (typeof Ne.trace > "u" ? !Ne.wasm.trace : !Ne.trace) || fa("END", e); }; }); ha = U(() => { "use strict"; $r2(); xr2(); Nn2(); Ir = class e { constructor(t) { this.handler = t; } async run(t, r, n) { We2(); let o = {}, i = {}; if (typeof t != "object" || t === null || t instanceof De || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let a = true; if (typeof r == "object") { if (r === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (r instanceof De) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(r)) { if (r.length === 0) throw new TypeError("'fetches' cannot be an empty array."); a = false; for (let p of r) { if (typeof p != "string") throw new TypeError("'fetches' must be a string array or an object."); if (this.outputNames.indexOf(p) === -1) throw new RangeError(`'fetches' contains invalid output name: ${p}.`); o[p] = null; } if (typeof n == "object" && n !== null) i = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else { let p = false, m2 = Object.getOwnPropertyNames(r); for (let u of this.outputNames) if (m2.indexOf(u) !== -1) { let h = r[u]; (h === null || h instanceof De) && (p = true, a = false, o[u] = h); } if (p) { if (typeof n == "object" && n !== null) i = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else i = r; } } else if (typeof r < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let p of this.inputNames) if (typeof t[p] > "u") throw new Error(`input '${p}' is missing in 'feeds'.`); if (a) for (let p of this.outputNames) o[p] = null; let l = await this.handler.run(t, o, i), d = {}; for (let p in l) if (Object.hasOwnProperty.call(l, p)) { let m2 = l[p]; m2 instanceof De ? d[p] = m2 : d[p] = new De(m2.type, m2.data, m2.dims); } return Me2(), d; } async release() { return this.handler.dispose(); } static async create(t, r, n, o) { We2(); let i, a = {}; if (typeof t == "string") { if (i = t, typeof r == "object" && r !== null) a = r; else if (typeof r < "u") throw new TypeError("'options' must be an object."); } else if (t instanceof Uint8Array) { if (i = t, typeof r == "object" && r !== null) a = r; else if (typeof r < "u") throw new TypeError("'options' must be an object."); } else if (t instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && t instanceof SharedArrayBuffer) { let m2 = t, u = 0, h = t.byteLength; if (typeof r == "object" && r !== null) a = r; else if (typeof r == "number") { if (u = r, !Number.isSafeInteger(u)) throw new RangeError("'byteOffset' must be an integer."); if (u < 0 || u >= m2.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${m2.byteLength}).`); if (h = t.byteLength - u, typeof n == "number") { if (h = n, !Number.isSafeInteger(h)) throw new RangeError("'byteLength' must be an integer."); if (h <= 0 || u + h > m2.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${m2.byteLength - u}].`); if (typeof o == "object" && o !== null) a = o; else if (typeof o < "u") throw new TypeError("'options' must be an object."); } else if (typeof n < "u") throw new TypeError("'byteLength' must be a number."); } else if (typeof r < "u") throw new TypeError("'options' must be an object."); i = new Uint8Array(m2, u, h); } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); let [l, d] = await vr(a), p = await l.createInferenceSessionHandler(i, d); return Me2(), new e(p); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } }; }); ga = U(() => { "use strict"; ha(); dp2 = Ir; }); ya = U(() => { "use strict"; }); ba = U(() => { "use strict"; }); wa = U(() => { "use strict"; }); va = U(() => { "use strict"; }); $a = U(() => { "use strict"; $r2(); xr2(); lp2 = "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.", Cr2 = class e { constructor(t, r, n) { this.handler = t, this.hasOptimizerModel = r, this.hasEvalModel = n; } get trainingInputNames() { return this.handler.inputNames; } get trainingOutputNames() { return this.handler.outputNames; } get evalInputNames() { if (this.hasEvalModel) return this.handler.evalInputNames; throw new Error("This training session has no evalModel loaded."); } get evalOutputNames() { if (this.hasEvalModel) return this.handler.evalOutputNames; throw new Error("This training session has no evalModel loaded."); } static async create(t, r) { let n = t.evalModel || "", o = t.optimizerModel || "", i = r || {}, [a, l] = await vr(i); if (a.createTrainingSessionHandler) { let d = await a.createTrainingSessionHandler(t.checkpointState, t.trainModel, n, o, l); return new e(d, !!t.optimizerModel, !!t.evalModel); } else throw new Error(lp2); } typeNarrowingForRunStep(t, r, n, o, i) { let a = {}, l = {}; if (typeof n != "object" || n === null || n instanceof De || Array.isArray(n)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let d = true; if (typeof o == "object") { if (o === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (o instanceof De) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(o)) { if (o.length === 0) throw new TypeError("'fetches' cannot be an empty array."); d = false; for (let p of o) { if (typeof p != "string") throw new TypeError("'fetches' must be a string array or an object."); if (r.indexOf(p) === -1) throw new RangeError(`'fetches' contains invalid output name: ${p}.`); a[p] = null; } if (typeof i == "object" && i !== null) l = i; else if (typeof i < "u") throw new TypeError("'options' must be an object."); } else { let p = false, m2 = Object.getOwnPropertyNames(o); for (let u of r) if (m2.indexOf(u) !== -1) { let h = o[u]; (h === null || h instanceof De) && (p = true, d = false, a[u] = h); } if (p) { if (typeof i == "object" && i !== null) l = i; else if (typeof i < "u") throw new TypeError("'options' must be an object."); } else l = o; } } else if (typeof o < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let p of t) if (typeof n[p] > "u") throw new Error(`input '${p}' is missing in 'feeds'.`); if (d) for (let p of r) a[p] = null; return [a, l]; } convertHandlerReturnTypeToMapOfTensors(t) { let r = {}; for (let n in t) if (Object.hasOwnProperty.call(t, n)) { let o = t[n]; o instanceof De ? r[n] = o : r[n] = new De(o.type, o.data, o.dims); } return r; } async lazyResetGrad() { await this.handler.lazyResetGrad(); } async runTrainStep(t, r, n) { let [o, i] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, t, r, n), a = await this.handler.runTrainStep(t, o, i); return this.convertHandlerReturnTypeToMapOfTensors(a); } async runOptimizerStep(t) { if (this.hasOptimizerModel) await this.handler.runOptimizerStep(t || {}); else throw new Error("This TrainingSession has no OptimizerModel loaded."); } async runEvalStep(t, r, n) { if (this.hasEvalModel) { let [o, i] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, t, r, n), a = await this.handler.runEvalStep(t, o, i); return this.convertHandlerReturnTypeToMapOfTensors(a); } else throw new Error("This TrainingSession has no EvalModel loaded."); } async getParametersSize(t = true) { return this.handler.getParametersSize(t); } async loadParametersBuffer(t, r = true) { let n = await this.getParametersSize(r); if (t.length !== 4 * n) throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check."); return this.handler.loadParametersBuffer(t, r); } async getContiguousParameters(t = true) { return this.handler.getContiguousParameters(t); } async release() { return this.handler.dispose(); } }; }); _a = U(() => { "use strict"; $a(); cp2 = Cr2; }); Wn2 = {}; Ft2(Wn2, { InferenceSession: () => dp2, TRACE: () => Sr2, TRACE_FUNC_BEGIN: () => We2, TRACE_FUNC_END: () => Me2, Tensor: () => De, TrainingSession: () => cp2, env: () => be2, registerBackend: () => _t2 }); Ke2 = U(() => { "use strict"; Yi2(); Ji2(); ga(); xr2(); ya(); ba(); Nn2(); wa(); va(); _a(); }); Tr2 = U(() => { "use strict"; }); Ca = {}; Ft2(Ca, { default: () => pp2 }); Ta = U(() => { "use strict"; Hn2(); St(); jt2(); Sa = "ort-wasm-proxy-worker", Ia = globalThis.self?.name === Sa; Ia && (self.onmessage = (e) => { let { type: t, in: r } = e.data; try { switch (t) { case "init-wasm": Ar2(r.wasm).then(() => { Er(r).then(() => { postMessage({ type: t }); }, (n) => { postMessage({ type: t, err: n }); }); }, (n) => { postMessage({ type: t, err: n }); }); break; case "init-ep": { let { epName: n, env: o } = r; kr2(o, n).then(() => { postMessage({ type: t }); }, (i) => { postMessage({ type: t, err: i }); }); break; } case "copy-from": { let { buffer: n } = r, o = Kt2(n); postMessage({ type: t, out: o }); break; } case "create": { let { model: n, options: o } = r; Pr2(n, o).then((i) => { postMessage({ type: t, out: i }); }, (i) => { postMessage({ type: t, err: i }); }); break; } case "release": Or2(r), postMessage({ type: t }); break; case "run": { let { sessionId: n, inputIndices: o, inputs: i, outputIndices: a, options: l } = r; Dr(n, o, i, a, new Array(a.length).fill(null), l).then((d) => { d.some((p) => p[3] !== "cpu") ? postMessage({ type: t, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: t, out: d }, Br2([...i, ...d])); }, (d) => { postMessage({ type: t, err: d }); }); break; } case "end-profiling": zr2(r), postMessage({ type: t }); break; default: } } catch (n) { postMessage({ type: t, err: n }); } }); pp2 = Ia ? null : (e) => new Worker(e ?? Ut2, { type: "module", name: Sa }); }); Ea = {}; Ft2(Ea, { default: () => mp2 }); ka = U(() => { "use strict"; Aa = (Gn2 = import.meta.url, async function(e = {}) { function t() { return le3.buffer != re2.buffer && we2(), re2; } function r() { return le3.buffer != re2.buffer && we2(), se2; } function n() { return le3.buffer != re2.buffer && we2(), Z2; } function o() { return le3.buffer != re2.buffer && we2(), ne2; } function i() { return le3.buffer != re2.buffer && we2(), J3; } function a() { return le3.buffer != re2.buffer && we2(), ke3; } function l() { return le3.buffer != re2.buffer && we2(), R; } function d() { return le3.buffer != re2.buffer && we2(), Re2; } var p, m2, u = Object.assign({}, e), h = new Promise((s, c) => { p = s, m2 = c; }), w = typeof window == "object", g = typeof importScripts == "function", b = g && self.name == "em-pthread"; u.mountExternalData = (s, c) => { (u.Fb || (u.Fb = /* @__PURE__ */ new Map())).set(s, c); }, u.unmountExternalData = () => { delete u.Fb; }; var x2 = globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, shared: true }).buffer.constructor; let _ = () => { let s = (f, y, v) => (...C) => { let O2 = Je2, B3 = y?.(); C = f(...C); let N2 = y?.(); return B3 !== N2 && (f = N2, v(B3), y = v = null), Je2 != O2 ? new Promise((L, j3) => { An3 = { resolve: L, reject: j3 }; }) : C; }, c = (f) => async (...y) => { try { if (u.Eb) throw Error("Session already started"); let v = u.Eb = { bc: y[0], errors: [] }, C = await f(...y); if (u.Eb !== v) throw Error("Session mismatch"); u.Mb?.flush(); let O2 = v.errors; if (0 < O2.length) { let B3 = await Promise.all(O2); if (B3 = B3.filter((N2) => N2), 0 < B3.length) throw Error(B3.join(` `)); } return C; } finally { u.Eb = null; } }; u._OrtCreateSession = s(u._OrtCreateSession, () => u._OrtCreateSession, (f) => u._OrtCreateSession = f), u._OrtRun = c(s(u._OrtRun, () => u._OrtRun, (f) => u._OrtRun = f)), u._OrtRunWithBinding = c(s(u._OrtRunWithBinding, () => u._OrtRunWithBinding, (f) => u._OrtRunWithBinding = f)), u._OrtBindInput = s(u._OrtBindInput, () => u._OrtBindInput, (f) => u._OrtBindInput = f), _ = void 0; }; u.jsepInit = (s, c) => { if (_?.(), s === "webgpu") { [u.Mb, u.Tb, u.Xb, u.Nb, u.Wb, u.jb, u.Yb, u.$b, u.Ub, u.Vb, u.Zb] = c; let f = u.Mb; u.jsepRegisterBuffer = (y, v, C, O2) => f.registerBuffer(y, v, C, O2), u.jsepGetBuffer = (y) => f.getBuffer(y), u.jsepCreateDownloader = (y, v, C) => f.createDownloader(y, v, C), u.jsepOnReleaseSession = (y) => { f.onReleaseSession(y); }, u.jsepOnRunStart = (y) => f.onRunStart(y); } }; var $2, S, I2 = Object.assign({}, u), T3 = "./this.program", A2 = (s, c) => { throw c; }, D3 = ""; (w || g) && (g ? D3 = self.location.href : typeof document < "u" && document.currentScript && (D3 = document.currentScript.src), Gn2 && (D3 = Gn2), D3 = D3.startsWith("blob:") ? "" : D3.substr(0, D3.replace(/[?#].*/, "").lastIndexOf("/") + 1), g && (S = (s) => { var c = new XMLHttpRequest(); return c.open("GET", s, false), c.responseType = "arraybuffer", c.send(null), new Uint8Array(c.response); }), $2 = (s, c, f) => { var y = new XMLHttpRequest(); y.open("GET", s, true), y.responseType = "arraybuffer", y.onload = () => { y.status == 200 || y.status == 0 && y.response ? c(y.response) : f(); }, y.onerror = f, y.send(null); }); var z3, H3 = console.log.bind(console), W2 = console.error.bind(console), X = H3, Y3 = W2; if (Object.assign(u, I2), I2 = null, b) { let s = function(c) { try { var f = c.data, y = f.cmd; if (y === "load") { let v = []; self.onmessage = (C) => v.push(C), self.startWorker = () => { postMessage({ cmd: "loaded" }); for (let C of v) s(C); self.onmessage = s; }; for (let C of f.handlers) u[C] && !u[C].proxy || (u[C] = (...O2) => { postMessage({ Lb: "callHandler", kc: C, args: O2 }); }, C == "print" && (X = u[C]), C == "printErr" && (Y3 = u[C])); le3 = f.wasmMemory, we2(), pe2(f.wasmModule); } else if (y === "run") { On3(f.pthread_ptr, 0, 0, 1, 0, 0), In2(f.pthread_ptr), Hl2(), No3(), ue3 || (Mi3(), ue3 = true); try { Gl3(f.start_routine, f.arg); } catch (v) { if (v != "unwind") throw v; } } else y === "cancel" ? Mt2() && gr2(-1) : f.target !== "setimmediate" && (y === "checkMailbox" ? ue3 && sr3() : y && (Y3(`worker: received unknown command ${y}`), Y3(f))); } catch (v) { throw Ui3(), v; } }; var Ih2 = s, pe2, ue3 = false; Y3 = function(...c) { c = c.join(" "), console.error(c); }, self.alert = function(...c) { postMessage({ Lb: "alert", text: c.join(" "), mc: Mt2() }); }, u.instantiateWasm = (c, f) => new Promise((y) => { pe2 = (v) => { v = new WebAssembly.Instance(v, Bo3()), f(v), y(); }; }), self.onunhandledrejection = (c) => { throw c.reason || c; }, self.onmessage = s; } u.wasmBinary && (z3 = u.wasmBinary); var le3, K, de2, re2, se2, Z2, ne2, J3, ke3, R, F2, ce3, Re2, Se2 = false; function we2() { var s = le3.buffer; u.HEAP8 = re2 = new Int8Array(s), u.HEAP16 = Z2 = new Int16Array(s), u.HEAPU8 = se2 = new Uint8Array(s), u.HEAPU16 = ne2 = new Uint16Array(s), u.HEAP32 = J3 = new Int32Array(s), u.HEAPU32 = ke3 = new Uint32Array(s), u.HEAPF32 = R = new Float32Array(s), u.HEAPF64 = Re2 = new Float64Array(s), u.HEAP64 = F2 = new BigInt64Array(s), u.HEAPU64 = ce3 = new BigUint64Array(s); } if (!b) { if (!((le3 = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: true })).buffer instanceof x2)) throw Y3("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), Error("bad memory"); we2(); } var Lt3 = [], Pe3 = [], ze3 = [], Fe3 = 0, Ot = null, yt3 = null; function ko3() { if (--Fe3 == 0 && (Ot !== null && (clearInterval(Ot), Ot = null), yt3)) { var s = yt3; yt3 = null, s(); } } function Dt2(s) { throw Y3(s = "Aborted(" + s + ")"), Se2 = true, de2 = 1, s = new WebAssembly.RuntimeError(s + ". Build with -sASSERTIONS for more info."), m2(s), s; } var mn3, Po2 = (s) => s.startsWith("data:application/octet-stream;base64,"), Oo2 = (s) => s.startsWith("file://"); function Do2(s) { if (s == mn3 && z3) return new Uint8Array(z3); if (S) return S(s); throw "both async and sync fetching of the wasm failed"; } function zo2(s, c, f) { return (function(y) { if (!z3 && (w || g)) { if (typeof fetch == "function" && !Oo2(y)) return fetch(y, { credentials: "same-origin" }).then((v) => { if (!v.ok) throw `failed to load wasm binary file at '${y}'`; return v.arrayBuffer(); }).catch(() => Do2(y)); if ($2) return new Promise((v, C) => { $2(y, (O2) => v(new Uint8Array(O2)), C); }); } return Promise.resolve().then(() => Do2(y)); })(s).then((y) => WebAssembly.instantiate(y, c)).then(f, (y) => { Y3(`failed to asynchronously prepare wasm: ${y}`), Dt2(y); }); } function Bo3() { return { a: { M: Wl2, za: Nl3, b: Fl3, $: Lo2, z: jo, pa: Ko, X: Xo, Z: Zo2, qa: Qo2, na: Jo, ga: ei3, ma: ti, J: ri, Y: ni3, V: oi2, oa: ii3, W: ai2, va: ql2, D: Kl2, P: Yl3, O: Zl3, C: Jl2, s: ec3, p: tc3, E: rc3, y: dc3, Q: lc2, ta: cc3, ja: pc3, T: mc3, aa: fc3, F: hc3, ia: In2, sa: gc3, u: yc3, B: vc3, o: $c3, m: xc3, c: xn3, n: Sc3, k: Tc3, Aa: Ac3, r: Ec3, f: kc3, v: Pc3, l: Oc3, g: Dc3, i: zc3, j: Bc3, h: Rc3, e: Mc3, da: Uc3, ea: Vc3, fa: Nc3, ba: vi2, ca: $i3, S: Wc3, d: Hc3, N: Gc3, G: Lc3, K: Fc3, w: qc3, ra: jc3, U: Kc3, t: xi2, x: Yc3, L: Xc3, R: Zc3, ya: Qc3, xa: Jc3, ka: Ci3, la: Ti2, _: bn3, A: Ai3, I: Ei3, ha: ki2, H: Pi2, a: le3, wa: yn3, ua: zi3, q: rp3 } }; } var fn3 = { 849620: (s, c, f, y) => { if (u === void 0 || !u.Fb) return 1; if ((s = Ae3(s >>> 0)).startsWith("./") && (s = s.substring(2)), !(s = u.Fb.get(s))) return 2; if (y >>>= 0, (c >>>= 0) + (f >>>= 0) > s.byteLength) return 3; try { return r().set(s.subarray(c, c + f), y >>> 0), 0; } catch { return 4; } }, 850121: () => { u.Ub(); }, 850152: () => { u.Vb(); }, 850181: () => { u.Zb(); }, 850206: (s) => u.Tb(s), 850239: (s) => u.Xb(s), 850271: (s, c, f) => { u.Nb(s, c, f, true); }, 850310: (s, c, f) => { u.Nb(s, c, f); }, 850343: () => typeof wasmOffsetConverter < "u", 850400: (s) => { u.jb("Abs", s, void 0); }, 850451: (s) => { u.jb("Neg", s, void 0); }, 850502: (s) => { u.jb("Floor", s, void 0); }, 850555: (s) => { u.jb("Ceil", s, void 0); }, 850607: (s) => { u.jb("Reciprocal", s, void 0); }, 850665: (s) => { u.jb("Sqrt", s, void 0); }, 850717: (s) => { u.jb("Exp", s, void 0); }, 850768: (s) => { u.jb("Erf", s, void 0); }, 850819: (s) => { u.jb("Sigmoid", s, void 0); }, 850874: (s, c, f) => { u.jb("HardSigmoid", s, { alpha: c, beta: f }); }, 850953: (s) => { u.jb("Log", s, void 0); }, 851004: (s) => { u.jb("Sin", s, void 0); }, 851055: (s) => { u.jb("Cos", s, void 0); }, 851106: (s) => { u.jb("Tan", s, void 0); }, 851157: (s) => { u.jb("Asin", s, void 0); }, 851209: (s) => { u.jb("Acos", s, void 0); }, 851261: (s) => { u.jb("Atan", s, void 0); }, 851313: (s) => { u.jb("Sinh", s, void 0); }, 851365: (s) => { u.jb("Cosh", s, void 0); }, 851417: (s) => { u.jb("Asinh", s, void 0); }, 851470: (s) => { u.jb("Acosh", s, void 0); }, 851523: (s) => { u.jb("Atanh", s, void 0); }, 851576: (s) => { u.jb("Tanh", s, void 0); }, 851628: (s) => { u.jb("Not", s, void 0); }, 851679: (s, c, f) => { u.jb("Clip", s, { min: c, max: f }); }, 851748: (s) => { u.jb("Clip", s, void 0); }, 851800: (s, c) => { u.jb("Elu", s, { alpha: c }); }, 851858: (s) => { u.jb("Relu", s, void 0); }, 851910: (s, c) => { u.jb("LeakyRelu", s, { alpha: c }); }, 851974: (s, c) => { u.jb("ThresholdedRelu", s, { alpha: c }); }, 852044: (s, c) => { u.jb("Cast", s, { to: c }); }, 852102: (s) => { u.jb("Add", s, void 0); }, 852153: (s) => { u.jb("Sub", s, void 0); }, 852204: (s) => { u.jb("Mul", s, void 0); }, 852255: (s) => { u.jb("Div", s, void 0); }, 852306: (s) => { u.jb("Pow", s, void 0); }, 852357: (s) => { u.jb("Equal", s, void 0); }, 852410: (s) => { u.jb("Greater", s, void 0); }, 852465: (s) => { u.jb("GreaterOrEqual", s, void 0); }, 852527: (s) => { u.jb("Less", s, void 0); }, 852579: (s) => { u.jb("LessOrEqual", s, void 0); }, 852638: (s, c, f, y, v) => { u.jb("ReduceMean", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 852797: (s, c, f, y, v) => { u.jb("ReduceMax", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 852955: (s, c, f, y, v) => { u.jb("ReduceMin", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853113: (s, c, f, y, v) => { u.jb("ReduceProd", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853272: (s, c, f, y, v) => { u.jb("ReduceSum", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853430: (s, c, f, y, v) => { u.jb("ReduceL1", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853587: (s, c, f, y, v) => { u.jb("ReduceL2", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853744: (s, c, f, y, v) => { u.jb("ReduceLogSum", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 853905: (s, c, f, y, v) => { u.jb("ReduceSumSquare", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 854069: (s, c, f, y, v) => { u.jb("ReduceLogSumExp", s, { keepDims: !!c, noopWithEmptyAxes: !!f, axes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 854233: (s) => { u.jb("Where", s, void 0); }, 854286: (s, c, f) => { u.jb("Transpose", s, { perm: c ? Array.from(i().subarray(c >>> 0, f >>> 0)) : [] }); }, 854394: (s, c, f, y) => { u.jb("DepthToSpace", s, { blocksize: c, mode: Ae3(f), format: y ? "NHWC" : "NCHW" }); }, 854527: (s, c, f, y) => { u.jb("DepthToSpace", s, { blocksize: c, mode: Ae3(f), format: y ? "NHWC" : "NCHW" }); }, 854660: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3) => { u.jb("ConvTranspose", s, { format: N2 ? "NHWC" : "NCHW", autoPad: c, dilations: [f], group: y, kernelShape: [v], pads: [C, O2], strides: [B3], wIsConst: () => !!t()[L >>> 0], outputPadding: j3 ? Array.from(i().subarray(j3 >>> 0, me3 >>> 0)) : [], outputShape: he3 ? Array.from(i().subarray(he3 >>> 0, P2 >>> 0)) : [], activation: Ae3(ee3) }); }, 855061: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2) => { u.jb("ConvTranspose", s, { format: B3 ? "NHWC" : "NCHW", autoPad: c, dilations: Array.from(i().subarray(f >>> 0, 2 + (f >>> 0) >>> 0)), group: y, kernelShape: Array.from(i().subarray(v >>> 0, 2 + (v >>> 0) >>> 0)), pads: Array.from(i().subarray(C >>> 0, 4 + (C >>> 0) >>> 0)), strides: Array.from(i().subarray(O2 >>> 0, 2 + (O2 >>> 0) >>> 0)), wIsConst: () => !!t()[N2 >>> 0], outputPadding: L ? Array.from(i().subarray(L >>> 0, j3 >>> 0)) : [], outputShape: me3 ? Array.from(i().subarray(me3 >>> 0, he3 >>> 0)) : [], activation: Ae3(P2) }); }, 855626: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3) => { u.jb("ConvTranspose", s, { format: N2 ? "NHWC" : "NCHW", autoPad: c, dilations: [f], group: y, kernelShape: [v], pads: [C, O2], strides: [B3], wIsConst: () => !!t()[L >>> 0], outputPadding: j3 ? Array.from(i().subarray(j3 >>> 0, me3 >>> 0)) : [], outputShape: he3 ? Array.from(i().subarray(he3 >>> 0, P2 >>> 0)) : [], activation: Ae3(ee3) }); }, 856027: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2) => { u.jb("ConvTranspose", s, { format: B3 ? "NHWC" : "NCHW", autoPad: c, dilations: Array.from(i().subarray(f >>> 0, 2 + (f >>> 0) >>> 0)), group: y, kernelShape: Array.from(i().subarray(v >>> 0, 2 + (v >>> 0) >>> 0)), pads: Array.from(i().subarray(C >>> 0, 4 + (C >>> 0) >>> 0)), strides: Array.from(i().subarray(O2 >>> 0, 2 + (O2 >>> 0) >>> 0)), wIsConst: () => !!t()[N2 >>> 0], outputPadding: L ? Array.from(i().subarray(L >>> 0, j3 >>> 0)) : [], outputShape: me3 ? Array.from(i().subarray(me3 >>> 0, he3 >>> 0)) : [], activation: Ae3(P2) }); }, 856592: (s, c) => { u.jb("GlobalAveragePool", s, { format: c ? "NHWC" : "NCHW" }); }, 856683: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3, ye2) => { u.jb("AveragePool", s, { format: ye2 ? "NHWC" : "NCHW", auto_pad: c, ceil_mode: f, count_include_pad: y, storage_order: v, dilations: [C, O2], kernel_shape: [B3, N2], pads: [L, j3, me3, he3], strides: [P2, ee3] }); }, 856967: (s, c) => { u.jb("GlobalAveragePool", s, { format: c ? "NHWC" : "NCHW" }); }, 857058: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3, ye2) => { u.jb("AveragePool", s, { format: ye2 ? "NHWC" : "NCHW", auto_pad: c, ceil_mode: f, count_include_pad: y, storage_order: v, dilations: [C, O2], kernel_shape: [B3, N2], pads: [L, j3, me3, he3], strides: [P2, ee3] }); }, 857342: (s, c) => { u.jb("GlobalMaxPool", s, { format: c ? "NHWC" : "NCHW" }); }, 857429: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3, ye2) => { u.jb("MaxPool", s, { format: ye2 ? "NHWC" : "NCHW", auto_pad: c, ceil_mode: f, count_include_pad: y, storage_order: v, dilations: [C, O2], kernel_shape: [B3, N2], pads: [L, j3, me3, he3], strides: [P2, ee3] }); }, 857709: (s, c) => { u.jb("GlobalMaxPool", s, { format: c ? "NHWC" : "NCHW" }); }, 857796: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3, ye2) => { u.jb("MaxPool", s, { format: ye2 ? "NHWC" : "NCHW", auto_pad: c, ceil_mode: f, count_include_pad: y, storage_order: v, dilations: [C, O2], kernel_shape: [B3, N2], pads: [L, j3, me3, he3], strides: [P2, ee3] }); }, 858076: (s, c, f, y, v) => { u.jb("Gemm", s, { alpha: c, beta: f, transA: y, transB: v }); }, 858180: (s) => { u.jb("MatMul", s, void 0); }, 858234: (s, c, f, y) => { u.jb("ArgMax", s, { keepDims: !!c, selectLastIndex: !!f, axis: y }); }, 858342: (s, c, f, y) => { u.jb("ArgMin", s, { keepDims: !!c, selectLastIndex: !!f, axis: y }); }, 858450: (s, c) => { u.jb("Softmax", s, { axis: c }); }, 858513: (s, c) => { u.jb("Concat", s, { axis: c }); }, 858573: (s, c, f, y, v) => { u.jb("Split", s, { axis: c, numOutputs: f, splitSizes: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 858713: (s) => { u.jb("Expand", s, void 0); }, 858767: (s, c) => { u.jb("Gather", s, { axis: Number(c) }); }, 858838: (s, c) => { u.jb("GatherElements", s, { axis: Number(c) }); }, 858917: (s, c, f, y, v, C, O2, B3, N2, L, j3) => { u.jb("Resize", s, { antialias: c, axes: f ? Array.from(i().subarray(f >>> 0, y >>> 0)) : [], coordinateTransformMode: Ae3(v), cubicCoeffA: C, excludeOutside: O2, extrapolationValue: B3, keepAspectRatioPolicy: Ae3(N2), mode: Ae3(L), nearestMode: Ae3(j3) }); }, 859263: (s, c, f, y, v, C, O2) => { u.jb("Slice", s, { starts: c ? Array.from(i().subarray(c >>> 0, f >>> 0)) : [], ends: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [], axes: C ? Array.from(i().subarray(C >>> 0, O2 >>> 0)) : [] }); }, 859479: (s) => { u.jb("Tile", s, void 0); }, 859531: (s, c, f) => { u.jb("InstanceNormalization", s, { epsilon: c, format: f ? "NHWC" : "NCHW" }); }, 859645: (s, c, f) => { u.jb("InstanceNormalization", s, { epsilon: c, format: f ? "NHWC" : "NCHW" }); }, 859759: (s) => { u.jb("Range", s, void 0); }, 859812: (s, c) => { u.jb("Einsum", s, { equation: Ae3(c) }); }, 859893: (s, c, f, y, v) => { u.jb("Pad", s, { mode: c, value: f, pads: y ? Array.from(i().subarray(y >>> 0, v >>> 0)) : [] }); }, 860020: (s, c, f, y, v, C) => { u.jb("BatchNormalization", s, { epsilon: c, momentum: f, spatial: !!v, trainingMode: !!y, format: C ? "NHWC" : "NCHW" }); }, 860189: (s, c, f, y, v, C) => { u.jb("BatchNormalization", s, { epsilon: c, momentum: f, spatial: !!v, trainingMode: !!y, format: C ? "NHWC" : "NCHW" }); }, 860358: (s, c, f) => { u.jb("CumSum", s, { exclusive: Number(c), reverse: Number(f) }); }, 860455: (s, c, f, y, v, C, O2, B3, N2) => { u.jb("Attention", s, { numHeads: c, isUnidirectional: f, maskFilterValue: y, scale: v, doRotary: C, qkvHiddenSizes: O2 ? Array.from(i().subarray(Number(B3) >>> 0, Number(B3) + O2 >>> 0)) : [], pastPresentShareBuffer: !!N2 }); }, 860727: (s) => { u.jb("BiasAdd", s, void 0); }, 860782: (s) => { u.jb("BiasSplitGelu", s, void 0); }, 860843: (s) => { u.jb("FastGelu", s, void 0); }, 860899: (s, c, f, y, v, C, O2, B3, N2, L, j3, me3, he3, P2, ee3, ye2) => { u.jb("Conv", s, { format: me3 ? "NHWC" : "NCHW", auto_pad: c, dilations: f ? Array.from(i().subarray(f >>> 0, y >>> 0)) : [], group: v, kernel_shape: C ? Array.from(i().subarray(C >>> 0, O2 >>> 0)) : [], pads: B3 ? Array.from(i().subarray(B3 >>> 0, N2 >>> 0)) : [], strides: L ? Array.from(i().subarray(L >>> 0, j3 >>> 0)) : [], w_is_const: () => !!t()[he3 >>> 0], activation: Ae3(P2), activation_params: ee3 ? Array.from(l().subarray(ee3 >>> 0, ye2 >>> 0)) : [] }); }, 861395: (s) => { u.jb("Gelu", s, void 0); }, 861447: (s, c, f, y) => { u.jb("GroupQueryAttention", s, { numHeads: c, kvNumHeads: f, scale: y }); }, 861560: (s, c, f, y) => { u.jb("LayerNormalization", s, { axis: c, epsilon: f, simplified: !!y }); }, 861671: (s, c, f, y) => { u.jb("LayerNormalization", s, { axis: c, epsilon: f, simplified: !!y }); }, 861782: (s, c, f, y, v, C) => { u.jb("MatMulNBits", s, { k: c, n: f, accuracyLevel: y, bits: v, blockSize: C }); }, 861909: (s, c, f, y, v, C) => { u.jb("MultiHeadAttention", s, { numHeads: c, isUnidirectional: f, maskFilterValue: y, scale: v, doRotary: C }); }, 862068: (s, c) => { u.jb("QuickGelu", s, { alpha: c }); }, 862132: (s, c, f, y, v) => { u.jb("RotaryEmbedding", s, { interleaved: !!c, numHeads: f, rotaryEmbeddingDim: y, scale: v }); }, 862271: (s, c, f) => { u.jb("SkipLayerNormalization", s, { epsilon: c, simplified: !!f }); }, 862373: (s) => { u.Yb(s); }, 862407: (s, c) => u.$b(s, c, u.Eb.bc, u.Eb.errors), 862519: (s, c, f) => { u.jb("SkipLayerNormalization", s, { epsilon: c, simplified: !!f }); } }; function Nl3(s, c, f) { return hi3(async () => { await u.Wb(s, c, f); }); } function Wl2() { return typeof wasmOffsetConverter < "u"; } function hn3(s) { this.name = "ExitStatus", this.message = `Program terminated with exit(${s})`, this.status = s; } var gn3 = (s) => { s.terminate(), s.onmessage = () => { }; }, Ro3 = (s) => { ct2.length == 0 && (Ho2(), Wo(ct2[0])); var c = ct2.pop(); if (!c) return 6; wt.push(c), Ze[s.Ab] = c, c.Ab = s.Ab; var f = { cmd: "run", start_routine: s.cc, arg: s.Pb, pthread_ptr: s.Ab }; return c.postMessage(f, s.ic), 0; }, bt3 = 0, xe = (s, c, ...f) => { for (var y = 2 * f.length, v = Bn3(), C = zn3(8 * y), O2 = C >>> 3, B3 = 0; B3 < f.length; B3++) { var N2 = f[B3]; typeof N2 == "bigint" ? (F2[O2 + 2 * B3] = 1n, F2[O2 + 2 * B3 + 1] = N2) : (F2[O2 + 2 * B3] = 0n, d()[O2 + 2 * B3 + 1 >>> 0] = N2); } return s = Vi3(s, 0, y, C, c), yr3(v), s; }; function yn3(s) { if (b) return xe(0, 1, s); if (de2 = s, !(0 < bt3)) { for (var c of wt) gn3(c); for (c of ct2) gn3(c); ct2 = [], wt = [], Ze = [], Se2 = true; } A2(s, new hn3(s)); } function Mo(s) { if (b) return xe(1, 0, s); bn3(s); } var bn3 = (s) => { if (de2 = s, b) throw Mo(s), "unwind"; yn3(s); }, ct2 = [], wt = [], Uo3 = [], Ze = {}, Vo2 = (s) => { var c = s.Ab; delete Ze[c], ct2.push(s), wt.splice(wt.indexOf(s), 1), s.Ab = 0, Dn3(c); }; function No3() { Uo3.forEach((s) => s()); } var Wo = (s) => new Promise((c) => { s.onmessage = (v) => { var C = (v = v.data).cmd; if (v.targetThread && v.targetThread != Mt2()) { var O2 = Ze[v.targetThread]; O2 ? O2.postMessage(v, v.transferList) : Y3(`Internal error! Worker sent a message "${C}" to target pthread ${v.targetThread}, but that thread no longer exists!`); } else C === "checkMailbox" ? sr3() : C === "spawnThread" ? Ro3(v) : C === "cleanupThread" ? Vo2(Ze[v.thread]) : C === "killThread" ? (v = v.thread, C = Ze[v], delete Ze[v], gn3(C), Dn3(v), wt.splice(wt.indexOf(C), 1), C.Ab = 0) : C === "cancelThread" ? Ze[v.thread].postMessage({ cmd: "cancel" }) : C === "loaded" ? (s.loaded = true, c(s)) : C === "alert" ? alert(`Thread ${v.threadId}: ${v.text}`) : v.target === "setimmediate" ? s.postMessage(v) : C === "callHandler" ? u[v.handler](...v.args) : C && Y3(`worker sent an unknown command ${C}`); }, s.onerror = (v) => { throw Y3(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`), v; }; var f, y = []; for (f of []) u.hasOwnProperty(f) && y.push(f); s.postMessage({ cmd: "load", handlers: y, wasmMemory: le3, wasmModule: K }); }); function Ho2() { var s = new Worker(new URL(import.meta.url), { type: "module", workerData: "em-pthread", name: "em-pthread" }); ct2.push(s); } var ar2 = (s) => { for (; 0 < s.length; ) s.shift()(u); }, Hl2 = () => { var s = Mt2(), c = a()[s + 52 >>> 2 >>> 0]; s = a()[s + 56 >>> 2 >>> 0], Wi3(c, c - s), yr3(c); }, Gl3 = (s, c) => { bt3 = 0, s = Hi3(s, c), 0 < bt3 ? de2 = s : gr2(s); }; class Ll3 { constructor(c) { this.Ib = c - 24; } } function Fl3(s, c, f) { var y = new Ll3(s >>>= 0); throw c >>>= 0, f >>>= 0, a()[y.Ib + 16 >>> 2 >>> 0] = 0, a()[y.Ib + 4 >>> 2 >>> 0] = c, a()[y.Ib + 8 >>> 2 >>> 0] = f, s; } function Go2(s, c, f, y) { return b ? xe(2, 1, s, c, f, y) : Lo2(s, c, f, y); } function Lo2(s, c, f, y) { if (s >>>= 0, c >>>= 0, f >>>= 0, y >>>= 0, x2 === void 0) return Y3("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; var v = []; return b && v.length === 0 ? Go2(s, c, f, y) : (s = { cc: f, Ab: s, Pb: y, ic: v }, b ? (s.Lb = "spawnThread", postMessage(s, v), 0) : Ro3(s)); } var Fo3 = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0, qo = (s, c, f) => { var y = (c >>>= 0) + f; for (f = c; s[f] && !(f >= y); ) ++f; if (16 < f - c && s.buffer && Fo3) return Fo3.decode(s.buffer instanceof x2 ? s.slice(c, f) : s.subarray(c, f)); for (y = ""; c < f; ) { var v = s[c++]; if (128 & v) { var C = 63 & s[c++]; if ((224 & v) == 192) y += String.fromCharCode((31 & v) << 6 | C); else { var O2 = 63 & s[c++]; 65536 > (v = (240 & v) == 224 ? (15 & v) << 12 | C << 6 | O2 : (7 & v) << 18 | C << 12 | O2 << 6 | 63 & s[c++]) ? y += String.fromCharCode(v) : (v -= 65536, y += String.fromCharCode(55296 | v >> 10, 56320 | 1023 & v)); } } else y += String.fromCharCode(v); } return y; }, Ae3 = (s, c) => (s >>>= 0) ? qo(r(), s, c) : ""; function jo(s, c, f) { return b ? xe(3, 1, s, c, f) : 0; } function Ko(s, c) { if (b) return xe(4, 1, s, c); } var wn2 = (s) => { for (var c = 0, f = 0; f < s.length; ++f) { var y = s.charCodeAt(f); 127 >= y ? c++ : 2047 >= y ? c += 2 : 55296 <= y && 57343 >= y ? (c += 4, ++f) : c += 3; } return c; }, Yo2 = (s, c, f, y) => { if (!(0 < y)) return 0; var v = f >>>= 0; y = f + y - 1; for (var C = 0; C < s.length; ++C) { var O2 = s.charCodeAt(C); if (55296 <= O2 && 57343 >= O2 && (O2 = 65536 + ((1023 & O2) << 10) | 1023 & s.charCodeAt(++C)), 127 >= O2) { if (f >= y) break; c[f++ >>> 0] = O2; } else { if (2047 >= O2) { if (f + 1 >= y) break; c[f++ >>> 0] = 192 | O2 >> 6; } else { if (65535 >= O2) { if (f + 2 >= y) break; c[f++ >>> 0] = 224 | O2 >> 12; } else { if (f + 3 >= y) break; c[f++ >>> 0] = 240 | O2 >> 18, c[f++ >>> 0] = 128 | O2 >> 12 & 63; } c[f++ >>> 0] = 128 | O2 >> 6 & 63; } c[f++ >>> 0] = 128 | 63 & O2; } } return c[f >>> 0] = 0, f - v; }, zt2 = (s, c, f) => Yo2(s, r(), c, f); function Xo(s, c) { if (b) return xe(5, 1, s, c); } function Zo2(s, c, f) { if (b) return xe(6, 1, s, c, f); } function Qo2(s, c, f) { return b ? xe(7, 1, s, c, f) : 0; } function Jo(s, c) { if (b) return xe(8, 1, s, c); } function ei3(s, c, f) { if (b) return xe(9, 1, s, c, f); } function ti(s, c, f, y) { if (b) return xe(10, 1, s, c, f, y); } function ri(s, c, f, y) { if (b) return xe(11, 1, s, c, f, y); } function ni3(s, c, f, y) { if (b) return xe(12, 1, s, c, f, y); } function oi2(s) { if (b) return xe(13, 1, s); } function ii3(s, c) { if (b) return xe(14, 1, s, c); } function ai2(s, c, f) { if (b) return xe(15, 1, s, c, f); } var si2, pt2, ql2 = () => { Dt2(""); }, Qe = (s) => { for (var c = ""; r()[s >>> 0]; ) c += si2[r()[s++ >>> 0]]; return c; }, vn2 = {}, $n3 = {}, jl2 = {}; function st2(s, c, f = {}) { if (!("argPackAdvance" in c)) throw new TypeError("registerType registeredInstance requires argPackAdvance"); return (function(y, v, C = {}) { var O2 = v.name; if (!y) throw new pt2(`type "${O2}" must have a positive integer typeid pointer`); if ($n3.hasOwnProperty(y)) { if (C.Rb) return; throw new pt2(`Cannot register type '${O2}' twice`); } $n3[y] = v, delete jl2[y], vn2.hasOwnProperty(y) && (v = vn2[y], delete vn2[y], v.forEach((B3) => B3())); })(s, c, f); } var ui2 = (s, c, f) => { switch (c) { case 1: return f ? (y) => t()[y >>> 0] : (y) => r()[y >>> 0]; case 2: return f ? (y) => n()[y >>> 1 >>> 0] : (y) => o()[y >>> 1 >>> 0]; case 4: return f ? (y) => i()[y >>> 2 >>> 0] : (y) => a()[y >>> 2 >>> 0]; case 8: return f ? (y) => F2[y >>> 3] : (y) => ce3[y >>> 3]; default: throw new TypeError(`invalid integer width (${c}): ${s}`); } }; function Kl2(s, c, f) { f >>>= 0, st2(s >>>= 0, { name: c = Qe(c >>> 0), fromWireType: (y) => y, toWireType: function(y, v) { if (typeof v != "bigint" && typeof v != "number") throw v = v === null ? "null" : (y = typeof v) == "object" || y === "array" || y === "function" ? v.toString() : "" + v, new TypeError(`Cannot convert "${v}" to ${this.name}`); return typeof v == "number" && (v = BigInt(v)), v; }, argPackAdvance: mt2, readValueFromPointer: ui2(c, f, c.indexOf("u") == -1), Db: null }); } var mt2 = 8; function Yl3(s, c, f, y) { st2(s >>>= 0, { name: c = Qe(c >>> 0), fromWireType: function(v) { return !!v; }, toWireType: function(v, C) { return C ? f : y; }, argPackAdvance: mt2, readValueFromPointer: function(v) { return this.fromWireType(r()[v >>> 0]); }, Db: null }); } var _n3 = [], ut2 = []; function xn3(s) { 9 < (s >>>= 0) && --ut2[s + 1] == 0 && (ut2[s] = void 0, _n3.push(s)); } var qe3 = (s) => { if (!s) throw new pt2("Cannot use deleted val. handle = " + s); return ut2[s]; }, je3 = (s) => { switch (s) { case void 0: return 2; case null: return 4; case true: return 6; case false: return 8; default: let c = _n3.pop() || ut2.length; return ut2[c] = s, ut2[c + 1] = 1, c; } }; function Sn3(s) { return this.fromWireType(a()[s >>> 2 >>> 0]); } var Xl2 = { name: "emscripten::val", fromWireType: (s) => { var c = qe3(s); return xn3(s), c; }, toWireType: (s, c) => je3(c), argPackAdvance: mt2, readValueFromPointer: Sn3, Db: null }; function Zl3(s) { return st2(s >>> 0, Xl2); } var Ql3 = (s, c) => { switch (c) { case 4: return function(f) { return this.fromWireType(l()[f >>> 2 >>> 0]); }; case 8: return function(f) { return this.fromWireType(d()[f >>> 3 >>> 0]); }; default: throw new TypeError(`invalid float width (${c}): ${s}`); } }; function Jl2(s, c, f) { f >>>= 0, st2(s >>>= 0, { name: c = Qe(c >>> 0), fromWireType: (y) => y, toWireType: (y, v) => v, argPackAdvance: mt2, readValueFromPointer: Ql3(c, f), Db: null }); } function ec3(s, c, f, y, v) { if (s >>>= 0, f >>>= 0, c = Qe(c >>> 0), v === -1 && (v = 4294967295), v = (B3) => B3, y === 0) { var C = 32 - 8 * f; v = (B3) => B3 << C >>> C; } var O2 = c.includes("unsigned") ? function(B3, N2) { return N2 >>> 0; } : function(B3, N2) { return N2; }; st2(s, { name: c, fromWireType: v, toWireType: O2, argPackAdvance: mt2, readValueFromPointer: ui2(c, f, y !== 0), Db: null }); } function tc3(s, c, f) { function y(C) { var O2 = a()[C >>> 2 >>> 0]; return C = a()[C + 4 >>> 2 >>> 0], new v(t().buffer, C, O2); } var v = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array][c]; st2(s >>>= 0, { name: f = Qe(f >>> 0), fromWireType: y, argPackAdvance: mt2, readValueFromPointer: y }, { Rb: true }); } function rc3(s, c) { s >>>= 0; var f = (c = Qe(c >>> 0)) === "std::string"; st2(s, { name: c, fromWireType: function(y) { var v = a()[y >>> 2 >>> 0], C = y + 4; if (f) for (var O2 = C, B3 = 0; B3 <= v; ++B3) { var N2 = C + B3; if (B3 == v || r()[N2 >>> 0] == 0) { if (O2 = Ae3(O2, N2 - O2), L === void 0) var L = O2; else L += String.fromCharCode(0), L += O2; O2 = N2 + 1; } } else { for (L = Array(v), B3 = 0; B3 < v; ++B3) L[B3] = String.fromCharCode(r()[C + B3 >>> 0]); L = L.join(""); } return et2(y), L; }, toWireType: function(y, v) { v instanceof ArrayBuffer && (v = new Uint8Array(v)); var C = typeof v == "string"; if (!(C || v instanceof Uint8Array || v instanceof Uint8ClampedArray || v instanceof Int8Array)) throw new pt2("Cannot pass non-string to std::string"); var O2 = f && C ? wn2(v) : v.length, B3 = hr3(4 + O2 + 1), N2 = B3 + 4; if (a()[B3 >>> 2 >>> 0] = O2, f && C) zt2(v, N2, O2 + 1); else if (C) for (C = 0; C < O2; ++C) { var L = v.charCodeAt(C); if (255 < L) throw et2(N2), new pt2("String has UTF-16 code units that do not fit in 8 bits"); r()[N2 + C >>> 0] = L; } else for (C = 0; C < O2; ++C) r()[N2 + C >>> 0] = v[C]; return y !== null && y.push(et2, B3), B3; }, argPackAdvance: mt2, readValueFromPointer: Sn3, Db(y) { et2(y); } }); } var di2 = typeof TextDecoder < "u" ? new TextDecoder("utf-16le") : void 0, nc3 = (s, c) => { for (var f = s >> 1, y = f + c / 2; !(f >= y) && o()[f >>> 0]; ) ++f; if (32 < (f <<= 1) - s && di2) return di2.decode(r().slice(s, f)); for (f = "", y = 0; !(y >= c / 2); ++y) { var v = n()[s + 2 * y >>> 1 >>> 0]; if (v == 0) break; f += String.fromCharCode(v); } return f; }, oc3 = (s, c, f) => { if (f ??= 2147483647, 2 > f) return 0; var y = c; f = (f -= 2) < 2 * s.length ? f / 2 : s.length; for (var v = 0; v < f; ++v) { var C = s.charCodeAt(v); n()[c >>> 1 >>> 0] = C, c += 2; } return n()[c >>> 1 >>> 0] = 0, c - y; }, ic3 = (s) => 2 * s.length, ac3 = (s, c) => { for (var f = 0, y = ""; !(f >= c / 4); ) { var v = i()[s + 4 * f >>> 2 >>> 0]; if (v == 0) break; ++f, 65536 <= v ? (v -= 65536, y += String.fromCharCode(55296 | v >> 10, 56320 | 1023 & v)) : y += String.fromCharCode(v); } return y; }, sc3 = (s, c, f) => { if (c >>>= 0, f ??= 2147483647, 4 > f) return 0; var y = c; f = y + f - 4; for (var v = 0; v < s.length; ++v) { var C = s.charCodeAt(v); if (55296 <= C && 57343 >= C && (C = 65536 + ((1023 & C) << 10) | 1023 & s.charCodeAt(++v)), i()[c >>> 2 >>> 0] = C, (c += 4) + 4 > f) break; } return i()[c >>> 2 >>> 0] = 0, c - y; }, uc3 = (s) => { for (var c = 0, f = 0; f < s.length; ++f) { var y = s.charCodeAt(f); 55296 <= y && 57343 >= y && ++f, c += 4; } return c; }; function dc3(s, c, f) { if (s >>>= 0, c >>>= 0, f = Qe(f >>>= 0), c === 2) var y = nc3, v = oc3, C = ic3, O2 = (B3) => o()[B3 >>> 1 >>> 0]; else c === 4 && (y = ac3, v = sc3, C = uc3, O2 = (B3) => a()[B3 >>> 2 >>> 0]); st2(s, { name: f, fromWireType: (B3) => { for (var N2, L = a()[B3 >>> 2 >>> 0], j3 = B3 + 4, me3 = 0; me3 <= L; ++me3) { var he3 = B3 + 4 + me3 * c; me3 != L && O2(he3) != 0 || (j3 = y(j3, he3 - j3), N2 === void 0 ? N2 = j3 : (N2 += String.fromCharCode(0), N2 += j3), j3 = he3 + c); } return et2(B3), N2; }, toWireType: (B3, N2) => { if (typeof N2 != "string") throw new pt2(`Cannot pass non-string to C++ string type ${f}`); var L = C(N2), j3 = hr3(4 + L + c); return a()[j3 >>> 2 >>> 0] = L / c, v(N2, j3 + 4, L + c), B3 !== null && B3.push(et2, j3), j3; }, argPackAdvance: mt2, readValueFromPointer: Sn3, Db(B3) { et2(B3); } }); } function lc2(s, c) { st2(s >>>= 0, { Sb: true, name: c = Qe(c >>> 0), argPackAdvance: 0, fromWireType: () => { }, toWireType: () => { } }); } var cc3 = () => 1; function pc3(s) { On3(s >>> 0, !g, 1, !w, 131072, false), No3(); } var li2 = (s) => { if (!Se2) try { if (s(), !(0 < bt3)) try { b ? gr2(de2) : bn3(de2); } catch (c) { c instanceof hn3 || c == "unwind" || A2(1, c); } } catch (c) { c instanceof hn3 || c == "unwind" || A2(1, c); } }; function In2(s) { s >>>= 0, typeof Atomics.jc == "function" && (Atomics.jc(i(), s >>> 2, s).value.then(sr3), s += 128, Atomics.store(i(), s >>> 2, 1)); } var sr3 = () => { var s = Mt2(); s && (In2(s), li2(Ni3)); }; function mc3(s, c) { (s >>>= 0) == c >>> 0 ? setTimeout(sr3) : b ? postMessage({ targetThread: s, cmd: "checkMailbox" }) : (s = Ze[s]) && s.postMessage({ cmd: "checkMailbox" }); } var Cn3 = []; function fc3(s, c, f, y, v) { for (c >>>= 0, y /= 2, Cn3.length = y, f = v >>> 0 >>> 3, v = 0; v < y; v++) Cn3[v] = F2[f + 2 * v] ? F2[f + 2 * v + 1] : d()[f + 2 * v + 1 >>> 0]; return (c ? fn3[c] : np3[s])(...Cn3); } function hc3(s) { s >>>= 0, b ? postMessage({ cmd: "cleanupThread", thread: s }) : Vo2(Ze[s]); } function gc3(s) { } var Tn2 = (s, c) => { var f = $n3[s]; if (f === void 0) throw s = Ri3(s), f = Qe(s), et2(s), new pt2(`${c} has unknown type ${f}`); return f; }, ci2 = (s, c, f) => { var y = []; return s = s.toWireType(y, f), y.length && (a()[c >>> 2 >>> 0] = je3(y)), s; }; function yc3(s, c, f) { return c >>>= 0, f >>>= 0, s = qe3(s >>> 0), c = Tn2(c, "emval::as"), ci2(c, f, s); } var ur3 = (s) => { try { s(); } catch (c) { Dt2(c); } }, ft2 = 0, Je2 = null, pi2 = 0, dr3 = [], mi2 = {}, fi2 = {}, bc3 = 0, An3 = null, wc3 = []; function hi3(s) { return (function(c) { if (!Se2) { if (ft2 === 0) { var f = false, y = false; c((v = 0) => { if (!Se2 && (pi2 = v, f = true, y)) { ft2 = 2, ur3(() => Fi2(Je2)), typeof Browser < "u" && Browser.Jb.Qb && Browser.Jb.resume(), v = false; try { var C = (function() { var N2 = i()[Je2 + 8 >>> 2 >>> 0]; return N2 = q3[fi2[N2]], --bt3, N2(); })(); } catch (N2) { C = N2, v = true; } var O2 = false; if (!Je2) { var B3 = An3; B3 && (An3 = null, (v ? B3.reject : B3.resolve)(C), O2 = true); } if (v && !O2) throw C; } }), y = true, f || (ft2 = 1, Je2 = (function() { var v = hr3(65548), C = v + 12; a()[v >>> 2 >>> 0] = C, a()[v + 4 >>> 2 >>> 0] = C + 65536, C = dr3[0]; var O2 = mi2[C]; return O2 === void 0 && (O2 = bc3++, mi2[C] = O2, fi2[O2] = C), C = O2, i()[v + 8 >>> 2 >>> 0] = C, v; })(), typeof Browser < "u" && Browser.Jb.Qb && Browser.Jb.pause(), ur3(() => Gi3(Je2))); } else ft2 === 2 ? (ft2 = 0, ur3(qi3), et2(Je2), Je2 = null, wc3.forEach(li2)) : Dt2(`invalid state: ${ft2}`); return pi2; } })((c) => { s().then(c); }); } function vc3(s) { return s >>>= 0, hi3(() => (s = qe3(s)).then(je3)); } var lr3 = []; function $c3(s, c, f, y) { return f >>>= 0, y >>>= 0, (s = lr3[s >>> 0])(null, c = qe3(c >>> 0), f, y); } var _c3 = {}, cr3 = (s) => { var c = _c3[s]; return c === void 0 ? Qe(s) : c; }; function xc3(s, c, f, y, v) { return f >>>= 0, y >>>= 0, v >>>= 0, (s = lr3[s >>> 0])(c = qe3(c >>> 0), c[f = cr3(f)], y, v); } var gi2 = () => typeof globalThis == "object" ? globalThis : Function("return this")(); function Sc3(s) { return (s >>>= 0) == 0 ? je3(gi2()) : (s = cr3(s), je3(gi2()[s])); } var Ic3 = (s) => { var c = lr3.length; return lr3.push(s), c; }, Cc3 = (s, c) => { for (var f = Array(s), y = 0; y < s; ++y) f[y] = Tn2(a()[c + 4 * y >>> 2 >>> 0], "parameter " + y); return f; }, yi2 = (s, c) => Object.defineProperty(c, "name", { value: s }); function Tc3(s, c, f) { var y = (c = Cc3(s, c >>> 0)).shift(); s--; var v = `return function (obj, func, destructorsRef, args) { `, C = 0, O2 = []; f === 0 && O2.push("obj"); for (var B3 = ["retType"], N2 = [y], L = 0; L < s; ++L) O2.push("arg" + L), B3.push("argType" + L), N2.push(c[L]), v += ` var arg${L} = argType${L}.readValueFromPointer(args${C ? "+" + C : ""}); `, C += c[L].argPackAdvance; return v += ` var rv = ${f === 1 ? "new func" : "func.call"}(${O2.join(", ")}); `, y.Sb || (B3.push("emval_returnValue"), N2.push(ci2), v += ` return emval_returnValue(retType, destructorsRef, rv); `), B3.push(v + `}; `), s = (function(j3) { var me3 = Function; if (!(me3 instanceof Function)) throw new TypeError(`new_ called with constructor type ${typeof me3} which is not a function`); var he3 = yi2(me3.name || "unknownFunctionName", function() { }); return he3.prototype = me3.prototype, he3 = new he3(), (j3 = me3.apply(he3, j3)) instanceof Object ? j3 : he3; })(B3)(...N2), f = `methodCaller<(${c.map((j3) => j3.name).join(", ")}) => ${y.name}>`, Ic3(yi2(f, s)); } function Ac3(s) { return s = cr3(s >>> 0), je3(u[s]); } function Ec3(s, c) { return c >>>= 0, s = qe3(s >>> 0), c = qe3(c), je3(s[c]); } function kc3(s) { 9 < (s >>>= 0) && (ut2[s + 1] += 1); } function Pc3() { return je3([]); } function Oc3(s) { s = qe3(s >>> 0); for (var c = Array(s.length), f = 0; f < s.length; f++) c[f] = s[f]; return je3(c); } function Dc3(s) { return je3(cr3(s >>> 0)); } function zc3() { return je3({}); } function Bc3(s) { for (var c = qe3(s >>>= 0); c.length; ) { var f = c.pop(); c.pop()(f); } xn3(s); } function Rc3(s, c, f) { c >>>= 0, f >>>= 0, s = qe3(s >>> 0), c = qe3(c), f = qe3(f), s[c] = f; } function Mc3(s, c) { return c >>>= 0, s = (s = Tn2(s >>> 0, "_emval_take_value")).readValueFromPointer(c), je3(s); } function Uc3(s, c) { s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), c >>>= 0, s = new Date(1e3 * s), i()[c >>> 2 >>> 0] = s.getUTCSeconds(), i()[c + 4 >>> 2 >>> 0] = s.getUTCMinutes(), i()[c + 8 >>> 2 >>> 0] = s.getUTCHours(), i()[c + 12 >>> 2 >>> 0] = s.getUTCDate(), i()[c + 16 >>> 2 >>> 0] = s.getUTCMonth(), i()[c + 20 >>> 2 >>> 0] = s.getUTCFullYear() - 1900, i()[c + 24 >>> 2 >>> 0] = s.getUTCDay(), s = (s.getTime() - Date.UTC(s.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i()[c + 28 >>> 2 >>> 0] = s; } var Bt2 = (s) => s % 4 == 0 && (s % 100 != 0 || s % 400 == 0), bi2 = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], wi2 = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; function Vc3(s, c) { s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), c >>>= 0, s = new Date(1e3 * s), i()[c >>> 2 >>> 0] = s.getSeconds(), i()[c + 4 >>> 2 >>> 0] = s.getMinutes(), i()[c + 8 >>> 2 >>> 0] = s.getHours(), i()[c + 12 >>> 2 >>> 0] = s.getDate(), i()[c + 16 >>> 2 >>> 0] = s.getMonth(), i()[c + 20 >>> 2 >>> 0] = s.getFullYear() - 1900, i()[c + 24 >>> 2 >>> 0] = s.getDay(); var f = (Bt2(s.getFullYear()) ? bi2 : wi2)[s.getMonth()] + s.getDate() - 1 | 0; i()[c + 28 >>> 2 >>> 0] = f, i()[c + 36 >>> 2 >>> 0] = -60 * s.getTimezoneOffset(), f = new Date(s.getFullYear(), 6, 1).getTimezoneOffset(); var y = new Date(s.getFullYear(), 0, 1).getTimezoneOffset(); s = 0 | (f != y && s.getTimezoneOffset() == Math.min(y, f)), i()[c + 32 >>> 2 >>> 0] = s; } function Nc3(s) { s >>>= 0; var c = new Date(i()[s + 20 >>> 2 >>> 0] + 1900, i()[s + 16 >>> 2 >>> 0], i()[s + 12 >>> 2 >>> 0], i()[s + 8 >>> 2 >>> 0], i()[s + 4 >>> 2 >>> 0], i()[s >>> 2 >>> 0], 0), f = i()[s + 32 >>> 2 >>> 0], y = c.getTimezoneOffset(), v = new Date(c.getFullYear(), 6, 1).getTimezoneOffset(), C = new Date(c.getFullYear(), 0, 1).getTimezoneOffset(), O2 = Math.min(C, v); return 0 > f ? i()[s + 32 >>> 2 >>> 0] = +(v != C && O2 == y) : 0 < f != (O2 == y) && (v = Math.max(C, v), c.setTime(c.getTime() + 6e4 * ((0 < f ? O2 : v) - y))), i()[s + 24 >>> 2 >>> 0] = c.getDay(), f = (Bt2(c.getFullYear()) ? bi2 : wi2)[c.getMonth()] + c.getDate() - 1 | 0, i()[s + 28 >>> 2 >>> 0] = f, i()[s >>> 2 >>> 0] = c.getSeconds(), i()[s + 4 >>> 2 >>> 0] = c.getMinutes(), i()[s + 8 >>> 2 >>> 0] = c.getHours(), i()[s + 12 >>> 2 >>> 0] = c.getDate(), i()[s + 16 >>> 2 >>> 0] = c.getMonth(), i()[s + 20 >>> 2 >>> 0] = c.getYear(), s = c.getTime(), BigInt(isNaN(s) ? -1 : s / 1e3); } function vi2(s, c, f, y, v, C, O2) { return b ? xe(16, 1, s, c, f, y, v, C, O2) : -52; } function $i3(s, c, f, y, v, C) { if (b) return xe(17, 1, s, c, f, y, v, C); } function Wc3(s, c, f, y) { s >>>= 0, c >>>= 0, f >>>= 0, y >>>= 0; var v = (/* @__PURE__ */ new Date()).getFullYear(), C = new Date(v, 0, 1), O2 = new Date(v, 6, 1); v = C.getTimezoneOffset(); var B3 = O2.getTimezoneOffset(), N2 = Math.max(v, B3); a()[s >>> 2 >>> 0] = 60 * N2, i()[c >>> 2 >>> 0] = +(v != B3), C = (s = (L) => L.toLocaleTimeString(void 0, { hour12: false, timeZoneName: "short" }).split(" ")[1])(C), O2 = s(O2), B3 < v ? (zt2(C, f, 17), zt2(O2, y, 17)) : (zt2(C, y, 17), zt2(O2, f, 17)); } var En3 = [], _i2 = (s, c) => { En3.length = 0; for (var f; f = r()[s++ >>> 0]; ) { var y = f != 105; c += (y &= f != 112) && c % 8 ? 4 : 0, En3.push(f == 112 ? a()[c >>> 2 >>> 0] : f == 106 ? F2[c >>> 3] : f == 105 ? i()[c >>> 2 >>> 0] : d()[c >>> 3 >>> 0]), c += y ? 8 : 4; } return En3; }; function Hc3(s, c, f) { return s >>>= 0, c = _i2(c >>> 0, f >>> 0), fn3[s](...c); } function Gc3(s, c, f) { return s >>>= 0, c = _i2(c >>> 0, f >>> 0), fn3[s](...c); } var Lc3 = () => { }, Fc3 = () => Date.now(); function qc3(s, c) { return Y3(Ae3(s >>> 0, c >>> 0)); } var xi2, jc3 = () => { throw bt3 += 1, "unwind"; }; function Kc3() { return 4294901760; } xi2 = () => performance.timeOrigin + performance.now(); var Yc3 = () => navigator.hardwareConcurrency; function Xc3() { return Dt2("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"), 0; } function Zc3(s) { s >>>= 0; var c = r().length; if (s <= c || 4294901760 < s) return false; for (var f = 1; 4 >= f; f *= 2) { var y = c * (1 + 0.2 / f); y = Math.min(y, s + 100663296); var v = Math; y = Math.max(s, y); e: { v = (v.min.call(v, 4294901760, y + (65536 - y % 65536) % 65536) - le3.buffer.byteLength + 65535) / 65536; try { le3.grow(v), we2(); var C = 1; break e; } catch { } C = void 0; } if (C) return true; } return false; } var pr3 = () => (Dt2("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"), 0), Rt2 = {}, Si3 = (s) => { s.forEach((c) => { var f = pr3(); f && (Rt2[f] = c); }); }; function Qc3() { var s = Error().stack.toString().split(` `); return s[0] == "Error" && s.shift(), Si3(s), Rt2.Ob = pr3(), Rt2.ac = s, Rt2.Ob; } function Jc3(s, c, f) { if (s >>>= 0, c >>>= 0, Rt2.Ob == s) var y = Rt2.ac; else (y = Error().stack.toString().split(` `))[0] == "Error" && y.shift(), Si3(y); for (var v = 3; y[v] && pr3() != s; ) ++v; for (s = 0; s < f && y[s + v]; ++s) i()[c + 4 * s >>> 2 >>> 0] = pr3(); return s; } var kn3, Pn3 = {}, Ii3 = () => { if (!kn3) { var s, c = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: T3 || "./this.program" }; for (s in Pn3) Pn3[s] === void 0 ? delete c[s] : c[s] = Pn3[s]; var f = []; for (s in c) f.push(`${s}=${c[s]}`); kn3 = f; } return kn3; }; function Ci3(s, c) { if (b) return xe(18, 1, s, c); s >>>= 0, c >>>= 0; var f = 0; return Ii3().forEach((y, v) => { var C = c + f; for (v = a()[s + 4 * v >>> 2 >>> 0] = C, C = 0; C < y.length; ++C) t()[v++ >>> 0] = y.charCodeAt(C); t()[v >>> 0] = 0, f += y.length + 1; }), 0; } function Ti2(s, c) { if (b) return xe(19, 1, s, c); s >>>= 0, c >>>= 0; var f = Ii3(); a()[s >>> 2 >>> 0] = f.length; var y = 0; return f.forEach((v) => y += v.length + 1), a()[c >>> 2 >>> 0] = y, 0; } function Ai3(s) { return b ? xe(20, 1, s) : 52; } function Ei3(s, c, f, y) { return b ? xe(21, 1, s, c, f, y) : 52; } function ki2(s, c, f, y) { return b ? xe(22, 1, s, c, f, y) : 70; } var ep3 = [null, [], []]; function Pi2(s, c, f, y) { if (b) return xe(23, 1, s, c, f, y); c >>>= 0, f >>>= 0, y >>>= 0; for (var v = 0, C = 0; C < f; C++) { var O2 = a()[c >>> 2 >>> 0], B3 = a()[c + 4 >>> 2 >>> 0]; c += 8; for (var N2 = 0; N2 < B3; N2++) { var L = r()[O2 + N2 >>> 0], j3 = ep3[s]; L === 0 || L === 10 ? ((s === 1 ? X : Y3)(qo(j3, 0)), j3.length = 0) : j3.push(L); } v += B3; } return a()[y >>> 2 >>> 0] = v, 0; } var Oi2 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Di2 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], tp3 = (s, c) => { t().set(s, c >>> 0); }; function zi3(s, c, f, y) { function v(P2, ee3, ye2) { for (P2 = typeof P2 == "number" ? P2.toString() : P2 || ""; P2.length < ee3; ) P2 = ye2[0] + P2; return P2; } function C(P2, ee3) { return v(P2, ee3, "0"); } function O2(P2, ee3) { function ye2(Ki3) { return 0 > Ki3 ? -1 : 0 < Ki3 ? 1 : 0; } var vt3; return (vt3 = ye2(P2.getFullYear() - ee3.getFullYear())) === 0 && (vt3 = ye2(P2.getMonth() - ee3.getMonth())) === 0 && (vt3 = ye2(P2.getDate() - ee3.getDate())), vt3; } function B3(P2) { switch (P2.getDay()) { case 0: return new Date(P2.getFullYear() - 1, 11, 29); case 1: return P2; case 2: return new Date(P2.getFullYear(), 0, 3); case 3: return new Date(P2.getFullYear(), 0, 2); case 4: return new Date(P2.getFullYear(), 0, 1); case 5: return new Date(P2.getFullYear() - 1, 11, 31); case 6: return new Date(P2.getFullYear() - 1, 11, 30); } } function N2(P2) { var ee3 = P2.Bb; for (P2 = new Date(new Date(P2.Cb + 1900, 0, 1).getTime()); 0 < ee3; ) { var ye2 = P2.getMonth(), vt3 = (Bt2(P2.getFullYear()) ? Oi2 : Di2)[ye2]; if (!(ee3 > vt3 - P2.getDate())) { P2.setDate(P2.getDate() + ee3); break; } ee3 -= vt3 - P2.getDate() + 1, P2.setDate(1), 11 > ye2 ? P2.setMonth(ye2 + 1) : (P2.setMonth(0), P2.setFullYear(P2.getFullYear() + 1)); } return ye2 = new Date(P2.getFullYear() + 1, 0, 4), ee3 = B3(new Date(P2.getFullYear(), 0, 4)), ye2 = B3(ye2), 0 >= O2(ee3, P2) ? 0 >= O2(ye2, P2) ? P2.getFullYear() + 1 : P2.getFullYear() : P2.getFullYear() - 1; } s >>>= 0, c >>>= 0, f >>>= 0, y >>>= 0; var L = a()[y + 40 >>> 2 >>> 0]; for (var j3 in y = { fc: i()[y >>> 2 >>> 0], ec: i()[y + 4 >>> 2 >>> 0], Gb: i()[y + 8 >>> 2 >>> 0], Kb: i()[y + 12 >>> 2 >>> 0], Hb: i()[y + 16 >>> 2 >>> 0], Cb: i()[y + 20 >>> 2 >>> 0], ub: i()[y + 24 >>> 2 >>> 0], Bb: i()[y + 28 >>> 2 >>> 0], nc: i()[y + 32 >>> 2 >>> 0], dc: i()[y + 36 >>> 2 >>> 0], hc: L ? Ae3(L) : "" }, f = Ae3(f), L = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) f = f.replace(new RegExp(j3, "g"), L[j3]); var me3 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), he3 = "January February March April May June July August September October November December".split(" "); for (j3 in L = { "%a": (P2) => me3[P2.ub].substring(0, 3), "%A": (P2) => me3[P2.ub], "%b": (P2) => he3[P2.Hb].substring(0, 3), "%B": (P2) => he3[P2.Hb], "%C": (P2) => C((P2.Cb + 1900) / 100 | 0, 2), "%d": (P2) => C(P2.Kb, 2), "%e": (P2) => v(P2.Kb, 2, " "), "%g": (P2) => N2(P2).toString().substring(2), "%G": N2, "%H": (P2) => C(P2.Gb, 2), "%I": (P2) => ((P2 = P2.Gb) == 0 ? P2 = 12 : 12 < P2 && (P2 -= 12), C(P2, 2)), "%j": (P2) => { for (var ee3 = 0, ye2 = 0; ye2 <= P2.Hb - 1; ee3 += (Bt2(P2.Cb + 1900) ? Oi2 : Di2)[ye2++]) ; return C(P2.Kb + ee3, 3); }, "%m": (P2) => C(P2.Hb + 1, 2), "%M": (P2) => C(P2.ec, 2), "%n": () => ` `, "%p": (P2) => 0 <= P2.Gb && 12 > P2.Gb ? "AM" : "PM", "%S": (P2) => C(P2.fc, 2), "%t": () => " ", "%u": (P2) => P2.ub || 7, "%U": (P2) => C(Math.floor((P2.Bb + 7 - P2.ub) / 7), 2), "%V": (P2) => { var ee3 = Math.floor((P2.Bb + 7 - (P2.ub + 6) % 7) / 7); if (2 >= (P2.ub + 371 - P2.Bb - 2) % 7 && ee3++, ee3) ee3 == 53 && ((ye2 = (P2.ub + 371 - P2.Bb) % 7) == 4 || ye2 == 3 && Bt2(P2.Cb) || (ee3 = 1)); else { ee3 = 52; var ye2 = (P2.ub + 7 - P2.Bb - 1) % 7; (ye2 == 4 || ye2 == 5 && Bt2(P2.Cb % 400 - 1)) && ee3++; } return C(ee3, 2); }, "%w": (P2) => P2.ub, "%W": (P2) => C(Math.floor((P2.Bb + 7 - (P2.ub + 6) % 7) / 7), 2), "%y": (P2) => (P2.Cb + 1900).toString().substring(2), "%Y": (P2) => P2.Cb + 1900, "%z": (P2) => { var ee3 = 0 <= (P2 = P2.dc); return P2 = Math.abs(P2) / 60, (ee3 ? "+" : "-") + ("0000" + (P2 / 60 * 100 + P2 % 60)).slice(-4); }, "%Z": (P2) => P2.hc, "%%": () => "%" }, f = f.replace(/%%/g, "\0\0"), L) f.includes(j3) && (f = f.replace(new RegExp(j3, "g"), L[j3](y))); return j3 = (function(P2) { var ee3 = Array(wn2(P2) + 1); return Yo2(P2, ee3, 0, ee3.length), ee3; })(f = f.replace(/\0\0/g, "%")), j3.length > c ? 0 : (tp3(j3, s), j3.length - 1); } function rp3(s, c, f, y) { return zi3(s >>> 0, c >>> 0, f >>> 0, y >>> 0); } b || (function() { for (var s = u.numThreads - 1; s--; ) Ho2(); Lt3.unshift(() => { Fe3++, (function(c) { b ? c() : Promise.all(ct2.map(Wo)).then(c); })(() => ko3()); }); })(); for (var Bi3 = Array(256), mr3 = 0; 256 > mr3; ++mr3) Bi3[mr3] = String.fromCharCode(mr3); si2 = Bi3, pt2 = u.BindingError = class extends Error { constructor(s) { super(s), this.name = "BindingError"; } }, u.InternalError = class extends Error { constructor(s) { super(s), this.name = "InternalError"; } }, ut2.push(0, 1, void 0, 1, null, 1, true, 1, false, 1), u.count_emval_handles = () => ut2.length / 2 - 5 - _n3.length; var np3 = [yn3, Mo, Go2, jo, Ko, Xo, Zo2, Qo2, Jo, ei3, ti, ri, ni3, oi2, ii3, ai2, vi2, $i3, Ci3, Ti2, Ai3, Ei3, ki2, Pi2], q3 = (function() { function s(f, y) { return q3 = f.exports, q3 = (function() { var v = q3, C = {}; for (let [O2, B3] of Object.entries(v)) C[O2] = typeof B3 == "function" ? (...N2) => { dr3.push(O2); try { return B3(...N2); } finally { Se2 || (dr3.pop(), Je2 && ft2 === 1 && dr3.length === 0 && (ft2 = 0, bt3 += 1, ur3(Li2), typeof Fibers < "u" && Fibers.oc())); } } : B3; return C; })(), q3 = (function() { var v = q3, C = (B3) => (N2) => B3(N2) >>> 0, O2 = (B3) => () => B3() >>> 0; return (v = Object.assign({}, v)).Ca = C(v.Ca), v.fb = O2(v.fb), v.gb = C(v.gb), v.emscripten_main_runtime_thread_id = O2(v.emscripten_main_runtime_thread_id), v.sb = C(v.sb), v.tb = O2(v.tb), v; })(), Uo3.push(q3.ib), Pe3.unshift(q3.Ba), K = y, ko3(), q3; } var c = Bo3(); if (Fe3++, u.instantiateWasm) try { return u.instantiateWasm(c, s); } catch (f) { Y3(`Module.instantiateWasm callback failed with error: ${f}`), m2(f); } return mn3 ||= u.locateFile ? Po2("ort-wasm-simd-threaded.jsep.wasm") ? "ort-wasm-simd-threaded.jsep.wasm" : u.locateFile ? u.locateFile("ort-wasm-simd-threaded.jsep.wasm", D3) : D3 + "ort-wasm-simd-threaded.jsep.wasm" : new URL("ort-wasm-simd-threaded.jsep.wasm", import.meta.url).href, (function(f, y) { var v = mn3; return z3 || typeof WebAssembly.instantiateStreaming != "function" || Po2(v) || Oo2(v) || typeof fetch != "function" ? zo2(v, f, y) : fetch(v, { credentials: "same-origin" }).then((C) => WebAssembly.instantiateStreaming(C, f).then(y, function(O2) { return Y3(`wasm streaming compile failed: ${O2}`), Y3("falling back to ArrayBuffer instantiation"), zo2(v, f, y); })); })(c, function(f) { s(f.instance, f.module); }).catch(m2), {}; })(), Ri3 = (s) => (Ri3 = q3.Ca)(s), Mi3 = () => (Mi3 = q3.Da)(); u._OrtInit = (s, c) => (u._OrtInit = q3.Ea)(s, c), u._OrtGetLastError = (s, c) => (u._OrtGetLastError = q3.Fa)(s, c), u._OrtCreateSessionOptions = (s, c, f, y, v, C, O2, B3, N2, L) => (u._OrtCreateSessionOptions = q3.Ga)(s, c, f, y, v, C, O2, B3, N2, L), u._OrtAppendExecutionProvider = (s, c) => (u._OrtAppendExecutionProvider = q3.Ha)(s, c), u._OrtAddFreeDimensionOverride = (s, c, f) => (u._OrtAddFreeDimensionOverride = q3.Ia)(s, c, f), u._OrtAddSessionConfigEntry = (s, c, f) => (u._OrtAddSessionConfigEntry = q3.Ja)(s, c, f), u._OrtReleaseSessionOptions = (s) => (u._OrtReleaseSessionOptions = q3.Ka)(s), u._OrtCreateSession = (s, c, f) => (u._OrtCreateSession = q3.La)(s, c, f), u._OrtReleaseSession = (s) => (u._OrtReleaseSession = q3.Ma)(s), u._OrtGetInputOutputCount = (s, c, f) => (u._OrtGetInputOutputCount = q3.Na)(s, c, f), u._OrtGetInputName = (s, c) => (u._OrtGetInputName = q3.Oa)(s, c), u._OrtGetOutputName = (s, c) => (u._OrtGetOutputName = q3.Pa)(s, c), u._OrtFree = (s) => (u._OrtFree = q3.Qa)(s), u._OrtCreateTensor = (s, c, f, y, v, C) => (u._OrtCreateTensor = q3.Ra)(s, c, f, y, v, C), u._OrtGetTensorData = (s, c, f, y, v) => (u._OrtGetTensorData = q3.Sa)(s, c, f, y, v), u._OrtReleaseTensor = (s) => (u._OrtReleaseTensor = q3.Ta)(s), u._OrtCreateRunOptions = (s, c, f, y) => (u._OrtCreateRunOptions = q3.Ua)(s, c, f, y), u._OrtAddRunConfigEntry = (s, c, f) => (u._OrtAddRunConfigEntry = q3.Va)(s, c, f), u._OrtReleaseRunOptions = (s) => (u._OrtReleaseRunOptions = q3.Wa)(s), u._OrtCreateBinding = (s) => (u._OrtCreateBinding = q3.Xa)(s), u._OrtBindInput = (s, c, f) => (u._OrtBindInput = q3.Ya)(s, c, f), u._OrtBindOutput = (s, c, f, y) => (u._OrtBindOutput = q3.Za)(s, c, f, y), u._OrtClearBoundOutputs = (s) => (u._OrtClearBoundOutputs = q3._a)(s), u._OrtReleaseBinding = (s) => (u._OrtReleaseBinding = q3.$a)(s), u._OrtRunWithBinding = (s, c, f, y, v) => (u._OrtRunWithBinding = q3.ab)(s, c, f, y, v), u._OrtRun = (s, c, f, y, v, C, O2, B3) => (u._OrtRun = q3.bb)(s, c, f, y, v, C, O2, B3), u._OrtEndProfiling = (s) => (u._OrtEndProfiling = q3.cb)(s), u._JsepOutput = (s, c, f) => (u._JsepOutput = q3.db)(s, c, f), u._JsepGetNodeName = (s) => (u._JsepGetNodeName = q3.eb)(s); var fr3, Mt2 = () => (Mt2 = q3.fb)(), hr3 = u._malloc = (s) => (hr3 = u._malloc = q3.gb)(s), et2 = u._free = (s) => (et2 = u._free = q3.hb)(s), On3 = (s, c, f, y, v, C) => (On3 = q3.kb)(s, c, f, y, v, C), Ui3 = () => (Ui3 = q3.lb)(), Vi3 = (s, c, f, y, v) => (Vi3 = q3.mb)(s, c, f, y, v), Dn3 = (s) => (Dn3 = q3.nb)(s), gr2 = (s) => (gr2 = q3.ob)(s), Ni3 = () => (Ni3 = q3.pb)(), Wi3 = (s, c) => (Wi3 = q3.qb)(s, c), yr3 = (s) => (yr3 = q3.rb)(s), zn3 = (s) => (zn3 = q3.sb)(s), Bn3 = () => (Bn3 = q3.tb)(), Hi3 = u.dynCall_ii = (s, c) => (Hi3 = u.dynCall_ii = q3.vb)(s, c), Gi3 = (s) => (Gi3 = q3.wb)(s), Li2 = () => (Li2 = q3.xb)(), Fi2 = (s) => (Fi2 = q3.yb)(s), qi3 = () => (qi3 = q3.zb)(); function ji3() { 0 < Fe3 || (b ? (p(u), b || ar2(Pe3), startWorker(u)) : (ar2(Lt3), 0 < Fe3 || fr3 || (fr3 = true, u.calledRun = true, Se2 || (b || ar2(Pe3), p(u), b || ar2(ze3))))); } return u.___start_em_js = 862621, u.___stop_em_js = 862843, u.stackSave = () => Bn3(), u.stackRestore = (s) => yr3(s), u.stackAlloc = (s) => zn3(s), u.UTF8ToString = Ae3, u.stringToUTF8 = zt2, u.lengthBytesUTF8 = wn2, yt3 = function s() { fr3 || ji3(), fr3 || (yt3 = s); }, ji3(), h; }), mp2 = Aa; globalThis.self?.name === "em-pthread" && Aa(); }); jt2 = U(() => { "use strict"; Tr2(); Ut2 = false ? void 0 : import.meta.url ?? (typeof document < "u" ? document.currentScript?.src : typeof self < "u" ? self.location?.href : void 0), fp2 = typeof location > "u" ? void 0 : location.origin, hp2 = (e, t) => { try { let r = t ?? Ut2; return (r ? new URL(e, r) : new URL(e)).origin === fp2; } catch { return false; } }, gp2 = async (e) => { let r = await (await fetch(e, { credentials: "same-origin" })).blob(); return URL.createObjectURL(r); }, Pa = (Ta(), br2(Ca)).default, Oa = async () => { if (!Ut2) throw new Error("Failed to load proxy worker: cannot determine the script source URL."); if (hp2(Ut2)) return [void 0, Pa()]; let e = await gp2(Ut2); return [e, Pa(e)]; }, yp2 = (ka(), br2(Ea)).default, Da = async (e, t, r) => [void 0, yp2]; }); St = U(() => { "use strict"; jt2(); Fn2 = false, Rr2 = false, za = false, bp2 = () => { if (typeof SharedArrayBuffer > "u") return false; try { return typeof MessageChannel < "u" && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11])); } catch { return false; } }, wp2 = () => { try { return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11])); } catch { return false; } }, Ar2 = async (e) => { if (Fn2) return Promise.resolve(); if (Rr2) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); if (za) throw new Error("previous call to 'initializeWebAssembly()' failed."); Rr2 = true; let t = e.initTimeout, r = e.numThreads; if (!wp2()) throw new Error("WebAssembly SIMD is not supported in the current environment."); let n = bp2(); r > 1 && !n && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + r + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."), console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."), e.numThreads = r = 1); let o = e.wasmPaths, i = typeof o == "string" ? o : void 0, a = o?.mjs, l = a?.href ?? a, d = o?.wasm, p = d?.href ?? d, m2 = e.wasmBinary, [u, h] = await Da(l, i, r > 1), w = false, g = []; if (t > 0 && g.push(new Promise((b) => { setTimeout(() => { w = true, b(); }, t); })), g.push(new Promise((b, x2) => { let _ = { numThreads: r }; m2 ? _.wasmBinary = m2 : (p || i) && (_.locateFile = ($2, S) => p ?? (i ?? S) + $2), h(_).then(($2) => { Rr2 = false, Fn2 = true, Ln2 = $2, b(), u && URL.revokeObjectURL(u); }, ($2) => { Rr2 = false, za = true, x2($2); }); })), await Promise.race(g), w) throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`); }, Ie2 = () => { if (Fn2 && Ln2) return Ln2; throw new Error("WebAssembly is not initialized yet."); }; }); Mr2 = U(() => { "use strict"; St(); Te = (e, t) => { let r = Ie2(), n = r.lengthBytesUTF8(e) + 1, o = r._malloc(n); return r.stringToUTF8(e, o, n), t.push(o), o; }, Yt2 = (e, t, r, n) => { if (typeof e == "object" && e !== null) { if (r.has(e)) throw new Error("Circular reference in options"); r.add(e); } Object.entries(e).forEach(([o, i]) => { let a = t ? t + o : o; if (typeof i == "object") Yt2(i, a + ".", r, n); else if (typeof i == "string" || typeof i == "number") n(a, i.toString()); else if (typeof i == "boolean") n(a, i ? "1" : "0"); else throw new Error(`Can't handle extra config type: ${typeof i}`); }); }, _e = (e) => { let t = Ie2(), r = t.stackSave(); try { let n = t.stackAlloc(8); t._OrtGetLastError(n, n + 4); let o = t.HEAP32[n / 4], i = t.HEAPU32[n / 4 + 1], a = i ? t.UTF8ToString(i) : ""; throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`); } finally { t.stackRestore(r); } }; }); Ra = U(() => { "use strict"; St(); Mr2(); Ba = (e) => { let t = Ie2(), r = 0, n = [], o = e || {}; try { if (e?.logSeverityLevel === void 0) o.logSeverityLevel = 2; else if (typeof e.logSeverityLevel != "number" || !Number.isInteger(e.logSeverityLevel) || e.logSeverityLevel < 0 || e.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`); if (e?.logVerbosityLevel === void 0) o.logVerbosityLevel = 0; else if (typeof e.logVerbosityLevel != "number" || !Number.isInteger(e.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`); e?.terminate === void 0 && (o.terminate = false); let i = 0; return e?.tag !== void 0 && (i = Te(e.tag, n)), r = t._OrtCreateRunOptions(o.logSeverityLevel, o.logVerbosityLevel, !!o.terminate, i), r === 0 && _e("Can't create run options."), e?.extra !== void 0 && Yt2(e.extra, "", /* @__PURE__ */ new WeakSet(), (a, l) => { let d = Te(a, n), p = Te(l, n); t._OrtAddRunConfigEntry(r, d, p) !== 0 && _e(`Can't set a run config entry: ${a} - ${l}.`); }), [r, n]; } catch (i) { throw r !== 0 && t._OrtReleaseRunOptions(r), n.forEach((a) => t._free(a)), i; } }; }); Ua = U(() => { "use strict"; St(); Mr2(); vp2 = (e) => { switch (e) { case "disabled": return 0; case "basic": return 1; case "extended": return 2; case "all": return 99; default: throw new Error(`unsupported graph optimization level: ${e}`); } }, $p2 = (e) => { switch (e) { case "sequential": return 0; case "parallel": return 1; default: throw new Error(`unsupported execution mode: ${e}`); } }, _p2 = (e) => { e.extra || (e.extra = {}), e.extra.session || (e.extra.session = {}); let t = e.extra.session; t.use_ort_model_bytes_directly || (t.use_ort_model_bytes_directly = "1"), e.executionProviders && e.executionProviders.some((r) => (typeof r == "string" ? r : r.name) === "webgpu") && (e.enableMemPattern = false); }, xp2 = (e, t, r) => { for (let n of t) { let o = typeof n == "string" ? n : n.name; switch (o) { case "webnn": if (o = "WEBNN", typeof n != "string") { let l = n?.deviceType; if (l) { let d = Te("deviceType", r), p = Te(l, r); Ie2()._OrtAddSessionConfigEntry(e, d, p) !== 0 && _e(`Can't set a session config entry: 'deviceType' - ${l}.`); } } break; case "webgpu": if (o = "JS", typeof n != "string") { let a = n; if (a?.preferredLayout) { if (a.preferredLayout !== "NCHW" && a.preferredLayout !== "NHWC") throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`); let l = Te("preferredLayout", r), d = Te(a.preferredLayout, r); Ie2()._OrtAddSessionConfigEntry(e, l, d) !== 0 && _e(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`); } } break; case "wasm": case "cpu": continue; default: throw new Error(`not supported execution provider: ${o}`); } let i = Te(o, r); Ie2()._OrtAppendExecutionProvider(e, i) !== 0 && _e(`Can't append execution provider: ${o}.`); } }, Ma = (e) => { let t = Ie2(), r = 0, n = [], o = e || {}; _p2(o); try { let i = vp2(o.graphOptimizationLevel ?? "all"), a = $p2(o.executionMode ?? "sequential"), l = typeof o.logId == "string" ? Te(o.logId, n) : 0, d = o.logSeverityLevel ?? 2; if (!Number.isInteger(d) || d < 0 || d > 4) throw new Error(`log serverity level is not valid: ${d}`); let p = o.logVerbosityLevel ?? 0; if (!Number.isInteger(p) || p < 0 || p > 4) throw new Error(`log verbosity level is not valid: ${p}`); let m2 = typeof o.optimizedModelFilePath == "string" ? Te(o.optimizedModelFilePath, n) : 0; if (r = t._OrtCreateSessionOptions(i, !!o.enableCpuMemArena, !!o.enableMemPattern, a, !!o.enableProfiling, 0, l, d, p, m2), r === 0 && _e("Can't create session options."), o.executionProviders && xp2(r, o.executionProviders, n), o.enableGraphCapture !== void 0) { if (typeof o.enableGraphCapture != "boolean") throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`); let u = Te("enableGraphCapture", n), h = Te(o.enableGraphCapture.toString(), n); t._OrtAddSessionConfigEntry(r, u, h) !== 0 && _e(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`); } if (o.freeDimensionOverrides) for (let [u, h] of Object.entries(o.freeDimensionOverrides)) { if (typeof u != "string") throw new Error(`free dimension override name must be a string: ${u}`); if (typeof h != "number" || !Number.isInteger(h) || h < 0) throw new Error(`free dimension override value must be a non-negative integer: ${h}`); let w = Te(u, n); t._OrtAddFreeDimensionOverride(r, w, h) !== 0 && _e(`Can't set a free dimension override: ${u} - ${h}.`); } return o.extra !== void 0 && Yt2(o.extra, "", /* @__PURE__ */ new WeakSet(), (u, h) => { let w = Te(u, n), g = Te(h, n); t._OrtAddSessionConfigEntry(r, w, g) !== 0 && _e(`Can't set a session config entry: ${u} - ${h}.`); }), [r, n]; } catch (i) { throw r !== 0 && t._OrtReleaseSessionOptions(r), n.forEach((a) => t._free(a)), i; } }; }); Q = U(() => { "use strict"; qn2 = (e) => { switch (e) { case "int8": return 3; case "uint8": return 2; case "bool": return 9; case "int16": return 5; case "uint16": return 4; case "int32": return 6; case "uint32": return 12; case "float16": return 10; case "float32": return 1; case "float64": return 11; case "string": return 8; case "int64": return 7; case "uint64": return 13; default: throw new Error(`unsupported data type: ${e}`); } }, ht2 = (e) => { switch (e) { case 3: return "int8"; case 2: return "uint8"; case 9: return "bool"; case 5: return "int16"; case 4: return "uint16"; case 6: return "int32"; case 12: return "uint32"; case 10: return "float16"; case 1: return "float32"; case 11: return "float64"; case 8: return "string"; case 7: return "int64"; case 13: return "uint64"; default: throw new Error(`unsupported data type: ${e}`); } }, It = (e) => [void 0, 4, 1, 1, 2, 2, 4, 8, void 0, 1, 2, 8, 4, 8, void 0, void 0, void 0][e], Ur2 = (e) => { switch (e) { case "float16": return typeof Float16Array < "u" && Float16Array.from ? Float16Array : Uint16Array; case "float32": return Float32Array; case "uint8": return Uint8Array; case "int8": return Int8Array; case "uint16": return Uint16Array; case "int16": return Int16Array; case "int32": return Int32Array; case "bool": return Uint8Array; case "float64": return Float64Array; case "uint32": return Uint32Array; case "int64": return BigInt64Array; case "uint64": return BigUint64Array; default: throw new Error(`unsupported type: ${e}`); } }, Xt2 = (e) => { switch (e) { case "verbose": return 0; case "info": return 1; case "warning": return 2; case "error": return 3; case "fatal": return 4; default: throw new Error(`unsupported logging level: ${e}`); } }, Vr2 = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint8" || e === "bool", jn2 = (e) => { switch (e) { case "none": return 0; case "cpu": return 1; case "cpu-pinned": return 2; case "texture": return 3; case "gpu-buffer": return 4; default: throw new Error(`unsupported data location: ${e}`); } }; }); Kn2 = U(() => { "use strict"; Tr2(); Zt = async (e) => { if (typeof e == "string") if (false) try { let { readFile: t } = Mn2("node:fs/promises"); return new Uint8Array(await t(e)); } catch (t) { if (t.code === "ERR_FS_FILE_TOO_LARGE") { let { createReadStream: r } = Mn2("node:fs"), n = r(e), o = []; for await (let i of n) o.push(i); return new Uint8Array(Buffer.concat(o)); } throw t; } else { let t = await fetch(e); if (!t.ok) throw new Error(`failed to load external data file: ${e}`); let r = t.headers.get("Content-Length"), n = r ? parseInt(r, 10) : 0; if (n < 1073741824) return new Uint8Array(await t.arrayBuffer()); { if (!t.body) throw new Error(`failed to load external data file: ${e}, no response body.`); let o = t.body.getReader(), i; try { i = new ArrayBuffer(n); } catch (l) { if (l instanceof RangeError) { let d = Math.ceil(n / 65536); i = new WebAssembly.Memory({ initial: d, maximum: d }).buffer; } else throw l; } let a = 0; for (; ; ) { let { done: l, value: d } = await o.read(); if (l) break; let p = d.byteLength; new Uint8Array(i, a, p).set(d), a += p; } return new Uint8Array(i, 0, n); } } else return e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : e instanceof Uint8Array ? e : new Uint8Array(e); }; }); dt2 = U(() => { "use strict"; Q(); Sp2 = ["V", "I", "W", "E", "F"], Ip2 = (e, t) => { console.log(`[${Sp2[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`); }, Wa = (e, t) => { Va = e, Na = t; }, Cp2 = (e, t) => { let r = Xt2(e), n = Xt2(Va); r >= n && Ip2(r, typeof t == "function" ? t() : t); }, ve = (...e) => { Na && Cp2(...e); }; }); Ga = U(() => { "use strict"; Q(); Ha = (e, t) => new (Ur2(t))(e); }); Nr2 = U(() => { "use strict"; }); Ka = U(() => { "use strict"; dt2(); Nr2(); La = /* @__PURE__ */ new Map([[64, 250], [128, 200], [256, 200], [512, 200], [2048, 230], [4096, 200], [8192, 50], [16384, 50], [32768, 50], [65536, 50], [131072, 50], [262144, 50], [524288, 50], [1048576, 50], [2097152, 30], [4194304, 20], [8388608, 10], [12582912, 10], [16777216, 10], [26214400, 15], [33554432, 22], [44236800, 2], [58982400, 6], [67108864, 6], [134217728, 6], [167772160, 6]]), Yn2 = [], Xn2 = (e) => Math.ceil(e / 16) * 16, Tp2 = (e) => { for (let t = 0; t < Yn2.length; t++) { let r = Yn2[t]; if (e <= r) return r; } return Math.ceil(e / 16) * 16; }, Ap2 = 1, Fa = () => Ap2++, Qn2 = async (e, t, r, n) => { let o = Xn2(r), i = e.device.createBuffer({ size: o, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); try { let a = e.getCommandEncoder(); e.endComputePass(), a.copyBufferToBuffer(t, 0, i, 0, o), e.flush(), await i.mapAsync(GPUMapMode.READ); let l = i.getMappedRange(); if (n) { let d = n(); return d.set(new Uint8Array(l, 0, r)), d; } else return new Uint8Array(l.slice(0, r)); } finally { i.destroy(); } }, Zn2 = class { constructor(t) { this.backend = t; this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.buffersForUploadingPending = [], this.buffersPending = [], this.externalBuffers = /* @__PURE__ */ new Map(), this.capturedPendingBuffers = /* @__PURE__ */ new Map(); for (let [r] of La) Yn2.push(r), this.freeBuffers.set(r, []), this.freeUniformBuffers.set(r, []); } upload(t, r) { let n = r.buffer, o = r.byteOffset, i = r.byteLength, a = Xn2(i), l = this.storageCache.get(t); if (!l) throw new Error("gpu data for uploading does not exist"); if (l.originalSize !== i) throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`); let d = this.backend.device.createBuffer({ mappedAtCreation: true, size: a, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC }), p = d.getMappedRange(); new Uint8Array(p).set(new Uint8Array(n, o, i)), d.unmap(); let m2 = this.backend.getCommandEncoder(); this.backend.endComputePass(), m2.copyBufferToBuffer(d, 0, l.gpuData.buffer, 0, a), ve("verbose", () => `[WebGPU] GpuDataManager.upload(id=${t})`), this.buffersForUploadingPending.push(d); } memcpy(t, r) { let n = this.storageCache.get(t); if (!n) throw new Error("source gpu data for memcpy does not exist"); let o = this.storageCache.get(r); if (!o) throw new Error("destination gpu data for memcpy does not exist"); if (n.originalSize !== o.originalSize) throw new Error("inconsistent source and destination gpu data size"); let i = Xn2(n.originalSize), a = this.backend.getCommandEncoder(); this.backend.endComputePass(), a.copyBufferToBuffer(n.gpuData.buffer, 0, o.gpuData.buffer, 0, i); } registerExternalBuffer(t, r, n) { let o; if (n) { if (o = this.externalBuffers.get(n), o === void 0) throw new Error("previous buffer is not registered"); if (t === n) return ve("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`), o; if (this.backend.capturedCommandList.has(this.backend.currentSessionId)) throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`); this.externalBuffers.delete(n); } else o = Fa(); return this.storageCache.set(o, { gpuData: { id: o, type: 0, buffer: t }, originalSize: r }), this.externalBuffers.set(t, o), ve("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`), o; } unregisterExternalBuffer(t) { let r = this.externalBuffers.get(t); r !== void 0 && (this.storageCache.delete(r), this.externalBuffers.delete(t), ve("verbose", () => `[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`)); } create(t, r = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) { let n = Tp2(t), o, i = (r & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE, a = (r & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM; if (i || a) { let p = (i ? this.freeBuffers : this.freeUniformBuffers).get(n); p ? p.length > 0 ? o = p.pop() : o = this.backend.device.createBuffer({ size: n, usage: r }) : o = this.backend.device.createBuffer({ size: n, usage: r }); } else o = this.backend.device.createBuffer({ size: n, usage: r }); let l = { id: Fa(), type: 0, buffer: o }; return this.storageCache.set(l.id, { gpuData: l, originalSize: t }), ve("verbose", () => `[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`), l; } get(t) { return this.storageCache.get(t)?.gpuData; } release(t) { let r = this.storageCache.get(t); if (!r) throw new Error("releasing data does not exist"); return ve("verbose", () => `[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`), this.storageCache.delete(t), this.buffersPending.push(r.gpuData.buffer), r.originalSize; } async download(t, r) { let n = this.storageCache.get(t); if (!n) throw new Error("data does not exist"); await Qn2(this.backend, n.gpuData.buffer, n.originalSize, r); } refreshPendingBuffers() { for (let t of this.buffersForUploadingPending) t.destroy(); if (this.buffersForUploadingPending = [], this.buffersPending.length !== 0) if (this.backend.sessionStatus === "default") { for (let t of this.buffersPending) { let r = La.get(t.size); if ((t.usage & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE) { let n = this.freeBuffers.get(t.size) || []; r === void 0 || n.length >= r ? t.destroy() : n.push(t); } else if ((t.usage & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM) { let n = this.freeUniformBuffers.get(t.size) || []; r === void 0 || n.length >= r ? t.destroy() : n.push(t); } else t.destroy(); } this.buffersPending = []; } else { let t = this.capturedPendingBuffers.get(this.backend.currentSessionId); t || (t = [], this.capturedPendingBuffers.set(this.backend.currentSessionId, t)); for (let r of this.buffersPending) t.push(r); this.buffersPending = []; } } dispose() { this.freeBuffers.forEach((t) => { t.forEach((r) => { r.destroy(); }); }), this.freeUniformBuffers.forEach((t) => { t.forEach((r) => { r.destroy(); }); }), this.storageCache.forEach((t) => { t.gpuData.buffer.destroy(); }), this.capturedPendingBuffers.forEach((t) => { t.forEach((r) => { r.destroy(); }); }), this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.capturedPendingBuffers = /* @__PURE__ */ new Map(); } onReleaseSession(t) { let r = this.capturedPendingBuffers.get(t); r && (r.forEach((n) => { n.destroy(); }), this.capturedPendingBuffers.delete(t)); } }, ja = (...e) => new Zn2(...e); }); Ce2 = U(() => { "use strict"; Jn2 = class { constructor(t) { Object.assign(this, t); } get cacheKey() { return this.key || (this.key = Object.getOwnPropertyNames(this).sort().map((t) => `${this[t]}`).join(";")), this.key; } }, te = (e) => new Jn2(e); }); ae = U(() => { "use strict"; eo2 = class { static calcMatMulShape(t, r) { return t[1] !== r[0] ? void 0 : [t[0], r[1]]; } }, tt2 = class { static calcShape(t, r, n = false) { let o = t.length, i = r.length; if (o === 0) return r; if (i === 0) return t; let a = Math.max(t.length, r.length), l = new Array(a); if (n) { if (o < 2 || i < 2) return; let d = eo2.calcMatMulShape([t[o - 2], t[o - 1]], [r[i - 2], r[i - 1]]); if (d === void 0) return; [l[a - 2], l[a - 1]] = d; } for (let d = n ? 3 : 1; d <= a; d++) { let p = o - d < 0 ? 1 : t[o - d], m2 = i - d < 0 ? 1 : r[i - d]; if (p !== m2 && p > 1 && m2 > 1) return; let u = Math.max(p, m2); if (p && m2) l[a - d] = Math.max(p, m2); else { if (u > 1) return; l[a - d] = 0; } } return l; } static isValidBroadcast(t, r) { let n = t.length, o = r.length; if (n > o) return false; for (let i = 1; i <= n; i++) if (t[n - i] !== 1 && t[n - i] !== r[o - i]) return false; return true; } }, k2 = class e { static size(t) { return e.getSizeFromDimensionRange(t, 0, t.length); } static convertShape(t, r = 4) { let n = t.length; if (n === 0) return []; let o = new Array(n), i = n - 1; for (; i >= 0; ) { if (t[i] % r === 0) { o[i] = t[i] / r; break; } if (r % t[i] !== 0) throw new Error("cannot convert shape"); o[i] = 1, r /= t[i], i--; } for (i--; i >= 0; i--) o[i] = t[i]; return o; } static sizeFromDimension(t, r) { if (r < 0 || r > t.length) throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`); return e.getSizeFromDimensionRange(t, r, t.length); } static sizeToDimension(t, r) { if (r < 0 || r > t.length) throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`); return e.getSizeFromDimensionRange(t, 0, r); } static getSizeFromDimensionRange(t, r, n) { let o = 1; for (let i = r; i < n; i++) { if (t[i] < 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them."); o *= t[i]; } return o; } static computeStrides(t) { let r = t.length; if (r === 0) return []; if (r === 1) return [1]; let n = new Array(r); n[r - 1] = 1, n[r - 2] = t[r - 1]; for (let o = r - 3; o >= 0; --o) n[o] = n[o + 1] * t[o + 1]; return n; } static normalizeAxis(t, r) { if (t < -r && t >= r) throw new Error("unsupported axis for this operation."); return t < 0 ? t + r : t; } static normalizeAxes(t, r) { return t.map((n) => this.normalizeAxis(n, r ?? t.length)); } static sortBasedOnPerm(t, r) { return r ? r.map((n) => t[n]) : t.slice().reverse(); } static padShape(t, r) { let n = t.length; return t.map((o, i) => o + r[i] + r[i + n]); } static areEqual(t, r) { return t.length !== r.length ? false : t.every((n, o) => n === r[o]); } }, Ct = class e { static adjustPoolAttributes(t, r, n, o, i, a) { if (!t && n.length !== r.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); if (t) for (let l = 0; l < r.length - 2; l++) l >= n.length ? n.push(r[l + 2]) : n[l] = r[l + 2]; for (let l = 0; l < n.length; l++) if (l < o.length) { if (o[l] < 0) throw new Error("strides should be greater than or equal to 1"); } else o.push(1); for (let l = 0; l < n.length; l++) if (l < i.length) { if (i[l] < 0) throw new Error("dilations should be greater than or equal to 1"); } else i.push(1); for (let l = 0; l < n.length * 2; l++) if (l < a.length) { if (a[l] < 0) throw new Error("pad should be greater than or equal to 1"); } else a.push(0); for (let l = 0; l < n.length; l++) { if (n[l] <= 0) throw new Error("kernel shapes need to be greater than 0"); if (a[l] >= n[l] || a[l + n.length] >= n[l]) throw new Error("pads should be smaller than kernel"); } } static adjustPadsBasedOnAutoPad(t, r, n, o, i, a, l) { if (l) { if (i.length !== 2 * (t.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); if (r.length !== t.length - 2) throw new Error("length of strides should be the length of data dimensions"); if (o.length !== t.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions"); for (let d = 0; d < t.length - 2; d++) e.adjustPadAndReturnShape(t[d + (a ? 1 : 2)], r[d], n[d], o[d], i, d, d + t.length - 2, l); } } static computePoolOutputShape(t, r, n, o, i, a, l) { if (r.length <= 0) throw new Error("input shape must be of size greater than 0"); let d = [r[0], r[1]]; return e.computeShapeHelper(t, r, d, n, o, i, a, l), d; } static computeConvOutputShape(t, r, n, o, i, a, l) { if (t.length <= 0 || r.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); let d = [t[0], r[0]]; return e.computeShapeHelper(false, t, d, n, o, i, a, l), d; } static computeShapeHelper(t, r, n, o, i, a, l, d) { if (t) for (let p = 0; p < r.length - 2; p++) n.push(1); else for (let p = 0; p < r.length - 2; p++) n.push(e.adjustPadAndReturnShape(r[p + 2], o[p], i[p], a[p], l, p, p + r.length - 2, d)); } static adjustPadAndReturnShape(t, r, n, o, i, a, l, d) { let p = n * (o - 1) + 1; if (d && d !== "NOTSET") switch (d) { case "VALID": return i[a] = 0, i[l] = 0, Math.floor((t - p) / r + 1); case "SAME_LOWER": case "SAME_UPPER": if (n !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); { let u = ((t + r - 1) / r - 1) * r + o - t; return i[a] = Math.floor(d === "SAME_LOWER" ? (u + 1) / 2 : u / 2), i[l] = u - i[a], Math.floor((t + u - o) / r + 1); } default: throw new Error("Unsupported AutoPad type"); } else return Math.floor((t + i[a] + i[l] - p) / r + 1); } }, Wr2 = class { static getShapeOfGemmResult(t, r, n, o, i) { if (t.length !== 2 || n.length !== 2) throw new Error("shape need to be of size 2"); let a, l, d; r ? (a = t[1], l = t[0]) : (a = t[0], l = t[1]); let p = -1; if (o ? (d = n[0], p = 1) : (d = n[1], p = 0), n[p] !== l) throw new Error("dimension mismatch"); if (a <= 0 || d <= 0 || l <= 0) throw new Error("invalid shape specified"); if (i && !tt2.isValidBroadcast(i, [a, d])) throw new Error("gemm: invalid bias shape for broadcast"); return [a, d, l]; } }, Hr2 = -34028234663852886e22, Gr2 = 34028234663852886e22; }); ie = U(() => { "use strict"; Q(); ae(); Tt2 = 64, ro2 = (e, t) => { if (t === 3) throw new Error("vec3 has same alignment as vec4, use vec4 instead"); switch (e) { case 10: return t > 1 ? `vec${t}` : "f16"; case 1: return t > 1 ? `vec${t}` : "f32"; case 6: return t > 1 ? `vec${t}` : "i32"; case 12: return t > 1 ? `vec${t}` : "u32"; case 7: if (t > 1) throw new Error("currently not supported vecX of uint64 yet"); return ["vec2", "i32"]; case 13: if (t > 1) throw new Error("currently not supported vecX of uint64 yet"); return ["vec2", "u32"]; case 9: if (t !== 4) throw new Error("bool must be vec4"); return ["u32", "vec4"]; default: throw new Error(`Unknown data type: ${e}`); } }, ge = (e, t = 1) => { let r = ro2(e, t); return typeof r == "string" ? r : r[0]; }, Oe2 = (e, t = 1) => { let r = ro2(e, t); return typeof r == "string" ? r : r[1]; }, V = (...e) => { let t = []; return e.forEach((r) => { r.length !== 0 && t.push({ type: 12, data: r }, { type: 12, data: k2.computeStrides(r) }); }), t; }, $e2 = (e) => e % 4 === 0 ? 4 : e % 2 === 0 ? 2 : 1, gt2 = (e = "f32", t, r = "0") => !t || t === 1 ? `${e}(${r})` : `vec${t}<${e}>(${r})`, At = (e, t, r) => e === "f32" ? r : t === 1 ? `f32(${r})` : `vec${t}(${r})`, Xe2 = (e, t) => t === 4 ? `(${e}.x + ${e}.y + ${e}.z + ${e}.w)` : t === 2 ? `(${e}.x + ${e}.y)` : t === 3 ? `(${e}.x + ${e}.y + ${e}.z)` : e, G2 = (e, t, r, n) => e.startsWith("uniforms.") && r > 4 ? typeof t == "string" ? n === "f16" ? `${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]` : `${e}[(${t}) / 4][(${t}) % 4]` : n === "f16" ? `${e}[${Math.floor(t / 8)}][${Math.floor(t % 8 / 4)}][${t % 8 % 4}]` : `${e}[${Math.floor(t / 4)}][${t % 4}]` : r > 1 ? `${e}[${t}]` : e, no2 = (e, t, r, n, o) => { let i = typeof r == "number", a = i ? r : r.length, l = [...new Array(a).keys()], d = a < 2 ? "u32" : a <= 4 ? `vec${a}` : `array`, p = ro2(t, o), m2 = typeof p == "string" ? p : p[1], u = typeof p == "string" ? p : p[0], h = { indices: d, value: m2, storage: u, tensor: t }, w = (R) => typeof R == "string" ? R : `${R}u`, g = { offsetToIndices: false, indicesToOffset: false, broadcastedIndicesToOffset: false, set: false, setByIndices: false, get: false, getByIndices: false }, b = i ? "uniforms." : "", x2 = `${b}${e}_shape`, _ = `${b}${e}_strides`, $2 = ""; for (let R = 0; R < a - 1; R++) $2 += ` let dim${R} = current / ${G2(_, R, a)}; let rest${R} = current % ${G2(_, R, a)}; indices[${R}] = dim${R}; current = rest${R}; `; $2 += `indices[${a - 1}] = current;`; let S = a < 2 ? "" : ` fn o2i_${e}(offset: u32) -> ${h.indices} { var indices: ${h.indices}; var current = offset; ${$2} return indices; }`, I2 = (R) => (g.offsetToIndices = true, a < 2 ? R : `o2i_${e}(${R})`), T3 = []; if (a >= 2) for (let R = a - 1; R >= 0; R--) T3.push(`${G2(_, R, a)} * (indices[${R}])`); let A2 = a < 2 ? "" : ` fn i2o_${e}(indices: ${h.indices}) -> u32 { return ${T3.join("+")}; }`, D3 = (R) => (g.indicesToOffset = true, a < 2 ? R : `i2o_${e}(${R})`), z3 = (...R) => a === 0 ? "0u" : `${h.indices}(${R.map(w).join(",")})`, H3 = (R, F2) => a < 2 ? `${R}` : `${G2(R, F2, a)}`, W2 = (R, F2, ce3) => a < 2 ? `${R}=${ce3};` : `${G2(R, F2, a)}=${ce3};`, X = {}, Y3 = (R, F2) => { g.broadcastedIndicesToOffset = true; let ce3 = `${F2.name}broadcastedIndicesTo${e}Offset`; if (ce3 in X) return `${ce3}(${R})`; let Re2 = []; for (let Se2 = a - 1; Se2 >= 0; Se2--) { let we2 = F2.indicesGet("outputIndices", Se2 + F2.rank - a); Re2.push(`${H3(_, Se2)} * (${we2} % ${H3(x2, Se2)})`); } return X[ce3] = `fn ${ce3}(outputIndices: ${F2.type.indices}) -> u32 { return ${Re2.length > 0 ? Re2.join("+") : "0u"}; }`, `${ce3}(${R})`; }, pe2 = (R, F2) => (() => { if (h.storage === h.value) return `${e}[${R}]=${F2};`; if (h.storage === "vec2" && h.value === "i32") return `${e}[${R}]=vec2(u32(${F2}), select(0u, 0xFFFFFFFFu, ${F2} < 0));`; if (h.storage === "vec2" && h.value === "u32") return `${e}[${R}]=vec2(u32(${F2}), 0u);`; if (h.storage === "u32" && h.value === "vec4") return `${e}[${R}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F2}));`; throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`); })(), ue3 = (R) => (() => { if (h.storage === h.value) return `${e}[${R}]`; if (h.storage === "vec2" && h.value === "i32") return `i32(${e}[${R}].x)`; if (h.storage === "vec2" && h.value === "u32") return `u32(${e}[${R}].x)`; if (h.storage === "u32" && h.value === "vec4") return `vec4(bool(${e}[${R}] & 0xFFu), bool(${e}[${R}] & 0xFF00u), bool(${e}[${R}] & 0xFF0000u), bool(${e}[${R}] & 0xFF000000u))`; throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`); })(), le3 = a < 2 ? "" : ` fn get_${e}ByIndices(indices: ${h.indices}) -> ${m2} { return ${ue3(`i2o_${e}(indices)`)}; }`, K = a < 2 ? "" : (() => { let R = l.map((ce3) => `d${ce3}: u32`).join(", "), F2 = l.map((ce3) => `d${ce3}`).join(", "); return ` fn get_${e}(${R}) -> ${m2} { return get_${e}ByIndices(${z3(F2)}); }`; })(), de2 = (...R) => { if (R.length !== a) throw new Error(`indices length must be ${a}`); let F2 = R.map(w).join(","); return a === 0 ? ue3("0u") : a === 1 ? ue3(F2[0]) : (g.get = true, g.getByIndices = true, g.indicesToOffset = true, `get_${e}(${F2})`); }, re2 = (R) => a < 2 ? ue3(R) : (g.getByIndices = true, g.indicesToOffset = true, `get_${e}ByIndices(${R})`), se2 = a < 2 ? "" : ` fn set_${e}ByIndices(indices: ${h.indices}, value: ${m2}) { ${pe2(`i2o_${e}(indices)`, "value")} }`, Z2 = a < 2 ? "" : (() => { let R = l.map((ce3) => `d${ce3}: u32`).join(", "), F2 = l.map((ce3) => `d${ce3}`).join(", "); return ` fn set_${e}(${R}, value: ${m2}) { set_${e}ByIndices(${z3(F2)}, value); }`; })(); return { impl: () => { let R = [], F2 = false; return g.offsetToIndices && (R.push(S), F2 = true), g.indicesToOffset && (R.push(A2), F2 = true), g.broadcastedIndicesToOffset && (Object.values(X).forEach((ce3) => R.push(ce3)), F2 = true), g.set && (R.push(Z2), F2 = true), g.setByIndices && (R.push(se2), F2 = true), g.get && (R.push(K), F2 = true), g.getByIndices && (R.push(le3), F2 = true), !i && F2 && R.unshift(`const ${x2} = ${h.indices}(${r.join(",")});`, `const ${_} = ${h.indices}(${k2.computeStrides(r).join(",")});`), R.join(` `); }, type: h, offsetToIndices: I2, indicesToOffset: D3, broadcastedIndicesToOffset: Y3, indices: z3, indicesGet: H3, indicesSet: W2, set: (...R) => { if (R.length !== a + 1) throw new Error(`indices length must be ${a}`); let F2 = R[a]; if (typeof F2 != "string") throw new Error("value must be string"); let ce3 = R.slice(0, a).map(w).join(","); return a === 0 ? pe2("0u", F2) : a === 1 ? pe2(ce3[0], F2) : (g.set = true, g.setByIndices = true, g.indicesToOffset = true, `set_${e}(${ce3}, ${F2})`); }, setByOffset: pe2, setByIndices: (R, F2) => a < 2 ? pe2(R, F2) : (g.setByIndices = true, g.indicesToOffset = true, `set_${e}ByIndices(${R}, ${F2});`), get: de2, getByOffset: ue3, getByIndices: re2, usage: n, name: e, strides: _, shape: x2, rank: a }; }, E = (e, t, r, n = 1) => no2(e, t, r, "input", n), M = (e, t, r, n = 1) => no2(e, t, r, "output", n), Lr = (e, t, r, n = 1) => no2(e, t, r, "internal", n), to2 = class { constructor(t, r) { this.normalizedDispatchGroup = t; this.limits = r; this.internalVariables = []; this.variables = []; this.uniforms = []; this.variableIndex = 0; } guardAgainstOutOfBoundsWorkgroupSizes(t) { return `if (global_idx >= ${typeof t == "number" ? `${t}u` : t}) { return; }`; } mainStart(t = Tt2) { let r = typeof t == "number" ? t : t[0], n = typeof t == "number" ? 1 : t[1], o = typeof t == "number" ? 1 : t[2]; if (r > this.limits.maxComputeWorkgroupSizeX || n > this.limits.maxComputeWorkgroupSizeY || o > this.limits.maxComputeWorkgroupSizeZ) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`); if (r * n * o > this.limits.maxComputeInvocationsPerWorkgroup) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`); let i = this.normalizedDispatchGroup[1] === 1 && this.normalizedDispatchGroup[2] === 1, a = i ? `@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3` : `@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`, l = i ? "let global_idx = global_id.x; let local_idx = local_id.x;" : `let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r * n * o}u + local_idx;`; return `@compute @workgroup_size(${r}, ${n}, ${o}) fn main(${a}) { ${l} `; } appendVariableUniforms(t) { t.rank !== 0 && (t.shape.startsWith("uniforms.") && this.uniforms.push({ name: t.shape.replace("uniforms.", ""), type: "u32", length: t.rank }), t.strides.startsWith("uniforms.") && this.uniforms.push({ name: t.strides.replace("uniforms.", ""), type: "u32", length: t.rank })); } declareVariable(t, r) { if (t.usage === "internal") throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead."); this.variables.push(t), this.appendVariableUniforms(t); let n = t.usage === "input" ? "read" : "read_write", o = t.type.storage; return `@group(0) @binding(${r}) var ${t.name}: array<${o}>;`; } declareVariables(...t) { return t.map((r) => this.declareVariable(r, this.variableIndex++)).join(` `); } registerInternalVariable(t) { if (t.usage !== "internal") throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead."); this.internalVariables.push(t), this.appendVariableUniforms(t); } registerInternalVariables(...t) { return t.forEach((r) => this.registerInternalVariable(r)), this; } registerUniform(t, r, n = 1) { return this.uniforms.push({ name: t, type: r, length: n }), this; } registerUniforms(t) { return this.uniforms = this.uniforms.concat(t), this; } uniformDeclaration() { if (this.uniforms.length === 0) return ""; let t = []; for (let { name: r, type: n, length: o } of this.uniforms) if (o && o > 4) n === "f16" ? t.push(`@align(16) ${r}:array, ${Math.ceil(o / 8)}>`) : t.push(`${r}:array, ${Math.ceil(o / 4)}>`); else { let i = o == null || o === 1 ? n : `vec${o}<${n}>`; t.push(`${r}:${i}`); } return ` struct Uniforms { ${t.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`; } get additionalImplementations() { return this.uniformDeclaration() + this.variables.map((t) => t.impl()).join(` `) + this.internalVariables.map((t) => t.impl()).join(` `); } get variablesInfo() { if (this.uniforms.length === 0) return; let t = (r) => [12, 10, 1, 6][["u32", "f16", "f32", "i32"].indexOf(r)]; return this.uniforms.map((r) => [t(r.type), r.length ?? 1]); } }, Ya = (e, t) => new to2(e, t), Nt2 = (e, t) => { let r = e.length, n = []; for (let o = 0; o < r; o++) { let i = r - 1 - o, a = e[i] || 1; (t[t.length - 1 - o] || 1) > 1 && a === 1 && n.unshift(i); } return n; }; }); Et = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); Ep2 = (e) => { if (!e || e.length !== 1) throw new Error("Transpose requires 1 input."); }, Xa = (e, t) => t && t.length !== e ? [...new Array(e).keys()].reverse() : t, kp2 = (e, t) => k2.sortBasedOnPerm(e, Xa(e.length, t)), Pp2 = (e, t, r, n) => { let o = []; o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`); for (let i = 0; i < t; ++i) o.push(r.indicesSet("a", e[i], `i[${i}]`)); return o.push("return a;}"), o.join(` `); }, Ue2 = (e, t) => { let r = e.dataType, n = e.dims.length, o = Xa(n, t), i = kp2(e.dims, o), a = M("output", r, i.length), l = E("a", r, n), d; if (o.length === 2 && o[0] === 1 && o[1] === 0) { let p = a.type.value, m2 = [16, 16, 1]; d = (u) => ` ${u.registerUniform("output_size", "u32").declareVariables(l, a)} var tile : array, ${m2[0]}>; ${u.mainStart(m2)} var x = workgroup_id.x * ${m2[0]}u + local_id.x; var y = workgroup_id.y * ${m2[0]}u + local_id.y; let width = uniforms.output_shape[0]; let height = uniforms.output_shape[1]; if (x < width && y < height) { tile[local_id.y][local_id.x] = ${l.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${m2[0]}u + local_id.x; y = workgroup_id.x * ${m2[0]}u + local_id.y; if (x < height && y < width) { ${a.setByOffset("y * height + x", "tile[local_id.x][local_id.y]")} } }`; } else d = (p) => ` ${p.registerUniform("output_size", "u32").declareVariables(l, a)} ${Pp2(o, n, l, a)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${a.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${a.setByOffset("global_idx", l.getByIndices("aIndices"))} }`; return { name: "Transpose", shaderCache: { hint: `${t}`, inputDependencies: ["rank"] }, getRunData: (p) => { let m2 = k2.size(i); return { outputs: [{ dims: i, dataType: p[0].dataType }], dispatchGroup: { x: Math.ceil(m2 / 64) }, programUniforms: [{ type: 12, data: m2 }, ...V(p[0].dims, i)] }; }, getShaderSource: d }; }, Za2 = (e, t) => { Ep2(e.inputs), e.compute(Ue2(e.inputs[0], t.perm)); }, Qa2 = (e) => te({ perm: e.perm }); }); ds2 = U(() => { "use strict"; Q(); ae(); ie(); Fr2(); Et(); Op2 = { max: "select(bestValue, candidate, candidate > bestValue)", min: "select(bestValue, candidate, candidate < bestValue)", mean: "bestValue + candidate", sum: "bestValue + candidate", prod: "bestValue * candidate", sumSquare: "bestValue + candidate * candidate", logSumExp: "bestValue + exp(candidate)", l1: "bestValue + abs(candidate)", l2: "bestValue + candidate * candidate", logSum: "bestValue + candidate" }, Dp2 = { max: "select(bestValue, candidate, candidate > bestValue)", min: "select(bestValue, candidate, candidate < bestValue)", mean: "bestValue + candidate", sum: "bestValue + candidate", prod: "bestValue * candidate", sumSquare: "bestValue + candidate", logSumExp: "bestValue + candidate", l1: "bestValue + candidate", l2: "bestValue + candidate", logSum: "bestValue + candidate" }, zp2 = { max: "_A[offset]", min: "_A[offset]", mean: "0", sum: "0", prod: "1", sumSquare: "0", logSumExp: "0", l1: "0", l2: "0", logSum: "0" }, Bp2 = { max: "bestValue", min: "bestValue", sum: "bestValue", prod: "bestValue", sumSquare: "bestValue", logSumExp: "log(bestValue)", l1: "bestValue", l2: "sqrt(bestValue)", logSum: "log(bestValue)" }, Rp2 = (e, t) => { let r = []; for (let n = t - e; n < t; ++n) r.push(n); return r; }, Mp2 = (e, t) => { let r = [], n = e.length; for (let i = 0; i < n; i++) t.indexOf(i) === -1 && r.push(e[i]); let o = t.map((i) => e[i]); return [r, o]; }, Up2 = (e, t) => { let r = e.length + t.length, n = [], o = 0; for (let i = 0; i < r; i++) t.indexOf(i) === -1 ? n.push(e[o++]) : n.push(1); return n; }, Vp2 = (e, t) => { for (let r = 0; r < e.length; ++r) if (e[e.length - r - 1] !== t - 1 - r) return false; return true; }, Np2 = (e, t) => { let r = []; if (!Vp2(e, t)) { for (let n = 0; n < t; ++n) e.indexOf(n) === -1 && r.push(n); e.forEach((n) => r.push(n)); } return r; }, Wp2 = (e, t, r, n, o, i, a) => { let l = r[0].dims, d = k2.size(i), p = k2.size(a), m2 = E("_A", r[0].dataType, l), u = M("output", o, i), h = 32, w = ` var aBestValues : array; `; return { name: e, shaderCache: t, getShaderSource: (b) => ` ${b.registerUniform("reduceSize", "u32").declareVariables(m2, u)} ${w} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${b.mainStart(h)} let outputIndex = global_idx / ${h}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${zp2[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${h}) { let candidate = f32(${m2.getByOffset("offset + k")}); bestValue = ${Op2[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${h}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Dp2[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${u.setByOffset("outputIndex", `${n === "mean" ? `${u.type.storage}(bestValue / f32(uniforms.reduceSize))` : `${u.type.storage}(${Bp2[n]})`}`)}; } }`, getRunData: () => ({ outputs: [{ dims: i, dataType: o }], dispatchGroup: { x: d }, programUniforms: [{ type: 12, data: p }] }) }; }, rt2 = (e, t, r, n) => { let o = e.inputs.length === 1 ? r : oo2(e.inputs, r), i = o.axes; i.length === 0 && !o.noopWithEmptyAxes && (i = e.inputs[0].dims.map((w, g) => g)); let a = k2.normalizeAxes(i, e.inputs[0].dims.length), l = a, d = e.inputs[0], p = Np2(l, e.inputs[0].dims.length); p.length > 0 && (d = e.compute(Ue2(e.inputs[0], p), { inputs: [0], outputs: [-1] })[0], l = Rp2(l.length, d.dims.length)); let [m2, u] = Mp2(d.dims, l), h = m2; o.keepDims && (h = Up2(m2, a)), e.compute(Wp2(t, { hint: o.cacheKey, inputDependencies: ["type"] }, [d], n, e.inputs[0].dataType, h, u), { inputs: [d] }); }, Ja = (e, t) => { rt2(e, "ReduceMeanShared", t, "mean"); }, es2 = (e, t) => { rt2(e, "ReduceL1Shared", t, "l1"); }, ts2 = (e, t) => { rt2(e, "ReduceL2Shared", t, "l2"); }, rs2 = (e, t) => { rt2(e, "ReduceLogSumExpShared", t, "logSumExp"); }, ns2 = (e, t) => { rt2(e, "ReduceMaxShared", t, "max"); }, os2 = (e, t) => { rt2(e, "ReduceMinShared", t, "min"); }, is2 = (e, t) => { rt2(e, "ReduceProdShared", t, "prod"); }, as2 = (e, t) => { rt2(e, "ReduceSumShared", t, "sum"); }, ss2 = (e, t) => { rt2(e, "ReduceSumSquareShared", t, "sumSquare"); }, us2 = (e, t) => { rt2(e, "ReduceLogSumShared", t, "logSum"); }; }); Fr2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); ds2(); nt = (e) => { if (!e || e.length === 0 || e.length > 2) throw new Error("Reduce op requires 1 or 2 inputs."); if (e.length === 2 && e[1].dims.length !== 1) throw new Error("Invalid axes input dims."); }, Hp2 = (e) => ["", "", `var value = ${e.getByIndices("input_indices")};`, ""], qr2 = (e, t, r, n, o, i, a = false, l = false) => { let d = [], p = r[0].dims, m2 = p.length, u = k2.normalizeAxes(o, m2), h = !l && u.length === 0; p.forEach((x2, _) => { h || u.indexOf(_) >= 0 ? a && d.push(1) : d.push(x2); }); let w = d.length, g = k2.size(d); return { name: e, shaderCache: t, getShaderSource: (x2) => { let _ = [], $2 = E("_A", r[0].dataType, m2), S = M("output", i, w), I2 = n($2, S, u), T3 = I2[2]; for (let A2 = 0, D3 = 0; A2 < m2; A2++) h || u.indexOf(A2) >= 0 ? (a && D3++, T3 = `for(var j${A2}: u32 = 0; j${A2} < ${p[A2]}; j${A2}++) { ${I2[2].includes("last_index") ? `let last_index = j${A2};` : ""} ${$2.indicesSet("input_indices", A2, `j${A2}`)} ${T3} }`) : (_.push(`${$2.indicesSet("input_indices", A2, S.indicesGet("output_indices", D3))};`), D3++); return ` ${x2.registerUniform("output_size", "u32").declareVariables($2, S)} ${x2.mainStart()} ${x2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${$2.type.indices}; let output_indices = ${S.offsetToIndices("global_idx")}; ${_.join(` `)} ${I2[0]} // init ops for reduce max/min ${I2[1]} ${T3} ${I2[3]} ${I2.length === 4 ? S.setByOffset("global_idx", "value") : I2.slice(4).join(` `)} }`; }, getRunData: () => ({ outputs: [{ dims: d, dataType: i }], dispatchGroup: { x: Math.ceil(g / 64) }, programUniforms: [{ type: 12, data: g }, ...V(p, d)] }) }; }, oo2 = (e, t) => { let r = []; return e[1].dims[0] > 0 && e[1].getBigInt64Array().forEach((n) => r.push(Number(n))), te({ axes: r, keepDims: t.keepDims, noopWithEmptyAxes: t.noopWithEmptyAxes }); }, ot2 = (e, t, r, n) => { let o = e.inputs, i = o.length === 1 ? r : oo2(o, r); e.compute(qr2(t, { hint: i.cacheKey, inputDependencies: ["rank"] }, [o[0]], i.noopWithEmptyAxes && i.axes.length === 0 ? Hp2 : n, i.axes, o[0].dataType, i.keepDims, i.noopWithEmptyAxes), { inputs: [0] }); }, Gp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceLogSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, "value = log(value);"]); }, Lp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceL1", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += abs(${n.getByIndices("input_indices")});`, ""]); }, Fp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceL2", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += (t * t);`, "value = sqrt(value);"]); }, qp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceLogSumExp", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += exp(${n.getByIndices("input_indices")});`, "value = log(value);"]); }, jp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceMax", t, (n, o, i) => { let a = []; for (let l = 0; l < n.rank; l++) (i.indexOf(l) >= 0 || i.length === 0) && a.push(n.indicesSet("input_indices", l, 0)); return [`${a.join(` `)}`, `var value = ${n.getByIndices("input_indices")};`, `value = max(value, ${n.getByIndices("input_indices")});`, ""]; }); }, Kp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceMean", t, (n, o, i) => { let a = 1; for (let l = 0; l < n.rank; l++) (i.indexOf(l) >= 0 || i.length === 0) && (a *= e.inputs[0].dims[l]); return ["var sum = f32(0);", "", `sum += f32(${n.getByIndices("input_indices")});`, `let value = ${o.type.value}(sum / ${a});`]; }); }, Yp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceMin", t, (n, o, i) => { let a = []; for (let l = 0; l < n.rank; l++) (i.indexOf(l) >= 0 || i.length === 0) && a.push(`input_indices[${l}] = 0;`); return [`${a.join(` `)}`, `var value = ${n.getByIndices("input_indices")};`, `value = min(value, ${n.getByIndices("input_indices")});`, ""]; }); }, Xp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceProd", t, (n, o) => [`var value = ${o.type.storage}(1);`, "", `value *= ${n.getByIndices("input_indices")};`, ""]); }, Zp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, ""]); }, Qp2 = (e, t) => { nt(e.inputs), ot2(e, "ReduceSumSquare", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += t * t;`, ""]); }, it = (e, t, r) => { if (t.length === 0) return r; let n = 1, o = 1; for (let i = 0; i < t.length; i++) t.indexOf(i) === -1 ? n *= e[i] : o *= e[i]; return o < 32 && n > 1024; }, ls2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Kp2(e, t) : Ja(e, t); }, cs2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Lp2(e, t) : es2(e, t); }, ps2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Fp2(e, t) : ts2(e, t); }, ms2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? qp2(e, t) : rs2(e, t); }, fs4 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? jp2(e, t) : ns2(e, t); }, hs2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Yp2(e, t) : os2(e, t); }, gs2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Xp2(e, t) : is2(e, t); }, ys2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Zp2(e, t) : as2(e, t); }, bs2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Qp2(e, t) : ss2(e, t); }, ws2 = (e, t) => { it(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Gp2(e, t) : us2(e, t); }; }); xs2 = U(() => { "use strict"; Q(); Ce2(); Fr2(); vs2 = (e) => { if (!e || e.length === 0 || e.length > 2) throw new Error("ArgMinMaxOp op requires 1 or 2 inputs."); if (e[0].dataType !== 1) throw new Error("Invalid input type."); }, $s2 = (e, t) => { vs2(e.inputs); let r = (n, o, i) => { let a = []; for (let l = 0; l < n.rank; l++) (i.indexOf(l) >= 0 || i.length === 0) && a.push(`input_indices[${l}] = 0;`); return [`${a.join(` `)}`, `var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? "<=" : "<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`, "", o.setByOffset("global_idx", "best_index")]; }; e.compute(qr2("ArgMin", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] }); }, _s2 = (e, t) => { vs2(e.inputs); let r = (n, o, i) => { let a = []; for (let l = 0; l < n.rank; l++) (i.indexOf(l) >= 0 || i.length === 0) && a.push(`input_indices[${l}] = 0;`); return [`${a.join(` `)}`, `var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? ">=" : ">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); }`, "", o.setByOffset("global_idx", "best_index")]; }; e.compute(qr2("argMax", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] }); }, io2 = (e) => te(e); }); jr = U(() => { "use strict"; Q(); Nr2(); ie(); Jp2 = (e, t) => { let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4], l = e[5]; if (a && l) throw new Error("Attention cannot have both past and relative_position_bias"); if (r.dims.length !== 3) throw new Error('Input "input" must have 3 dimensions'); let d = r.dims[0], p = r.dims[1], m2 = r.dims[2]; if (o.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimensions'); if (n.dims.length !== 2) throw new Error('Input "weights" is expected to have 2 dimensions'); if (n.dims[0] !== m2) throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0"); if (o.dims[0] !== n.dims[1]) throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"'); let u = o.dims[0] / 3, h = u, w = h; if (t.qkvHiddenSizes.length > 0) { if (t.qkvHiddenSizes.length !== 3) throw new Error("qkv_hidden_sizes attribute should have 3 elements"); for (let S of t.qkvHiddenSizes) if (S % t.numHeads !== 0) throw new Error("qkv_hidden_sizes should be divisible by num_heads"); u = t.qkvHiddenSizes[0], h = t.qkvHiddenSizes[1], w = t.qkvHiddenSizes[2]; } let g = p; if (u !== h) throw new Error("qkv_hidden_sizes first element should be same as the second"); if (o.dims[0] !== u + h + w) throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes'); let b = 0; if (a) { if (h !== w) throw new Error('Input "past" expect k_hidden_size == v_hidden_size'); if (a.dims.length !== 5) throw new Error('Input "past" must have 5 dimensions'); if (a.dims[0] !== 2) throw new Error('Input "past" first dimension must be 2'); if (a.dims[1] !== d) throw new Error('Input "past" second dimension must be batch_size'); if (a.dims[2] !== t.numHeads) throw new Error('Input "past" third dimension must be num_heads'); if (a.dims[4] !== h / t.numHeads) throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads'); t.pastPresentShareBuffer || (b = a.dims[3]); } let x2 = g + b, _ = -1, $2 = 0; if (i) throw new Error("Mask not supported"); if (a) throw new Error("past is not supported"); return { batchSize: d, sequenceLength: p, pastSequenceLength: b, kvSequenceLength: g, totalSequenceLength: x2, maxSequenceLength: _, inputHiddenSize: m2, hiddenSize: u, vHiddenSize: w, headSize: Math.floor(u / t.numHeads), vHeadSize: Math.floor(w / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: $2, scale: t.scale, broadcastResPosBias: false, passPastInKv: false, qkvFormat: 1 }; }, em2 = (e, t, r, n) => { let o = $e2(n), i = 64, a = n / o; a < i ? i = 1 : a / 8 < 64 && (i = Math.ceil(a / 8)); let l = Math.ceil(n / o / i), d = [{ type: t.dataType, data: 1 / n }, { type: 12, data: a }, { type: 12, data: l }], p = ge(t.dataType, o), m2 = Oe2(1, o), u = (h) => { let w = M("x", t.dataType, t.dims, o), b = [{ name: "d_inv", type: Oe2(t.dataType) }, { name: "d_comp", type: "u32" }, { name: "elements_per_thread", type: "u32" }]; return ` var thread_max: array; var thread_sum: array; ${h.registerUniforms(b).declareVariables(w)} ${h.mainStart([i, 1, 1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = workgroup_id.x * uniforms.d_comp + local_offset; var thread_max_vector = ${m2}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${m2}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(() => { switch (o) { case 1: return "thread_max_vector"; case 2: return "max(thread_max_vector.x, thread_max_vector.y)"; case 4: return "max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))"; default: throw new Error(`Unsupported components: ${o}`); } })()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${i}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${m2}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${m2}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(() => { switch (o) { case 1: return "sum_vector"; case 2: return "sum_vector.x + sum_vector.y"; case 4: return "sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w"; default: throw new Error(`Unsupported components: ${o}`); } })()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${i}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${w.type.value}(uniforms.d_inv); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${m2}(x[offset + i]); x[offset + i] = ${w.type.value}(exp(f32input - max_value) / sum); } } }`; }; return { name: "AttentionProbsSoftmax", shaderCache: { hint: `${i};${p};${o}` }, getShaderSource: u, getRunData: () => ({ outputs: [], dispatchGroup: { x: r }, programUniforms: d }) }; }, tm2 = (e, t, r, n, o, i, a, l) => { let d = l + i.kvSequenceLength, p = [i.batchSize, i.numHeads, i.sequenceLength, d], m2 = i.kvNumHeads === void 0 && e.outputCount > 1, u = m2 ? [i.batchSize, i.numHeads, d, i.headSize] : void 0, h = a.scale === 0 ? 1 / Math.sqrt(i.headSize) : a.scale, w = $e2(i.headSize), g = i.headSize / w, b = 12, x2 = { x: Math.ceil(d / b), y: Math.ceil(i.sequenceLength / b), z: i.batchSize * i.numHeads }, _ = [{ type: 12, data: i.sequenceLength }, { type: 12, data: g }, { type: 12, data: d }, { type: 12, data: i.numHeads }, { type: 1, data: h }, { type: 12, data: l }, { type: 12, data: i.kvSequenceLength }], $2 = ["type", "type"]; n && $2.push("type"), o && $2.push("type"); let S = [{ dims: p, dataType: t.dataType, gpuDataType: 0 }]; m2 && S.push({ dims: u, dataType: t.dataType, gpuDataType: 0 }); let I2 = (T3) => { let A2 = E("q", t.dataType, t.dims, w), D3 = E("key", r.dataType, r.dims, w), z3 = [A2, D3]; if (n) { let pe2 = E("past_key", n.dataType, n.dims, w); z3.push(pe2); } o && z3.push(E("relative_position_bias", o.dataType, o.dims)); let H3 = M("output", t.dataType, p), W2 = [H3]; m2 && W2.push(M("present_key", t.dataType, u, w)); let X = Oe2(1, w), Y3 = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "alpha", type: "f32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }]; return ` const TILE_SIZE = ${b}u; var tileQ: array<${A2.type.storage}, ${b * b}>; var tileK: array<${A2.type.storage}, ${b * b}>; ${T3.registerUniforms(Y3).declareVariables(...z3, ...W2)} ${T3.mainStart([b, b, 1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${/* @__PURE__ */ (() => n && m2 ? ` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;` : ` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`)()} ${m2 ? "let presentKeyOffset = headIdx * uniforms.N * uniforms.K;" : ""} var value = ${X}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${/* @__PURE__ */ (() => n && m2 ? ` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }` : "tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];")()} ${m2 ? "present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];" : ""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${X}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(() => { switch (w) { case 1: return "value"; case 2: return "value.x + value.y"; case 4: return "value.x + value.y + value.z + value.w"; default: throw new Error(`Unsupported components: ${w}`); } })()}; output[outputIdx] = ${H3.type.value} (sum * uniforms.alpha) + ${o ? "relative_position_bias[outputIdx]" : "0.0"}; } }`; }; return { name: "AttentionProbs", shaderCache: { hint: `${w};${o !== void 0};${n !== void 0};${e.outputCount}`, inputDependencies: $2 }, getRunData: () => ({ outputs: S, dispatchGroup: x2, programUniforms: _ }), getShaderSource: I2 }; }, rm2 = (e, t, r, n, o, i) => { let a = i + o.kvSequenceLength, l = o.nReps ? o.nReps : 1, d = o.vHiddenSize * l, p = o.kvNumHeads == null && e.outputCount > 1, m2 = p ? [o.batchSize, o.numHeads, a, o.headSize] : void 0, u = [o.batchSize, o.sequenceLength, d], h = 12, w = { x: Math.ceil(o.vHeadSize / h), y: Math.ceil(o.sequenceLength / h), z: o.batchSize * o.numHeads }, g = [{ type: 12, data: o.sequenceLength }, { type: 12, data: a }, { type: 12, data: o.vHeadSize }, { type: 12, data: o.numHeads }, { type: 12, data: d }, { type: 12, data: i }, { type: 12, data: o.kvSequenceLength }], b = n ? ["type", "type", "type"] : ["type", "type"], x2 = [{ dims: u, dataType: t.dataType, gpuDataType: 0 }]; p && x2.push({ dims: m2, dataType: t.dataType, gpuDataType: 0 }); let _ = ($2) => { let S = E("probs", t.dataType, t.dims), I2 = E("v", r.dataType, r.dims), T3 = [S, I2]; n && T3.push(E("past_value", n.dataType, n.dims)); let D3 = [M("output", t.dataType, u)]; p && D3.push(M("present_value", t.dataType, m2)); let z3 = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "v_hidden_size", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }]; return ` const TILE_SIZE = ${h}u; var tileQ: array<${S.type.value}, ${h * h}>; var tileK: array<${S.type.value}, ${h * h}>; ${$2.registerUniforms(z3).declareVariables(...T3, ...D3)} ${$2.mainStart([h, h, 1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${/* @__PURE__ */ (() => n && p ? ` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; ` : ` let offsetB = headIdx * uniforms.N * uniforms.K + n; `)()} ${p ? "let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;" : ""} var value = ${S.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${/* @__PURE__ */ (() => n && p ? ` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } ` : ` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `)()} ${p ? "present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];" : ""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`; }; return { name: "AttentionScore", shaderCache: { hint: `${n !== void 0};${e.outputCount}`, inputDependencies: b }, getRunData: () => ({ outputs: x2, dispatchGroup: w, programUniforms: g }), getShaderSource: _ }; }, Wt2 = (e, t, r, n, o, i, a, l, d, p, m2) => { let u = e.outputCount, h = p.kvNumHeads !== void 0 || u > 1 ? p.pastSequenceLength : 0, w = h + p.kvSequenceLength, g = p.kvNumHeads === void 0 && u > 1 && a ? [t, r, a] : [t, r]; d && g.push(d); let b = e.compute(tm2(e, t, r, u > 1 ? a : void 0, d, p, m2, h), { inputs: g, outputs: p.kvNumHeads === void 0 && u > 1 ? [-1, 1] : [-1] })[0]; e.compute(em2(e, b, p.batchSize * p.numHeads * p.sequenceLength, w), { inputs: [b], outputs: [] }); let x2 = p.kvNumHeads === void 0 && u > 1 && l ? [b, n, l] : [b, n]; e.compute(rm2(e, b, n, u > 1 && l ? l : void 0, p, h), { inputs: x2, outputs: p.kvNumHeads === void 0 && u > 1 ? [0, 2] : [0] }); }, nm2 = (e, t) => { let r = [t.batchSize, t.numHeads, t.sequenceLength, t.headSize], n = t.sequenceLength, o = t.inputHiddenSize, i = t.headSize, a = 12, l = { x: Math.ceil(t.headSize / a), y: Math.ceil(t.sequenceLength / a), z: t.batchSize * t.numHeads }, d = [e.inputs[0], e.inputs[1], e.inputs[2]], p = [{ type: 12, data: n }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: t.numHeads }, { type: 12, data: t.headSize }, { type: 12, data: t.hiddenSize }, { type: 12, data: t.hiddenSize + t.hiddenSize + t.vHiddenSize }], m2 = (u) => { let h = M("output_q", d[0].dataType, r), w = M("output_k", d[0].dataType, r), g = M("output_v", d[0].dataType, r), b = E("input", d[0].dataType, d[0].dims), x2 = E("weight", d[1].dataType, d[1].dims), _ = E("bias", d[2].dataType, d[2].dims), $2 = b.type.storage, S = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "ldb", type: "u32" }]; return ` const TILE_SIZE = ${a}u; var tileInput: array<${$2}, ${a * a}>; var tileWeightQ: array<${$2}, ${a * a}>; var tileWeightK: array<${$2}, ${a * a}>; var tileWeightV: array<${$2}, ${a * a}>; ${u.registerUniforms(S).declareVariables(b, x2, _, h, w, g)} ${u.mainStart([a, a, 1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${$2}(0); var valueK = ${$2}(0); var valueV = ${$2}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k ({ outputs: [{ dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }], dispatchGroup: l, programUniforms: p }), getShaderSource: m2 }, { inputs: d, outputs: [-1, -1, -1] }); }, Ss2 = (e, t) => { let r = Jp2(e.inputs, t), [n, o, i] = nm2(e, r); return Wt2(e, n, o, i, e.inputs[4], void 0, void 0, void 0, e.inputs[5], r, t); }; }); Cs2 = U(() => { "use strict"; Ke2(); Q(); ae(); Ce2(); ie(); om2 = (e, t) => { if (!e || e.length !== 5) throw new Error("BatchNormalization requires 5 inputs"); let r = (n, o, i) => { let a = o.length; if (a !== n.length) throw new Error(`${i}: num dimensions != ${a}`); o.forEach((l, d) => { if (l !== n[d]) throw new Error(`${i}: dim[${d}] do not match`); }); }; if (e[0].dims.length > 1) { let n = t.format === "NHWC" ? t.spatial ? e[0].dims.slice(-1) : e[0].dims.slice(-1).concat(e[0].dims.slice(1, e[0].dims.length - 1)) : e[0].dims.slice(1, t.spatial ? 2 : void 0); r(e[1].dims, n, "Invalid input scale"), r(e[2].dims, n, "Invalid input B"), r(e[3].dims, n, "Invalid input mean"), r(e[4].dims, n, "Invalid input var"); } else r(e[1].dims, [1], "Invalid input scale"), r(e[2].dims, [1], "Invalid input B"), r(e[3].dims, [1], "Invalid input mean"), r(e[4].dims, [1], "Invalid input var"); }, im2 = (e, t) => { let { epsilon: r, spatial: n, format: o } = t, i = e[0].dims, a = n ? $e2(i[i.length - 1]) : 1, l = o === "NHWC" && i.length > 1 ? a : 1, d = k2.size(i) / a, p = n, m2 = p ? i.length : i, u = E("x", e[0].dataType, e[0].dims, a), h = E("scale", e[1].dataType, e[1].dims, l), w = E("bias", e[2].dataType, e[2].dims, l), g = E("inputMean", e[3].dataType, e[3].dims, l), b = E("inputVar", e[4].dataType, e[4].dims, l), x2 = M("y", e[0].dataType, m2, a), _ = () => { let S = ""; if (n) S = `let cOffset = ${i.length === 1 ? "0u" : o === "NHWC" ? `outputIndices[${i.length - 1}] / ${a}` : "outputIndices[1]"};`; else if (o === "NCHW") S = ` ${x2.indicesSet("outputIndices", "0", "0")} let cOffset = ${x2.indicesToOffset("outputIndices")};`; else { S = `var cIndices = ${h.type.indices}(0); cIndices[0] = outputIndices[${i.length - 1}];`; for (let I2 = 1; I2 < h.rank; I2++) S += `cIndices[${I2}] = outputIndices[${I2}];`; S += `let cOffset = ${h.indicesToOffset("cIndices")};`; } return S; }, $2 = (S) => ` const epsilon = ${r}; ${S.registerUniform("outputSize", "u32").declareVariables(u, h, w, g, b, x2)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${x2.offsetToIndices(`global_idx * ${a}`)}; ${_()} let scale = ${h.getByOffset("cOffset")}; let bias = ${w.getByOffset("cOffset")}; let inputMean = ${g.getByOffset("cOffset")}; let inputVar = ${b.getByOffset("cOffset")}; let x = ${u.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${x2.setByOffset("global_idx", "value")} }`; return { name: "BatchNormalization", shaderCache: { hint: `${t.epsilon}_${t.format}_${n}_${a}`, inputDependencies: p ? ["rank", "type", "type", "type", "type"] : void 0 }, getShaderSource: $2, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: p ? [{ type: 12, data: d }, ...V(i)] : [{ type: 12, data: d }] }) }; }, am2 = (e) => te(e), Is2 = (e, t) => { let { inputs: r, outputCount: n } = e, o = am2({ ...t, outputCount: n }); if (be2.webgpu.validateInputContent && om2(r, o), t.trainingMode) throw new Error("BatchNormalization trainingMode is not supported yet."); e.compute(im2(r, o)); }; }); As2 = U(() => { "use strict"; ae(); ie(); sm2 = (e) => { if (e[0].dims.length !== 3) throw new Error("input should have 3 dimensions"); if (![320, 640, 1280].includes(e[0].dims[2])) throw new Error("number of channels should be 320, 640 or 1280"); if (e[1].dims.length !== 1) throw new Error("bias is expected to have 1 dimensions"); if (e[0].dims[2] !== e[1].dims[0]) throw new Error("last dimension of input and bias are not the same"); }, um2 = (e) => { let t = e[0].dims, r = e[0].dims[2], n = k2.size(t) / 4, o = e[0].dataType, i = E("input", o, t, 4), a = E("bias", o, [r], 4), l = E("residual", o, t, 4), d = M("output", o, t, 4); return { name: "BiasAdd", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(n / 64) } }), getShaderSource: (m2) => ` const channels = ${r}u / 4; ${m2.declareVariables(i, a, l, d)} ${m2.mainStart()} ${m2.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${i.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")}; ${d.setByOffset("global_idx", "value")} }` }; }, Ts2 = (e) => { sm2(e.inputs), e.compute(um2(e.inputs)); }; }); Yr = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); dm2 = (e, t, r, n, o, i) => { let a = Math.ceil(t / 4), l = ""; typeof o == "string" ? l = `${o}(a)` : l = o("a"); let d = E("inputData", r, [a], 4), p = M("outputData", n, [a], 4); return ` ${e.registerUniform("vec_size", "u32").declareVariables(d, p)} ${i ?? ""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx", l)} }`; }, fe2 = (e, t, r, n, o, i = e.dataType) => ({ name: t, shaderCache: { hint: o, inputDependencies: ["type"] }, getShaderSource: (a) => dm2(a, k2.size(e.dims), e.dataType, i, r, n), getRunData: (a) => ({ outputs: [{ dims: e.dims, dataType: i }], dispatchGroup: { x: Math.ceil(k2.size(a[0].dims) / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(k2.size(e.dims) / 4) }] }) }), Es2 = (e) => { e.compute(fe2(e.inputs[0], "Abs", "abs")); }, ks2 = (e) => { e.compute(fe2(e.inputs[0], "Acos", "acos")); }, Ps2 = (e) => { e.compute(fe2(e.inputs[0], "Acosh", "acosh")); }, Os2 = (e) => { e.compute(fe2(e.inputs[0], "Asin", "asin")); }, Ds2 = (e) => { e.compute(fe2(e.inputs[0], "Asinh", "asinh")); }, zs2 = (e) => { e.compute(fe2(e.inputs[0], "Atan", "atan")); }, Bs2 = (e) => { e.compute(fe2(e.inputs[0], "Atanh", "atanh")); }, Rs2 = (e) => te(e), Ms2 = (e, t) => { let r; switch (t.to) { case 10: r = "vec4"; break; case 1: r = "vec4"; break; case 12: r = "vec4"; break; case 6: r = "vec4"; break; case 9: r = "vec4"; break; default: throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`); } e.compute(fe2(e.inputs[0], "Cast", r, void 0, t.cacheKey, t.to)); }, lm2 = (e) => { let t = e.length >= 2 && e[1].data !== 0 ? e[1].getFloat32Array()[0] : Hr2, r = e.length >= 3 && e[2].data !== 0 ? e[2].getFloat32Array()[0] : Gr2; return te({ min: t, max: r }); }, Us2 = (e, t) => { let r = e.inputs.length === 1 ? t : lm2(e.inputs), n = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "Clip", (o) => `clamp(${o}, clip_min_, clip_max_)`, ` const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); `, r.cacheKey), { inputs: [0] }); }, Vs2 = (e) => { e.compute(fe2(e.inputs[0], "Ceil", "ceil")); }, Ns2 = (e) => { e.compute(fe2(e.inputs[0], "Cos", "cos")); }, Ws = (e) => { e.compute(fe2(e.inputs[0], "Cosh", "cosh")); }, Qt = (e) => te(e), Hs2 = (e, t) => { let r = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "Elu", (n) => `elu_vf32(${n})`, ` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`, t.cacheKey)); }, Kr = (e = "f32") => ` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; const r3: ${e} = 1.421413741; const r4: ${e} = -1.453152027; const r5: ${e} = 1.061405429; fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`, Gs2 = (e) => { let t = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "Erf", (r) => `erf_vf32(${r})`, Kr(t))); }, Ls2 = (e) => { e.compute(fe2(e.inputs[0], "Exp", "exp")); }, Fs2 = (e) => { e.compute(fe2(e.inputs[0], "Floor", "floor")); }, qs = (e) => { let t = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "Gelu", (r) => `0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`, Kr(t))); }, js = (e, t) => { let r = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "LeakyRelu", (n) => `select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`, `const leaky_relu_alpha_ = ${r}(${t.alpha});`, t.cacheKey)); }, Ks2 = (e) => { e.compute(fe2(e.inputs[0], "Not", (t) => `!${t}`)); }, Ys2 = (e) => { e.compute(fe2(e.inputs[0], "Neg", (t) => `-${t}`)); }, Xs = (e) => { e.compute(fe2(e.inputs[0], "Reciprocal", (t) => `1.0/${t}`)); }, Zs = (e) => { let t = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "Relu", (r) => `select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`)); }, Qs = (e) => { e.compute(fe2(e.inputs[0], "Sigmoid", (t) => `(1.0 / (1.0 + exp(-${t})))`)); }, Js = (e) => te(e), eu = (e, t) => { let r = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "HardSigmoid", (n) => `max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`, void 0, t.cacheKey)); }, tu = (e) => { e.compute(fe2(e.inputs[0], "Sin", "sin")); }, ru = (e) => { e.compute(fe2(e.inputs[0], "Sinh", "sinh")); }, nu = (e) => { e.compute(fe2(e.inputs[0], "Sqrt", "sqrt")); }, ou2 = (e) => { e.compute(fe2(e.inputs[0], "Tan", "tan")); }, iu2 = (e) => `sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`, au = (e) => { e.compute(fe2(e.inputs[0], "Tanh", iu2)); }, ao2 = (e = "f32") => ` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { return ${iu2("v")}; } `, so2 = (e) => `(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`, su2 = (e) => { let t = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "FastGelu", so2, ao2(t), void 0, e.inputs[0].dataType)); }, uu = (e, t) => { let r = Oe2(e.inputs[0].dataType); return e.compute(fe2(e.inputs[0], "ThresholdedRelu", (n) => `select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`, `const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`, t.cacheKey)), 0; }, du = (e) => { e.compute(fe2(e.inputs[0], "Log", "log")); }, cm2 = (e, t) => ` const alpha = vec4<${e}>(${t}); const one = ${e}(1.0); const zero = ${e}(0.0); fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let v = x *alpha; var x1 : vec4<${e}>; for (var i = 0; i < 4; i = i + 1) { if (v[i] >= zero) { x1[i] = one / (one + exp(-v[i])); } else { x1[i] = one - one / (one + exp(v[i])); } } return x * x1; } `, pm2 = (e) => `quick_gelu_impl(${e})`, lu2 = (e, t) => { let r = Oe2(e.inputs[0].dataType); e.compute(fe2(e.inputs[0], "QuickGelu", pm2, cm2(r, t.alpha), t.cacheKey, e.inputs[0].dataType)); }; }); mu = U(() => { "use strict"; ae(); ie(); Yr(); mm2 = (e) => { if (e[0].dims.length !== 3) throw new Error("input should have 3 dimensions"); if (![2560, 5120, 10240].includes(e[0].dims[2])) throw new Error("hidden state should be 2560, 5120 or 10240"); if (e[1].dims.length !== 1) throw new Error("bias is expected to have 1 dimensions"); if (e[0].dims[2] !== e[1].dims[0]) throw new Error("last dimension of input and bias are not the same"); }, fm2 = (e) => { let t = e[0].dims.slice(); t[2] = t[2] / 2; let r = E("input", e[0].dataType, e[0].dims, 4), n = E("bias", e[0].dataType, [e[0].dims[2]], 4), o = M("output", e[0].dataType, t, 4), i = k2.size(t) / 4, a = ge(e[0].dataType); return { name: "BiasSplitGelu", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) } }), getShaderSource: (d) => ` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2] / 4 / 2}u; ${d.declareVariables(r, n, o)} ${Kr(a)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${o.setByOffset("global_idx", "valueLeft * geluRight")} }` }; }, pu = (e) => { mm2(e.inputs), e.compute(fm2(e.inputs)); }; }); Su = U(() => { "use strict"; Q(); ae(); ie(); hm2 = (e, t, r, n, o, i, a, l, d, p, m2, u) => { let h, w; typeof l == "string" ? h = w = ($2, S) => `${l}((${$2}),(${S}))` : typeof l == "function" ? h = w = l : (h = l.scalar, w = l.vector); let g = M("outputData", m2, n.length, 4), b = E("aData", d, t.length, 4), x2 = E("bData", p, r.length, 4), _; if (o) if (i) { let $2 = k2.size(t) === 1, S = k2.size(r) === 1, I2 = t.length > 0 && t[t.length - 1] % 4 === 0, T3 = r.length > 0 && r[r.length - 1] % 4 === 0; $2 || S ? _ = g.setByOffset("global_idx", w($2 ? `${b.type.value}(${b.getByOffset("0")}.x)` : b.getByOffset("global_idx"), S ? `${x2.type.value}(${x2.getByOffset("0")}.x)` : x2.getByOffset("global_idx"))) : _ = ` let outputIndices = ${g.offsetToIndices("global_idx * 4u")}; let offsetA = ${b.broadcastedIndicesToOffset("outputIndices", g)}; let offsetB = ${x2.broadcastedIndicesToOffset("outputIndices", g)}; ${g.setByOffset("global_idx", w(a || I2 ? b.getByOffset("offsetA / 4u") : `${b.type.value}(${b.getByOffset("offsetA / 4u")}[offsetA % 4u])`, a || T3 ? x2.getByOffset("offsetB / 4u") : `${x2.type.value}(${x2.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `; } else _ = g.setByOffset("global_idx", w(b.getByOffset("global_idx"), x2.getByOffset("global_idx"))); else { if (!i) throw new Error("no necessary to use scalar implementation for element-wise binary op implementation."); let $2 = (S, I2, T3 = "") => { let A2 = `aData[indexA${I2}][componentA${I2}]`, D3 = `bData[indexB${I2}][componentB${I2}]`; return ` let outputIndices${I2} = ${g.offsetToIndices(`global_idx * 4u + ${I2}u`)}; let offsetA${I2} = ${b.broadcastedIndicesToOffset(`outputIndices${I2}`, g)}; let offsetB${I2} = ${x2.broadcastedIndicesToOffset(`outputIndices${I2}`, g)}; let indexA${I2} = offsetA${I2} / 4u; let indexB${I2} = offsetB${I2} / 4u; let componentA${I2} = offsetA${I2} % 4u; let componentB${I2} = offsetB${I2} % 4u; ${S}[${I2}] = ${T3}(${h(A2, D3)}); `; }; m2 === 9 ? _ = ` var data = vec4(0); ${$2("data", 0, "u32")} ${$2("data", 1, "u32")} ${$2("data", 2, "u32")} ${$2("data", 3, "u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : _ = ` ${$2("outputData[global_idx]", 0)} ${$2("outputData[global_idx]", 1)} ${$2("outputData[global_idx]", 2)} ${$2("outputData[global_idx]", 3)} `; } return ` ${e.registerUniform("vec_size", "u32").declareVariables(b, x2, g)} ${u ?? ""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${_} }`; }, gm2 = (e, t, r, n, o, i, a = r.dataType) => { let l = !k2.areEqual(r.dims, n.dims), d = r.dims, p = k2.size(r.dims), m2 = false, u = false, h = [l]; if (l) { let w = tt2.calcShape(r.dims, n.dims, false); if (!w) throw new Error("Can't perform binary op on the given tensors"); d = w, p = k2.size(d); let g = k2.size(r.dims) === 1, b = k2.size(n.dims) === 1, x2 = r.dims.length > 0 && r.dims[r.dims.length - 1] % 4 === 0, _ = n.dims.length > 0 && n.dims[n.dims.length - 1] % 4 === 0; h.push(g), h.push(b), h.push(x2), h.push(_); let $2 = 1; for (let S = 1; S < d.length; S++) { let I2 = r.dims[r.dims.length - S] ?? 1, T3 = n.dims[n.dims.length - S] ?? 1; if (I2 === T3) $2 *= I2; else break; } $2 % 4 === 0 ? (u = true, m2 = true) : (g || b || x2 || _) && (m2 = true); } else m2 = true; return h.push(m2), { name: e, shaderCache: { hint: t + h.map((w) => w.toString()).join("_"), inputDependencies: ["rank", "rank"] }, getShaderSource: (w) => hm2(w, r.dims, n.dims, d, m2, l, u, o, r.dataType, n.dataType, a, i), getRunData: () => ({ outputs: [{ dims: d, dataType: a }], dispatchGroup: { x: Math.ceil(p / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(k2.size(d) / 4) }, ...V(r.dims, n.dims, d)] }) }; }, at = (e, t, r, n, o, i) => { e.compute(gm2(t, o ?? "", e.inputs[0], e.inputs[1], r, n, i)); }, fu = (e) => { at(e, "Add", (t, r) => `${t}+${r}`); }, hu = (e) => { at(e, "Div", (t, r) => `${t}/${r}`); }, gu = (e) => { at(e, "Equal", { scalar: (t, r) => `u32(${t}==${r})`, vector: (t, r) => `vec4(${t}==${r})` }, void 0, void 0, 9); }, yu = (e) => { at(e, "Mul", (t, r) => `${t}*${r}`); }, bu = (e) => { let t = E("input", e.inputs[0].dataType, e.inputs[0].dims).type.value; at(e, "Pow", { scalar: (n, o) => `pow_custom(${n},${o})`, vector: (n, o) => `pow_vector_custom(${n},${o})` }, ` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t === "i32" ? "round" : ""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `); }, wu = (e) => { at(e, "Sub", (t, r) => `${t}-${r}`); }, vu = (e) => { at(e, "Greater", { scalar: (t, r) => `u32(${t}>${r})`, vector: (t, r) => `vec4(${t}>${r})` }, void 0, void 0, 9); }, $u = (e) => { at(e, "Less", { scalar: (t, r) => `u32(${t}<${r})`, vector: (t, r) => `vec4(${t}<${r})` }, void 0, void 0, 9); }, _u = (e) => { at(e, "GreaterOrEqual", { scalar: (t, r) => `u32(${t}>=${r})`, vector: (t, r) => `vec4(${t}>=${r})` }, void 0, void 0, 9); }, xu = (e) => { at(e, "LessOrEqual", { scalar: (t, r) => `u32(${t}<=${r})`, vector: (t, r) => `vec4(${t}<=${r})` }, void 0, void 0, 9); }; }); Tu2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); bm2 = (e, t) => { if (!e || e.length < 1) throw new Error("too few inputs"); let r = 0, n = e[r], o = n.dataType, i = n.dims.length; e.forEach((a, l) => { if (l !== r) { if (a.dataType !== o) throw new Error("input tensors should be one type"); if (a.dims.length !== i) throw new Error("input tensors should have the same shape"); a.dims.forEach((d, p) => { if (p !== t && d !== n.dims[p]) throw new Error("non concat dimensions must match"); }); } }); }, wm2 = (e, t) => ` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${t}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${e}u; }`, vm2 = (e, t) => { let r = e.length, n = []; for (let o = 0; o < r; ++o) { let i = t.setByOffset("global_idx", e[o].getByIndices("indices")); r === 1 ? n.push(i) : o === 0 ? n.push(`if (inputIndex == ${o}u) { ${i} }`) : o === r - 1 ? n.push(`else { ${i} }`) : n.push(`else if (inputIndex == ${o}) { ${i} }`); } return n.join(` `); }, $m2 = (e, t, r, n) => { let o = k2.size(r), i = new Array(e.length), a = new Array(e.length), l = 0, d = [], p = [], m2 = [{ type: 12, data: o }]; for (let b = 0; b < e.length; ++b) l += e[b].dims[t], i[b] = l, p.push(e[b].dims.length), a[b] = E(`input${b}`, n, p[b]), d.push("rank"), m2.push({ type: 12, data: i[b] }); for (let b = 0; b < e.length; ++b) m2.push(...V(e[b].dims)); m2.push(...V(r)); let u = M("output", n, r.length), h = u.indicesGet("indices", t), w = Array.from(Array(i.length).keys()).map((b) => `uniforms.sizeInConcatAxis${b}`).join(","), g = (b) => ` ${(() => { b.registerUniform("outputSize", "u32"); for (let x2 = 0; x2 < e.length; x2++) b.registerUniform(`sizeInConcatAxis${x2}`, "u32"); return b.declareVariables(...a, u); })()} ${wm2(i.length, w)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var indices = ${u.offsetToIndices("global_idx")}; let inputIndex = calculateInputIndex(${h}); if (inputIndex != 0u) { let sizeInConcatAxis = array(${w}); ${h} -= sizeInConcatAxis[inputIndex - 1u]; } ${vm2(a, u)} }`; return { name: "Concat", shaderCache: { hint: `${t}`, inputDependencies: d }, getRunData: () => ({ outputs: [{ dims: r, dataType: n }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: m2 }), getShaderSource: g }; }, Iu = (e, t) => { let r = e.inputs, n = r[0].dims, o = k2.normalizeAxis(t.axis, n.length); bm2(r, o); let i = n.slice(); i[o] = r.reduce((l, d) => l + (d.dims.length > o ? d.dims[o] : 0), 0); let a = r.filter((l) => k2.size(l.dims) > 0); e.compute($m2(a, o, i, r[0].dataType), { inputs: a }); }, Cu = (e) => te({ axis: e.axis }); }); lt = U(() => { "use strict"; Q(); ae(); He2 = (e, t, r = "f32") => { switch (e.activation) { case "Relu": return `value = max(value, ${t}(0.0));`; case "Sigmoid": return `value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`; case "Clip": return `value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`; case "HardSigmoid": return `value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`; case "LeakyRelu": return `value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`; case "Tanh": return `let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `; case "": return ""; default: throw new Error(`Unsupported activation ${e.activation}`); } }, Ge2 = (e, t) => { e.activation === "Clip" ? t.push({ type: 1, data: e.clipMax }, { type: 1, data: e.clipMin }) : e.activation === "HardSigmoid" ? t.push({ type: 1, data: e.alpha }, { type: 1, data: e.beta }) : e.activation === "LeakyRelu" && t.push({ type: 1, data: e.alpha }); }, Le = (e, t) => { e.activation === "Clip" ? t.push({ name: "clip_max", type: "f32" }, { name: "clip_min", type: "f32" }) : e.activation === "HardSigmoid" ? t.push({ name: "alpha", type: "f32" }, { name: "beta", type: "f32" }) : e.activation === "LeakyRelu" && t.push({ name: "alpha", type: "f32" }); }, Xr = (e) => { let t = e?.activation || ""; if (t === "HardSigmoid") { let [r, n] = e?.activation_params || [0.2, 0.5]; return { activation: t, alpha: r, beta: n }; } else if (t === "Clip") { let [r, n] = e?.activation_params || [Hr2, Gr2]; return { activation: t, clipMax: n, clipMin: r }; } else if (t === "LeakyRelu") { let [r] = e?.activation_params || [0.01]; return { activation: t, alpha: r }; } return { activation: t }; }; }); Jt2 = U(() => { "use strict"; Ee = (e, t) => { switch (e) { case 1: return t; case 2: return `vec2<${t}>`; case 3: return `vec3<${t}>`; case 4: return `vec4<${t}>`; default: throw new Error(`${e}-component is not supported.`); } }, Zr = (e) => ` ${e ? "value = value + getBiasByOutputCoords(coords);" : ""} `; }); uo2 = U(() => { "use strict"; Qr = (e) => ` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } `; }); rr2 = U(() => { "use strict"; Q(); ae(); ie(); lt(); Jt2(); _m2 = (e, t) => e ? ` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${t ? ", batchIndices" : ""}); ` : ` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${t ? ", batchIndices" : ""}); `, xm2 = (e, t) => e ? ` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${t === 3 ? "" : "let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${t === 3 ? "" : "acc[i] = BCached3 * ACached3[i] + acc[i];"} }` : ` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t === 3 ? "" : "acc[i] = BCached3 * ACached.w + acc[i];"} }`, er = (e, t, r = "f32", n, o = false, i = 32, a = false, l = 32) => { let d = t[1] * e[1], p = t[0] * e[0], m2 = o ? d : i, u = o ? i : d, h = m2 / t[0], w = i / t[1]; if (!((o && h === 4 && e[1] === 4 || !o && (h === 3 || h === 4)) && m2 % t[0] === 0 && i % t[1] === 0 && e[0] === 4)) throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${h} must be 3 or 4. tileAWidth ${m2} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`); return ` var mm_Asub: array, ${m2 / h}>, ${u}>; var mm_Bsub: array, ${p / e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${h}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${a ? "0" : "i32(globalId.z)"}; ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""} let globalRowStart = i32(workgroupId.y) * ${d}; let num_tiles = ${a ? `${Math.ceil(l / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a ? `i32(globalId.z) * ${l}` : "0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${w}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${_m2(o, n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n ? ", batchIndices" : ""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${h === 3 ? "" : "let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${xm2(o, h)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`; }, Au = (e, t) => e ? ` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${t ? ", batchIndices" : ""}); ` : ` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${t ? ", batchIndices" : ""}); `, Sm2 = (e) => e ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];", tr = (e, t, r = "f32", n, o = false, i = 32, a = false, l = 32, d = false) => { let p = e[1] * t[1], m2 = e[0] * t[0], u = o ? p : i, h = o ? i : p; if (!(h % t[1] === 0 && u % t[0] === 0 && i % t[1] === 0)) throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`); let w = h / t[1], g = u / t[0], b = i / t[1], x2 = d ? ` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${p}; let globalColStart = i32(workgroupId.x) * ${m2}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { ${Au(o, n)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${m2}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${n ? ", batchIndices" : ""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${o ? `mm_Asub[k][localRow + innerRow * ${t[1]}];` : `mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } ` : ` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${p}; let tileRowA = i32(localId.y) * ${w}; let tileColA = i32(localId.x) * ${g}; let tileRowB = i32(localId.y) * ${b}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Au(o, n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${n ? ", batchIndices" : ""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${r}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Sm2(o)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `; return ` var mm_Asub : array, ${h}>; var mm_Bsub : array, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${a ? "0" : "i32(globalId.z)"}; ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""} let num_tiles = ${a ? `${Math.ceil(l / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a ? `i32(globalId.z) * ${l}` : "0"}; var acc : array, rowPerThread>; ${x2} } `; }, Im = (e, t, r, n, o, i = false) => { let [a, l, d] = o, [p, m2, u, h] = n, w = Nt2(a, d), g = Nt2(l, d), b = ge(n[0].type.tensor), x2 = () => { let S = m2.rank, I2 = p.rank, T3 = `var aIndices: ${m2.type.indices};`; for (let A2 = S - 2 - 1, D3 = I2 - 1; A2 >= 0; A2--, D3--) T3 += ` aIndices[${A2}] = ${I2 > 1 ? `batchIndices[${D3}]` : "batchIndices"};`; return w.forEach((A2) => { T3 += ` aIndices[${A2}] = 0;`; }), T3 += ` aIndices[${S - 2}] = u32(row); aIndices[${S - 1}] = u32(colIn);`, T3; }, _ = () => { let S = u.rank, I2 = p.rank, T3 = `var bIndices: ${u.type.indices};`; for (let A2 = S - 2 - 1, D3 = I2 - 1; A2 >= 0; A2--, D3--) T3 += ` bIndices[${A2}] = ${I2 > 1 ? `batchIndices[${D3}]` : "batchIndices"};`; return g.forEach((A2) => { T3 += ` bIndices[${A2}] = 0;`; }), T3 += ` bIndices[${S - 2}] = u32(row); bIndices[${S - 1}] = u32(colIn);`, T3; }; return ` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ee(e, b)} { var value = ${Ee(e, b)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${x2()} value = ${m2.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ee(e, b)} { var value = ${Ee(e, b)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${_()} value = ${u.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ee(e, b)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t ? `value = value + ${i ? "bias[colIn]" : `${Ee(e, b)}(bias[row])`};` : ""} ${r} ${h.setByIndices("vec3(coords)", "value")} } } `; }, Jr = (e, t, r, n, o = false) => { let i = e[0].dims, a = e[1].dims, l = i.slice(0, -2), d = a.slice(0, -2), p = n ? n.slice(0, -2) : r.slice(0, -2), m2 = k2.size(p), u = i[i.length - 2], h = i[i.length - 1], w = a[a.length - 1], g = h % 4 === 0 && w % 4 === 0, b = u <= 8 ? [4, 1, 1] : [4, 4, 1], x2 = [8, 8, 1], _ = [Math.ceil(w / x2[0] / b[0]), Math.ceil(u / x2[1] / b[1]), Math.ceil(m2 / x2[2] / b[2])], $2 = g ? 4 : 1, S = [...l, u, h / $2], I2 = S.length, T3 = [...d, h, w / $2], A2 = T3.length, D3 = [m2, u, w / $2], z3 = [{ type: 6, data: u }, { type: 6, data: w }, { type: 6, data: h }]; Ge2(t, z3), z3.push(...V(p, S, T3)); let H3 = ["rank", "rank"], W2 = e.length > 2; W2 && (z3.push(...V(e[2].dims)), H3.push("rank")), z3.push(...V(D3)); let X = (Y3) => { let pe2 = p.length, ue3 = Lr("batchDims", e[0].dataType, pe2, 1), le3 = ge(e[0].dataType), K = E("a", e[0].dataType, I2, $2), de2 = E("b", e[1].dataType, A2, $2), re2 = M("result", e[0].dataType, D3.length, $2), se2 = [K, de2]; if (W2) { let R = o ? $2 : 1; se2.push(E("bias", e[2].dataType, e[2].dims.length, R)); } let Z2 = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }]; Le(t, Z2); let ne2 = ge(re2.type.tensor), J3 = He2(t, re2.type.value, ne2), ke3 = Im($2, W2, J3, [ue3, K, de2, re2], [l, d, p], o); return ` ${Y3.registerUniforms(Z2).registerInternalVariables(ue3).declareVariables(...se2, re2)} ${ke3} ${g ? er(b, x2, le3, ue3) : tr(b, x2, le3, ue3)} `; }; return { name: "MatMul", shaderCache: { hint: `${b};${t.activation};${g};${o}`, inputDependencies: H3 }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: _[0], y: _[1], z: _[2] }, programUniforms: z3 }), getShaderSource: X }; }; }); ku2 = U(() => { "use strict"; Q(); dt2(); ie(); lt(); Jt2(); uo2(); rr2(); Cm2 = (e, t, r, n, o = false, i, a = 4, l = 4, d = 4, p = "f32") => { let m2 = (W2) => { switch (W2) { case 1: return "resData = x[xIndex];"; case 3: return `resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`; case 4: return "resData = x[xIndex / 4];"; default: throw new Error(`innerElementSize ${W2} is not supported.`); } }, u = (W2) => { switch (W2) { case 1: return "return w[row * i32(uniforms.w_shape[3]) + colIn];"; case 4: return "return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];"; default: throw new Error(`innerElementSize ${W2} is not supported.`); } }, h = e ? ` let coord = vec4(batch, xRow, xCol, xCh); ` : ` let coord = vec4(batch, xCh, xRow, xCol); `, w = e ? ` let coords = vec4( batch, row / outWidth, row % outWidth, col); ` : ` let coords = vec4( batch, row, col / outWidth, col % outWidth); `, g = e ? "i32(uniforms.x_shape[1])" : "i32(uniforms.x_shape[2])", b = e ? "i32(uniforms.x_shape[2])" : "i32(uniforms.x_shape[3])", x2 = e ? "row" : "col", _ = e ? "col" : "row", $2 = ` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; let outRow = ${x2} / outWidth; let outCol = ${x2} % outWidth; let WRow = ${_} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${_} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${_} % inChannels; var resData = ${Ee(a, p)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${g} && xCol >= 0 && xCol < ${b}) { ${h} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${m2(a)} } return resData;`, S = e ? t && n ? ` let col = colIn * ${a}; ${$2}` : ` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${$2} } return ${Ee(a, p)}(0.0);` : n && r ? ` let col = colIn * ${a}; ${$2}` : ` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${$2} } return ${Ee(a, p)}(0.0);`, I2 = `${u(l)}`, T3 = Ee(d, p), A2 = e ? Ee(a, p) : Ee(l, p), D3 = e ? Ee(l, p) : Ee(a, p), z3 = He2(i, T3, p); return ` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A2} { ${e ? S : I2} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${D3} { ${e ? I2 : S} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${T3}) { let col = colIn * ${d}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; ${w} ${Zr(o)} ${z3} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`; }, Eu2 = (e, t, r, n, o, i, a, l) => { let d = t.format === "NHWC", p = d ? e[0].dims[3] : e[0].dims[1], m2 = r[0], u = d ? r[2] : r[3], h = d ? r[1] : r[2], w = d ? r[3] : r[1], g = d && (p % 4 === 0 || p % 3 === 0) && w % 4 === 0, b = d ? w : u * h, x2 = d ? u * h : w, _ = [8, 8, 1], $2 = n <= 8 ? [4, 1, 1] : [4, 4, 1], S = [Math.ceil(b / _[0] / $2[0]), Math.ceil(x2 / _[1] / $2[1]), Math.ceil(m2 / _[2] / $2[2])]; ve("verbose", () => `[conv2d_mm_webgpu] dispatch = ${S}`); let I2 = g ? d && p % 4 !== 0 ? 3 : 4 : 1, T3 = _[1] * $2[1], A2 = _[0] * $2[0], D3 = Math.max(_[0] * I2, _[1]), z3 = n % T3 === 0, H3 = o % A2 === 0, W2 = i % D3 === 0, X = g ? [I2, 4, 4] : [1, 1, 1], Y3 = [{ type: 6, data: n }, { type: 6, data: o }, { type: 6, data: i }, { type: 6, data: [t.pads[0], t.pads[1]] }, { type: 6, data: t.strides }, { type: 6, data: t.dilations }]; Ge2(t, Y3), Y3.push(...V(e[0].dims, e[1].dims)); let pe2 = ["rank", "rank"]; a && (Y3.push(...V(e[2].dims)), pe2.push("rank")), Y3.push(...V(r)); let ue3 = (le3) => { let K = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }, { name: "pad", type: "i32", length: 2 }, { name: "stride", type: "i32", length: 2 }, { name: "dilation", type: "i32", length: 2 }]; Le(t, K); let de2 = g ? 4 : 1, re2 = ge(e[0].dataType), se2 = ` fn setOutputAtIndex(flatIndex : i32, value : ${g ? `vec4<${re2}>` : re2}) { result[flatIndex] = ${g ? `vec4<${re2}>` : re2}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g ? `vec4<${re2}>` : re2}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${g ? "/ 4" : ""}, value); }`, Z2 = E("x", e[0].dataType, e[0].dims.length, I2 === 3 ? 1 : I2), ne2 = E("w", e[1].dataType, e[1].dims.length, de2), J3 = [Z2, ne2], ke3 = M("result", e[0].dataType, r.length, de2); if (a) { let R = E("bias", e[2].dataType, e[2].dims.length, de2); J3.push(R), se2 += ` fn getBiasByOutputCoords(coords : vec4) -> ${g ? `vec4<${re2}>` : re2} { return bias[coords.${d ? "w" : "y"}${g ? "/ 4" : ""}]; }`; } return ` ${Qr("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${le3.registerUniforms(K).declareVariables(...J3, ke3)} ${se2} ${Cm2(d, z3, H3, W2, a, t, X[0], X[1], X[2], re2)} ${g ? er($2, _, re2, void 0, !d, D3) : tr($2, _, re2, void 0, !d, D3, false, void 0, l)}`; }; return { name: "Conv2DMatMul", shaderCache: { hint: `${t.cacheKey};${I2};${g};${z3};${H3};${W2};${T3};${A2};${D3}`, inputDependencies: pe2 }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: S[0], y: S[1], z: S[2] }, programUniforms: Y3 }), getShaderSource: ue3 }; }; }); Bu = U(() => { "use strict"; Q(); dt2(); ae(); ie(); lt(); Jt2(); Tm2 = (e) => { let t = 1; for (let r = 0; r < e.length; r++) t *= e[r]; return t; }, Pu = (e) => typeof e == "number" ? [e, e, e] : e, en = (e, t) => t <= 1 ? e : e + (e - 1) * (t - 1), Am2 = (e, t, r, n = 1) => { let o = en(t, n); return Math.floor((e[0] * (r - 1) - r + o) / 2); }, Ou = (e, t, r, n, o) => { o == null && (o = Am2(e, t[0], n[0])); let i = [0, 0, 0, r]; for (let a = 0; a < 3; a++) e[a] + 2 * o >= t[a] && (i[a] = Math.trunc((e[a] - t[a] + 2 * o) / n[a] + 1)); return i; }, Em2 = (e, t, r, n, o, i, a, l, d, p) => { let m2, u, h, w; if (e === "VALID" && (e = 0), typeof e == "number") { m2 = { top: e, bottom: e, left: e, right: e, front: e, back: e }; let g = Ou([t, r, n, 1], [l, d, p], 1, [o, i, a], e); u = g[0], h = g[1], w = g[2]; } else if (Array.isArray(e)) { if (!e.every((b, x2, _) => b === _[0])) throw Error(`Unsupported padding parameter: ${e}`); m2 = { top: e[0], bottom: e[1], left: e[2], right: e[3], front: e[4], back: e[5] }; let g = Ou([t, r, n, 1], [l, d, p], 1, [o, i, a], e[0]); u = g[0], h = g[1], w = g[2]; } else if (e === "SAME_UPPER") { u = Math.ceil(t / o), h = Math.ceil(r / i), w = Math.ceil(n / a); let g = (u - 1) * o + l - t, b = (h - 1) * i + d - r, x2 = (w - 1) * a + p - n, _ = Math.floor(g / 2), $2 = g - _, S = Math.floor(b / 2), I2 = b - S, T3 = Math.floor(x2 / 2), A2 = x2 - T3; m2 = { top: S, bottom: I2, left: T3, right: A2, front: _, back: $2 }; } else throw Error(`Unknown padding parameter: ${e}`); return { padInfo: m2, outDepth: u, outHeight: h, outWidth: w }; }, Du = (e, t, r, n, o, i = false, a = "channelsLast") => { let l, d, p, m2, u; if (a === "channelsLast") [l, d, p, m2, u] = e; else if (a === "channelsFirst") [l, u, d, p, m2] = e; else throw new Error(`Unknown dataFormat ${a}`); let [h, , w, g, b] = t, [x2, _, $2] = Pu(r), [S, I2, T3] = Pu(n), A2 = en(w, S), D3 = en(g, I2), z3 = en(b, T3), { padInfo: H3, outDepth: W2, outHeight: X, outWidth: Y3 } = Em2(o, d, p, m2, x2, _, $2, A2, D3, z3), pe2 = i ? h * u : h, ue3 = [0, 0, 0, 0, 0]; return a === "channelsFirst" ? ue3 = [l, pe2, W2, X, Y3] : a === "channelsLast" && (ue3 = [l, W2, X, Y3, pe2]), { batchSize: l, dataFormat: a, inDepth: d, inHeight: p, inWidth: m2, inChannels: u, outDepth: W2, outHeight: X, outWidth: Y3, outChannels: pe2, padInfo: H3, strideDepth: x2, strideHeight: _, strideWidth: $2, filterDepth: w, filterHeight: g, filterWidth: b, effectiveFilterDepth: A2, effectiveFilterHeight: D3, effectiveFilterWidth: z3, dilationDepth: S, dilationHeight: I2, dilationWidth: T3, inShape: e, outShape: ue3, filterShape: t }; }, zu2 = (e, t, r, n, o, i) => { let a = i === "channelsLast", l = a ? e[0].dims[3] : e[0].dims[1], d = false, p = [64, 1, 1], m2 = { x: r.map(($2, S) => S) }, u = [Math.ceil(Tm2(m2.x.map(($2) => r[$2])) / p[0]), 1, 1]; ve("verbose", () => `[conv3d_naive_webgpu] dispatch = ${u}`); let h = d ? a && l % 4 !== 0 ? 3 : 4 : 1, w = k2.size(r), g = [{ type: 12, data: w }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: t.strides }, { type: 12, data: t.dilations }]; Ge2(t, g), g.push(...V(e[0].dims, e[1].dims)); let b = ["rank", "rank"], x2 = e.length === 3; x2 && (g.push(...V(e[2].dims)), b.push("rank")), g.push(...V(r)); let _ = ($2) => { let S = [{ name: "output_size", type: "u32" }, { name: "filter_dims", type: "u32", length: n.length }, { name: "pads", type: "u32", length: o.length }, { name: "strides", type: "u32", length: t.strides.length }, { name: "dilations", type: "u32", length: t.dilations.length }]; Le(t, S); let I2 = d ? 4 : 1, T3 = ge(e[0].dataType), A2 = E("x", e[0].dataType, e[0].dims.length, h === 3 ? 1 : h), D3 = E("W", e[1].dataType, e[1].dims.length, I2), z3 = [A2, D3], H3 = M("result", e[0].dataType, r.length, I2), W2 = ""; if (x2) { let pe2 = E("bias", e[2].dataType, e[2].dims.length, I2); z3.push(pe2), W2 += ` fn getBiasByOutputCoords(coords : array) -> ${d ? `vec4<${T3}>` : T3} { return bias[${a ? G2("coords", 4, 5) : G2("coords", 1, 5)}${d ? "/ 4" : ""}]; }`; } let X = Ee(h, T3), Y3 = He2(t, X, T3); return ` ${W2} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${A2.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${D3.getByIndices("aIndices")}; } ${$2.registerUniforms(S).declareVariables(...z3, H3)} ${$2.mainStart()} ${$2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${H3.offsetToIndices("global_idx")}; let batch = ${G2("coords", 0, A2.rank)}; let d2 = ${a ? G2("coords", A2.rank - 1, A2.rank) : G2("coords", 1, A2.rank)}; let xFRCCorner = vec3(${a ? G2("coords", 1, A2.rank) : G2("coords", 2, A2.rank)}, ${a ? G2("coords", 2, A2.rank) : G2("coords", 3, A2.rank)}, ${a ? G2("coords", 3, A2.rank) : G2("coords", 4, A2.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${a ? G2("uniforms.x_shape", 1, A2.rank) : G2("uniforms.x_shape", 2, A2.rank)}; let xShapeZ = ${a ? G2("uniforms.x_shape", 2, A2.rank) : G2("uniforms.x_shape", 3, A2.rank)}; let xShapeW = ${a ? G2("uniforms.x_shape", 3, A2.rank) : G2("uniforms.x_shape", 4, A2.rank)}; let xShapeU = ${a ? G2("uniforms.x_shape", 4, A2.rank) : G2("uniforms.x_shape", 1, A2.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${a ? `let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); ` : `let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${a ? `value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);` : `value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${a ? `let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); ` : `let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${a ? `let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); ` : `let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${x2 ? "value = value + getBiasByOutputCoords(coords)" : ""}; ${Y3} result[global_idx] = f32(value); }`; }; return { name: "Conv3DNaive", shaderCache: { hint: `${t.cacheKey};${a};${h};${x2}`, inputDependencies: b }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: u[0], y: u[1], z: u[2] }, programUniforms: g }), getShaderSource: _ }; }; }); Mu2 = U(() => { "use strict"; Q(); ae(); ie(); co2(); lt(); lo2 = (e, t, r) => { let n = e.length > 2, o = n ? "value += b[output_channel];" : "", i = e[0].dims, a = e[1].dims, l = a[0] / t.group, d = t.format === "NHWC", p = tn(i, a, t.dilations, t.pads, t.strides, d), m2 = k2.size(p), u = [{ type: 12, data: m2 }, { type: 12, data: t.dilations }, { type: 12, data: [t.strides[0], t.strides[1]] }, { type: 12, data: [t.pads[0], t.pads[1]] }, { type: 12, data: l }]; Ge2(t, u), u.push(...V(i, a)); let h = ["rank", "rank"]; n && (u.push(...V(e[2].dims)), h.push("rank")), u.push(...V(p)); let w = (g) => { let b = M("output", e[0].dataType, p.length), x2 = ge(b.type.tensor), _ = He2(t, b.type.value, x2), $2 = E("x", e[0].dataType, i.length), S = E("w", e[1].dataType, a.length), I2 = [$2, S]; n && I2.push(E("b", e[2].dataType, e[2].dims.length)); let T3 = [{ name: "output_size", type: "u32" }, { name: "dilations", type: "u32", length: t.dilations.length }, { name: "strides", type: "u32", length: 2 }, { name: "pads", type: "u32", length: 2 }, { name: "output_channels_per_group", type: "u32" }]; return Le(t, T3), ` ${g.registerUniforms(T3).declareVariables(...I2, b)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${b.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${d ? 3 : 1}]; let xRCCorner: vec2 = vec2(outputIndices[${d ? 1 : 2}], outputIndices[${d ? 2 : 3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${b.type.value} = ${b.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[${d ? 1 : 2}]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[${d ? 2 : 3}]) { continue; } let xVal = ${d ? $2.get("batch", "xHeight", "xWidth", "input_channel") : $2.get("batch", "input_channel", "xHeight", "xWidth")}; let wVal = ${S.get("output_channel", "wInChannel", "wHeight", "wWidth")}; value += xVal*wVal; } } } ${o} ${_} ${b.setByOffset("global_idx", "value")} }`; }; return { name: "GroupedConv", shaderCache: { hint: t.cacheKey, inputDependencies: h }, getRunData: () => ({ outputs: [{ dims: r ? r(p) : p, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(m2 / 64) }, programUniforms: u }), getShaderSource: w }; }, Ru2 = (e, t, r) => { let n = e.length > 2, o = $e2(r[3]), i = $e2(r[2]), a = k2.size(r) / o / i, l = [e[0].dims[0], e[0].dims[1], e[0].dims[2], e[0].dims[3] / o], d = [e[1].dims[0], e[1].dims[1], e[1].dims[2], e[1].dims[3] / o], p = [r[0], r[1], r[2], r[3] / o], m2 = [{ type: 12, data: a }, { type: 6, data: [t.strides[0], t.strides[1]] }, { type: 6, data: [t.pads[0], t.pads[1]] }]; Ge2(t, m2), m2.push(...V(l, d, p)); let u = (i - 1) * t.strides[1] + d[1], h = (w) => { let g = M("output", e[0].dataType, p.length, o), b = ge(g.type.tensor), x2 = He2(t, g.type.value, b), _ = E("x", e[0].dataType, l.length, o), $2 = E("w", e[1].dataType, d.length, o), S = [_, $2]; n && S.push(E("b", e[2].dataType, e[2].dims, o)); let I2 = n ? "value += b[output_channel];" : "", T3 = [{ name: "output_size", type: "u32" }, { name: "strides", type: "i32", length: 2 }, { name: "pads", type: "i32", length: 2 }]; return Le(t, T3), ` ${w.registerUniforms(T3).declareVariables(...S, g)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${i}u; let col = (index1 % width1) * ${i}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${_.type.value}, ${u}>; var values: array<${g.type.value}, ${i}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${d[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${u}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${_.get("batch", "u32(x_height)", "u32(x_width)", "input_channel")}; } else { x_vals[i] = ${_.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${d[1]}; w_width++) { let w_val = ${$2.get("w_height", "w_width", "0", "output_channel")}; for (var i = 0u; i < ${i}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${i}u; i++) { var value = values[i]; ${I2} ${x2} ${g.set("batch", "row", "col + i", "output_channel", "value")}; } }`; }; return { name: "GroupedConv-Vectorize", shaderCache: { hint: `${t.cacheKey};${o};${i};${u};${d[0]};${d[1]}`, inputDependencies: n ? ["rank", "rank", "type"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: m2 }), getShaderSource: h }; }; }); mo2 = U(() => { "use strict"; Q(); ae(); rr2(); ie(); lt(); po2 = (e, t, r, n, o = false) => { let i = e[0].dims, a = e[1].dims, l = i[i.length - 2], d = a[a.length - 1], p = i[i.length - 1], m2 = $e2(d), u = $e2(p), h = $e2(l), w = k2.size(r) / m2 / h, g = e.length > 2, b = n ? n.slice(0, -2) : r.slice(0, -2), _ = [k2.size(b), l, d], $2 = [{ type: 12, data: w }, { type: 12, data: l }, { type: 12, data: d }, { type: 12, data: p }]; Ge2(t, $2), $2.push(...V(b, i, a)), g && $2.push(...V(e[2].dims)), $2.push(...V(_)); let S = (I2) => { let T3 = Lr("batch_dims", e[0].dataType, b.length), A2 = E("a", e[0].dataType, i.length, u), D3 = E("b", e[1].dataType, a.length, m2), z3 = M("output", e[0].dataType, _.length, m2), H3 = ge(z3.type.tensor), W2 = He2(t, z3.type.value, H3), X = [A2, D3], Y3 = ""; if (g) { let Z2 = o ? m2 : 1; X.push(E("bias", e[2].dataType, e[2].dims.length, Z2)), Y3 = `${o ? `value += bias[col / ${Z2}];` : `value += ${z3.type.value}(bias[row + i]);`}`; } let pe2 = i.slice(0, -2), ue3 = a.slice(0, -2), le3 = Nt2(pe2, b), K = Nt2(ue3, b), de2 = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }]; Le(t, de2); let re2 = (Z2, ne2) => { let J3 = Z2.rank, ke3 = Z2.name; if (J3 === 2) return `var ${ke3}_indices = ${Z2.type.indices}(0u, 0u);`; let R = T3.rank, F2 = `var ${ke3}_indices: ${Z2.type.indices};`; for (let ce3 = J3 - 2 - 1, Re2 = R - 1; ce3 >= 0; ce3--, Re2--) F2 += ` ${ke3}_indices[${ce3}] = ${R > 1 ? `batch_indices[${Re2}]` : "batch_indices"};`; return ne2.forEach((ce3) => { F2 += ` ${ke3}_indices[${ce3}] = 0;`; }), F2 += `${ke3}_indices[${J3 - 2}] = 0u; ${ke3}_indices[${J3 - 1}] = 0u;`, F2; }, se2 = () => { let Z2 = `var a_data: ${A2.type.value};`; for (let ne2 = 0; ne2 < u; ne2++) Z2 += ` let b_data${ne2} = b[(b_offset + (k + ${ne2}) * uniforms.N + col) / ${m2}];`; for (let ne2 = 0; ne2 < h; ne2++) { Z2 += `a_data = a[(a_offset + (row + ${ne2}) * uniforms.K + k) / ${u}];`; for (let J3 = 0; J3 < u; J3++) Z2 += ` values[${ne2}] = fma(${D3.type.value}(a_data${u === 1 ? "" : `[${J3}]`}), b_data${J3}, values[${ne2}]); `; } return Z2; }; return ` ${I2.registerUniforms(de2).registerInternalVariables(T3).declareVariables(...X, z3)} ${I2.mainStart()} ${I2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let col = (global_idx % (uniforms.N / ${m2})) * ${m2}; var index1 = global_idx / (uniforms.N / ${m2}); let stride1 = uniforms.M / ${h}; let row = (index1 % stride1) * ${h}; let batch = index1 / stride1; ${r.length === 2 ? "" : `let batch_indices = ${T3.offsetToIndices("batch")};`} ${re2(A2, le3)} let a_offset = ${A2.indicesToOffset("a_indices")}; ${re2(D3, K)} let b_offset = ${D3.indicesToOffset("b_indices")}; var values: array<${z3.type.value}, ${h}>; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${se2()} } for (var i = 0u; i < ${h}u; i++) { var value = values[i]; ${Y3} ${W2} let cur_indices = ${z3.type.indices}(batch, row + i, col); let offset = ${z3.indicesToOffset("cur_indices")}; ${z3.setByOffset(`offset / ${m2}`, "value")}; } } `; }; return { name: "MatMulNaive", shaderCache: { hint: `${t.activation};${m2};${u};${h};${o}`, inputDependencies: g ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(w / 64) }, programUniforms: $2 }), getShaderSource: S }; }, km2 = (e) => { if (!e || e.length !== 2) throw new Error("MatMul requires 2 inputs."); if (e[0].dims[e[0].dims.length - 1] !== e[1].dims[e[1].dims.length - 2]) throw new Error("shared dimension does not match."); }, Uu = (e) => { km2(e.inputs); let t = tt2.calcShape(e.inputs[0].dims, e.inputs[1].dims, true); if (!t) throw new Error("Can't use matmul on the given tensors"); let r = t[t.length - 1], n = e.inputs[0].dims[e.inputs[0].dims.length - 1]; r < 8 && n < 8 ? e.compute(po2(e.inputs, { activation: "" }, t)) : e.compute(Jr(e.inputs, { activation: "" }, t)); }; }); co2 = U(() => { "use strict"; ae(); ku2(); Bu(); rr2(); Mu2(); lt(); mo2(); Et(); tn = (e, t, r, n, o, i) => { let a = e[0], l = e.slice(i ? 1 : 2, i ? 3 : 4), d = l.length, p = t[0], u = t.slice(2).map((g, b) => g + (g - 1) * (r[b] - 1)), w = l.map((g, b) => g + n[b] + n[b + d]).map((g, b) => Math.floor((g - u[b] + o[b]) / o[b])); return w.splice(0, 0, a), w.splice(i ? 3 : 1, 0, p), w; }, fo2 = [2, 3, 1, 0], Pm2 = (e, t) => { if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (e[0].dims.length > 5) throw new Error("greater than 5D is not supported"); if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input"); let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[1] * t.group; if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); if (e.length === 3 && (e[2].dims.length !== 1 || e[1].dims[0] !== e[2].dims[0])) throw new Error("invalid bias"); let o = e[0].dims.length - 2; if (t.dilations.length !== o) throw new Error(`dilations should be ${o}D`); if (t.strides.length !== o) throw new Error(`strides should be ${o}D`); if (t.pads.length !== o * 2) throw new Error(`pads should be ${o * 2}D`); if (t.kernelShape.length !== 0 && t.kernelShape.length !== e[1].dims.length - 2) throw new Error("invalid kernel shape"); }, ho2 = (e, t) => { let r = e.kernelShape.slice(); for (let i = 2; i < t[1].dims.length; ++i) r[i - 2] === 0 && (r[i - 2] = t[1].dims[i]); let n = e.pads.slice(); Ct.adjustPadsBasedOnAutoPad(t[0].dims, e.strides, e.dilations, r, n, e.format === "NHWC", e.autoPad); let o = Object.assign({}, e); return Object.assign(o, { kernelShape: r, pads: n }), o; }, go2 = (e) => { let t = Xr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], o = e.dilations, i = e.group, a = e.kernel_shape, l = e.pads, d = e.strides, p = e.w_is_const(); return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, pads: l, strides: d, wIsConst: p, ...t, cacheKey: `${e.format};${t.activation};` }; }, Om2 = (e, t, r) => { let n = ho2(r, t), o = r.format === "NHWC"; if (r.group !== 1) { if (!e.adapterInfo.isArchitecture("ampere") && o && t[1].dims[0] === r.group && t[1].dims[1] === 1 && r.dilations[0] === 1 && r.dilations[1] === 1) { let D3 = tn(t[0].dims, t[1].dims, r.dilations, n.pads, r.strides, o), z3 = e.kernelCustomData.wT ?? e.compute(Ue2(t[1], fo2), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = z3); let H3 = [t[0], z3]; t.length === 3 && H3.push(t[2]), e.compute(Ru2(H3, n, D3), { inputs: H3 }); } else e.compute(lo2(t, n)); return; } let i = t.length === 3, a = t[0].dims[o ? 1 : 2], l = t[0].dims[o ? 2 : 3], d = t[0].dims[o ? 3 : 1], p = t[1].dims[2], m2 = t[1].dims[3], u = tn(t[0].dims, t[1].dims, r.dilations, n.pads, r.strides, o), h = u[o ? 1 : 2], w = u[o ? 2 : 3], g = u[o ? 3 : 1], b = o && p === a && m2 === l && r.pads[0] === 0 && r.pads[1] === 0; if (b || p === 1 && m2 === 1 && r.dilations[0] === 1 && r.dilations[1] === 1 && r.strides[0] === 1 && r.strides[1] === 1 && r.pads[0] === 0 && r.pads[1] === 0) { let A2 = u[0], D3, z3, H3, W2 = []; if (o) { let pe2 = e.kernelCustomData.wT ?? e.compute(Ue2(t[1], fo2), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; if (r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = pe2), b) { let ue3 = a * l * d; D3 = t[0].reshape([1, A2, ue3]), z3 = pe2.reshape([1, ue3, g]), H3 = [1, A2, g]; } else D3 = t[0].reshape([A2, a * l, d]), z3 = pe2.reshape([1, d, g]), H3 = [A2, h * w, g]; W2.push(D3), W2.push(z3); } else D3 = t[0].reshape([A2, d, a * l]), z3 = t[1].reshape([1, g, d]), H3 = [A2, g, h * w], W2.push(z3), W2.push(D3); i && W2.push(t[2]); let X = H3[2], Y3 = W2[0].dims[W2[0].dims.length - 1]; X < 8 && Y3 < 8 ? e.compute(po2(W2, n, u, H3, o), { inputs: W2 }) : e.compute(Jr(W2, n, u, H3, o), { inputs: W2 }); return; } let x2 = true, _ = e.kernelCustomData.wT ?? e.compute(Ue2(t[1], fo2), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = _); let $2 = [t[0], _]; i && $2.push(t[2]); let S = o ? h * w : g, I2 = o ? g : h * w, T3 = p * m2 * d; e.compute(Eu2($2, n, u, S, I2, T3, i, x2), { inputs: $2 }); }, Dm2 = (e, t) => { let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])]; e.inputs.length === 3 && n.push(e.inputs[2]); let o = [0, t.pads[0], 0, t.pads[1]], i = [1].concat(t.strides), a = [1].concat(t.dilations), l = [1].concat(t.kernelShape), d = ho2({ ...t, pads: o, strides: i, dilations: a, kernelShape: l }, n); e.compute(lo2(n, d, (p) => r ? [p[0], p[2], p[3]] : [])); }, zm2 = (e, t, r) => { let n = r.format === "NHWC" ? "channelsLast" : "channelsFirst", o = ho2(r, t), i = r.autoPad === "NOTSET" ? r.pads : r.autoPad, a = Du(t[0].dims, t[1].dims, r.strides, r.dilations, i, false, n); e.compute(zu2(t, o, a.outShape, [a.filterDepth, a.filterHeight, a.filterWidth], [a.padInfo.front, a.padInfo.top, a.padInfo.left], n)); }, yo2 = (e, t) => { Pm2(e.inputs, t), e.inputs[0].dims.length === 3 ? Dm2(e, t) : e.inputs[0].dims.length === 5 ? zm2(e, e.inputs, t) : Om2(e, e.inputs, t); }; }); Nu = U(() => { "use strict"; Q(); dt2(); ie(); lt(); Jt2(); uo2(); rr2(); Bm2 = (e, t = false, r, n, o = 4) => { let i = (_) => { switch (_) { case 1: return "return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];"; case 4: return ` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${n}(v0, v1, v2, v3); `; default: throw new Error(`innerElementSize ${_} is not supported.`); } }, a = e ? ` let coord = vec4(batch, iXR, iXC, xCh); ` : ` let coord = vec4(batch, xCh, iXR, iXC); `, l = e ? ` let coords = vec4( batch, row / outWidth, row % outWidth, col); ` : ` let coords = vec4( batch, row, col / outWidth, col % outWidth); `, d = e ? "i32(uniforms.x_shape[1])" : "i32(uniforms.x_shape[2])", p = e ? "i32(uniforms.x_shape[2])" : "i32(uniforms.x_shape[3])", m2 = e ? "row" : "col", u = e ? "col" : "row", h = ` let inChannels = ${e ? "i32(uniforms.x_shape[3])" : "i32(uniforms.x_shape[1])"}; let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; let outRow = ${m2} / outWidth; let outCol = ${m2} % outWidth; let WRow = ${u} / (uniforms.filter_dims[1] * inChannels); let WCol = ${u} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { return ${n}(0.0); } if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { return ${n}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${u} % inChannels; ${a} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`, w = e ? ` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${h} } return ${n}(0.0);` : ` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${h} } return ${n}(0.0);`, g = ` let col = colIn * ${o}; let inChannels = ${e ? "i32(uniforms.x_shape[3])" : "i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e ? "row < uniforms.dim_inner && col < uniforms.dim_b_outer" : "row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${i(o)} } return ${n}(0.0); `, b = He2(r, n); return ` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { ${e ? w : g} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { ${e ? g : w} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; ${l} ${Zr(t)} ${b} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value; } }`; }, Vu2 = (e, t, r, n, o, i, a, l) => { let d = t.format === "NHWC", p = d ? e[0].dims[3] : e[0].dims[1], m2 = r[0], u = d ? r[2] : r[3], h = d ? r[1] : r[2], w = d ? r[3] : r[1], g = d && p % 4 === 0 && p % 3 && w % 4 === 0, b = d ? w : u * h, x2 = d ? u * h : w, _ = [8, 8, 1], $2 = n <= 8 ? [4, 1, 1] : [4, 4, 1], S = [Math.ceil(b / _[0] / $2[0]), Math.ceil(x2 / _[1] / $2[1]), Math.ceil(m2 / _[2] / $2[2])]; ve("verbose", () => `[conv_backprop_mm_webgpu] dispatch = ${S}`); let I2 = g ? 4 : 1, T3 = Math.max(_[0] * I2, _[1]), A2 = g ? 4 : 1, D3 = [t.kernelShape[d ? 1 : 2], t.kernelShape[d ? 2 : 3]], z3 = [D3[0] + (t.dilations[0] <= 1 ? 0 : (D3[0] - 1) * (t.dilations[0] - 1)), D3[1] + (t.dilations[1] <= 1 ? 0 : (D3[1] - 1) * (t.dilations[1] - 1))], H3 = [z3[0] - 1 - Math.floor((t.pads[0] + t.pads[2]) / 2), z3[1] - 1 - Math.floor((t.pads[1] + t.pads[3]) / 2)], W2 = [{ type: 6, data: n }, { type: 6, data: o }, { type: 6, data: i }, { type: 6, data: t.strides }, { type: 6, data: t.dilations }, { type: 6, data: D3 }, { type: 6, data: H3 }]; Ge2(t, W2), W2.push(...V(e[0].dims, e[1].dims)); let X = ["rank", "rank"]; a && (W2.push(...V(e[2].dims)), X.push("rank")), W2.push(...V(r)); let Y3 = (pe2) => { let ue3 = E("x", e[0].dataType, e[0].dims.length, A2), le3 = E("w", e[1].dataType, e[1].dims.length, 1), K = M("result", e[0].dataType, r.length, A2), de2 = [ue3, le3], re2 = ""; if (a) { let ne2 = E("bias", e[2].dataType, e[2].dims.length, A2); de2.push(ne2), re2 += ` fn getBiasByOutputCoords(coords : vec4) -> ${ne2.type.value} { return bias[coords.${d ? "w" : "y"}${g ? "/ 4" : ""}]; }`; } let se2 = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }, { name: "strides", type: "i32", length: 2 }, { name: "dilations", type: "i32", length: 2 }, { name: "filter_dims", type: "i32", length: D3.length }, { name: "pads", type: "i32", length: H3.length }]; Le(t, se2); let Z2 = ge(e[0].dataType, 1); if (Z2 !== "f16" && Z2 !== "f32") throw new Error(`elemType ${Z2} is not supported.`); return ` ${Qr("uniforms.result_strides")} ${pe2.registerUniforms(se2).declareVariables(...de2, K)}; ${re2} ${Bm2(d, a, t, ue3.type.value, I2)} ${g ? er($2, _, Z2, void 0, !d, T3) : tr($2, _, Z2, void 0, !d, T3, false, void 0, l)}`; }; return { name: "Conv2DTransposeMatMul", shaderCache: { hint: `${t.cacheKey};${$2};${_};${g}`, inputDependencies: X }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: S[0], y: S[1], z: S[2] }, programUniforms: W2 }), getShaderSource: Y3 }; }; }); Wu2 = U(() => { "use strict"; Q(); dt2(); ae(); ie(); Rm2 = (e, t, r, n, o, i = false, a, l, d = false) => { let p = d ? 1 : 2, m2 = d ? 2 : 3, u = d ? 3 : 1, h = i ? 2 : 1, w = ` fn setOutputAtIndex(flatIndex : u32, value : ${i ? `vec4<${a}>` : a}) { result[flatIndex] = ${i ? `vec4<${a}>` : a}(value); }`; n && (w += ` fn getBiasByOutputCoords(coords : vec4) -> ${i ? `vec4<${a}>` : a} { return bias[coords.${d ? "w" : "y"}${i ? "/ 4" : ""}]; }`); let g = i ? 4 : 1, b = E("W", t[1].dataType, t[1].dims.length, g), x2 = E("Dy", t[0].dataType, t[0].dims.length, g), _ = [x2, b]; n && _.push(E("bias", t[2].dataType, [r[u]].length, g)); let $2 = M("result", t[0].dataType, r.length, g), S = `{ let batch: u32 = ${o ? "global_id.z" : "workgroup_id.z"} / uniforms.result_shape[1]; let r = ${o ? "global_id.z" : "workgroup_id.z"} % uniforms.result_shape[1]; let c = ${o ? "global_id.y" : "workgroup_id.y"} * ${h}; let d1: u32 = ${o ? "global_id.x" : "workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${h}>; for (var i = 0; i < ${h}; i++) { dotProd[i] = vec4<${a}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y); let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1", "d2")}; let wValue1 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 1", "d2")}; let wValue2 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 2", "d2")}; let wValue3 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 3", "d2")}; var xValue = ${x2.get("batch", "idyR", "idyC", "d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${x2.get("batch", "idyR", "idyC2", "d2")}; dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${u}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1", "d2")}; let wValue1 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 1", "d2")}; let wValue2 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 2", "d2")}; let wValue3 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 3", "d2")}; var xValue = ${x2.get("batch", "idyR", "idyC", "d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1", "d2")}; let wValue1 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 1", "d2")}; let wValue2 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 2", "d2")}; let wValue3 = ${b.get("u32(wRPerm)", "u32(wCPerm)", "d1 + 3", "d2")}; var xValue = ${x2.get("batch", "idyR", "idyC2", "d2")}; let tmpval = vec4<${a}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${h}; i = i + 1) { let value = dotProd[i] + ${n ? "bias[c+i]" : `vec4<${a}>(0.0)`}; ${$2.set("batch", "r", "c + i", "d1", "value")}; } }`, I2 = ` let outputIndices = ${$2.offsetToIndices("global_idx")}; let batch = ${$2.indicesGet("outputIndices", 0)}; let d1 = ${$2.indicesGet("outputIndices", u)}; let r = ${$2.indicesGet("outputIndices", p)}; let c = ${$2.indicesGet("outputIndices", m2)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${a}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${m2}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${d ? x2.get("batch", "idyR", "idyC", "inputChannel") : x2.get("batch", "inputChannel", "idyR", "idyC")}; let wValue = ${b.get("inputChannel", "wOutChannel", "u32(wRPerm)", "u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${n ? "bias[d1]" : `${a}(0.0)`}; ${$2.setByOffset("global_idx", "value")}; `; return ` ${e.registerUniforms(l).declareVariables(..._, $2)} ${w} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${i ? S : I2}}`; }, bo2 = (e, t, r) => { let n = e.length > 2, o = t.outputShape, i = k2.size(o), a = [Math.ceil(i / 64), 1, 1]; ve("verbose", () => `[conv2d_backprop_webgpu] dispatch = ${a}`); let l = t.format === "NHWC", d = ["rank", "rank"], p = [t.strides[0], t.strides[1]], m2 = [t.kernelShape[l ? 1 : 2], t.kernelShape[l ? 2 : 3]], u = [t.dilations[0], t.dilations[1]], h = [m2[0] + (t.dilations[0] <= 1 ? 0 : (t.kernelShape[l ? 1 : 2] - 1) * (t.dilations[0] - 1)), m2[1] + (t.dilations[1] <= 1 ? 0 : (t.kernelShape[l ? 2 : 3] - 1) * (t.dilations[1] - 1))], w = [h[0] - 1 - Math.floor((t.pads[0] + t.pads[2]) / 2), h[1] - 1 - Math.floor(t.pads[1] + t.pads[3]) / 2], g = false, b = t.group, x2 = e[1].dims, _ = x2[0] / b, $2 = x2[1], S = [{ type: 12, data: i }, { type: 12, data: p }, { type: 12, data: m2 }, { type: 12, data: u }, { type: 12, data: h }, { type: 6, data: w }, { type: 12, data: _ }, { type: 12, data: $2 }, ...V(e[0].dims, e[1].dims)]; n && (S.push(...V(e[2].dims)), d.push("rank")), S.push(...V(o)); let I2 = a[1] === 1 && a[2] === 1, T3 = (A2) => { let D3 = [{ name: "output_size", type: "u32" }, { name: "strides", type: "u32", length: p.length }, { name: "filter_dims", type: "u32", length: m2.length }, { name: "dilations", type: "u32", length: m2.length }, { name: "effective_filter_dims", type: "u32", length: h.length }, { name: "pads", type: "i32", length: w.length }, { name: "input_channels_per_group", type: "u32" }, { name: "output_channels_per_group", type: "u32" }], z3 = ge(e[0].dataType); return `${Rm2(A2, e, o, n, I2, g, z3, D3, l)}`; }; return { name: "ConvTranspose2D", shaderCache: { hint: `${t.cacheKey};`, inputDependencies: d }, getRunData: () => ({ dispatchGroup: { x: a[0], y: a[1], z: a[2] }, outputs: [{ dims: r ? r(o) : o, dataType: e[0].dataType }], programUniforms: S }), getShaderSource: T3 }; }; }); Fu2 = U(() => { "use strict"; Nu(); Wu2(); lt(); Et(); Mm2 = (e, t, r, n, o, i) => (e - 1) * t + r + (n - 1) * o + 1 - i, Um2 = (e, t, r, n, o) => { let i = Math.floor(e / 2); t === "SAME_UPPER" ? (r[n] = i, r[o] = e - i) : t === "SAME_LOWER" && (r[n] = e - i, r[o] = i); }, Vm2 = (e, t, r, n, o, i, a, l, d, p) => { let m2 = e.length - 2, u = p.length === 0; if (d.length === 0) for (let g = 0; g < m2; ++g) d.push(0); let h = e[0], w = t[l ? 3 : 1] * o; for (let g = 0, b = e.length - m2 - (l ? 1 : 0); g < m2; ++g, ++b) { let x2 = e[b], _ = u ? x2 * a[g] : p[g], $2 = Mm2(x2, a[g], i[g], t[b], r[g], _); Um2($2, n, i, g, g + m2), u && p.push(a[g] * (x2 - 1) + d[g] + (t[b] - 1) * r[g] + 1 - i[g] - i[g + m2]); } p.splice(0, 0, h), p.splice(l ? 3 : 1, 0, w); }, Hu2 = (e, t) => { let r = e.kernelShape.slice(); if (e.kernelShape.length === 0 || e.kernelShape.reduce((u, h) => u * h, 1) === 0) { r.length = 0; for (let u = 2; u < t[1].dims.length; ++u) r.push(t[1].dims[u]); } let n = e.format === "NHWC"; r.splice(0, 0, t[1].dims[0]), r.splice(n ? 3 : 1, 0, t[1].dims[1]); let o = e.pads.slice(), i = e.outputShape.slice(), a = e.outputPadding.slice(), l = t[0].dims, d = e.dilations.slice(); if (d.reduce((u, h) => u + h, 0) === 0) { let u = t[0].dims.length - 2; d = new Array(u).fill(1); } let p = e.strides.slice(); if (p.reduce((u, h) => u + h, 0) === 0) { let u = t[0].dims.length - 2; p = new Array(u).fill(1); } Vm2(l, r, d, e.autoPad, e.group, o, p, n, a, i); let m2 = Object.assign({}, e); return Object.assign(m2, { kernelShape: r, pads: o, outputPadding: a, outputShape: i, dilations: d, strides: p }), m2; }, Gu = (e) => { let t = Xr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][typeof e.autoPad > "u" ? 0 : e.autoPad], o = e.dilations, i = e.group, a = e.kernelShape, l = e.pads, d = e.strides, p = e.wIsConst(), m2 = e.outputPadding, u = e.outputShape; return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, outputPadding: m2, outputShape: u, pads: l, strides: d, wIsConst: p, ...t, cacheKey: `${e.format};${t.activation};` }; }, Nm2 = (e, t) => { if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (e[0].dims.length !== 4 && e[0].dims.length !== 3) throw new Error("currently only support 2-dimensional conv"); if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input"); let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[0]; if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); let o = e[1].dims[1] * t.group; if (e.length === 3 && (e[2].dims.length !== 1 || e[2].dims[0] !== o)) throw new Error("invalid bias"); let i = e[0].dims.length - 2; if (t.dilations.reduce((m2, u) => m2 + u, 0) > 0 && t.dilations.length !== i) throw new Error(`dilations should be ${i}D`); if (t.strides.reduce((m2, u) => m2 + u, 0) > 0 && t.strides.length !== i) throw new Error(`strides should be ${i}D`); if (t.pads.reduce((m2, u) => m2 + u, 0) > 0 && t.pads.length !== i * 2) throw new Error(`pads should be ${i * 2}D`); if (t.outputPadding.length !== i && t.outputPadding.length !== 0) throw new Error(`output_padding should be ${i}D`); if (t.kernelShape.reduce((m2, u) => m2 + u, 0) > 0 && t.kernelShape.length !== 0 && t.kernelShape.length !== e[1].dims.length - 2) throw new Error("invalid kernel shape"); if (t.outputShape.length !== 0 && t.outputShape.length !== e[0].dims.length - 2) throw new Error("invalid output shape"); }, Wm2 = [2, 3, 1, 0], Hm2 = (e, t, r) => { let n = Hu2(r, t), o = r.format === "NHWC", i = n.outputShape, a = i[o ? 3 : 1], l = t[0].dims[o ? 3 : 1]; if (n.group !== 1 || a === 1 && l === 1) { e.compute(bo2(t, n)); return; } let d = i[o ? 1 : 2], p = i[o ? 2 : 3], m2 = t[1].dims[2], u = t[1].dims[3], h = o ? d * p : a, w = o ? a : d * p, g = m2 * u * l, b = true, x2 = e.kernelCustomData.wT ?? e.compute(Ue2(t[1], Wm2), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = x2); let _ = [t[0], x2], $2 = t.length === 3; $2 && (!o && t[2].dims.length === 1 ? _.push(t[2].reshape([t[2].dims[0], 1, 1])) : _.push(t[2])), e.compute(Vu2(_, n, i, h, w, g, $2, b), { inputs: _ }); }, Gm2 = (e, t) => { let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])]; e.inputs.length === 3 && n.push(e.inputs[2]); let o = t.kernelShape; (o.length === 0 || o[0] === 0) && (o = [e.inputs[1].dims[2]]); let i = t.dilations; (i.length === 0 || i[0] === 0) && (i = [1]); let a = t.strides; (a.length === 0 || a[0] === 0) && (a = [1]); let l = t.pads; l.length === 0 && (l = [0, 0]), l = [0, l[0], 0, l[1]], a = [1].concat(a), i = [1].concat(i), o = [1].concat(o); let d = Hu2({ ...t, pads: l, strides: a, dilations: i, kernelShape: o }, n); e.compute(bo2(n, d, (p) => r ? [p[0], p[2], p[3]] : [p[0], p[1], p[3]])); }, Lu2 = (e, t) => { Nm2(e.inputs, t), e.inputs[0].dims.length === 3 ? Gm2(e, t) : Hm2(e, e.inputs, t); }; }); Ku2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); Lm2 = (e, t, r, n) => { let o = k2.size(t), i = t.length, a = E("input", e, i), l = M("output", e, i), d = r.dataType === 6 ? r.getInt32Array()[0] : Number(r.getBigInt64Array()[0]), p = k2.normalizeAxis(d, i), m2 = (u) => { let h = ` i32(${a.indicesGet("inputIndices", "uniforms.axis")}) `, w = G2("uniforms.input_shape", "uniforms.axis", i), g = n.reverse ? h + (n.exclusive ? " + 1" : "") : "0", b = n.reverse ? w : h + (n.exclusive ? "" : " + 1"); return ` ${u.registerUniform("outputSize", "u32").registerUniform("axis", "u32").declareVariables(a, l)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${l.offsetToIndices("global_idx")}; var sum = ${l.type.value}(0); let first : i32 = ${g}; let last : i32 = ${b}; for (var i : i32 = first; i < last; i++) { ${a.indicesSet("inputIndices", "uniforms.axis", "u32(i)")}; sum = sum + ${a.getByIndices("inputIndices")}; } ${l.setByOffset("global_idx", "sum")}; }`; }; return { name: "CumSum", shaderCache: { hint: n.cacheKey, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: t, dataType: e }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: [{ type: 12, data: o }, { type: 12, data: p }, ...V(t, t)] }), getShaderSource: m2 }; }, qu2 = (e, t) => { let r = e.inputs[0].dims, n = e.inputs[0].dataType, o = e.inputs[1]; e.compute(Lm2(n, r, o, t), { inputs: [0] }); }, ju2 = (e) => { let t = e.exclusive === 1, r = e.reverse === 1; return te({ exclusive: t, reverse: r }); }; }); Zu2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); Fm2 = (e) => { if (!e || e.length !== 1) throw new Error("DepthToSpace requires 1 input."); if (e[0].dims.length !== 4) throw new Error("DepthToSpace requires 4D input."); }, qm2 = (e, t, r, n) => { let o = []; o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`); for (let i = 0; i < t; ++i) o.push(r.indicesSet("a", e[i], `i[${i}]`)); return o.push("return a;}"), o.join(` `); }, jm2 = (e, t) => { let r, n, o, i, a, l, d = t.format === "NHWC", p = t.blocksize, m2 = t.mode === "DCR"; d ? ([r, n, o, i] = e.dims, a = m2 ? [r, n, o, p, p, i / p ** 2] : [r, n, o, i / p ** 2, p, p], l = m2 ? [0, 1, 3, 2, 4, 5] : [0, 1, 4, 2, 5, 3]) : ([r, n, o, i] = [e.dims[0], e.dims[2], e.dims[3], e.dims[1]], a = m2 ? [r, p, p, i / p ** 2, n, o] : [r, i / p ** 2, p, p, n, o], l = m2 ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3]); let u = e.reshape(a), h = u.dims.length, w = e.dataType, g = E("a", w, h), b = M("output", w, h), x2 = (_) => ` ${_.registerUniform("output_size", "u32").declareVariables(g, b)} ${qm2(l, h, g, b)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${b.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${b.setByOffset("global_idx", g.getByIndices("aIndices"))} }`; return { name: "DepthToSpace", shaderCache: { hint: `${e.dims};${t.blocksize};${t.mode}`, inputDependencies: ["rank"] }, getRunData: (_) => { let $2 = d ? [r, n * p, o * p, i / p ** 2] : [r, i / p ** 2, n * p, o * p], S = k2.size($2), I2 = u.dims, T3 = k2.sortBasedOnPerm(I2, l); return { outputs: [{ dims: $2, dataType: _[0].dataType }], dispatchGroup: { x: Math.ceil(S / 64) }, programUniforms: [{ type: 12, data: S }, ...V(I2, T3)] }; }, getShaderSource: x2 }; }, Yu2 = (e, t) => { Fm2(e.inputs), e.compute(jm2(e.inputs[0], t)); }, Xu2 = (e) => te({ blocksize: e.blocksize, mode: e.mode, format: e.format }); }); rd2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); wo = "[a-zA-Z]|\\.\\.\\.", rn = "(" + wo + ")+", Qu2 = "^" + rn + "$", Km2 = "(" + rn + ",)*" + rn, Ym2 = "^" + Km2 + "$", vo = class { constructor(t = -1) { this.symbolToIndices = /* @__PURE__ */ new Map(), this.inputIndex = t; } addSymbol(t, r) { let n = this.symbolToIndices.get(t); n === void 0 ? n = [r] : n.push(r), this.symbolToIndices.set(t, n); } }, $o = class { constructor(t, r) { this.equation = r; this.hasEllipsis = false, this.symbolToInfo = /* @__PURE__ */ new Map(), this.lhs = new Array(), this.outputDims = []; let [n, o] = r.includes("->") ? r.split("->", 2) : [r, ""]; if (!n.match(RegExp(Ym2))) throw new Error("Invalid LHS term"); if (n.split(",").forEach((l, d) => { let p = t[d].dims.slice(); if (!l.match(RegExp(Qu2))) throw new Error("Invalid LHS term"); let m2 = this.processTerm(l, true, p, d); this.lhs.push(m2); }), o === "") o += [...this.symbolToInfo.entries()].filter(([l, d]) => d.count === 1 || l === "...").map(([l]) => l).join(""); else if (!o.match(RegExp(rn))) throw new Error("Invalid RHS"); o.match(RegExp(wo, "g"))?.forEach((l) => { if (l === "...") this.outputDims = this.outputDims.concat(this.ellipsisDims); else { let d = this.symbolToInfo.get(l); if (d === void 0) throw new Error("Invalid RHS symbol"); this.outputDims.push(d.dimValue); } }), this.rhs = this.processTerm(o, false, this.outputDims); } addSymbol(t, r, n) { let o = this.symbolToInfo.get(t); if (o !== void 0) { if (o.dimValue !== r && o.count !== 1) throw new Error("Dimension mismatch"); o.count++, o.inputIndices.push(n); } else o = { count: 1, dimValue: r, inputIndices: [n] }; this.symbolToInfo.set(t, o); } processTerm(t, r, n, o = -1) { let i = n.length, a = false, l = [], d = 0; if (!t.match(RegExp(Qu2)) && !r && t !== "") throw new Error("Invalid LHS term"); let p = t.match(RegExp(wo, "g")), m2 = new vo(o); return p?.forEach((u, h) => { if (u === "...") { if (a) throw new Error("Only one ellipsis is allowed per input term"); a = true; let w = i - p.length + 1; if (w < 0) throw new Error("Ellipsis out of bounds"); if (l = n.slice(d, d + w), this.hasEllipsis) { if (this.ellipsisDims.length !== l.length || this.ellipsisDims.toString() !== l.toString()) throw new Error("Ellipsis dimensions mismatch"); } else if (r) this.hasEllipsis = true, this.ellipsisDims = l; else throw new Error("Ellipsis must be specified in the LHS"); for (let g = 0; g < l.length; g++) { let b = String.fromCharCode("0".charCodeAt(0) + g); m2.addSymbol(b, h + g), this.addSymbol(b, n[d++], o); } } else m2.addSymbol(u, h + (this.hasEllipsis ? this.ellipsisDims.length - 1 : 0)), this.addSymbol(u, n[d++], o); }), m2; } }, Ju2 = (e) => e + "_max", Xm2 = (e, t, r, n) => { let i = e.map((m2) => m2.length).map((m2, u) => E(`input${u}`, t, m2)), a = k2.size(n), l = M("output", t, n.length), d = [...r.symbolToInfo.keys()].filter((m2) => !r.rhs.symbolToIndices.has(m2)), p = (m2) => { let u = [], h = "var prod = 1.0;", w = "var sum = 0.0;", g = "sum += prod;", b = [], x2 = [], _ = [], $2 = [], S = r.symbolToInfo.size === r.rhs.symbolToIndices.size; r.symbolToInfo.forEach((T3, A2) => { if (r.rhs.symbolToIndices.has(A2)) { let D3 = r.rhs.symbolToIndices.get(A2)?.[0]; D3 !== void 0 && r.lhs.forEach((z3, H3) => { if (T3.inputIndices.includes(H3)) { let W2 = z3.symbolToIndices.get(A2); if (W2 === void 0) throw new Error("Invalid symbol error"); W2.forEach((X) => { u.push(`${i[H3].indicesSet(`input${H3}Indices`, X, l.indicesGet("outputIndices", D3))}`); }); } }); } else r.lhs.forEach((D3, z3) => { if (T3.inputIndices.includes(z3)) { let H3 = D3.symbolToIndices.get(A2); if (H3 === void 0) throw new Error("Invalid symbol error"); H3.forEach((W2) => { b.push(`${i[z3].indicesSet(`input${z3}Indices`, W2, `${A2}`)}`); }), $2.push(`prod *= ${i[z3].getByIndices(`input${z3}Indices`)};`); } }), x2.push(`for(var ${A2}: u32 = 0; ${A2} < uniforms.${Ju2(A2)}; ${A2}++) {`), _.push("}"); }); let I2 = S ? [...u, `let sum = ${i.map((T3, A2) => T3.getByIndices(`input${A2}Indices`)).join(" * ")};`] : [...u, w, ...x2, ...b, h, ...$2, g, ..._]; return ` ${m2.registerUniforms(d.map((T3) => ({ name: `${Ju2(T3)}`, type: "u32" }))).registerUniform("outputSize", "u32").declareVariables(...i, l)} ${m2.mainStart()} ${m2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${l.offsetToIndices("global_idx")}; ${i.map((T3, A2) => `var input${A2}Indices: ${i[A2].type.indices};`).join(` `)} ${I2.join(` `)}; ${l.setByOffset("global_idx", "sum")}; }`; }; return { name: "Einsum", shaderCache: { hint: r.equation, inputDependencies: e.map(() => "rank") }, getRunData: () => { let m2 = d.filter((h) => r.symbolToInfo.has(h)).map((h) => ({ type: 12, data: r.symbolToInfo.get(h)?.dimValue || 0 })); m2.push({ type: 12, data: a }); let u = e.map((h, w) => [...V(h)]).reduce((h, w) => h.concat(w), m2); return u.push(...V(n)), { outputs: [{ dims: n, dataType: t }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: u }; }, getShaderSource: p }; }, ed2 = (e, t) => { let r = new $o(e.inputs, t.equation), n = r.outputDims, o = e.inputs.map((i, a) => i.dims); e.compute(Xm2(o, e.inputs[0].dataType, r, n)); }, td2 = (e) => { let t = e.equation.replace(/\s+/g, ""); return te({ equation: t }); }; }); id2 = U(() => { "use strict"; Q(); ae(); ie(); Zm2 = (e) => { if (!e || e.length !== 2) throw new Error("Expand requires 2 input."); let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = r.length < t.length ? 0 : r.length - t.length, o = t.length < r.length ? 0 : t.length - r.length; for (; n < r.length && o < t.length; ++n, ++o) if (r[n] !== t[o] && r[n] !== 1 && t[o] !== 1) throw new Error("Expand requires shape to be broadcastable to input"); }, nd2 = (e, t) => { let r = e.length - t.length, n = []; for (let o = 0; o < r; ++o) n.push(e[o]); for (let o = 0; o < t.length; ++o) n.push(t[o] === 1 ? e[o + r] : t[o]); return n; }, Qm2 = (e, t) => e.length > t.length ? nd2(e, t) : nd2(t, e), Jm2 = (e) => { let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = Qm2(t, r), o = e[0].dataType, i = o === 9 ? 4 : 1, a = Math.ceil(k2.size(n) / i), l = (p) => { let m2 = E("input", o, t.length, i), u = M("output", o, n.length, i), h; if (o === 9) { let w = (g, b, x2 = "") => ` let outputIndices${b} = ${u.offsetToIndices(`outputOffset + ${b}u`)}; let offset${b} = ${m2.broadcastedIndicesToOffset(`outputIndices${b}`, u)}; let index${b} = offset${b} / 4u; let component${b} = offset${b} % 4u; ${g}[${b}] = ${x2}(${m2.getByOffset(`index${b}`)}[component${b}]); `; h = ` let outputOffset = global_idx * ${i}; var data = vec4(0); ${w("data", 0, "u32")} ${w("data", 1, "u32")} ${w("data", 2, "u32")} ${w("data", 3, "u32")} ${u.setByOffset("global_idx", "data")} }`; } else h = ` let outputIndices = ${u.offsetToIndices("global_idx")}; let inputOffset = ${m2.broadcastedIndicesToOffset("outputIndices", u)}; ${u.setByOffset("global_idx", m2.getByOffset("inputOffset"))} }`; return ` ${p.registerUniform("vec_size", "u32").declareVariables(m2, u)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h}`; }, d = [{ type: 12, data: a }, ...V(t, n)]; return { name: "Expand", shaderCache: { hint: `${n.length}`, inputDependencies: ["rank"] }, getShaderSource: l, getRunData: () => ({ outputs: [{ dims: n, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: d }) }; }, od2 = (e) => { Zm2(e.inputs), e.compute(Jm2(e.inputs), { inputs: [0] }); }; }); sd2 = U(() => { "use strict"; Q(); ae(); ie(); Yr(); ef2 = (e) => { let t = e[0].dataType, r = k2.size(e[0].dims), n = k2.size(e[1].dims), o = n % 4 === 0, i = (a) => { let l = E("x", t, [1], 4), d = E("bias", t, [1], 4), p = M("y", t, [1], 4), m2 = [{ name: "output_vec_size", type: "u32" }, { name: "bias_size", type: "u32" }], u = (w) => ` let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size; let bias${w} = ${d.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`, h = o ? ` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};` : `${u(0)}${u(1)}${u(2)}${u(3)} let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`; return `${a.registerUniforms(m2).declareVariables(l, d, p)} ${ao2(Oe2(t))} ${a.mainStart(Tt2)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${l.getByOffset("global_idx")}; ${h} let x_in = x + bias; ${p.setByOffset("global_idx", so2("x_in"))} }`; }; return { name: "FastGeluWithBias", shaderCache: { hint: `${o}`, inputDependencies: ["type", "type"] }, getShaderSource: i, getRunData: (a) => ({ outputs: [{ dims: a[0].dims, dataType: a[0].dataType }], programUniforms: [{ type: 12, data: Math.ceil(r / 4) }, { type: 12, data: n }], dispatchGroup: { x: Math.ceil(r / Tt2 / 4) } }) }; }, ad2 = (e) => { e.inputs.length < 2 || k2.size(e.inputs[1].dims) === 0 ? su2(e) : e.compute(ef2(e.inputs)); }; }); ld2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); tf2 = (e) => { if (!e || e.length !== 2) throw new Error("Gather requires 2 inputs."); }, rf2 = (e, t) => { let r = e[0].dims, n = e[1].dims, o = r.length, i = k2.normalizeAxis(t.axis, o), a = r.slice(0); a.splice(i, 1, ...n); let l = r[i], d = e[0].dataType === 9 ? 4 : 1, p = Math.ceil(k2.size(a) / d), m2 = [{ type: 12, data: p }, { type: 6, data: l }, { type: 12, data: i }, ...V(e[0].dims, e[1].dims, a)], u = (h) => { let w = E("data", e[0].dataType, e[0].dims.length, d), g = E("inputIndices", e[1].dataType, e[1].dims.length), b = M("output", e[0].dataType, a.length, d), x2 = ($2) => { let S = n.length, I2 = `var indicesIndices${$2} = ${g.type.indices}(0);`; for (let T3 = 0; T3 < S; T3++) I2 += `${S > 1 ? `indicesIndices${$2}[${T3}]` : `indicesIndices${$2}`} = ${a.length > 1 ? `outputIndices${$2}[uniforms.axis + ${T3}]` : `outputIndices${$2}`};`; I2 += ` var idx${$2} = ${g.getByIndices(`indicesIndices${$2}`)}; if (idx${$2} < 0) { idx${$2} = idx${$2} + uniforms.axisDimLimit; } var dataIndices${$2} : ${w.type.indices}; `; for (let T3 = 0, A2 = 0; T3 < o; T3++) T3 === i ? (I2 += `${o > 1 ? `dataIndices${$2}[${T3}]` : `dataIndices${$2}`} = u32(idx${$2});`, A2 += S) : (I2 += `${o > 1 ? `dataIndices${$2}[${T3}]` : `dataIndices${$2}`} = ${a.length > 1 ? `outputIndices${$2}[${A2}]` : `outputIndices${$2}`};`, A2++); return I2; }, _; if (e[0].dataType === 9) { let $2 = (S, I2, T3 = "") => ` let outputIndices${I2} = ${b.offsetToIndices(`outputOffset + ${I2}u`)}; ${x2(I2)}; let offset${I2} = ${w.indicesToOffset(`dataIndices${I2}`)}; let index${I2} = offset${I2} / 4u; let component${I2} = offset${I2} % 4u; ${S}[${I2}] = ${T3}(${w.getByOffset(`index${I2}`)}[component${I2}]); `; _ = ` let outputOffset = global_idx * ${d}; var value = vec4(0); ${$2("value", 0, "u32")} ${$2("value", 1, "u32")} ${$2("value", 2, "u32")} ${$2("value", 3, "u32")} ${b.setByOffset("global_idx", "value")} `; } else _ = ` let outputIndices = ${b.offsetToIndices("global_idx")}; ${x2("")}; let value = ${w.getByIndices("dataIndices")}; ${b.setByOffset("global_idx", "value")}; `; return ` ${h.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(w, g, b)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${_} }`; }; return { name: "Gather", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: a, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: m2 }), getShaderSource: u }; }, ud2 = (e) => te({ axis: e.axis }), dd = (e, t) => { let r = e.inputs; tf2(r), e.compute(rf2(e.inputs, t)); }; }); md = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); nf2 = (e) => { if (!e || e.length !== 2) throw new Error("GatherElements requires 2 inputs."); if (e[0].dims.length < 1) throw new Error("GatherElements requires that the data input be rank >= 1."); if (e[0].dims.length !== e[1].dims.length) throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`); }, of2 = (e, t) => { let r = e[0].dims, n = e[0].dataType, o = r.length, i = e[1].dims, a = e[1].dataType, l = k2.normalizeAxis(t.axis, o), d = r[l], p = i.slice(0), m2 = k2.size(p), u = E("input", n, o), h = E("indicesInput", a, i.length), w = M("output", n, p.length), g = [{ type: 12, data: m2 }, { type: 6, data: d }, { type: 12, data: l }]; return g.push(...V(r, i, p)), { name: "GatherElements", shaderCache: { inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: p, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(m2 / 64) }, programUniforms: g }), getShaderSource: (_) => ` ${_.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(u, h, w)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${w.offsetToIndices("global_idx")}; var idx = ${h.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${u.type.indices}(outputIndices); ${u.indicesSet("inputIndices", "uniforms.axis", "u32(idx)")}; let value = ${u.getByIndices("inputIndices")}; ${w.setByOffset("global_idx", "value")}; }` }; }, cd2 = (e) => te({ axis: e.axis }), pd = (e, t) => { let r = e.inputs; nf2(r), e.compute(of2(e.inputs, t)); }; }); gd = U(() => { "use strict"; Q(); ae(); ie(); af2 = (e) => { if (!e) throw new Error("Input is missing"); if (e.length < 2 || e.length > 3) throw new Error("Invaid input number."); if (e.length === 3 && e[2].dims.length > 2) throw new Error("Invalid input shape of C"); if (e[0].dataType !== e[1].dataType || e.length === 3 && e[0].dataType !== e[2].dataType) throw new Error("Input types are mismatched"); }, sf2 = (e, t) => { let r = e[0].dims.slice(), n = e[1].dims.slice(), [o, i, a] = Wr2.getShapeOfGemmResult(r, t.transA, n, t.transB, e.length === 3 ? e[2].dims : void 0), l = [o, i]; if (!l) throw new Error("Can't use gemm on the given tensors"); let d = k2.size(l), p = [{ type: 12, data: d }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: a }, { type: 1, data: t.alpha }, { type: 1, data: t.beta }], m2 = ["type", "type"]; e.length === 3 && (p.push(...V(e[2].dims)), m2.push("rank")), p.push(...V(l)); let u = (h) => { let w = ""; t.transA && t.transB ? w = "value += a[k * uniforms.M + m] * b[n * uniforms.K + k];" : t.transA && !t.transB ? w = "value += a[k * uniforms.M + m] * b[k * uniforms.N + n];" : !t.transA && t.transB ? w = "value += a[m * uniforms.K + k] * b[n * uniforms.K + k];" : !t.transA && !t.transB && (w = "value += a[m * uniforms.K + k] * b[k * uniforms.N + n];"); let g = t.alpha === 1 ? "" : "value *= uniforms.alpha;", b = E("a", e[0].dataType, e[0].dims), x2 = E("b", e[1].dataType, e[1].dims), _ = b.type.value, $2 = null, S = [b, x2]; e.length === 3 && ($2 = E("c", e[2].dataType, e[2].dims.length), S.push($2)); let I2 = M("output", e[0].dataType, l.length); S.push(I2); let T3 = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }, { name: "alpha", type: "f32" }, { name: "beta", type: "f32" }]; return ` ${h.registerUniforms(T3).declareVariables(...S)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${_}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${w} } ${g} ${(() => $2 != null ? `let cOffset = ${$2.broadcastedIndicesToOffset("vec2(m, n)", I2)}; value += ${_}(uniforms.beta) * ${$2.getByOffset("cOffset")};` : "")()} output[global_idx] = value; }`; }; return { name: "Gemm", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: m2 }, getRunData: () => ({ outputs: [{ dims: l, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: p }), getShaderSource: u }; }, fd2 = (e) => { let t = e.transA, r = e.transB, n = e.alpha, o = e.beta; return { transA: t, transB: r, alpha: n, beta: o, cacheKey: `${e.transA};${e.transB};${e.alpha === 1}` }; }, hd = (e, t) => { af2(e.inputs), e.compute(sf2(e.inputs, t)); }; }); _o = U(() => { "use strict"; Q(); ae(); Ce2(); Nr2(); jr(); ie(); Et(); Ve2 = (e, t) => e.length > t && e[t].dims.length > 0 && k2.size(e[t].dims) > 0 ? e[t] : void 0, lf2 = (e, t) => { let r = e[0], n = Ve2(e, 1), o = Ve2(e, 2), i = Ve2(e, 3), a = Ve2(e, 4), l = Ve2(e, 5), d = Ve2(e, 6), p = Ve2(e, 7); if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); let m2 = false, u = r.dims[0], h = r.dims[1], w = r.dims.length === 3 ? m2 ? r.dims[2] / 3 : r.dims[2] : t.numHeads * r.dims[4], g = h, b = 0, x2 = 0, _ = Math.floor(w / t.numHeads); if (d && p) { if (d.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions'); if (d.dims[0] !== u || d.dims[1] !== t.numHeads || d.dims[3] !== _) throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)'); if (p.dims[0] !== u || p.dims[1] !== t.numHeads || p.dims[3] !== _) throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)'); if (d.dims[2] !== p.dims[2]) throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)'); if (p.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions'); b = d.dims[2], x2 = d.dims[2]; } else if (d || p) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); let $2; if (n) { if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given'); if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions'); if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)'); if (n.dims.length === 3) { if (n.dims[2] !== r.dims[2]) throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)'); $2 = 2, g = n.dims[1]; } else if (n.dims.length === 5) { if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== _) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv'); if (o) throw new Error('Expect "value" be none when "key" has packed kv format.'); $2 = 5, g = n.dims[1]; } else { if (n.dims[1] !== t.numHeads || n.dims[3] !== _) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); $2 = 0, g = n.dims[2]; } } else { if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty'); if (r.dims.length === 5 && (r.dims[2] !== t.numHeads || r.dims[3] !== 3)) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); $2 = 3; } if (i) { if (i.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimension'); if (o && r.dims.length === 5 && r.dims[3] === 2) throw new Error("bias is not allowed for packed kv."); } let S = 0; if (a) { S = 8; let z3 = a.dims; throw z3.length === 1 ? z3[0] === u ? S = 1 : z3[0] === 3 * u + 2 && (S = 3) : z3.length === 2 && z3[0] === u && z3[1] === g && (S = 5), S === 8 ? new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)') : new Error("Mask not supported"); } let I2 = false, T3 = w; if (o) { if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)'); if (o.dims.length === 3) { if (g !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)'); T3 = o.dims[2]; } else { if (g !== o.dims[2]) throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)'); T3 = o.dims[1] * o.dims[3], I2 = true; } } let A2 = b + g, D3 = false; if (a) throw new Error("Key padding mask is not supported"); if (l) { if (l.dims.length !== 4) throw new Error('Input "relative_position_bias" is expected to have 4 dimensions'); if (l.dims[0] !== u && l.dims[0] !== 1 || l.dims[1] !== t.numHeads || l.dims[2] !== h || l.dims[3] !== A2) throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)'); } return { batchSize: u, sequenceLength: h, pastSequenceLength: b, kvSequenceLength: g, totalSequenceLength: A2, maxSequenceLength: x2, inputHiddenSize: 0, hiddenSize: w, vHiddenSize: T3, headSize: _, vHeadSize: Math.floor(T3 / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: S, scale: t.scale, broadcastResPosBias: D3, passPastInKv: I2, qkvFormat: $2 }; }, bd = (e) => te({ ...e }), yd = te({ perm: [0, 2, 1, 3] }), cf2 = (e, t, r, n, o, i, a) => { let l = [n, o, i], d = k2.size(l), p = [{ type: 12, data: d }, { type: 12, data: a }, { type: 12, data: i }], m2 = (u) => { let h = M("qkv_with_bias", t.dataType, l), w = E("qkv", t.dataType, l), g = E("bias", r.dataType, l), b = [{ name: "output_size", type: "u32" }, { name: "bias_offset", type: "u32" }, { name: "hidden_size", type: "u32" }]; return ` ${u.registerUniforms(b).declareVariables(w, g, h)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`; }; return e.compute({ name: "MultiHeadAttentionAddBias", shaderCache: { inputDependencies: ["type", "type"] }, getRunData: () => ({ outputs: [{ dims: l, dataType: t.dataType, gpuDataType: 0 }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: p }), getShaderSource: m2 }, { inputs: [t, r], outputs: [-1] })[0]; }, nr2 = (e, t, r, n, o, i, a, l) => { let d = i; if (a) { if (n === 1) throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV"); return d = cf2(e, i, a, t, n, r * o, l), d = d.reshape([t, n, r, o]), e.compute(Ue2(d, yd.perm), { inputs: [d], outputs: [-1] })[0]; } else return i.dims.length === 3 && (d = i.reshape([t, n, r, o])), e.compute(Ue2(d, yd.perm), { inputs: [d], outputs: [-1] })[0]; }, wd = (e, t) => { let r = lf2(e.inputs, t), n = e.inputs[0], o = Ve2(e.inputs, 1), i = Ve2(e.inputs, 2), a = Ve2(e.inputs, 3), l = Ve2(e.inputs, 4), d = Ve2(e.inputs, 5), p = Ve2(e.inputs, 6), m2 = Ve2(e.inputs, 7); if (n.dims.length === 5) throw new Error("Packed QKV is not implemented"); if (o?.dims.length === 5) throw new Error("Packed KV is not implemented"); let u = o && i && o.dims.length === 4 && i.dims.length === 4, h = nr2(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, n, a, 0); if (u) return Wt2(e, h, o, i, l, void 0, p, m2, d, r, t); if (!o || !i) throw new Error("key and value must be provided"); let w = nr2(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.headSize, o, a, r.hiddenSize), g = nr2(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.vHeadSize, i, a, 2 * r.hiddenSize); Wt2(e, h, w, g, l, void 0, p, m2, d, r, t); }; }); So = U(() => { "use strict"; Q(); ae(); ie(); vd = (e) => Array.from(e.getBigInt64Array(), Number), pf2 = (e) => { if (!e || e.length !== 2) throw new Error("Tile requires 2 inputs."); if (e[0].dataType !== 1 && e[0].dataType !== 10 && e[0].dataType !== 6 && e[0].dataType !== 12) throw new Error("Tile only support float, float16, int32, and uint32 data types"); if (e[1].dataType !== 7) throw new Error("Tile `repeats` input should be of int64 data type"); if (e[1].dims.length !== 1) throw new Error("Tile `repeats` input should be 1-D"); if (vd(e[1]).length !== e[0].dims.length) throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor"); }, mf2 = (e, t) => { let r = []; for (let n = 0; n < e.length; ++n) r.push(e[n] * t[n]); return r; }, xo2 = (e, t) => { let r = e[0].dims, n = t ?? vd(e[1]), o = mf2(r, n), i = k2.size(o), a = e[0].dataType, l = E("input", a, r.length), d = M("output", a, o.length), p = (m2) => ` const inputShape = ${l.indices(...r)}; ${m2.registerUniform("output_size", "u32").declareVariables(l, d)} ${m2.mainStart()} ${m2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${d.offsetToIndices("global_idx")}; var input_indices: ${l.type.indices}; for (var i = 0; i < ${r.length}; i++) { let input_dim_i = ${l.indicesGet("uniforms.input_shape", "i")}; let input_dim_value = ${d.indicesGet("output_indices", "i")} % input_dim_i; ${l.indicesSet("input_indices", "i", "input_dim_value")} } ${d.setByOffset("global_idx", l.getByIndices("input_indices"))} }`; return { name: "Tile", shaderCache: { hint: `${n}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: [{ type: 12, data: i }, ...V(e[0].dims, o)] }), getShaderSource: p }; }, $d = (e) => { pf2(e.inputs), e.compute(xo2(e.inputs), { inputs: [0] }); }; }); Cd = U(() => { "use strict"; Q(); ae(); Ce2(); jr(); ie(); _o(); So(); Et(); ff2 = (e, t) => { let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4]; if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); let l = false, d = r.dims[0], p = r.dims[1], m2 = r.dims.length === 3 ? l ? r.dims[2] / 3 : r.dims[2] : t.numHeads * r.dims[4], u = p, h = 0, w = 0, g = Math.floor(m2 / t.numHeads), b = i && i.dims.length !== 0, x2 = a && a.dims.length !== 0, _ = true; if (b && x2) { if (i.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions'); if (a.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions'); _ ? (h = i.dims[1], w = i.dims[1]) : (h = i.dims[2], w = i.dims[2]); } else if (b || x2) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); let $2; if (n) { if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given'); if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions'); if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)'); if (n.dims.length === 3) { if (r.dims[2] % n.dims[2] !== 0) throw new Error('Dimension 2 of "query" should be a multiple of "key"'); $2 = 2, u = n.dims[1]; } else if (n.dims.length === 5) { if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== g) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv'); if (o) throw new Error('Expect "value" be none when "key" has packed kv format.'); $2 = 5, u = n.dims[1]; } else { if (n.dims[1] !== t.numHeads || n.dims[3] !== g) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); $2 = 0, u = n.dims[2]; } } else { if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty'); if (r.dims.length === 5 && (r.dims[2] !== t.numHeads || r.dims[3] !== 3)) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); $2 = 3; } let S = 0, I2 = false, T3 = m2; if (o) { if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)'); if (o.dims.length === 3) { if (u !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)'); T3 = o.dims[2]; } else { if (u !== o.dims[2]) throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)'); T3 = o.dims[1] * o.dims[3], I2 = true; } } let A2 = h + u, D3 = false; return { batchSize: d, sequenceLength: p, pastSequenceLength: h, kvSequenceLength: u, totalSequenceLength: A2, maxSequenceLength: w, inputHiddenSize: 0, hiddenSize: m2, vHiddenSize: T3, headSize: g, vHeadSize: Math.floor(T3 / t.kvNumHeads), numHeads: t.numHeads, kvNumHeads: t.kvNumHeads, nReps: t.numHeads / t.kvNumHeads, pastPresentShareBuffer: false, maskType: S, scale: t.scale, broadcastResPosBias: D3, passPastInKv: I2, qkvFormat: $2, isPastkvBSNH: _ }; }, _d = (e, t, r, n) => { let o = [n.batchSize, n.totalSequenceLength, n.kvNumHeads, n.headSize], i = 4, a = k2.size(o) / i, l = n.totalSequenceLength, d = M("present_kv", r, o.length, i), p = E("new_kv", e.dataType, e.dims.length, i), m2 = t ? E("past_kv", t.dataType, t.dims.length, i) : void 0, u = Math.ceil(n.headSize / i), h = { x: l, y: e.dims[0], z: 1 }, w = t ? ["rank", "rank"] : ["rank"], g = [{ type: 12, data: a }, { type: 12, data: n.pastSequenceLength }, { type: 12, data: n.kvSequenceLength }, { type: 12, data: n.totalSequenceLength }], b = [p]; m2 ? (g.push(...V(e.dims), ...V(t.dims), ...V(o)), b.push(m2)) : g.push(...V(e.dims), ...V(o)); let x2 = [{ name: "output_size", type: "u32" }, { name: "past_seqlen", type: "u32" }, { name: "new_seqlen", type: "u32" }, { name: "present_seqlen", type: "u32" }], _ = ` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`, $2 = ` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`, S = t ? `if (s < past_seqlen) { ${_} } else if (s < past_seqlen + uniforms.new_seqlen) { ${$2} }` : `if (s < past_seqlen + uniforms.new_seqlen) { ${$2} }`, I2 = (T3) => ` ${T3.registerUniforms(x2).declareVariables(...b, d)} ${T3.mainStart([u, n.kvNumHeads, 1])} ${T3.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${d.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${n.kvNumHeads}u; let H = ${u}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${n.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${S} }`; return { name: "ConcatPastNew", shaderCache: { hint: `${n.kvNumHeads}${u}${!!t}`, inputDependencies: w }, getRunData: () => ({ outputs: [{ dims: o, dataType: r }], dispatchGroup: h, programUniforms: g }), getShaderSource: I2 }; }, Sd = (e) => te({ ...e }), hf2 = te({ perm: [0, 2, 1, 3] }), xd = (e, t, r, n, o) => { let i = t, a = n.kvNumHeads, l = n.nReps; return t.dims.length === 3 && n.kvSequenceLength !== 0 && (i = t.reshape([n.batchSize, n.kvSequenceLength, a, n.headSize])), r ? i = e.compute(_d(i, r, i.dataType, n), { inputs: [i, r], outputs: [n.isPastkvBSNH ? o : -1] })[0] : i = e.compute(_d(i, void 0, i.dataType, n), { inputs: [i], outputs: [n.isPastkvBSNH ? o : -1] })[0], l !== 1 && (i = e.compute(xo2([i], [1, 1, 1, l]), { inputs: [i], outputs: [-1] })[0], i = i.reshape([n.batchSize, n.totalSequenceLength, a * l, n.headSize])), e.compute(Ue2(i, hf2.perm), { inputs: [i], outputs: [-1] })[0]; }, Id = (e, t) => { let r = ff2(e.inputs, t); if (e.inputs[0].dims.length === 5) throw new Error("Packed QKV is not implemented"); if (e.inputs[1]?.dims.length === 5) throw new Error("Packed KV is not implemented"); let n = nr2(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, e.inputs[0], void 0, 0), o = e.inputs[3] && e.inputs[3].dims.length !== 0 ? e.inputs[3] : void 0, i = e.inputs[4] && e.inputs[4].dims.length !== 0 ? e.inputs[4] : void 0, a = xd(e, e.inputs[1], o, r, 1), l = xd(e, e.inputs[2], i, r, 2); Wt2(e, n, a, l, void 0, void 0, void 0, void 0, void 0, r, t); }; }); Ad = U(() => { "use strict"; Q(); ae(); ie(); gf2 = (e, t) => { let r = e[0].dims, n = r, o = 2, i = k2.sizeToDimension(r, o), a = k2.sizeFromDimension(r, o), l = $e2(a), d = a / l, p = [r[0], r[1], d], m2 = ["rank", "type", "type"], u = [{ type: 12, data: a }, { type: 12, data: d }]; u.push(...V(p, p)); let h = (w) => { let g = E("x", e[0].dataType, p.length, l), b = E("scale", e[1].dataType, e[1].dims), x2 = E("bias", e[2].dataType, e[2].dims), _ = M("output", e[0].dataType, p.length, l), $2 = [g, b, x2, _], S = g.type.value, I2 = l === 1 ? "f32" : `vec${l}`, T3 = 64, A2 = [{ name: "normSize", type: "u32" }, { name: "normPackedSize", type: "u32" }]; return ` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${I2}, ${T3}>; const workgroupSize = ${T3}u; ${w.registerUniforms(A2).declareVariables(...$2)} ${w.mainStart(T3)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${I2}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${I2}(${g.get("batch", "channel", "h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${Xe2("workgroupShared[0]", l)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${I2}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${I2}(${g.get("batch", "channel", "h")}) - ${I2}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${Xe2("workgroupShared[0]", l)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${b.getByOffset("channel")}); let channelShift = f32(${x2.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${g.get("batch", "channel", "h")} * ${S}(${I2}(channelScale)) + ${S}(${I2}(channelShift)); ${_.set("batch", "channel", "h", "value")}; } }`; }; return { name: "InstanceNormalization", shaderCache: { hint: `${t.epsilon};${l}`, inputDependencies: m2 }, getRunData: () => ({ outputs: [{ dims: n, dataType: e[0].dataType }], dispatchGroup: { x: i }, programUniforms: u }), getShaderSource: h }; }, yf2 = (e, t, r, n, o, i, a, l) => { let d = $e2(a), p = 64, m2 = d === 1 ? "vec2f" : `mat2x${d}f`, u = d === 1 ? "f32" : `vec${d}f`, h = (A2, D3) => `${m2}(${A2}, ${D3})`, w = o * a / d, g = Math.ceil(i / p), b = ["type"], x2 = [{ type: 12, data: g }, { type: 12, data: i }, { type: 12, data: Math.floor(a / d) }, { type: 12, data: Math.floor(i * a / d) }], _ = (A2) => { let D3 = E("input", t.dataType, t.dims, d); return ` ${A2.declareVariables(D3)} @group(0) @binding(1) var output : array<${m2}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${A2.mainStart(p)} let currentImageNumber = global_idx / ${p} / uniforms.C; let currentChannelNumber = (global_idx / ${p}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${gt2("f32", d)}; var squaredSum = ${gt2("f32", d)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${u}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${h("sum", "squaredSum")}; }`; }, $2 = e.compute({ name: "InstanceNormComputeMean", shaderCache: { hint: `${d}`, inputDependencies: b }, getRunData: () => ({ outputs: [{ dims: [o, a, p, 2], dataType: 1 }], dispatchGroup: { x: o * a / d }, programUniforms: x2 }), getShaderSource: _ }, { inputs: [t], outputs: [-1] })[0], S = [{ type: 12, data: w }, { type: 12, data: i }, { type: 12, data: Math.floor(a / d) }, { type: 12, data: Math.floor(p * a / d) }], I2 = ["type", "type", "type"], T3 = (A2) => { let D3 = E("scale", r.dataType, r.dims, d), z3 = E("bias", n.dataType, n.dims, d); return ` @group(0) @binding(0) var input : array<${m2}>; @group(0) @binding(1) var scale : array<${D3.type.storage}>; @group(0) @binding(2) var bias : array<${z3.type.storage}>; @group(0) @binding(3) var output : array<${m2}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${A2.mainStart()} ${A2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${gt2("f32", d)}; var squaredSum = ${gt2("f32", d)}; for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${p}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l})); let channelScale = invStdDev * ${u}(scale[currentChannelNumber]); let channelShift = ${u}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${h("channelScale", "channelShift")}; }`; }; return e.compute({ name: "InstanceNormComputeChannelScaleShift", shaderCache: { hint: `${d};${l}`, inputDependencies: I2 }, getRunData: () => ({ outputs: [{ dims: [o, a, 2], dataType: 1 }], dispatchGroup: { x: Math.ceil(w / 64) }, programUniforms: S }), getShaderSource: T3 }, { inputs: [$2, r, n], outputs: [-1] })[0]; }, bf2 = (e, t, r) => { let n = t[0].dims, o = n, i = n[0], a = n[n.length - 1], l = k2.sizeFromDimension(n, 1) / a, d = $e2(a), p = k2.size(o) / d, m2 = [{ type: 12, data: l }, { type: 12, data: Math.floor(a / d) }], u = ["type", "type"], h = yf2(e, t[0], t[1], t[2], i, l, a, r.epsilon), w = (g) => { let b = ge(t[0].dataType), x2 = d === 1 ? "vec2f" : `mat2x${d}f`, _ = d === 1 ? b : `vec${d}<${b}>`, $2 = E("input", t[0].dataType, t[0].dims, d), S = M("output", t[0].dataType, o, d); return ` @group(0) @binding(0) var input : array<${$2.type.storage}>; @group(0) @binding(1) var scaleInput : array<${x2}>; @group(0) @binding(2) var output : array<${S.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${g.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${_}(scale[0]), ${_}(scale[1])); }`; }; e.compute({ name: "InstanceNormalizationNHWC", shaderCache: { hint: `${d}`, inputDependencies: u }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: m2 }), getShaderSource: w }, { inputs: [t[0], h] }); }, Td = (e, t) => { t.format === "NHWC" ? bf2(e, e.inputs, t) : e.compute(gf2(e.inputs, t)); }; }); kd = U(() => { "use strict"; Q(); ae(); ie(); wf2 = (e) => { if (!e || e.length < 2) throw new Error("layerNorm requires at least 2 inputs."); }, vf2 = (e, t, r) => { let n = t.simplified, o = e[0].dims, i = e[1], a = !n && e[2], l = o, d = k2.normalizeAxis(t.axis, o.length), p = k2.sizeToDimension(o, d), m2 = k2.sizeFromDimension(o, d), u = k2.size(i.dims), h = a ? k2.size(a.dims) : 0; if (u !== m2 || a && h !== m2) throw new Error(`Size of X.shape()[axis:] == ${m2}. Size of scale and bias (if provided) must match this. Got scale size of ${u} and bias size of ${h}`); let w = []; for (let T3 = 0; T3 < o.length; ++T3) T3 < d ? w.push(o[T3]) : w.push(1); let g = $e2(m2), b = ["type", "type"], x2 = [{ type: 12, data: p }, { type: 1, data: m2 }, { type: 12, data: Math.floor(m2 / g) }, { type: 1, data: t.epsilon }]; a && b.push("type"); let _ = r > 1, $2 = r > 2, S = (T3) => { let A2 = ge(e[0].dataType), D3 = [E("x", e[0].dataType, e[0].dims, g), E("scale", i.dataType, i.dims, g)]; a && D3.push(E("bias", a.dataType, a.dims, g)), D3.push(M("output", e[0].dataType, l, g)), _ && D3.push(M("mean_data_output", 1, w)), $2 && D3.push(M("inv_std_output", 1, w)); let z3 = [{ name: "norm_count", type: "u32" }, { name: "norm_size", type: "f32" }, { name: "norm_size_vectorized", type: "u32" }, { name: "epsilon", type: "f32" }]; return ` ${T3.registerUniforms(z3).declareVariables(...D3)} ${T3.mainStart()} ${T3.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${gt2("f32", g)}; var mean_square_vector = ${gt2("f32", g)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${At(A2, g, "x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Xe2("mean_vector", g)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Xe2("mean_square_vector", g)} / uniforms.norm_size ${n ? "" : "- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${At(A2, g, "x[j + offset]")}; let f32scale = ${At(A2, g, "scale[j]")}; output[j + offset] = ${D3[0].type.value}((f32input ${n ? "" : "- mean"}) * inv_std_dev * f32scale ${a ? `+ ${At(A2, g, "bias[j]")}` : ""} ); } ${_ ? "mean_data_output[global_idx] = mean" : ""}; ${$2 ? "inv_std_output[global_idx] = inv_std_dev" : ""}; }`; }, I2 = [{ dims: l, dataType: e[0].dataType }]; return _ && I2.push({ dims: w, dataType: 1 }), $2 && I2.push({ dims: w, dataType: 1 }), { name: "LayerNormalization", shaderCache: { hint: `${g};${r};${n}`, inputDependencies: b }, getRunData: () => ({ outputs: I2, dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: x2 }), getShaderSource: S }; }, Ed = (e, t) => { wf2(e.inputs), e.compute(vf2(e.inputs, t, e.outputCount)); }; }); Dd = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); $f2 = (e, t) => { if (e.length < 3 || e.length > 4) throw new Error("MatMulNBits requires 3 or 4 inputs"); let r = e[0], n = r.dims.length; if (r.dims[n - 1] !== t.k) throw new Error("The last dim of input shape does not match the k value"); let o = Math.floor((t.k + t.blockSize - 1) / t.blockSize), i = t.blockSize / 8 * t.bits, a = e[1]; if (!k2.areEqual(a.dims, [t.n, o, i])) throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize"); let d = e[2].dims; if (k2.size(d) !== t.n * o) throw new Error("scales input size error."); if (e.length === 4) { let m2 = e[3].dims, u = t.bits > 4 ? t.n * o : t.n * Math.floor((o + 1) / 2); if (k2.size(m2) !== u) throw new Error("zeroPoints input size error."); } }, _f2 = (e, t, r, n) => { let o = e[0].dims, i = o.length, a = Math.floor((t.k + t.blockSize - 1) / t.blockSize), l = o[i - 2], d = t.k, p = t.n, m2 = o.slice(0, i - 2), u = k2.size(m2), w = t.blockSize / 8 * t.bits / 4, g = e[0].dataType, b = $e2(l), x2 = $e2(t.k), _ = $e2(w), $2 = It(g), S = l * a * $2, I2 = Math.floor(n / S), T3 = a <= r[0] && I2 > 0, A2 = !T3 || I2 >= 4 ? $e2(p) : I2 >= 2 && $e2(p) >= 2 ? 2 : 1, D3 = m2.concat([l, p]), z3 = k2.size(D3) / A2 / b, H3 = T3 ? [] : [{ type: 12, data: z3 }, { type: 12, data: t.blockSize }], W2 = [u, l, d / x2], X = k2.convertShape(e[1].dims).slice(); X.splice(-1, 1, w / _), H3.push(...V(W2)), H3.push(...V(X)), H3.push(...V(e[2].dims)), e.length === 4 && H3.push(...V(k2.convertShape(e[3].dims))); let Y3 = [u, l, p / A2]; H3.push(...V(Y3)); let pe2 = (ue3) => { let le3 = W2.length, K = E("a", e[0].dataType, le3, x2), de2 = E("b", 12, X.length, _), re2 = E("scales", e[2].dataType, e[2].dims.length), se2 = [K, de2, re2], Z2 = e.length === 4 ? E("zero_points", 12, e[3].dims.length) : void 0; Z2 && se2.push(Z2); let ne2 = Y3.length, J3 = M("output", e[0].dataType, ne2, A2), ke3 = [{ name: "output_size", type: "u32" }, { name: "block_size", type: "u32" }], R = ge(e[0].dataType), F2 = (() => { switch (x2) { case 1: return `array<${R}, 8>`; case 2: return `mat4x2<${R}>`; case 4: return `mat2x4<${R}>`; default: throw new Error(`${x2}-component is not supported.`); } })(), ce3 = ` for (var word: u32 = 0; word < ${w}; word += ${_}) { ${de2.indicesSet("b_indices", "2", "word")}; let b_data = ${de2.getByIndices("b_indices")}; for (var i: u32 = 0; i < ${_}; i++) { let b_value: u32 = ${_ === 1 ? "b_data" : "b_data[word + i]"}; let b_mask: u32 = 0x0F0F0F0Fu; let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); let b_quantized_values = ${F2}(${Array.from({ length: 4 }, (Se2, we2) => `${R}(b_value_lower[${we2}]), ${R}(b_value_upper[${we2}])`).join(", ")}); let b_dequantized_values = ${(() => x2 === 1 ? `${F2}(${Array.from({ length: 8 }, (Se2, we2) => `(b_quantized_values[${we2}] - zero_point) * scale`).join(", ")});` : `(b_quantized_values - ${F2}(${Array(8).fill("zero_point").join(",")})) * scale;`)()}; // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 for (var m: u32 = 0; m < ${T3 ? l : b}u; m++) { ${K.indicesSet("a_indices", le3 - 2, T3 ? "m" : `row * ${b} + m`)}; ${K.indicesSet("a_indices", le3 - 1, "word_offset")}; var input_offset = ${K.indicesToOffset("a_indices")}; var a_data: ${F2}; for (var j: u32 = 0; j < ${8 / x2}; j++) { a_data[j] = ${K.getByOffset("input_offset")}; input_offset++; } ${T3 ? "workgroup_shared[workgroup_shared_offset + m]" : "output_values[m]"}${A2 > 1 ? "[c]" : ""} += ${Array.from({ length: 8 / x2 }, (Se2, we2) => `${x2 === 1 ? `a_data[${we2}] * b_dequantized_values[${we2}]` : `dot(a_data[${we2}], b_dequantized_values[${we2}])`}`).join(" + ")}; } word_offset += ${8 / x2}; } }`, Re2 = Z2 ? ` zero_point_offset += 4; if (zero_point_offset == 32) { zero_point_offset = 0; zero_point_index++; zero_point_word = ${Z2.getByOffset("zero_point_index")}; }` : ""; return T3 ? ` var workgroup_shared: array<${J3.type.value}, ${l * a}>; ${ue3.declareVariables(...se2, J3)} ${ue3.mainStart([a, 1, 1])} var a_indices: ${K.type.indices}; var block = local_id.x; var col = workgroup_id.y; var batch = workgroup_id.z; ${K.indicesSet("a_indices", "0", "batch")}; // Two zero points are packed into one byte when uniforms.bits is 4. for (var c: u32 = 0; c < ${A2}; c++) { let col_times_components_plus_c = col * ${A2} + c; ${Z2 ? ` var zero_point_bytes_per_col: u32 = (${a} + 1) / 2; var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; var zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); var zero_point_word: u32 = ${Z2.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;` : ""} var b_indices: ${de2.type.indices}; ${de2.indicesSet("b_indices", "0", "col_times_components_plus_c")}; // The scale and zero points are computed per block. var scales_index = col_times_components_plus_c * ${a} + block; let scale = ${re2.getByOffset("scales_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${R}(${Z2 ? "(zero_point_word) & 0xFu" : 8}); ${de2.indicesSet("b_indices", "1", "block")}; var word_offset: u32 = block * ${t.blockSize / x2}; var workgroup_shared_offset: u32 = block * ${l}; ${ce3} } workgroupBarrier(); var output_indices: ${J3.type.indices}; var elements_per_thread: u32 = ${Math.ceil(l / a)}; ${J3.indicesSet("output_indices", "0", "batch")}; ${J3.indicesSet("output_indices", ne2 - 1, "col")}; ${J3.indicesSet("output_indices", ne2 - 2, "local_id.x * elements_per_thread")}; var output_offset = ${J3.indicesToOffset("output_indices")}; for (var m: u32 = 0u; m < elements_per_thread; m++) { var row = m + local_id.x * elements_per_thread; if (row < ${l}) { var output_value: ${J3.type.value} = ${J3.type.value}(0); var workgroup_shared_offset: u32 = row; for (var b: u32 = 0u; b < ${a}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${l}; } ${J3.setByOffset("output_offset", "output_value")}; output_offset += ${p / A2}; } } }` : ` ${ue3.registerUniforms(ke3).declareVariables(...se2, J3)} ${ue3.mainStart()} ${ue3.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var output_values: array<${J3.type.value}, ${b}>; var output_indices = ${J3.offsetToIndices("global_idx")}; var col = ${J3.indicesGet("output_indices", ne2 - 1)}; var row = ${J3.indicesGet("output_indices", ne2 - 2)}; var a_indices: ${K.type.indices} = output_indices; // Two zero points are packed into one byte because uniforms.bits <= 4. // zero_point_offset is either 0 or 4. It is bit offset within one byte. // TODO support zero_point_offset for bits > 4 ${Z2 ? ` var zero_point_abs_offset = col * ${A2} * ((${a} + 1) / 2); var zero_point_index: u32 = zero_point_abs_offset / 4; var zero_point_word: u32 = ${Z2.getByOffset("zero_point_index")}; var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;` : ""} var scale_index = col * ${a * A2}; var b_indices: ${de2.type.indices}; for (var c: u32 = 0; c < ${A2}; c++) { ${de2.indicesSet("b_indices", "0", `col * ${A2} + c`)}; var block_offset: u32 = 0; for (var block: u32 = 0; block < ${a}; block++) { // The scale and zero points are computed per block. let scale = ${re2.getByOffset("scale_index")}; // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${R}(${Z2 ? "extractBits(zero_point_word, zero_point_offset, 4)" : 8}); ${de2.indicesSet("b_indices", "1", "block")}; var word_offset: u32 = block_offset; ${ce3} scale_index++; ${Re2} block_offset += uniforms.block_size / ${x2}; } // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. ${Z2 ? `if (zero_point_offset % 8 > 0) { ${Re2} }` : ""} } for (var k: u32 = 0u; k < ${b}u; k++) { ${J3.indicesSet("output_indices", ne2 - 2, `${b} * row + k`)}; ${J3.setByIndices("output_indices", "output_values[k]")} } }`; }; return { name: T3 ? "BlockwiseMatMulNBits" : "MatMulNBits", shaderCache: { hint: `${t.cacheKey};${l};${g};${e.length}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: D3, dataType: g }], name: T3 ? "BlockwiseMatMulNBits" : "MatMulNBits", dispatchGroup: T3 ? { x: 1, y: Math.ceil(p / A2), z: u } : { x: Math.ceil(z3 / 64) }, programUniforms: H3 }), getShaderSource: pe2 }; }, Pd = (e, t) => { $f2(e.inputs, t); let r = e.getMaxComputeWorkgroupSizes(), n = e.getMaxComputeWorkgroupStoragesize(); e.compute(_f2(e.inputs, t, r, n)); }, Od = (e) => te(e); }); Bd = U(() => { "use strict"; Q(); ae(); ie(); xf2 = (e) => { if (!e || e.length < 1) throw new Error("Too few inputs"); if (e[0].dataType !== 1 && e[0].dataType !== 10) throw new Error("Input type must be float or float16."); if (e.length >= 2) { let t = e[0].dims.length * 2 === e[1].dims[0]; if (e.length === 4 && (t = e[3].dims[0] * 2 === e[1].dims[0]), !t) throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes]."); } }, Sf2 = (e, t, r) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${G2("uniforms.pads", o, r)}; if (k < 0) { break; } if (k >= i32(${G2("uniforms.x_shape", o, t)})) { break; } offset += k * i32(${G2("uniforms.x_strides", o, t)}); `; return ` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${n} value = x[offset]; } `; }, If3 = (e, t, r) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${G2("uniforms.pads", o, r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${G2("uniforms.x_shape", o, t)}) - 1); k = k % _2n_1; if(k >= i32(${G2("uniforms.x_shape", o, t)})) { k = _2n_1 - k; } } offset += k * i32(${G2("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, Cf2 = (e, t, r) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${G2("uniforms.pads", o, r)}; if (k < 0) { k = 0; } if (k >= i32(${G2("uniforms.x_shape", o, t)})) { k = i32(${G2("uniforms.x_shape", o, t)}) - 1; } offset += k * i32(${G2("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, Tf2 = (e, t, r) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${G2("uniforms.pads", o, r)}; if (k < 0) { k += i32(${G2("uniforms.x_shape", o, t)}]); } if (k >= i32(${G2("uniforms.x_shape", o, t)})) { k -= i32(${G2("uniforms.x_shape", o, t)}); } offset += k * i32(${G2("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, Af2 = (e, t, r) => { switch (r.mode) { case 0: return Sf2(e, t, r.pads.length); case 1: return If3(e, t, r.pads.length); case 2: return Cf2(e, t, r.pads.length); case 3: return Tf2(e, t, r.pads.length); default: throw new Error("Invalid mode"); } }, Ef2 = (e, t) => { let r = k2.padShape(e[0].dims.slice(), t.pads), n = e[0].dims, o = k2.size(r), i = [{ type: 12, data: o }, { type: 6, data: t.pads }]; t.mode === 0 && i.push({ type: e[0].dataType, data: t.value }), i.push(...V(e[0].dims, r)); let a = ["rank"], l = (d) => { let p = M("output", e[0].dataType, r.length), m2 = E("x", e[0].dataType, n.length), u = m2.type.value, h = Af2(p, n.length, t), w = [{ name: "output_size", type: "u32" }, { name: "pads", type: "i32", length: t.pads.length }]; return t.mode === 0 && w.push({ name: "constant_value", type: u }), ` ${d.registerUniforms(w).declareVariables(m2, p)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${p.offsetToIndices("global_idx")}; var value = ${u}(0); ${h} output[global_idx] = value; }`; }; return { name: "Pad", shaderCache: { hint: `${t.mode}`, inputDependencies: a }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k2.size(r) / 64) }, programUniforms: i }), getShaderSource: l }; }, kf2 = (e, t) => { if (e.length > 1) { let r = e[1].getBigInt64Array(), n = e.length >= 3 && e[2].data ? e[2].getFloat32Array()[0] : 0, o = e[0].dims.length, i = new Int32Array(2 * o).fill(0); if (e.length >= 4) { let l = e[3].getBigInt64Array(); for (let d = 0; d < l.length; d++) i[Number(l[d])] = Number(r[d]), i[Number(l[d]) + o] = Number(r[d + l.length]); } else r.forEach((l, d) => i[Number(d)] = Number(l)); let a = []; return i.forEach((l) => a.push(l)), { mode: t.mode, value: n, pads: a }; } else return t; }, zd2 = (e, t) => { xf2(e.inputs); let r = kf2(e.inputs, t); e.compute(Ef2(e.inputs, r), { inputs: [0] }); }; }); Qd2 = U(() => { "use strict"; Ke2(); Q(); ae(); ie(); nn2 = (e) => { if (be2.webgpu.validateInputContent && (!e || e.length !== 1)) throw new Error("Pool ops requires 1 input."); }, Rd = (e, t, r) => { let n = t.format === "NHWC", o = e.dims.slice(); n && o.splice(1, 0, o.pop()); let i = Object.hasOwnProperty.call(t, "dilations"), a = t.kernelShape.slice(), l = t.strides.slice(), d = i ? t.dilations.slice() : [], p = t.pads.slice(); Ct.adjustPoolAttributes(r, o, a, l, d, p); let m2 = Ct.computePoolOutputShape(r, o, l, d, a, p, t.autoPad), u = Object.assign({}, t); i ? Object.assign(u, { kernelShape: a, strides: l, pads: p, dilations: d, cacheKey: t.cacheKey }) : Object.assign(u, { kernelShape: a, strides: l, pads: p, cacheKey: t.cacheKey }); let h = m2.slice(); return h.push(h.splice(1, 1)[0]), [u, n ? h : m2]; }, Md = (e, t) => { let r = t.format === "NHWC", n = k2.size(e), o = k2.size(t.kernelShape), i = [{ type: 12, data: n }, { type: 12, data: o }], a = [{ name: "outputSize", type: "u32" }, { name: "kernelSize", type: "u32" }]; if (t.kernelShape.length <= 2) { let l = t.kernelShape[t.kernelShape.length - 1], d = t.strides[t.strides.length - 1], p = t.pads[t.pads.length / 2 - 1], m2 = t.pads[t.pads.length - 1], u = !!(p + m2); i.push({ type: 12, data: l }, { type: 12, data: d }, { type: 12, data: p }, { type: 12, data: m2 }), a.push({ name: "kw", type: "u32" }, { name: "sw", type: "u32" }, { name: "pwStart", type: "u32" }, { name: "pwEnd", type: "u32" }); let h = false; if (t.kernelShape.length === 2) { let w = t.kernelShape[t.kernelShape.length - 2], g = t.strides[t.strides.length - 2], b = t.pads[t.pads.length / 2 - 2], x2 = t.pads[t.pads.length - 2]; h = !!(b + x2), i.push({ type: 12, data: w }, { type: 12, data: g }, { type: 12, data: b }, { type: 12, data: x2 }), a.push({ name: "kh", type: "u32" }, { name: "sh", type: "u32" }, { name: "phStart", type: "u32" }, { name: "phEnd", type: "u32" }); } return [i, a, true, u, h]; } else { if (r) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); let l = k2.computeStrides(t.kernelShape); i.push({ type: 12, data: l }, { type: 12, data: t.pads }, { type: 12, data: t.strides }), a.push({ name: "kernelStrides", type: "u32", length: l.length }, { name: "pads", type: "u32", length: t.pads.length }, { name: "strides", type: "u32", length: t.strides.length }); let d = t.pads.reduce((p, m2) => p + m2); return [i, a, !!d, false, false]; } }, Ud = (e, t, r, n, o, i, a, l, d, p, m2, u) => { let h = o.format === "NHWC", w = t.type.value, g = M("output", t.type.tensor, n); if (o.kernelShape.length <= 2) { let b = "", x2 = "", _ = "", $2 = r - (h ? 2 : 1); if (m2 ? b = ` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${$2}] = indices[${$2}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${$2}] < 0 || xIndices[${$2}] >= uniforms.x_shape[${$2}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }` : b = ` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${$2}] = indices[${$2}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`, o.kernelShape.length === 2) { let I2 = r - (h ? 3 : 2); u ? x2 = ` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${I2}] = indices[${I2}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${I2}] < 0 || xIndices[${I2}] >= uniforms.x_shape[${I2}]) { pad += i32(uniforms.kw); continue; } ` : x2 = ` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${I2}] = indices[${I2}] * uniforms.sh - uniforms.phStart + j; `, _ = ` } `; } return ` ${e.registerUniforms(d).declareVariables(t, g)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${g.offsetToIndices("global_idx")}; var xIndices = ${g.offsetToIndices("global_idx")}; var value = ${w}(${l}); var pad = 0; ${x2} ${b} ${_} ${a} output[global_idx] = value; }`; } else { if (h) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); let b = o.kernelShape.length, x2 = o.pads.length, _ = ""; return p ? _ = ` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }` : _ = ` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `, ` ${e.registerUniforms(d).declareVariables(t, g)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${g.offsetToIndices("global_idx")}; var xIndices = ${g.offsetToIndices("global_idx")}; var offsets: array; var value = ${w}(${l}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${b - 1}u; j++) { offsets[j] = offset / ${G2("uniforms.kernelStrides", "j", b)}; offset -= offsets[j] * ${G2("uniforms.kernelStrides", "j", b)}; } offsets[${b - 1}] = offset; isPad = false; for (var j = ${r - b}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${G2("uniforms.strides", `j - ${r - b}u`, b)} + offsets[j - ${r - b}u] - ${G2("uniforms.pads", "j - 2u", x2)}; ${_} } ${a} output[global_idx] = value; }`; } }, Vd = (e) => `${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`, Pf2 = (e) => `${Vd(e)};${e.countIncludePad}`, Of2 = (e) => `${Vd(e)};${e.storageOrder};${e.dilations}`, Nd = (e) => ({ format: e.format, autoPad: ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], ceilMode: e.ceil_mode, kernelShape: e.kernel_shape, strides: e.strides, pads: e.pads }), Wd2 = (e, t, r, n) => { let [o, i] = Rd(t, n, r), a = E("x", t.dataType, t.dims.length), l = a.type.value, d = "value += x_val;", p = ""; o.countIncludePad ? p += `value /= ${l}(uniforms.kernelSize);` : p += `value /= ${l}(i32(uniforms.kernelSize) - pad);`; let [m2, u, h, w, g] = Md(i, o); m2.push(...V(t.dims, i)); let b = ["rank"]; return { name: e, shaderCache: { hint: `${n.cacheKey};${h};${w};${g}`, inputDependencies: b }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k2.size(i) / 64) }, programUniforms: m2 }), getShaderSource: (x2) => Ud(x2, a, t.dims.length, i.length, o, d, p, 0, u, h, w, g) }; }, Hd2 = (e) => { let t = e.count_include_pad !== 0, r = Nd(e); if (r.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); let n = { countIncludePad: t, ...r, cacheKey: "" }; return { ...n, cacheKey: Pf2(n) }; }, Gd = (e, t) => { nn2(e.inputs), e.compute(Wd2("AveragePool", e.inputs[0], false, t)); }, Ld = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [] }, Fd = (e) => { let t = e.format; return { format: t, ...Ld, cacheKey: t }; }, qd2 = (e, t) => { nn2(e.inputs), e.compute(Wd2("GlobalAveragePool", e.inputs[0], true, t)); }, jd2 = (e, t, r, n) => { let [o, i] = Rd(t, n, r), a = ` value = max(x_val, value); `, l = "", d = E("x", t.dataType, t.dims.length), p = ["rank"], [m2, u, h, w, g] = Md(i, o); return m2.push(...V(t.dims, i)), { name: e, shaderCache: { hint: `${n.cacheKey};${h};${w};${g}`, inputDependencies: p }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k2.size(i) / 64) }, programUniforms: m2 }), getShaderSource: (b) => Ud(b, d, t.dims.length, i.length, o, a, l, t.dataType === 10 ? -65504 : -1e5, u, h, w, g) }; }, Kd2 = (e, t) => { nn2(e.inputs), e.compute(jd2("MaxPool", e.inputs[0], false, t)); }, Yd2 = (e) => { let t = e.storage_order, r = e.dilations, n = Nd(e); if (t !== 0) throw new Error("column major storage order is not yet supported for MaxPool"); if (n.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); let o = { storageOrder: t, dilations: r, ...n, cacheKey: "" }; return { ...o, cacheKey: Of2(o) }; }, Xd2 = (e) => { let t = e.format; return { format: t, ...Ld, cacheKey: t }; }, Zd2 = (e, t) => { nn2(e.inputs), e.compute(jd2("GlobalMaxPool", e.inputs[0], true, t)); }; }); el2 = U(() => { "use strict"; Ke2(); Q(); ie(); zf2 = (e, t, r) => { let n = e === t, o = e < t && r < 0, i = e > t && r > 0; if (n || o || i) throw new Error("Range these inputs' contents are invalid."); }, Bf2 = (e, t, r, n) => { let o = Math.abs(Math.ceil((t - e) / r)), i = [o], a = o, l = [{ type: 12, data: a }, { type: n, data: e }, { type: n, data: r }, ...V(i)], d = (p) => { let m2 = M("output", n, i.length), u = m2.type.value, h = [{ name: "outputSize", type: "u32" }, { name: "start", type: u }, { name: "delta", type: u }]; return ` ${p.registerUniforms(h).declareVariables(m2)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; }`; }; return { name: "Range", shaderCache: { hint: `${n}` }, getShaderSource: d, getRunData: () => ({ outputs: [{ dims: i, dataType: n }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: l }) }; }, Jd2 = (e) => { let t = 0, r = 0, n = 0; e.inputs[0].dataType === 6 ? (t = e.inputs[0].getInt32Array()[0], r = e.inputs[1].getInt32Array()[0], n = e.inputs[2].getInt32Array()[0]) : e.inputs[0].dataType === 1 && (t = e.inputs[0].getFloat32Array()[0], r = e.inputs[1].getFloat32Array()[0], n = e.inputs[2].getFloat32Array()[0]), be2.webgpu.validateInputContent && zf2(t, r, n), e.compute(Bf2(t, r, n, e.inputs[0].dataType), { inputs: [] }); }; }); ol2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); Rf2 = (e, t) => { if (e.every((r) => r > 0 || (() => { throw new Error("Resize requires scales input values to be positive"); })), e.length > 0) { if (t.mode === "linear") { if (!(e.length === 2 || e.length === 3 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1 || e.length === 5 && e[0] === 1 && e[1] === 1)) throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`); } else if (t.mode === "cubic" && !(e.length === 2 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1)) throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode"); } }, Mf2 = (e, t, r) => { t.every((o) => o >= 0 && o < r || (() => { throw new Error("Resize requires axes input values to be positive and less than rank"); })); let n = new Array(r).fill(1); return t.forEach((o, i) => n[o] = e[i]), n; }, Uf2 = (e, t, r, n, o, i) => { let [a, l, d] = r > 10 ? [1, 2, 3] : [-1, e.length > 1 ? 1 : -1, -1], p = e[0].dims.length; if (a > 0 && e.length > a && e[a].dims.length > 0) e[a].getFloat32Array().forEach((m2) => i.push(m2)); else if (t.coordinateTransformMode === "tf_crop_and_resize") throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize"); if (l > 0 && e.length > l && e[l].dims.length > 0) { if (e[l].getFloat32Array().forEach((m2) => n.push(m2)), n.length !== 0 && n.length !== p && r >= 18 && n.length !== t.axes.length) throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up"); Rf2(n, t), t.axes.length > 0 && Mf2(n, t.axes, p).forEach((m2, u) => n[u] = m2); } if (d > 0 && e.length > d && (e[d].getBigInt64Array().forEach((m2) => o.push(Number(m2))), o.length !== p || r >= 18 && o.length === t.axes.length)) throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up"); if (t.axes.length > 0) { if (n.length !== t.axes.length) throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified'); if (o.length !== t.axes.length) throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified'); } if (typeof n < "u" && typeof o < "u" && n.length > 0 && o.length > p) throw new Error("Resize requires only of scales or sizes to be specified"); }, Vf2 = (e, t) => `fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { ` + (() => { switch (e) { case "asymmetric": return `return ${t}(xResized) / ${t}(xScale);`; case "pytorch_half_pixel": return `if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`; case "tf_half_pixel_for_nn": return `return (${t}(xResized) + 0.5) / ${t}(xScale);`; case "align_corners": return `if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`; case "tf_crop_and_resize": return `if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`; case "half_pixel_symmetric": return `const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`; case "half_pixel": return `return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`; default: throw new Error(`Coordinate transform mode ${e} is not supported`); } })() + "}", Nf2 = (e, t, r) => `fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {` + (() => { switch (e) { case "round_prefer_ceil": return "if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }"; case "floor": return "return floor(xOriginal);"; case "ceil": return "return ceil(xOriginal);"; case "round_prefer_floor": return "if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }"; case "simple": default: if (t < 11) return "if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }"; throw new Error(`Nearest mode ${e} is not supported`); } })() + "}", Wf2 = (e, t, r) => { let n = new Array(r).fill(0).concat(new Array(r).fill(1)), o = e.length === 0 ? n : e.slice(); return t.length > 0 ? (t.forEach((i, a) => { n[i] = o[a], n[a + r] = o[t.length + a]; }), n) : o; }, Hf2 = (e, t, r, n) => { let o = []; if (r.length > 0) if (n.length > 0) { if (e.forEach((i) => o.push(i)), Math.max(...n) > e.length) throw new Error("axes is out of bound"); n.forEach((i, a) => o[i] = r[a]); } else r.forEach((i) => o.push(i)); else { if (t.length === 0) throw new Error("Resize requires either scales or sizes."); o = e.map((i, a) => Math.round(i * t[a])); } return o; }, Gf2 = (e, t, r) => { let n = (() => { switch (r.keepAspectRatioPolicy) { case "not_larger": return r.axes.length > 0 ? Math.min(...r.axes.map((i) => t[i]), Number.MAX_VALUE) : Math.min(...t, Number.MAX_VALUE); case "not_smaller": return r.axes.length > 0 ? Math.max(...r.axes.map((i) => t[i]), Number.MIN_VALUE) : Math.max(...t, Number.MIN_VALUE); default: throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`); } })(); t.fill(1, 0, t.length); let o = e.slice(); return r.axes.length > 0 ? (r.axes.forEach((i) => t[i] = n), r.axes.forEach((i) => o[i] = Math.round(e[i] * t[i]))) : (t.fill(n, 0, t.length), o.forEach((i, a) => o[a] = Math.round(i * t[a]))), o; }, Lf2 = (e, t, r, n, o) => ` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${e.indicesGet("output_indices", "i")}; var scale = ${G2("uniforms.scales", "i", n)}; var roi_low = ${G2("uniforms.roi", "i", o)}; var roi_hi = ${G2("uniforms.roi", `i + ${t.length}`, o)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${G2("uniforms.input_shape", "i", t.length)}; var output_shape_i = ${G2("uniforms.output_shape", "i", r.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`, Ff2 = (e, t, r, n, o, i, a) => ` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${t.indicesGet("output_indices", "i")}; var input_index: u32; var scale = ${G2("uniforms.scales", "i", o)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${G2("uniforms.roi", "i", i)}; var roi_hi = ${G2("uniforms.roi", `i + ${r.length}`, i)}; var input_shape_i = ${G2("uniforms.input_shape", "i", r.length)}; var output_shape_i = ${G2("uniforms.output_shape", "i", n.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices", "i", " input_index")} } return input_indices; }`, qf2 = (e, t) => ` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices", "i")}; if (input_index < 0 || input_index >= ${G2("uniforms.input_shape", "i", t.length)}) { return false; } } return true; }`, tl2 = (e, t, r, n) => e.rank > n ? ` ${e.indicesSet("input_indices", t, "channel")}; ${e.indicesSet("input_indices", r, "batch")}; ` : "", jf2 = (e, t, r, n, o) => { let [a, l, d, p] = r.length === 2 ? [-1, 0, 1, -1] : [0, 2, 3, 1], m2 = e.type.value; return ` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m2} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices", l, `max(0, min(row, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices", d, `max(0, min(col, ${r[d]} - 1))`)}; ${tl2(e, p, a, 2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m2} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${m2} = originalIndices[${l}]; var col:${m2} = originalIndices[${d}]; ${n ? `if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[d]} - 1)) { return ${o}; }` : ""}; row = max(0, min(row, ${r[l]} - 1)); col = max(0, min(col, ${r[d]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${r.length > 2 ? `u32(originalIndices[${p}])` : "0"}; var batch: u32 = ${r.length > 2 ? `u32(originalIndices[${a}])` : "0"}; var x11: ${m2} = getInputValue(batch, channel, row1, col1); var x12: ${m2} = getInputValue(batch, channel, row1, col2); var x21: ${m2} = getInputValue(batch, channel, row2, col1); var x22: ${m2} = getInputValue(batch, channel, row2, col2); var dx1: ${m2} = abs(row - ${m2}(row1)); var dx2: ${m2} = abs(${m2}(row2) - row); var dy1: ${m2} = abs(col - ${m2}(col1)); var dy2: ${m2} = abs(${m2}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`; }, Kf2 = (e, t, r, n, o, i, a, l, d, p) => { let m2 = r.length === 2, u = true, [h, w] = m2 ? [0, 1] : u ? [2, 3] : [1, 2], g = e.type.value, b = (x2) => { let _ = x2 === h ? "row" : "col"; return ` fn ${_}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${g} { var output_index = ${t.indicesGet("output_indices", x2)}; var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x2]}, ${n[x2]}, ${r[x2]}, ${i[x2]}, ${i[x2]} + ${r.length}); var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${l} && (originalIdx < 0 || originalIdx > (${r[x2]} - 1))) { return ${d}; } var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${_}: ${g} = originalIdx + ${g}(i); if (${_} < 0 || ${_} >= ${r[x2]}) { ${(() => p ? `coefs[i + 1] = 0.0; continue;` : l ? `return ${d};` : `${_} = max(0, min(${_}, ${r[x2]} - 1));`)()}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy", x2, `u32(${_})`)}; data[i + 1] = ${x2 === h ? e.getByIndices("input_indices_copy") : "rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`; }; return ` ${b(h)}; ${b(w)}; fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { var absS = abs(s); var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${g} = 1.0 - absS; var twoMinusAbsS: ${g} = 2.0 - absS; var onePlusAbsS: ${g} = 1.0 + absS; coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; return coeffs; } fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { var coefsSum: ${g} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${g} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `; }, Yf2 = (e, t, r, n, o) => { let [a, l, d, p, m2] = r.length === 3 ? [-1, 0, 1, 2, -1] : [0, 2, 3, 4, 1], u = e.type.value; return ` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices", l, `max(0, min(depth, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices", d, `max(0, min(height, ${r[d]} - 1))`)}; ${e.indicesSet("input_indices", p, `max(0, min(width, ${r[p]} - 1))`)}; ${tl2(e, m2, a, 3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${u} = originalIndices[${l}]; var height:${u} = originalIndices[${d}]; var width:${u} = originalIndices[${p}]; ${n ? `if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) { return ${o}; }` : ""}; depth = max(0, min(depth, ${r[l]} - 1)); height = max(0, min(height, ${r[d]} - 1)); width = max(0, min(width, ${r[p]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${r.length > 3 ? `u32(originalIndices[${m2}])` : "0"}; var batch: u32 = ${r.length > 3 ? `u32(originalIndices[${a}])` : "0"}; var x111: ${u} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${u} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${u} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${u} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${u} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${u} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${u} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${u} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${u} = abs(depth - ${u}(depth1)); var dx2: ${u} = abs(${u}(depth2) - depth); var dy1: ${u} = abs(height - ${u}(height1)); var dy2: ${u} = abs(${u}(height2) - height); var dz1: ${u} = abs(width - ${u}(width1)); var dz2: ${u} = abs(${u}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`; }, Xf2 = (e, t, r, n, o, i) => { let a = e.dims, l = Wf2(i, t.axes, a.length), d = Hf2(a, n, o, t.axes), p = n.slice(); n.length === 0 && (p = a.map(($2, S) => $2 === 0 ? 1 : d[S] / $2), t.keepAspectRatioPolicy !== "stretch" && (d = Gf2(a, p, t))); let m2 = M("output", e.dataType, d.length), u = E("input", e.dataType, a.length), h = k2.size(d), w = a.length === d.length && a.every(($2, S) => $2 === d[S]), g = t.coordinateTransformMode === "tf_crop_and_resize", b = t.extrapolationValue, x2 = u.type.value, _ = ($2) => ` ${w ? "" : ` ${Vf2(t.coordinateTransformMode, x2)}; ${(() => { switch (t.mode) { case "nearest": return ` ${qf2(u, a)}; ${Nf2(t.nearestMode, r, x2)}; ${Ff2(u, m2, a, d, p.length, l.length, g)}; `; case "linear": return ` ${Lf2(m2, a, d, p.length, l.length)}; ${(() => { if (a.length === 2 || a.length === 4) return `${jf2(u, m2, a, g, b)}`; if (a.length === 3 || a.length === 5) return `${Yf2(u, m2, a, g, b)}`; throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode."); })()}; `; case "cubic": return ` ${(() => { if (a.length === 2 || a.length === 4) return `${Kf2(u, m2, a, d, p, l, t.cubicCoeffA, g, t.extrapolationValue, t.excludeOutside)}`; throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode."); })()}; `; default: throw Error("Invalid resize mode"); } })()}; `} ${$2.registerUniform("output_size", "u32").registerUniform("scales", "f32", p.length).registerUniform("roi", "f32", l.length).declareVariables(u, m2)} ${$2.mainStart()} ${$2.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${w ? "output[global_idx] = input[global_idx];" : ` let output_indices = ${m2.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; ${(() => { switch (t.mode) { case "nearest": return `input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${u.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`; case "linear": return `output[global_idx] = ${a.length === 2 || a.length === 4 ? "bilinearInterpolation" : "trilinearInterpolation"}(output_indices);`; case "cubic": return "output[global_idx] = bicubicInterpolation(output_indices);"; default: throw Error(`Unsupported resize mode: ${t.mode}`); } })()}; `} }`; return { name: "Resize", shaderCache: { hint: `${t.cacheKey}|${r}|${p.length > 0 ? p : ""}|${o.length > 0 ? o : ""}|${l.length > 0 ? l : ""}|${w}|${a}`, inputDependencies: ["rank"] }, getShaderSource: _, getRunData: () => ({ outputs: [{ dims: d, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(h / 64) }, programUniforms: [{ type: 12, data: h }, { type: 1, data: p }, { type: 1, data: l }, ...V(a, d)] }) }; }, Zf2 = (e) => { let t = e.customDataBuffer; return new Uint32Array(t, t.byteOffset, 1)[0]; }, rl2 = (e, t) => { let r = [], n = [], o = [], i = Zf2(e); if (t.antialias !== 0) throw Error("Only default value (0) for Antialias attribute is supported"); Uf2(e.inputs, t, i, r, n, o), e.compute(Xf2(e.inputs[0], t, i, r, n, o), { inputs: [0] }); }, nl2 = (e) => { let t = e.antialias, r = e.axes, n = e.coordinateTransformMode, o = e.cubicCoeffA, i = e.excludeOutside !== 0, a = e.extrapolationValue, l = e.keepAspectRatioPolicy, d = e.mode, p = e.nearestMode === "" ? "simple" : e.nearestMode; return te({ antialias: t, axes: r, coordinateTransformMode: n, cubicCoeffA: o, excludeOutside: i, extrapolationValue: a, keepAspectRatioPolicy: l, mode: d, nearestMode: p }); }; }); al2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); Qf2 = (e, t) => { let [r, n, o, i] = e, { numHeads: a, rotaryEmbeddingDim: l } = t; if (r.dims.length !== 3 && r.dims.length !== 4) throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`); if (!k2.areEqual(n.dims, []) && !k2.areEqual(n.dims, [1]) && n.dims.length !== 2) throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`); if (o.dims.length !== 2) throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`); if (i.dims.length !== 2) throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`); if (!k2.areEqual(o.dims, i.dims)) throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape"); if (l > 0 && a === 0) throw new Error("num_heads must be provided if rotary_embedding_dim is specified"); let d = r.dims[0], p = r.dims[r.dims.length - 2], m2 = o.dims[0], u = k2.sizeFromDimension(r.dims, 1) / p, h = l === 0 ? o.dims[1] * 2 : u / a; if (l > h) throw new Error("rotary_embedding_dim must be less than or equal to head_size"); if (n.dims.length === 2) { if (d !== n.dims[0]) throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`); if (p !== n.dims[1]) throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`); } if (h / 2 !== o.dims[1] && l / 2 !== o.dims[1]) throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`); if (p > m2) throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported"); }, Jf2 = (e, t) => { let { interleaved: r, numHeads: n, rotaryEmbeddingDim: o, scale: i } = t, a = e[0].dims[0], l = k2.sizeFromDimension(e[0].dims, 1), d = e[0].dims[e[0].dims.length - 2], p = l / d, m2 = e[2].dims[1], u = o === 0 ? m2 * 2 : p / n, h = new Array(a, d, p / u, u - m2), w = k2.computeStrides(h), g = [{ type: 1, data: i }, { type: 12, data: h }, { type: 12, data: w }, ...e[0].dims.length === 3 ? new Array({ type: 12, data: [l, p, u, 1] }) : [], ...e[0].dims.length === 4 ? new Array({ type: 12, data: [l, u, d * u, 1] }) : [], ...V(e[0].dims, e[1].dims, e[2].dims, e[3].dims, e[0].dims)], b = (x2) => { let _ = E("input", e[0].dataType, e[0].dims.length), $2 = E("position_ids", e[1].dataType, e[1].dims.length), S = E("cos_cache", e[2].dataType, e[2].dims.length), I2 = E("sin_cache", e[3].dataType, e[3].dims.length), T3 = M("output", e[0].dataType, e[0].dims.length); return x2.registerUniforms([{ name: "scale", type: "f32" }, { name: "global_shape", type: "u32", length: h.length }, { name: "global_strides", type: "u32", length: w.length }, { name: "input_output_strides", type: "u32", length: w.length }]), ` ${x2.declareVariables(_, $2, S, I2, T3)} ${x2.mainStart(Tt2)} let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${x2.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${$2.broadcastedIndicesToOffset("bsnh.xy", M("", $2.type.tensor, 2))}; let position_id = u32(${$2.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); let j = i + select(half_rotary_emb_dim, 1, ${r}); let re = ${_.getByOffset("i")} * ${S.get("position_id", "bsnh[3]")} - ${_.getByOffset("j")} * ${I2.get("position_id", "bsnh[3]")}; ${T3.setByOffset("i", "re")} let im = ${_.getByOffset("i")} * ${I2.get("position_id", "bsnh[3]")} + ${_.getByOffset("j")} * ${S.get("position_id", "bsnh[3]")}; ${T3.setByOffset("j", "im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${T3.setByOffset("k", _.getByOffset("k"))} } }`; }; return { name: "RotaryEmbedding", shaderCache: { hint: te({ interleaved: r }).cacheKey, inputDependencies: ["rank", "rank", "rank", "rank"] }, getShaderSource: b, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k2.size(h) / Tt2) }, programUniforms: g }) }; }, il2 = (e, t) => { Qf2(e.inputs, t), e.compute(Jf2(e.inputs, t)); }; }); ul = U(() => { "use strict"; Q(); ae(); ie(); eh = (e) => { if (!e || e.length < 3) throw new Error("layerNorm requires at least 3 inputs."); let t = e[0], r = e[1], n = e[2]; if (t.dataType !== r.dataType || t.dataType !== n.dataType) throw new Error("All inputs must have the same data type"); if (t.dims.length !== 3 && t.dims.length !== 2) throw new Error("Input must be 2D or 3D"); if (r.dims.length !== 3 && r.dims.length !== 2) throw new Error("Skip must be 2D or 3D"); let o = t.dims[t.dims.length - 1], i = t.dims[t.dims.length - 2]; if (r.dims[r.dims.length - 1] !== o) throw new Error("Skip must have the same hidden size as input"); if (r.dims[r.dims.length - 2] !== i) throw new Error("Skip must have the same sequence length as input"); if (n.dims.length !== 1) throw new Error("Gamma must be 1D"); if (n.dims[n.dims.length - 1] !== o) throw new Error("Gamma must have the same hidden size as input"); if (e.length > 3) { let a = e[3]; if (a.dims.length !== 1) throw new Error("Beta must be 1D"); if (a.dims[a.dims.length - 1] !== o) throw new Error("Beta must have the same hidden size as input"); } if (e.length > 4) { let a = e[4]; if (a.dims.length !== 1) throw new Error("Bias must be 1D"); if (a.dims[a.dims.length - 1] !== o) throw new Error("Bias must have the same hidden size as input"); } }, th2 = (e, t, r, n) => { let o = t.simplified, i = e[0].dims, a = k2.size(i), l = i, d = a, p = i.slice(-1)[0], m2 = n ? i.slice(0, -1).concat(1) : [], u = !o && e.length > 3, h = e.length > 4, w = n && r > 1, g = n && r > 2, b = r > 3, x2 = 64, _ = $e2(p), $2 = [{ type: 12, data: d }, { type: 12, data: _ }, { type: 12, data: p }, { type: 1, data: t.epsilon }], S = (T3) => { let A2 = [{ name: "output_size", type: "u32" }, { name: "components", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "epsilon", type: "f32" }], D3 = [E("x", e[0].dataType, e[0].dims, _), E("skip", e[1].dataType, e[1].dims, _), E("gamma", e[2].dataType, e[2].dims, _)]; u && D3.push(E("beta", e[3].dataType, e[3].dims, _)), h && D3.push(E("bias", e[4].dataType, e[4].dims, _)), D3.push(M("output", e[0].dataType, l, _)), w && D3.push(M("mean_output", 1, m2)), g && D3.push(M("inv_std_output", 1, m2)), b && D3.push(M("input_skip_bias_sum", e[0].dataType, l, _)); let z3 = ge(e[0].dataType), H3 = ge(1, _); return ` ${T3.registerUniforms(A2).declareVariables(...D3)} var sum_shared : array<${H3}, ${x2}>; var sum_squared_shared : array<${H3}, ${x2}>; ${T3.mainStart([x2, 1, 1])} let ix = local_id.x; let iy = global_id.x / ${x2}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${x2}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${x2 - 1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${h ? "bias[offset1d + i]" : z3 + "(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${b ? "input_skip_bias_sum[offset + i] = value;" : ""} output[offset + i] = value; let f32_value = ${At(z3, _, "value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${x2}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${Xe2("sum", _)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Xe2("square_sum", _)} / f32(uniforms.hidden_size) ${o ? "" : "- mean * mean"} + uniforms.epsilon); ${w ? "mean_output[global_idx] = mean;" : ""} ${g ? "inv_std_output[global_idx] = inv_std_dev;" : ""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${o ? "" : `- ${z3}(mean)`}) * ${z3}(inv_std_dev) * gamma[offset1d + i] ${u ? "+ beta[offset1d + i]" : ""}; } }`; }, I2 = [{ dims: l, dataType: e[0].dataType }]; return r > 1 && I2.push({ dims: m2, dataType: 1 }), r > 2 && I2.push({ dims: m2, dataType: 1 }), r > 3 && I2.push({ dims: i, dataType: e[0].dataType }), { name: "SkipLayerNormalization", shaderCache: { hint: `${_};${w};${g};${b}`, inputDependencies: e.map((T3, A2) => "type") }, getShaderSource: S, getRunData: () => ({ outputs: I2, dispatchGroup: { x: Math.ceil(d / p) }, programUniforms: $2 }) }; }, sl2 = (e, t) => { eh(e.inputs); let n = [0]; e.outputCount > 1 && n.push(-3), e.outputCount > 2 && n.push(-3), e.outputCount > 3 && n.push(3), e.compute(th2(e.inputs, t, e.outputCount, false), { outputs: n }); }; }); pl2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); rh2 = (e, t) => { if (!e || e.length < 1) throw new Error("too few inputs"); if (t.axes.length !== 0) { if (t.axes.length !== t.starts.length || t.axes.length !== t.ends.length) throw new Error("axes, starts and ends must have the same length"); } else if (t.starts.length !== t.ends.length) throw new Error("starts and ends must have the same length"); e.slice(1).forEach((r, n) => { if (e[n + 1].dataType !== 6 && e[n + 1].dataType !== 7) throw new Error(`Input ${n} must be an array of int32 or int64`); }); }, on2 = (e, t) => { let r = []; if (e.length > t) if (e[t].dataType === 7) e[t].getBigInt64Array().forEach((n) => r.push(Number(n))); else if (e[t].dataType === 6) e[t].getInt32Array().forEach((n) => r.push(Number(n))); else throw new Error(`Input ${t} must be an array of int32 or int64`); return r; }, nh = (e, t) => { if (e.length > 1) { let r = on2(e, 1), n = on2(e, 2), o = on2(e, 3); return o.length === 0 && (o = [...Array(e[0].dims.length).keys()]), te({ starts: r, ends: n, axes: o }); } else return t; }, dl2 = (e, t, r, n, o) => { let i = e; return e < 0 && (i += r[n[t]]), o[t] < 0 ? Math.max(0, Math.min(i, r[n[t]] - 1)) : Math.max(0, Math.min(i, r[n[t]])); }, oh = (e, t, r) => `fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { let input_shape_i = ${G2("uniforms.input_shape", "i", r.length)}; let steps_i = ${G2("uniforms.steps", "i", r.length)}; let signs_i = ${G2("uniforms.signs", "i", r.length)}; let starts_i = ${G2("uniforms.starts", "i", r.length)}; var output_index = ${t.indicesGet("output_indices", "i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices", "i", "input_index")}; } return input_indices; }`, ih = (e, t) => { let r = e[0].dims, n = k2.size(r), o = t.axes.length > 0 ? k2.normalizeAxes(t.axes, r.length) : [...Array(r.length).keys()], i = on2(e, 4); i.forEach((_) => _ !== 0 || (() => { throw new Error("step cannot be 0"); })), i.length === 0 && (i = Array(o.length).fill(1)); let a = t.starts.map((_, $2) => dl2(_, $2, r, o, i)), l = t.ends.map((_, $2) => dl2(_, $2, r, o, i)); if (o.length !== a.length || o.length !== l.length) throw new Error("start, ends and axes should have the same number of elements"); if (o.length !== r.length) for (let _ = 0; _ < r.length; ++_) o.includes(_) || (a.splice(_, 0, 0), l.splice(_, 0, r[_]), i.splice(_, 0, 1)); let d = i.map((_) => Math.sign(_)); i.forEach((_, $2, S) => { if (_ < 0) { let I2 = (l[$2] - a[$2]) / _, T3 = a[$2], A2 = T3 + I2 * i[$2]; a[$2] = A2, l[$2] = T3, S[$2] = -_; } }); let p = r.slice(0); o.forEach((_, $2) => { p[_] = Math.ceil((l[_] - a[_]) / i[_]); }); let m2 = { dims: p, dataType: e[0].dataType }, u = M("output", e[0].dataType, p.length), h = E("input", e[0].dataType, e[0].dims.length), w = k2.size(p), g = [{ name: "outputSize", type: "u32" }, { name: "starts", type: "u32", length: a.length }, { name: "signs", type: "i32", length: d.length }, { name: "steps", type: "u32", length: i.length }], b = [{ type: 12, data: w }, { type: 12, data: a }, { type: 6, data: d }, { type: 12, data: i }, ...V(e[0].dims, p)], x2 = (_) => ` ${_.registerUniforms(g).declareVariables(h, u)} ${oh(h, u, r)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx", h.getByIndices("input_indices"))} }`; return { name: "Slice", shaderCache: { hint: `${d.length}_${a.length}_${i.length}`, inputDependencies: ["rank"] }, getShaderSource: x2, getRunData: () => ({ outputs: [m2], dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: b }) }; }, ll2 = (e, t) => { rh2(e.inputs, t); let r = nh(e.inputs, t); e.compute(ih(e.inputs, r), { inputs: [0] }); }, cl2 = (e) => { let t = e.starts, r = e.ends, n = e.axes; return te({ starts: t, ends: r, axes: n }); }; }); hl2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); ah = (e) => { if (!e || e.length !== 1) throw new Error("Softmax op requires 1 input."); }, sh = (e, t) => { let r = e.dims, n = k2.size(r), o = 64, i = t.axis; if (i < 0 && (i = r.length + i), i < r.length - 1) throw new Error("softmax only supports last axis for now."); let a = r[i], l = n / a, d = $e2(a), p = a / d, m2 = (x2, _) => _ === 4 ? `max(max(${x2}.x, ${x2}.y), max(${x2}.z, ${x2}.w))` : _ === 2 ? `max(${x2}.x, ${x2}.y)` : _ === 3 ? `max(max(${x2}.x, ${x2}.y), ${x2}.z)` : x2, u = E("x", e.dataType, e.dims, d), h = M("result", e.dataType, e.dims, d), w = u.type.value, g = ge(e.dataType) === "f32" ? `var threadMax = ${w}(-3.402823e+38f);` : `var threadMax = ${w}(-65504.0h);`, b = (x2) => ` var rowMaxShared : ${w}; var rowSumShared : ${w}; var threadShared : array<${w}, ${o}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) { let index = row * row_stride + col; result[index] = value; } ${x2.registerUniform("packedCols", "i32").declareVariables(u, h)} ${x2.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${o}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${g} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${w}(${m2("threadShared[0]", d)}); } workgroupBarrier(); // find the rows sum var threadSum = ${w}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${w}(${Xe2("threadShared[0]", d)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`; return { name: "Softmax", shaderCache: { hint: `${d}`, inputDependencies: ["type"] }, getRunData: () => ({ outputs: [{ dims: r, dataType: e.dataType }], dispatchGroup: { x: l }, programUniforms: [{ type: 6, data: p }] }), getShaderSource: b }; }, ml2 = (e, t) => { ah(e.inputs), e.compute(sh(e.inputs[0], t)); }, fl2 = (e) => te({ axis: e.axis }); }); bl2 = U(() => { "use strict"; Q(); ae(); Ce2(); ie(); uh = (e) => { if (!e || e.length < 1) throw new Error("too few inputs"); }, dh2 = (e, t) => { let r = [], n = t.numOutputs; return e[1].dims[0] > 0 && (e[1].getBigInt64Array().forEach((o) => r.push(Number(o))), n = r.length), te({ numOutputs: n, axis: t.axis, splitSizes: r }); }, lh = (e) => ` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${G2("uniforms.size_in_split_axis", "i", e)}) { return i; } } return ${e}u; }`, ch = (e) => { let t = e.length, r = []; for (let n = 0; n < t; ++n) { let o = e[n].setByIndices("indices", "input[global_idx]"); t === 1 ? r.push(o) : n === 0 ? r.push(`if (output_number == ${n}u) { ${o} }`) : n === t - 1 ? r.push(`else { ${o} }`) : r.push(`else if (output_number == ${n}) { ${o} }`); } return ` fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) { ${r.join(` `)} }`; }, ph2 = (e, t) => { let r = e[0].dims, n = k2.size(r), o = e[0].dataType, i = k2.normalizeAxis(t.axis, r.length), a = new Array(t.numOutputs), l = E("input", o, r.length), d = new Array(t.numOutputs), p = [], m2 = [], u = 0, h = [{ type: 12, data: n }]; for (let g = 0; g < t.numOutputs; g++) { u += t.splitSizes[g], d[g] = u; let b = r.slice(); b[t.axis] = t.splitSizes[g], m2.push(b), a[g] = M(`output${g}`, o, b.length), p.push({ dims: m2[g], dataType: e[0].dataType }); } h.push({ type: 12, data: d }, ...V(r, ...m2)); let w = (g) => ` ${g.registerUniform("input_size", "u32").registerUniform("size_in_split_axis", "u32", d.length).declareVariables(l, ...a)} ${lh(d.length)} ${ch(a)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${l.offsetToIndices("global_idx")}; var index = ${l.indicesGet("indices", i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${G2("uniforms.size_in_split_axis", "output_number - 1u", d.length)}; ${l.indicesSet("indices", i, "index")}; } writeBufferData(output_number, indices, global_idx); }`; return { name: "Split", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank"] }, getShaderSource: w, getRunData: () => ({ outputs: p, dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: h }) }; }, gl2 = (e, t) => { uh(e.inputs); let r = e.inputs.length === 1 ? t : dh2(e.inputs, t); e.compute(ph2(e.inputs, r), { inputs: [0] }); }, yl2 = (e) => { let t = e.axis, r = e.splitSizes, n = e.numOutputs < 0 ? r.length : e.numOutputs; if (n !== r.length) throw new Error("numOutputs and splitSizes lengh must be equal"); return te({ axis: t, numOutputs: n, splitSizes: r }); }; }); vl2 = U(() => { "use strict"; Q(); ae(); ie(); mh2 = (e, t, r, n, o) => { let i = M("output_data", o, r.length, 4), a = E("a_data", t[1].dataType, t[1].dims.length, 4), l = E("b_data", t[2].dataType, t[2].dims.length, 4), d = E("c_data", t[0].dataType, t[0].dims.length, 4), p, m2 = (u, h, w) => `select(${h}, ${u}, ${w})`; if (!n) p = i.setByOffset("global_idx", m2(a.getByOffset("global_idx"), l.getByOffset("global_idx"), d.getByOffset("global_idx"))); else { let u = (h, w, g = "") => { let b = `a_data[index_a${w}][component_a${w}]`, x2 = `b_data[index_b${w}][component_b${w}]`, _ = `bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`; return ` let output_indices${w} = ${i.offsetToIndices(`global_idx * 4u + ${w}u`)}; let offset_a${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`, i)}; let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`, i)}; let offset_c${w} = ${d.broadcastedIndicesToOffset(`output_indices${w}`, i)}; let index_a${w} = offset_a${w} / 4u; let index_b${w} = offset_b${w} / 4u; let index_c${w} = offset_c${w} / 4u; let component_a${w} = offset_a${w} % 4u; let component_b${w} = offset_b${w} % 4u; let component_c${w} = offset_c${w} % 4u; ${h}[${w}] = ${g}(${m2(b, x2, _)}); `; }; o === 9 ? p = ` var data = vec4(0); ${u("data", 0, "u32")} ${u("data", 1, "u32")} ${u("data", 2, "u32")} ${u("data", 3, "u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : p = ` ${u("output_data[global_idx]", 0)} ${u("output_data[global_idx]", 1)} ${u("output_data[global_idx]", 2)} ${u("output_data[global_idx]", 3)} `; } return ` ${e.registerUniform("vec_size", "u32").declareVariables(d, a, l, i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${p} }`; }, fh = (e) => { let t = e[1].dims, r = e[2].dims, n = e[0].dims, o = e[1].dataType, i = !(k2.areEqual(t, r) && k2.areEqual(r, n)), a = t, l = k2.size(t); if (i) { let p = tt2.calcShape(tt2.calcShape(t, r, false), n, false); if (!p) throw new Error("Can't perform where op on the given tensors"); a = p, l = k2.size(a); } let d = Math.ceil(l / 4); return { name: "Where", shaderCache: { inputDependencies: ["rank", "rank", "rank"] }, getShaderSource: (p) => mh2(p, e, a, i, o), getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(l / 64 / 4) }, programUniforms: [{ type: 12, data: d }, ...V(n, t, r, a)] }) }; }, wl2 = (e) => { e.compute(fh(e.inputs)); }; }); _l2 = U(() => { "use strict"; xs2(); jr(); Cs2(); As2(); mu(); Su(); Tu2(); co2(); Fu2(); Ku2(); Zu2(); rd2(); id2(); sd2(); ld2(); md(); gd(); Cd(); Ad(); kd(); mo2(); Dd(); _o(); Bd(); Qd2(); el2(); Fr2(); ol2(); al2(); ul(); pl2(); hl2(); bl2(); So(); Et(); Yr(); vl2(); $l2 = /* @__PURE__ */ new Map([["Abs", [Es2]], ["Acos", [ks2]], ["Acosh", [Ps2]], ["Add", [fu]], ["ArgMax", [_s2, io2]], ["ArgMin", [$s2, io2]], ["Asin", [Os2]], ["Asinh", [Ds2]], ["Atan", [zs2]], ["Atanh", [Bs2]], ["Attention", [Ss2]], ["AveragePool", [Gd, Hd2]], ["BatchNormalization", [Is2]], ["BiasAdd", [Ts2]], ["BiasSplitGelu", [pu]], ["Cast", [Ms2, Rs2]], ["Ceil", [Vs2]], ["Clip", [Us2]], ["Concat", [Iu, Cu]], ["Conv", [yo2, go2]], ["ConvTranspose", [Lu2, Gu]], ["Cos", [Ns2]], ["Cosh", [Ws]], ["CumSum", [qu2, ju2]], ["DepthToSpace", [Yu2, Xu2]], ["Div", [hu]], ["Einsum", [ed2, td2]], ["Elu", [Hs2, Qt]], ["Equal", [gu]], ["Erf", [Gs2]], ["Exp", [Ls2]], ["Expand", [od2]], ["FastGelu", [ad2]], ["Floor", [Fs2]], ["FusedConv", [yo2, go2]], ["Gather", [dd, ud2]], ["GatherElements", [pd, cd2]], ["Gelu", [qs]], ["Gemm", [hd, fd2]], ["GlobalAveragePool", [qd2, Fd]], ["GlobalMaxPool", [Zd2, Xd2]], ["Greater", [vu]], ["GreaterOrEqual", [_u]], ["GroupQueryAttention", [Id, Sd]], ["HardSigmoid", [eu, Js]], ["InstanceNormalization", [Td]], ["LayerNormalization", [Ed]], ["LeakyRelu", [js, Qt]], ["Less", [$u]], ["LessOrEqual", [xu]], ["Log", [du]], ["MatMul", [Uu]], ["MatMulNBits", [Pd, Od]], ["MaxPool", [Kd2, Yd2]], ["Mul", [yu]], ["MultiHeadAttention", [wd, bd]], ["Neg", [Ys2]], ["Not", [Ks2]], ["Pad", [zd2]], ["Pow", [bu]], ["QuickGelu", [lu2, Qt]], ["Range", [Jd2]], ["Reciprocal", [Xs]], ["ReduceMin", [hs2]], ["ReduceMean", [ls2]], ["ReduceMax", [fs4]], ["ReduceSum", [ys2]], ["ReduceProd", [gs2]], ["ReduceL1", [cs2]], ["ReduceL2", [ps2]], ["ReduceLogSum", [ws2]], ["ReduceLogSumExp", [ms2]], ["ReduceSumSquare", [bs2]], ["Relu", [Zs]], ["Resize", [rl2, nl2]], ["RotaryEmbedding", [il2]], ["Sigmoid", [Qs]], ["Sin", [tu]], ["Sinh", [ru]], ["Slice", [ll2, cl2]], ["SkipLayerNormalization", [sl2]], ["Split", [gl2, yl2]], ["Sqrt", [nu]], ["Softmax", [ml2, fl2]], ["Sub", [wu]], ["Tan", [ou2]], ["Tanh", [au]], ["ThresholdedRelu", [uu, Qt]], ["Tile", [$d]], ["Transpose", [Za2, Qa2]], ["Where", [wl2]]]); }); xl2 = U(() => { "use strict"; Ke2(); dt2(); ie(); an2 = class { constructor(t) { this.backend = t; this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; } getArtifact(t) { return this.repo.get(t); } setArtifact(t, r) { this.repo.set(t, r); } run(t, r, n, o, i) { We2(t.programInfo.name); let a = this.backend.device, l = this.backend.getComputePassEncoder(); this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2); let d = []; for (let m2 of r) d.push({ binding: d.length, resource: { buffer: m2.buffer } }); for (let m2 of n) d.push({ binding: d.length, resource: { buffer: m2.buffer } }); i && d.push({ binding: d.length, resource: i }); let p = a.createBindGroup({ layout: t.computePipeline.getBindGroupLayout(0), entries: d, label: t.programInfo.name }); if (this.backend.sessionStatus === "capturing") { let m2 = { kernelId: this.backend.currentKernelId, computePipeline: t.computePipeline, bindGroup: p, dispatchGroup: o }; this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m2); } l.setPipeline(t.computePipeline), l.setBindGroup(0, p), l.dispatchWorkgroups(...o), this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2 + 1), this.backend.pendingDispatchNumber++, (this.backend.pendingDispatchNumber >= this.backend.maxDispatchNumber || this.backend.queryType === "at-passes") && this.backend.endComputePass(), this.backend.pendingDispatchNumber >= this.backend.maxDispatchNumber && this.backend.flush(), Me2(t.programInfo.name); } dispose() { } build(t, r) { We2(t.name); let n = this.backend.device, o = []; n.features.has("shader-f16") && o.push("enable f16;"); let i = Ya(r, this.backend.device.limits), a = t.getShaderSource(i), l = `${o.join(` `)} ${i.additionalImplementations} ${a}`, d = n.createShaderModule({ code: l, label: t.name }); ve("verbose", () => `[WebGPU] ${t.name} shader code: ${l}`); let p = n.createComputePipeline({ compute: { module: d, entryPoint: "main" }, layout: "auto", label: t.name }); return Me2(t.name), { programInfo: t, computePipeline: p, uniformVariablesInfo: i.variablesInfo }; } normalizeDispatchGroupSize(t) { let r = typeof t == "number" ? t : t.x, n = typeof t == "number" ? 1 : t.y || 1, o = typeof t == "number" ? 1 : t.z || 1, i = this.backend.device.limits.maxComputeWorkgroupsPerDimension; if (r <= i && n <= i && o <= i) return [r, n, o]; let a = r * n * o, l = Math.ceil(Math.sqrt(a)); if (l > i) { if (l = Math.ceil(Math.cbrt(a)), l > i) throw new Error("Total dispatch size exceeds WebGPU maximum."); return [l, l, l]; } else return [l, l, 1]; } }; }); Sl2 = U(() => { "use strict"; Ke2(); Q(); dt2(); Ga(); Ka(); _l2(); xl2(); hh2 = (e, t) => { if (t.length !== e.length) throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`); let r = []; for (let n = 0; n < e.length; ++n) { let o = e[n].dataType; switch (t[n]) { case "none": { r.push(""); break; } case "type": { r.push(`${o}`); break; } case "rank": { let i = e[n].dims.length; r.push(`${o};${i}`); break; } case "dims": { let i = e[n].dims.join(","); r.push(`${o};${i}`); break; } default: throw new Error(`unsupported input dependency: ${t[n]}`); } } return r.join("|"); }, gh2 = (e, t, r) => { let n = e.name; return e.shaderCache?.hint && (n += "[" + e.shaderCache.hint + "]"), n += ":" + r + `:${hh2(t, e.shaderCache?.inputDependencies ?? new Array(t.length).fill("dims"))}`, n; }, Io = class { constructor(t) { t && (this.architecture = t.architecture, this.vendor = t.vendor); } isArchitecture(t) { return this.architecture === t; } isVendor(t) { return this.vendor === t; } }, sn2 = class { constructor() { this.currentSessionId = null; this.currentKernelId = null; this.commandEncoder = null; this.computePassEncoder = null; this.maxDispatchNumber = 16; this.pendingDispatchNumber = 0; this.pendingKernels = []; this.pendingQueries = /* @__PURE__ */ new Map(); this.sessionStatus = "default"; this.capturedCommandList = /* @__PURE__ */ new Map(); this.capturedPendingKernels = /* @__PURE__ */ new Map(); this.sessionExternalDataMapping = /* @__PURE__ */ new Map(); } get currentKernelCustomData() { if (this.currentKernelId === null) throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)"); let t = this.kernelCustomData.get(this.currentKernelId); return t || (t = {}, this.kernelCustomData.set(this.currentKernelId, t)), t; } async initialize(t, r) { this.env = t; let n = [], o = { requiredLimits: { maxComputeWorkgroupStorageSize: r.limits.maxComputeWorkgroupStorageSize, maxComputeWorkgroupsPerDimension: r.limits.maxComputeWorkgroupsPerDimension, maxStorageBufferBindingSize: r.limits.maxStorageBufferBindingSize, maxBufferSize: r.limits.maxBufferSize, maxComputeInvocationsPerWorkgroup: r.limits.maxComputeInvocationsPerWorkgroup, maxComputeWorkgroupSizeX: r.limits.maxComputeWorkgroupSizeX, maxComputeWorkgroupSizeY: r.limits.maxComputeWorkgroupSizeY, maxComputeWorkgroupSizeZ: r.limits.maxComputeWorkgroupSizeZ }, requiredFeatures: n }; r.features.has("chromium-experimental-timestamp-query-inside-passes") ? n.push("chromium-experimental-timestamp-query-inside-passes") : r.features.has("timestamp-query") && n.push("timestamp-query"), r.features.has("shader-f16") && n.push("shader-f16"), this.device = await r.requestDevice(o), this.adapterInfo = new Io(r.info || await r.requestAdapterInfo()), this.gpuDataManager = ja(this), this.programManager = new an2(this), this.kernels = /* @__PURE__ */ new Map(), this.kernelPersistentData = /* @__PURE__ */ new Map(), this.kernelCustomData = /* @__PURE__ */ new Map(), Wa(t.logLevel, !!t.debug), this.device.onuncapturederror = (i) => { i.error instanceof GPUValidationError && console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`); }, Object.defineProperty(this.env.webgpu, "device", { value: this.device, writable: false, enumerable: true, configurable: false }), Object.defineProperty(this.env.webgpu, "adapter", { value: r, writable: false, enumerable: true, configurable: false }), this.setQueryType(); } dispose() { typeof this.querySet < "u" && this.querySet.destroy(), this.gpuDataManager.dispose(); } getCommandEncoder() { return this.commandEncoder || (this.commandEncoder = this.device.createCommandEncoder()), this.commandEncoder; } getComputePassEncoder() { if (!this.computePassEncoder) { let t = this.getCommandEncoder(), r = {}; this.queryType === "at-passes" && (r.timestampWrites = { querySet: this.querySet, beginningOfPassWriteIndex: this.pendingDispatchNumber * 2, endOfPassWriteIndex: this.pendingDispatchNumber * 2 + 1 }), this.computePassEncoder = t.beginComputePass(r); } return this.computePassEncoder; } endComputePass() { this.computePassEncoder && (this.computePassEncoder.end(), this.computePassEncoder = null); } flush() { if (!this.commandEncoder) return; We2(), this.endComputePass(); let t; this.queryType !== "none" && (this.commandEncoder.resolveQuerySet(this.querySet, 0, this.pendingDispatchNumber * 2, this.queryResolveBuffer, 0), t = this.device.createBuffer({ size: this.pendingDispatchNumber * 2 * 8, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }), this.pendingQueries.set(t, this.pendingKernels), this.pendingKernels = [], this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer, 0, t, 0, this.pendingDispatchNumber * 2 * 8)), this.device.queue.submit([this.commandEncoder.finish()]), this.gpuDataManager.refreshPendingBuffers(), this.commandEncoder = null, this.pendingDispatchNumber = 0, this.queryType !== "none" && t.mapAsync(GPUMapMode.READ).then(() => { let r = new BigUint64Array(t.getMappedRange()), n = this.pendingQueries.get(t); for (let o = 0; o < r.length / 2; o++) { let i = n[o], a = i.kernelId, l = this.kernels.get(a), d = l.kernelType, p = l.kernelName, m2 = i.programName, u = i.inputTensorViews, h = i.outputTensorViews, w = r[o * 2], g = r[o * 2 + 1]; typeof this.queryTimeBase > "u" && (this.queryTimeBase = w); let b = Number(w - this.queryTimeBase), x2 = Number(g - this.queryTimeBase); if (!Number.isSafeInteger(b) || !Number.isSafeInteger(x2)) throw new RangeError("incorrect timestamp range"); if (this.env.webgpu.profiling?.ondata) this.env.webgpu.profiling.ondata({ version: 1, inputsMetadata: u.map((_) => ({ dims: _.dims, dataType: ht2(_.dataType) })), outputsMetadata: h.map((_) => ({ dims: _.dims, dataType: ht2(_.dataType) })), kernelId: a, kernelType: d, kernelName: p, programName: m2, startTime: b, endTime: x2 }); else { let _ = ""; u.forEach((S, I2) => { _ += `input[${I2}]: [${S.dims}] | ${ht2(S.dataType)}, `; }); let $2 = ""; h.forEach((S, I2) => { $2 += `output[${I2}]: [${S.dims}] | ${ht2(S.dataType)}, `; }), console.log(`[profiling] kernel "${a}|${d}|${p}|${m2}" ${_}${$2}execution time: ${x2 - b} ns`); } Sr2("GPU", `${m2}::${w}::${g}`); } t.unmap(), this.pendingQueries.delete(t); }), Me2(); } run(t, r, n, o, i, a) { We2(t.name); let l = []; for (let S = 0; S < r.length; ++S) { let I2 = r[S].data; if (I2 === 0) continue; let T3 = this.gpuDataManager.get(I2); if (!T3) throw new Error(`no GPU data for input: ${I2}`); l.push(T3); } let { outputs: d, dispatchGroup: p, programUniforms: m2 } = t.getRunData(r), u = n.length === 0 ? d.map((S, I2) => I2) : n; if (u.length !== d.length) throw new Error(`Output size ${u.length} must be equal to ${d.length}.`); let h = [], w = []; for (let S = 0; S < d.length; ++S) { if (!Number.isInteger(u[S]) || u[S] < -3 || u[S] >= a) throw new Error(`Invalid output index: ${u[S]}`); if (u[S] === -3) continue; let I2 = u[S] === -1, T3 = u[S] === -2, A2 = I2 || T3 ? i(d[S].dataType, d[S].dims) : o(u[S], d[S].dataType, d[S].dims); if (h.push(A2), A2.data === 0) continue; let D3 = this.gpuDataManager.get(A2.data); if (!D3) throw new Error(`no GPU data for output: ${A2.data}`); if (I2 && this.temporaryData.push(D3), T3) { let z3 = this.kernelPersistentData.get(this.currentKernelId); z3 || (z3 = [], this.kernelPersistentData.set(this.currentKernelId, z3)), z3.push(D3); } w.push(D3); } if (l.length !== r.length || w.length !== h.length) { if (w.length === 0) return Me2(t.name), h; throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`); } let g; if (m2) { let S = 0, I2 = []; m2.forEach((z3) => { let H3 = typeof z3.data == "number" ? [z3.data] : z3.data; if (H3.length === 0) return; let W2 = z3.type === 10 ? 2 : 4, X, Y3; z3.type === 10 ? (Y3 = H3.length > 4 ? 16 : H3.length > 2 ? 8 : H3.length * W2, X = H3.length > 4 ? 16 : W2 * H3.length) : (Y3 = H3.length <= 2 ? H3.length * W2 : 16, X = 16), S = Math.ceil(S / Y3) * Y3, I2.push(S); let pe2 = z3.type === 10 ? 8 : 4; S += H3.length > 4 ? Math.ceil(H3.length / pe2) * X : H3.length * W2; }); let T3 = 16; S = Math.ceil(S / T3) * T3; let A2 = new ArrayBuffer(S); m2.forEach((z3, H3) => { let W2 = I2[H3], X = typeof z3.data == "number" ? [z3.data] : z3.data; if (z3.type === 6) new Int32Array(A2, W2, X.length).set(X); else if (z3.type === 12) new Uint32Array(A2, W2, X.length).set(X); else if (z3.type === 10) new Uint16Array(A2, W2, X.length).set(X); else if (z3.type === 1) new Float32Array(A2, W2, X.length).set(X); else throw new Error(`Unsupported uniform type: ${ht2(z3.type)}`); }); let D3 = this.gpuDataManager.create(S, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM); this.device.queue.writeBuffer(D3.buffer, 0, A2, 0, S), this.gpuDataManager.release(D3.id), g = { offset: 0, size: S, buffer: D3.buffer }; } let b = this.programManager.normalizeDispatchGroupSize(p), x2 = b[1] === 1 && b[2] === 1, _ = gh2(t, r, x2), $2 = this.programManager.getArtifact(_); if ($2 || ($2 = this.programManager.build(t, b), this.programManager.setArtifact(_, $2), ve("info", () => `[artifact] key: ${_}, programName: ${t.name}`)), m2 && $2.uniformVariablesInfo) { if (m2.length !== $2.uniformVariablesInfo.length) throw new Error(`Uniform variables count mismatch: expect ${$2.uniformVariablesInfo.length}, got ${m2.length} in program "${$2.programInfo.name}".`); for (let S = 0; S < m2.length; S++) { let I2 = m2[S], T3 = I2.type, A2 = typeof I2.data == "number" ? 1 : I2.data.length, [D3, z3] = $2.uniformVariablesInfo[S]; if (T3 !== D3 || A2 !== z3) throw new Error(`Uniform variable ${S} mismatch: expect type ${D3} with size ${z3}, got type ${T3} with size ${A2} in program "${$2.programInfo.name}".`); } } if (ve("info", () => `[ProgramManager] run "${t.name}" (key=${_}) with ${b[0]}x${b[1]}x${b[2]}`), this.queryType !== "none" || this.sessionStatus === "capturing") { let S = { kernelId: this.currentKernelId, programName: $2.programInfo.name, inputTensorViews: r, outputTensorViews: h }; this.pendingKernels.push(S), this.sessionStatus === "capturing" && this.capturedPendingKernels.get(this.currentSessionId).push(S); } return this.programManager.run($2, l, w, b, g), Me2(t.name), h; } upload(t, r) { this.gpuDataManager.upload(t, r); } memcpy(t, r) { this.gpuDataManager.memcpy(t, r); } async download(t, r) { await this.gpuDataManager.download(t, r); } alloc(t) { return this.gpuDataManager.create(t).id; } free(t) { return this.gpuDataManager.release(t); } createKernel(t, r, n, o) { let i = $l2.get(t); if (!i) throw new Error(`kernel not implemented: ${t}`); let a = { kernelType: t, kernelName: o, kernelEntry: i[0], attributes: [i[1], n] }; this.kernels.set(r, a); } releaseKernel(t) { let r = this.kernelPersistentData.get(t); if (r) { for (let n of r) this.gpuDataManager.release(n.id); this.kernelPersistentData.delete(t); } this.kernelCustomData.delete(t), this.kernels.delete(t); } computeKernel(t, r, n) { let o = this.kernels.get(t); if (!o) throw new Error(`kernel not created: ${t}`); let i = o.kernelType, a = o.kernelName, l = o.kernelEntry, d = o.attributes; if (this.currentKernelId !== null) throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`); this.currentKernelId = t, d[0] && (d[1] = d[0](d[1]), d[0] = void 0), ve("info", () => `[WebGPU] Start to run kernel "[${i}] ${a}"...`); let p = this.env.debug; this.temporaryData = []; try { return p && this.device.pushErrorScope("validation"), l(r, d[1]), 0; } catch (m2) { return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${m2}`)), 1; } finally { p && n.push(this.device.popErrorScope().then((m2) => m2 ? `GPU validation error for kernel "[${i}] ${a}": ${m2.message}` : null)); for (let m2 of this.temporaryData) this.gpuDataManager.release(m2.id); this.temporaryData = [], this.currentKernelId = null; } } registerBuffer(t, r, n, o) { let i = this.sessionExternalDataMapping.get(t); i || (i = /* @__PURE__ */ new Map(), this.sessionExternalDataMapping.set(t, i)); let a = i.get(r), l = this.gpuDataManager.registerExternalBuffer(n, o, a?.[1]); return i.set(r, [l, n]), l; } unregisterBuffers(t) { let r = this.sessionExternalDataMapping.get(t); r && (r.forEach((n) => this.gpuDataManager.unregisterExternalBuffer(n[1])), this.sessionExternalDataMapping.delete(t)); } getBuffer(t) { let r = this.gpuDataManager.get(t); if (!r) throw new Error(`no GPU data for buffer: ${t}`); return r.buffer; } createDownloader(t, r, n) { return async () => { let o = await Qn2(this, t, r); return Ha(o.buffer, n); }; } writeTimestamp(t) { this.queryType === "inside-passes" && this.computePassEncoder.writeTimestamp(this.querySet, t); } setQueryType() { this.queryType = "none", (this.env.webgpu.profiling?.mode === "default" || (typeof this.env.trace > "u" ? this.env.wasm.trace : this.env.trace)) && (this.device.features.has("chromium-experimental-timestamp-query-inside-passes") ? this.queryType = "inside-passes" : this.device.features.has("timestamp-query") && (this.queryType = "at-passes"), this.queryType !== "none" && typeof this.querySet > "u" && (this.querySet = this.device.createQuerySet({ type: "timestamp", count: this.maxDispatchNumber * 2 }), this.queryResolveBuffer = this.device.createBuffer({ size: this.maxDispatchNumber * 2 * 8, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.QUERY_RESOLVE }))); } captureBegin() { ve("info", "captureBegin"), this.capturedCommandList.get(this.currentSessionId) || this.capturedCommandList.set(this.currentSessionId, []), this.capturedPendingKernels.get(this.currentSessionId) || this.capturedPendingKernels.set(this.currentSessionId, []), this.flush(), this.sessionStatus = "capturing"; } captureEnd() { ve("info", "captureEnd"), this.flush(), this.sessionStatus = "default"; } replay() { ve("info", "replay"), this.sessionStatus = "replaying"; let t = this.capturedCommandList.get(this.currentSessionId), r = this.capturedPendingKernels.get(this.currentSessionId), n = t.length; this.pendingKernels = []; for (let o = 0; o < n; o++) { let i = this.getComputePassEncoder(), a = t[o]; this.writeTimestamp(this.pendingDispatchNumber * 2), i.setPipeline(a.computePipeline), i.setBindGroup(0, a.bindGroup), i.dispatchWorkgroups(...a.dispatchGroup), this.writeTimestamp(this.pendingDispatchNumber * 2 + 1), this.pendingDispatchNumber++, this.queryType !== "none" && this.pendingKernels.push(r[o]), (this.pendingDispatchNumber >= this.maxDispatchNumber || this.queryType === "at-passes") && this.endComputePass(), this.pendingDispatchNumber >= this.maxDispatchNumber && this.flush(); } this.flush(), this.sessionStatus = "default"; } onReleaseSession(t) { this.unregisterBuffers(t), this.capturedCommandList.has(t) && this.capturedCommandList.delete(t), this.capturedPendingKernels.has(t) && this.capturedPendingKernels.delete(t), this.gpuDataManager.onReleaseSession(t); } onRunStart(t) { this.currentSessionId = t, this.setQueryType(); } }; }); Il2 = {}; Ft2(Il2, { init: () => yh2 }); Cl2 = U(() => { "use strict"; Q(); Sl2(); dt2(); ae(); or2 = class e { constructor(t, r, n, o) { this.module = t; this.dataType = r; this.data = n; this.dims = o; } getFloat32Array() { if (this.dataType !== 1) throw new Error("Invalid data type"); let t = k2.size(this.dims); return t === 0 ? new Float32Array() : new Float32Array(this.module.HEAP8.buffer, this.data, t); } getBigInt64Array() { if (this.dataType !== 7) throw new Error("Invalid data type"); let t = k2.size(this.dims); return t === 0 ? new BigInt64Array() : new BigInt64Array(this.module.HEAP8.buffer, this.data, t); } getInt32Array() { if (this.dataType !== 6) throw new Error("Invalid data type"); let t = k2.size(this.dims); return t === 0 ? new Int32Array() : new Int32Array(this.module.HEAP8.buffer, this.data, t); } reshape(t) { if (k2.size(t) !== k2.size(this.dims)) throw new Error("Invalid new shape"); return new e(this.module, this.dataType, this.data, t); } }, Co2 = class { constructor(t, r, n) { this.module = t; this.backend = r; this.customDataOffset = 0; this.customDataSize = 0; this.adapterInfo = r.adapterInfo; let o = t.HEAPU32, i = n >>> 2; this.opKernelContext = o[i++]; let a = o[i++]; this.outputCount = o[i++], this.customDataOffset = o[i++], this.customDataSize = o[i++]; let l = []; for (let d = 0; d < a; d++) { let p = o[i++], m2 = o[i++], u = o[i++], h = []; for (let w = 0; w < u; w++) h.push(o[i++]); l.push(new or2(t, p, m2, h)); } this.inputs = l; } get kernelCustomData() { return this.backend.currentKernelCustomData; } get customDataBuffer() { return this.module.HEAPU8.subarray(this.customDataOffset, this.customDataOffset + this.customDataSize); } getMaxComputeWorkgroupSizes() { return [this.backend.device.limits.maxComputeWorkgroupSizeX, this.backend.device.limits.maxComputeWorkgroupSizeY, this.backend.device.limits.maxComputeWorkgroupSizeZ]; } getMaxComputeWorkgroupStoragesize() { return this.backend.device.limits.maxComputeWorkgroupStorageSize; } compute(t, r) { let n = r?.inputs?.map((l) => typeof l == "number" ? this.inputs[l] : l) ?? this.inputs, o = r?.outputs ?? [], i = (l, d, p) => new or2(this.module, d, this.output(l, p), p), a = (l, d) => { let p = It(l); if (!p) throw new Error(`Unsupported data type: ${l}`); let m2 = p * k2.size(d), u = m2 > 0 ? this.backend.gpuDataManager.create(m2).id : 0; return new or2(this.module, l, u, d); }; return this.backend.run(t, n, o, i, a, this.outputCount); } output(t, r) { let n = this.module.stackSave(); try { let o = this.module.stackAlloc((1 + r.length) * 4), i = o >> 2; this.module.HEAPU32[i++] = r.length; for (let a = 0; a < r.length; a++) this.module.HEAPU32[i++] = r[a]; return this.module._JsepOutput(this.opKernelContext, t, o); } catch (o) { throw new Error(`Failed to generate kernel's output[${t}] with dims [${r}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${o}`); } finally { this.module.stackRestore(n); } } }, yh2 = async (e, t, r, n) => { let o = t.jsepInit; if (!o) throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support."); if (e === "webgpu") { let i = new sn2(); await i.initialize(r, n), o("webgpu", [i, (a) => i.alloc(a), (a) => i.free(a), (a, l, d, p = false) => { if (p) ve("verbose", () => `[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${l}, size=${d}`), i.memcpy(a, l); else { ve("verbose", () => `[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${l}, size=${d}`); let m2 = t.HEAPU8.subarray(a >>> 0, (a >>> 0) + d); i.upload(l, m2); } }, async (a, l, d) => { ve("verbose", () => `[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`), await i.download(a, () => t.HEAPU8.subarray(l >>> 0, (l >>> 0) + d)); }, (a, l, d) => i.createKernel(a, l, d, t.UTF8ToString(t._JsepGetNodeName(l))), (a) => i.releaseKernel(a), (a, l, d, p) => { ve("verbose", () => `[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`); let m2 = new Co2(t, i, l); return i.computeKernel(a, m2, p); }, () => i.captureBegin(), () => i.captureEnd(), () => i.replay()]); } else o("webnn"); }; }); Hn2 = U(() => { "use strict"; Ra(); Ua(); Q(); St(); Mr2(); Kn2(); bh2 = (e, t) => { Ie2()._OrtInit(e, t) !== 0 && _e("Can't initialize onnxruntime."); }, Er = async (e) => { bh2(e.wasm.numThreads, Xt2(e.logLevel)); }, kr2 = async (e, t) => { { let r = (Cl2(), br2(Il2)).init; if (t === "webgpu") { if (typeof navigator > "u" || !navigator.gpu) throw new Error("WebGPU is not supported in current environment"); let n = e.webgpu.adapter; if (n) { if (typeof n.limits != "object" || typeof n.features != "object" || typeof n.requestDevice != "function") throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object."); } else { let o = e.webgpu.powerPreference; if (o !== void 0 && o !== "low-power" && o !== "high-performance") throw new Error(`Invalid powerPreference setting: "${o}"`); let i = e.webgpu.forceFallbackAdapter; if (i !== void 0 && typeof i != "boolean") throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`); if (n = await navigator.gpu.requestAdapter({ powerPreference: o, forceFallbackAdapter: i }), !n) throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.'); } await r("webgpu", Ie2(), e, n); } if (t === "webnn") { if (typeof navigator > "u" || !navigator.ml) throw new Error("WebNN is not supported in current environment"); await r("webnn", Ie2(), e); } } }, kt2 = /* @__PURE__ */ new Map(), wh2 = (e) => { let t = Ie2(), r = t.stackSave(); try { let n = t.stackAlloc(8); return t._OrtGetInputOutputCount(e, n, n + 4) !== 0 && _e("Can't get session input/output count."), [t.HEAP32[n / 4], t.HEAP32[n / 4 + 1]]; } finally { t.stackRestore(r); } }, Kt2 = (e) => { let t = Ie2(), r = t._malloc(e.byteLength); if (r === 0) throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`); return t.HEAPU8.set(e, r), [r, e.byteLength]; }, Pr2 = async (e, t) => { let r, n, o = Ie2(); Array.isArray(e) ? [r, n] = e : e.buffer === o.HEAPU8.buffer ? [r, n] = [e.byteOffset, e.byteLength] : [r, n] = Kt2(e); let i = 0, a = 0, l = 0, d = [], p = [], m2 = []; try { if ([a, d] = Ma(t), t?.externalData && o.mountExternalData) { let $2 = []; for (let S of t.externalData) { let I2 = typeof S == "string" ? S : S.path; $2.push(Zt(typeof S == "string" ? S : S.data).then((T3) => { o.mountExternalData(I2, T3); })); } await Promise.all($2); } for (let $2 of t?.executionProviders ?? []) if ((typeof $2 == "string" ? $2 : $2.name) === "webnn") { if (o.currentContext) throw new Error("WebNN execution provider is already set."); if (typeof $2 != "string") { let I2 = $2, T3 = I2?.context, A2 = I2?.gpuDevice, D3 = I2?.deviceType, z3 = I2?.numThreads, H3 = I2?.powerPreference; T3 ? o.currentContext = T3 : A2 ? o.currentContext = await navigator.ml.createContext(A2) : o.currentContext = await navigator.ml.createContext({ deviceType: D3, numThreads: z3, powerPreference: H3 }); } else o.currentContext = await navigator.ml.createContext(); break; } i = await o._OrtCreateSession(r, n, a), i === 0 && _e("Can't create a session."), o.currentContext && (o.currentContext = void 0); let [u, h] = wh2(i), w = !!t?.enableGraphCapture, g = [], b = [], x2 = []; for (let $2 = 0; $2 < u; $2++) { let S = o._OrtGetInputName(i, $2); S === 0 && _e("Can't get an input name."), p.push(S), g.push(o.UTF8ToString(S)); } for (let $2 = 0; $2 < h; $2++) { let S = o._OrtGetOutputName(i, $2); S === 0 && _e("Can't get an output name."), m2.push(S); let I2 = o.UTF8ToString(S); b.push(I2); { if (w && t?.preferredOutputLocation === void 0) { x2.push("gpu-buffer"); continue; } let T3 = typeof t?.preferredOutputLocation == "string" ? t.preferredOutputLocation : t?.preferredOutputLocation?.[I2] ?? "cpu"; if (T3 !== "cpu" && T3 !== "cpu-pinned" && T3 !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${T3}.`); if (w && T3 !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${T3}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`); x2.push(T3); } } let _ = null; return x2.some(($2) => $2 === "gpu-buffer") && (l = o._OrtCreateBinding(i), l === 0 && _e("Can't create IO binding."), _ = { handle: l, outputPreferredLocations: x2, outputPreferredLocationsEncoded: x2.map(($2) => jn2($2)) }), kt2.set(i, [i, p, m2, _, w, false]), [i, g, b]; } catch (u) { throw p.forEach((h) => o._OrtFree(h)), m2.forEach((h) => o._OrtFree(h)), l !== 0 && o._OrtReleaseBinding(l), i !== 0 && o._OrtReleaseSession(i), u; } finally { o._free(r), a !== 0 && o._OrtReleaseSessionOptions(a), d.forEach((u) => o._free(u)), o.unmountExternalData?.(); } }, Or2 = (e) => { let t = Ie2(), r = kt2.get(e); if (!r) throw new Error(`cannot release session. invalid session id: ${e}`); let [n, o, i, a, l] = r; a && (l && t._OrtClearBoundOutputs(a.handle), t._OrtReleaseBinding(a.handle)), t.jsepOnReleaseSession?.(e), o.forEach((d) => t._OrtFree(d)), i.forEach((d) => t._OrtFree(d)), t._OrtReleaseSession(n), kt2.delete(e); }, Tl2 = (e, t, r, n, o, i = false) => { if (!e) { t.push(0); return; } let a = Ie2(), l = e[0], d = e[1], p = e[3], m2, u; if (l === "string" && p === "gpu-buffer") throw new Error("String tensor is not supported on GPU."); if (i && p !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`); if (p === "gpu-buffer") { let g = e[2].gpuBuffer, b = It(qn2(l)); u = d.reduce((_, $2) => _ * $2, 1) * b; let x2 = a.jsepRegisterBuffer; if (!x2) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.'); m2 = x2(n, o, g, u); } else { let g = e[2]; if (Array.isArray(g)) { u = 4 * g.length, m2 = a._malloc(u), r.push(m2); let b = m2 / 4; for (let x2 = 0; x2 < g.length; x2++) { if (typeof g[x2] != "string") throw new TypeError(`tensor data at index ${x2} is not a string`); a.HEAPU32[b++] = Te(g[x2], r); } } else u = g.byteLength, m2 = a._malloc(u), r.push(m2), a.HEAPU8.set(new Uint8Array(g.buffer, g.byteOffset, u), m2); } let h = a.stackSave(), w = a.stackAlloc(4 * d.length); try { let g = w / 4; d.forEach((x2) => a.HEAP32[g++] = x2); let b = a._OrtCreateTensor(qn2(l), m2, u, w, d.length, jn2(p)); b === 0 && _e(`Can't create tensor for input/output. session=${n}, index=${o}.`), t.push(b); } finally { a.stackRestore(h); } }, Dr = async (e, t, r, n, o, i) => { let a = Ie2(), l = kt2.get(e); if (!l) throw new Error(`cannot run inference. invalid session id: ${e}`); let d = l[0], p = l[1], m2 = l[2], u = l[3], h = l[4], w = l[5], g = t.length, b = n.length, x2 = 0, _ = [], $2 = [], S = [], I2 = [], T3 = a.stackSave(), A2 = a.stackAlloc(g * 4), D3 = a.stackAlloc(g * 4), z3 = a.stackAlloc(b * 4), H3 = a.stackAlloc(b * 4); try { [x2, _] = Ba(i); for (let K = 0; K < g; K++) Tl2(r[K], $2, I2, e, t[K], h); for (let K = 0; K < b; K++) Tl2(o[K], S, I2, e, g + n[K], h); let W2 = A2 / 4, X = D3 / 4, Y3 = z3 / 4, pe2 = H3 / 4; for (let K = 0; K < g; K++) a.HEAPU32[W2++] = $2[K], a.HEAPU32[X++] = p[t[K]]; for (let K = 0; K < b; K++) a.HEAPU32[Y3++] = S[K], a.HEAPU32[pe2++] = m2[n[K]]; if (u && !w) { let { handle: K, outputPreferredLocations: de2, outputPreferredLocationsEncoded: re2 } = u; if (p.length !== g) throw new Error(`input count from feeds (${g}) is expected to be always equal to model's input count (${p.length}).`); for (let se2 = 0; se2 < g; se2++) { let Z2 = t[se2]; await a._OrtBindInput(K, p[Z2], $2[se2]) !== 0 && _e(`Can't bind input[${se2}] for session=${e}.`); } for (let se2 = 0; se2 < b; se2++) { let Z2 = n[se2]; o[se2]?.[3] ? a._OrtBindOutput(K, m2[Z2], S[se2], 0) !== 0 && _e(`Can't bind pre-allocated output[${se2}] for session=${e}.`) : a._OrtBindOutput(K, m2[Z2], 0, re2[Z2]) !== 0 && _e(`Can't bind output[${se2}] to ${de2[se2]} for session=${e}.`); } kt2.set(e, [d, p, m2, u, h, true]); } a.jsepOnRunStart?.(d); let ue3; u ? ue3 = await a._OrtRunWithBinding(d, u.handle, b, z3, x2) : ue3 = await a._OrtRun(d, D3, A2, g, H3, b, z3, x2), ue3 !== 0 && _e("failed to call OrtRun()."); let le3 = []; for (let K = 0; K < b; K++) { let de2 = a.HEAPU32[z3 / 4 + K]; if (de2 === S[K]) { le3.push(o[K]); continue; } let re2 = a.stackSave(), se2 = a.stackAlloc(4 * 4), Z2 = false, ne2, J3 = 0; try { a._OrtGetTensorData(de2, se2, se2 + 4, se2 + 8, se2 + 12) !== 0 && _e(`Can't access output tensor data on index ${K}.`); let R = se2 / 4, F2 = a.HEAPU32[R++]; J3 = a.HEAPU32[R++]; let ce3 = a.HEAPU32[R++], Re2 = a.HEAPU32[R++], Se2 = []; for (let Pe3 = 0; Pe3 < Re2; Pe3++) Se2.push(a.HEAPU32[ce3 / 4 + Pe3]); a._OrtFree(ce3); let we2 = Se2.reduce((Pe3, ze3) => Pe3 * ze3, 1); ne2 = ht2(F2); let Lt3 = u?.outputPreferredLocations[n[K]]; if (ne2 === "string") { if (Lt3 === "gpu-buffer") throw new Error("String tensor is not supported on GPU."); let Pe3 = [], ze3 = J3 / 4; for (let Fe3 = 0; Fe3 < we2; Fe3++) { let Ot = a.HEAPU32[ze3++], yt3 = Fe3 === we2 - 1 ? void 0 : a.HEAPU32[ze3] - Ot; Pe3.push(a.UTF8ToString(Ot, yt3)); } le3.push([ne2, Se2, Pe3, "cpu"]); } else if (Lt3 === "gpu-buffer" && we2 > 0) { let Pe3 = a.jsepGetBuffer; if (!Pe3) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.'); let ze3 = Pe3(J3), Fe3 = It(F2); if (Fe3 === void 0 || !Vr2(ne2)) throw new Error(`Unsupported data type: ${ne2}`); Z2 = true, le3.push([ne2, Se2, { gpuBuffer: ze3, download: a.jsepCreateDownloader(ze3, we2 * Fe3, ne2), dispose: () => { a._OrtReleaseTensor(de2); } }, "gpu-buffer"]); } else { let Pe3 = Ur2(ne2), ze3 = new Pe3(we2); new Uint8Array(ze3.buffer, ze3.byteOffset, ze3.byteLength).set(a.HEAPU8.subarray(J3, J3 + ze3.byteLength)), le3.push([ne2, Se2, ze3, "cpu"]); } } finally { a.stackRestore(re2), ne2 === "string" && J3 && a._free(J3), Z2 || a._OrtReleaseTensor(de2); } } return u && !h && (a._OrtClearBoundOutputs(u.handle), kt2.set(e, [d, p, m2, u, h, false])), le3; } finally { a.stackRestore(T3), $2.forEach((W2) => a._OrtReleaseTensor(W2)), S.forEach((W2) => a._OrtReleaseTensor(W2)), I2.forEach((W2) => a._free(W2)), x2 !== 0 && a._OrtReleaseRunOptions(x2), _.forEach((W2) => a._free(W2)); } }, zr2 = (e) => { let t = Ie2(), r = kt2.get(e); if (!r) throw new Error("invalid session id"); let n = r[0], o = t._OrtEndProfiling(n); o === 0 && _e("Can't get an profile file name."), t._OrtFree(o); }, Br2 = (e) => { let t = []; for (let r of e) { let n = r[2]; !Array.isArray(n) && "buffer" in n && t.push(n.buffer); } return t; }; }); Eo = U(() => { "use strict"; Ke2(); Hn2(); St(); jt2(); Pt2 = () => !!be2.wasm.proxy && typeof document < "u", ir2 = false, dn2 = false, ln2 = false, Ao = /* @__PURE__ */ new Map(), Ht2 = (e, t) => { let r = Ao.get(e); r ? r.push(t) : Ao.set(e, [t]); }, Gt = () => { if (ir2 || !dn2 || ln2 || !Ye) throw new Error("worker not ready"); }, $h2 = (e) => { switch (e.data.type) { case "init-wasm": ir2 = false, e.data.err ? (ln2 = true, To[1](e.data.err)) : (dn2 = true, To[0]()), un2 && (URL.revokeObjectURL(un2), un2 = void 0); break; case "init-ep": case "copy-from": case "create": case "release": case "run": case "end-profiling": { let t = Ao.get(e.data.type); e.data.err ? t.shift()[1](e.data.err) : t.shift()[0](e.data.out); break; } default: } }, Al2 = async () => { if (!dn2) { if (ir2) throw new Error("multiple calls to 'initWasm()' detected."); if (ln2) throw new Error("previous call to 'initWasm()' failed."); if (ir2 = true, Pt2()) return new Promise((e, t) => { Ye?.terminate(), Oa().then(([r, n]) => { try { Ye = n, Ye.onerror = (i) => t(i), Ye.onmessage = $h2, To = [e, t]; let o = { type: "init-wasm", in: be2 }; Ye.postMessage(o), un2 = r; } catch (o) { t(o); } }, t); }); try { await Ar2(be2.wasm), await Er(be2), dn2 = true; } catch (e) { throw ln2 = true, e; } finally { ir2 = false; } } }, El2 = async (e) => { if (Pt2()) return Gt(), new Promise((t, r) => { Ht2("init-ep", [t, r]); let n = { type: "init-ep", in: { epName: e, env: be2 } }; Ye.postMessage(n); }); await kr2(be2, e); }, kl2 = async (e) => Pt2() ? (Gt(), new Promise((t, r) => { Ht2("copy-from", [t, r]); let n = { type: "copy-from", in: { buffer: e } }; Ye.postMessage(n, [e.buffer]); })) : Kt2(e), Pl2 = async (e, t) => { if (Pt2()) { if (t?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); return Gt(), new Promise((r, n) => { Ht2("create", [r, n]); let o = { type: "create", in: { model: e, options: { ...t } } }, i = []; e instanceof Uint8Array && i.push(e.buffer), Ye.postMessage(o, i); }); } else return Pr2(e, t); }, Ol2 = async (e) => { if (Pt2()) return Gt(), new Promise((t, r) => { Ht2("release", [t, r]); let n = { type: "release", in: e }; Ye.postMessage(n); }); Or2(e); }, Dl2 = async (e, t, r, n, o, i) => { if (Pt2()) { if (r.some((a) => a[3] !== "cpu")) throw new Error("input tensor on GPU is not supported for proxy."); if (o.some((a) => a)) throw new Error("pre-allocated output tensor is not supported for proxy."); return Gt(), new Promise((a, l) => { Ht2("run", [a, l]); let d = r, p = { type: "run", in: { sessionId: e, inputIndices: t, inputs: d, outputIndices: n, options: i } }; Ye.postMessage(p, Br2(d)); }); } else return Dr(e, t, r, n, o, i); }, zl2 = async (e) => { if (Pt2()) return Gt(), new Promise((t, r) => { Ht2("end-profiling", [t, r]); let n = { type: "end-profiling", in: e }; Ye.postMessage(n); }); zr2(e); }; }); Rl2 = U(() => { "use strict"; Ke2(); Eo(); Q(); Tr2(); Kn2(); Bl2 = (e, t) => { switch (e.location) { case "cpu": return [e.type, e.dims, e.data, "cpu"]; case "gpu-buffer": return [e.type, e.dims, { gpuBuffer: e.gpuBuffer }, "gpu-buffer"]; default: throw new Error(`invalid data location: ${e.location} for ${t()}`); } }, _h2 = (e) => { switch (e[3]) { case "cpu": return new De(e[0], e[2], e[1]); case "gpu-buffer": { let t = e[0]; if (!Vr2(t)) throw new Error(`not supported data type: ${t} for deserializing GPU tensor`); let { gpuBuffer: r, download: n, dispose: o } = e[2]; return De.fromGpuBuffer(r, { dataType: t, dims: e[1], download: n, dispose: o }); } default: throw new Error(`invalid data location: ${e[3]}`); } }, cn2 = class { async fetchModelAndCopyToWasmMemory(t) { return kl2(await Zt(t)); } async loadModel(t, r) { We2(); let n; typeof t == "string" ? false ? n = await Zt(t) : n = await this.fetchModelAndCopyToWasmMemory(t) : n = t, [this.sessionId, this.inputNames, this.outputNames] = await Pl2(n, r), Me2(); } async dispose() { return Ol2(this.sessionId); } async run(t, r, n) { We2(); let o = [], i = []; Object.entries(t).forEach((h) => { let w = h[0], g = h[1], b = this.inputNames.indexOf(w); if (b === -1) throw new Error(`invalid input '${w}'`); o.push(g), i.push(b); }); let a = [], l = []; Object.entries(r).forEach((h) => { let w = h[0], g = h[1], b = this.outputNames.indexOf(w); if (b === -1) throw new Error(`invalid output '${w}'`); a.push(g), l.push(b); }); let d = o.map((h, w) => Bl2(h, () => `input "${this.inputNames[i[w]]}"`)), p = a.map((h, w) => h ? Bl2(h, () => `output "${this.outputNames[l[w]]}"`) : null), m2 = await Dl2(this.sessionId, i, d, l, p, n), u = {}; for (let h = 0; h < m2.length; h++) u[this.outputNames[l[h]]] = a[h] ?? _h2(m2[h]); return Me2(), u; } startProfiling() { } endProfiling() { zl2(this.sessionId); } }; }); Ml2 = U(() => { "use strict"; Ke2(); Eo(); Rl2(); jt2(); xh2 = () => { if ((typeof be2.wasm.initTimeout != "number" || be2.wasm.initTimeout < 0) && (be2.wasm.initTimeout = 0), be2.wasm.simd === false && console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'), typeof be2.wasm.proxy != "boolean" && (be2.wasm.proxy = false), typeof be2.wasm.trace != "boolean" && (be2.wasm.trace = false), typeof be2.wasm.numThreads != "number" || !Number.isInteger(be2.wasm.numThreads) || be2.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) be2.wasm.numThreads = 1; else { let e = typeof navigator > "u" ? Mn2("node:os").cpus().length : navigator.hardwareConcurrency; be2.wasm.numThreads = Math.min(4, Math.ceil((e || 1) / 2)); } }, pn2 = class { async init(t) { xh2(), await Al2(), await El2(t); } async createInferenceSessionHandler(t, r) { let n = new cn2(); return await n.loadModel(t, r), Promise.resolve(n); } }; }); Ul2 = {}; Ft2(Ul2, { wasmBackend: () => Sh2 }); Vl2 = U(() => { "use strict"; Ml2(); Sh2 = new pn2(); }); Ke2(); Ke2(); Ke2(); xa = "1.19.2"; K_ = Wn2; { let e = (Vl2(), br2(Ul2)).wasmBackend; _t2("webgpu", e, 5), _t2("webnn", e, 5), _t2("cpu", e, 10), _t2("wasm", e, 10); } Object.defineProperty(be2.versions, "web", { value: xa, enumerable: true }); } }); // node_modules/gliner/node_modules/onnxruntime-web/dist/ort.webgl.min.mjs function Nt3(a, e, o, t) { if (e === void 0) return Gl2(a); if (o === void 0) We3(a, e, 1); else if (typeof o == "number" && t === void 0) We3(a, e, o); else if (typeof o == "string" && t === void 0) We3(a, o, 1, e); else if (typeof o == "string" && typeof t == "number") We3(a, o, t, e); else throw new TypeError("input is valid"); } function Gl2(a) { return { verbose: Nt3.verbose.bind(null, a), info: Nt3.info.bind(null, a), warning: Nt3.warning.bind(null, a), error: Nt3.error.bind(null, a), fatal: Nt3.fatal.bind(null, a) }; } function We3(a, e, o, t) { let n = ye[t || ""] || ye[""]; Io2[a] < Io2[n.minimalSeverity] || (n.logDateTime && (e = `${(/* @__PURE__ */ new Date()).toISOString()}|${e}`), n.logSourceLocation, Cl3[n.provider].log(a, e, t)); } function So2(a, e, o) { for (let t of o) { let n = t[0], r = t[1], s = t[2], i = t[3], u = t[4]; if (a.opType === n) { for (let l of e) if ((l.domain === r || l.domain === "ai.onnx" && r === "") && Rl3(l.version, s)) return { opImpl: i, opInit: u }; } } throw new TypeError(`cannot resolve operator '${a.opType}' with opsets: ${e.map((t) => `${t.domain || "ai.onnx"} v${t.version}`).join(", ")}`); } function Rl3(a, e) { if (e.endsWith("+")) { let o = Number.parseInt(e.substring(0, e.length - 1), 10); return !isNaN(o) && o <= a; } else if (e.split("-").length === 2) { let o = e.split("-"), t = Number.parseInt(o[0], 10), n = Number.parseInt(o[1], 10); return !isNaN(t) && !isNaN(n) && t <= a && a <= n; } else return Number.parseInt(e, 10) === a; } function U2(a, e, o) { this.low = a | 0, this.high = e | 0, this.unsigned = !!o; } function rt3(a) { return (a && a.__isLong__) === true; } function Po(a) { var e = Math.clz32(a & -a); return a ? 31 - e : e; } function Ht3(a, e) { var o, t, n; return e ? (a >>>= 0, (n = 0 <= a && a < 256) && (t = Do[a], t) ? t : (o = V2(a, 0, true), n && (Do[a] = o), o)) : (a |= 0, (n = -128 <= a && a < 128) && (t = Eo2[a], t) ? t : (o = V2(a, a < 0 ? -1 : 0, false), n && (Eo2[a] = o), o)); } function ht3(a, e) { if (isNaN(a)) return e ? $t3 : Tt3; if (e) { if (a < 0) return $t3; if (a >= Bo2) return Co3; } else { if (a <= -$o2) return ut; if (a + 1 >= $o2) return No2; } return a < 0 ? ht3(-a, e).neg() : V2(a % ie2 | 0, a / ie2 | 0, e); } function V2(a, e, o) { return new U2(a, e, o); } function Mr3(a, e, o) { if (a.length === 0) throw Error("empty string"); if (typeof e == "number" ? (o = e, e = false) : e = !!e, a === "NaN" || a === "Infinity" || a === "+Infinity" || a === "-Infinity") return e ? $t3 : Tt3; if (o = o || 10, o < 2 || 36 < o) throw RangeError("radix"); var t; if ((t = a.indexOf("-")) > 0) throw Error("interior hyphen"); if (t === 0) return Mr3(a.substring(1), e, o).neg(); for (var n = ht3(Xe3(o, 8)), r = Tt3, s = 0; s < a.length; s += 8) { var i = Math.min(8, a.length - s), u = parseInt(a.substring(s, s + i), o); if (i < 8) { var l = ht3(Xe3(o, i)); r = r.mul(l).add(ht3(u)); } else r = r.mul(n), r = r.add(ht3(u)); } return r.unsigned = e, r; } function vt2(a, e) { return typeof a == "number" ? ht3(a, e) : typeof a == "string" ? Mr3(a, e) : V2(a.low, a.high, typeof e == "boolean" ? e : a.unsigned); } function ue2(a, e) { if (!a) throw new Error(typeof e == "string" ? e : e()); } function Ie3(a) { return new TextDecoder().decode(a); } function Zl2(a) { switch (a) { case "bool": case "int8": case "uint8": return 1; case "int16": case "uint16": return 2; case "int32": case "uint32": case "float32": return 4; case "float64": return 8; default: throw new Error(`cannot calculate sizeof() on type ${a}`); } } function Ni2(a) { switch (a) { case k3.onnx.TensorProto.DataType.UINT8: case k3.onnx.TensorProto.DataType.INT8: case k3.onnx.TensorProto.DataType.BOOL: return 1; case k3.onnx.TensorProto.DataType.UINT16: case k3.onnx.TensorProto.DataType.INT16: return 2; case k3.onnx.TensorProto.DataType.FLOAT: case k3.onnx.TensorProto.DataType.INT32: case k3.onnx.TensorProto.DataType.UINT32: return 4; case k3.onnx.TensorProto.DataType.INT64: case k3.onnx.TensorProto.DataType.DOUBLE: case k3.onnx.TensorProto.DataType.UINT64: return 8; default: throw new Error(`cannot calculate sizeof() on type ${k3.onnx.TensorProto.DataType[a]}`); } } function Yl2(a, e) { return new (Ri2(e))(a); } function Ri2(a) { switch (a) { case "bool": case "uint8": return Uint8Array; case "int8": return Int8Array; case "int16": return Int16Array; case "uint16": return Uint16Array; case "int32": return Int32Array; case "uint32": return Uint32Array; case "int64": return BigInt64Array; case "float32": return Float32Array; case "float64": return Float64Array; default: throw new Error("unspecified error"); } } function an3(a, e) { if (e === k3.onnx.TensorProto.DataType.INT64 || e === on3.TensorDataType.INT64) { if (a.greaterThanOrEqual(2147483648) || a.lessThan(-2147483648)) throw new TypeError("int64 is not supported"); } else if (e === k3.onnx.TensorProto.DataType.UINT32 || e === on3.TensorDataType.UINT32 || e === k3.onnx.TensorProto.DataType.UINT64 || e === on3.TensorDataType.UINT64) { if (a.greaterThanOrEqual(4294967296) || a.lessThan(0)) throw new TypeError("uint64 is not supported"); } else throw new TypeError(`not a LONG type: ${k3.onnx.TensorProto.DataType[e]}`); return a.toNumber(); } function Ci2(a, e, o) { switch (e) { case k3.onnx.TensorProto.DataType.BOOL: case k3.onnx.TensorProto.DataType.UINT8: return a.getUint8(o); case k3.onnx.TensorProto.DataType.INT8: return a.getInt8(o); case k3.onnx.TensorProto.DataType.UINT16: return a.getUint16(o, true); case k3.onnx.TensorProto.DataType.INT16: return a.getInt16(o, true); case k3.onnx.TensorProto.DataType.FLOAT: return a.getFloat32(o, true); case k3.onnx.TensorProto.DataType.INT32: return a.getInt32(o, true); case k3.onnx.TensorProto.DataType.UINT32: return a.getUint32(o, true); case k3.onnx.TensorProto.DataType.INT64: return an3(kt3.fromBits(a.getUint32(o, true), a.getUint32(o + 4, true), false), e); case k3.onnx.TensorProto.DataType.DOUBLE: return a.getFloat64(o, true); case k3.onnx.TensorProto.DataType.UINT64: return an3(kt3.fromBits(a.getUint32(o, true), a.getUint32(o + 4, true), true), e); default: throw new Error(`cannot read from DataView for type ${k3.onnx.TensorProto.DataType[e]}`); } } function D2(a) { return a === 1 ? Ql2 : tf3; } function Vi2(a) { let e = D2(a); return `${e.version} precision highp float; ${e.attribute} vec3 position; ${e.attribute} vec2 textureCoord; ${e.varyingVertex} vec2 TexCoords; void main() { gl_Position = vec4(position, 1.0); TexCoords = textureCoord; }`; } function zi2(a) { let e = D2(a); return `${e.version} precision highp float; precision highp int; precision highp sampler2D; ${e.varyingFrag} vec2 TexCoords; ${e.outputDeclaration} const vec2 halfCR = vec2(0.5, 0.5); // Custom vector types to handle higher dimenalities. struct ivec5 { int x; int y; int z; int w; int u; }; struct ivec6 { int x; int y; int z; int w; int u; int v; }; int imod(int x, int y) { return x - y * (x / y); } `; } function Mi2(a, e) { let o = D2(a); return ` void main() { int indices[${e}]; toVec(TexCoords, indices); vec4 result = vec4(process(indices)); ${o.output} = result; } `; } async function sn3(a, e = (t) => 0, o) { return new Promise((t, n) => { let r = 0, s = () => { if (a()) { t(); return; } r++; let i = e(r); if (o != null && r >= o) { n(); return; } setTimeout(s, i); }; s(); }); } function rr3(a) { return ue2(typeof a < "u" && a.length !== 0, () => "empty string found for sampler name"), "get" + a.charAt(0).toUpperCase() + a.slice(1); } function Ui2(a) { return ue2(typeof a < "u" && a.length !== 0, () => "empty string found for sampler name"), "get" + a.charAt(0).toUpperCase() + a.slice(1) + "AtOutCoords"; } function le2(a, e) { let o = JSON.parse(JSON.stringify(a)); return o = e, o; } function fe3(a, e) { return e.map((o) => a[o]).join(", "); } function at2(a) { if (a <= 1) return "int"; if (a === 2) return "ivec2"; if (a === 3) return "ivec3"; if (a === 4) return "ivec4"; if (a === 5) return "ivec5"; if (a === 6) return "ivec6"; throw Error(`GPU for rank ${a} is not yet supported`); } function St2(a = 6) { return ["x", "y", "z", "w", "u", "v"].slice(0, a); } function ef3(a, e) { return St2(e).map((o) => `${a}.${o}`); } function ce2(a, e) { return e === 1 ? [a] : ef3(a, e); } function Et2() { return ` float getChannel(vec4 frag, int dim) { int modCoord = imod(dim, 2); return modCoord == 0 ? frag.r : frag.g; } float getChannel(vec4 frag, vec2 innerDims) { vec2 modCoord = mod(innerDims, 2.); return modCoord.x == 0. ? (modCoord.y == 0. ? frag.r : frag.g) : (modCoord.y == 0. ? frag.b : frag.a); } `; } function nf3(a, e, o) { if (a === 0) return "false"; if (a === 1) return `rc > ${e[0]}`; let t = ""; for (let n = a - 2; n < a; n++) t += `${o[n]} >= ${e[n - a + 2]}`, n < a - 1 && (t += "||"); return t; } function of3(a, e) { let o = a.length; if (o === 0) return "getA(), 0, 0, 0"; if (o === 1) return `getA(rc), rc + 1 >= ${a[0]} ? 0. : getA(rc + 1), 0, 0`; let t = "r, c", n = "r, cp1", r = "rp1, c", s = "rp1, cp1", i = ""; if (o > 2) for (let u = 0; u < o - 2; ++u) i = i + `${e[u]},`; return `getA(${i}${t}), rEdge ? 0. : getA(${i}${r}), cEdge ? 0. : getA(${i}${n}), rEdge || cEdge ? 0. : getA(${i}${s})`; } function af3(a, e, o, t) { return a === 0 || a === 1 ? "" : ` int r = ${e[a - 2]}; int c = ${e[a - 1]}; int rp1 = ${e[a - 2]} + 1; int cp1 = ${e[a - 1]} + 1; bool rEdge = rp1 >= ${t}; bool cEdge = cp1 >= ${o}; `; } function un3(a) { if (a.length === 0) return [1, 1, 1]; let e = 1; for (let o = 0; o < a.length - 2; ++o) e *= a[o]; return [e, a.length > 1 ? a[a.length - 2] : 1, a[a.length - 1]]; } function Ki2(a, e) { let o = false; return a.length === 0 || e.length === 0 ? o = true : a.length < 2 || e.length < 2 ? o = a[a.length - 1] === e[e.length - 1] : o = a[a.length - 1] === e[e.length - 1] && a[a.length - 2] === e[e.length - 2], o; } function lf3(a) { let e = A.computeStrides(a), o = ["b", "r", "c"], t = "index"; return ` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${e.map((r, s) => { let i = `int ${o[s]} = ${t} / ${r}`, u = s === e.length - 1 ? `int ${o[s + 1]} = ${t} - ${o[s]} * ${r}` : `index -= ${o[s]} * ${r}`; return `${i}; ${u};`; }).join("")} return ivec3(b, r, c); } `; } function ff3(a) { let e = A.computeStrides(a); return ` int getFlattenedIndex(ivec3 coords) { // reverse y, z order return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y; } `; } function pf3(a, e) { if (a === 1) return "rc"; let o = ""; for (let t = 0; t < a; t++) o += e[t], t < a - 1 && (o += ","); return o; } function gf3() { let a = "add_"; return { body: ` float ${a}(float a, float b) { return a + b; } vec4 ${a}(vec4 v1, vec4 v2) { return v1 + v2; } `, name: a, type: 0 }; } function xf3() { let a = "div_"; return { body: ` float ${a}(float a, float b) { return a / b; } vec4 ${a}(vec4 v1, vec4 v2) { return v1 / v2; } `, name: a, type: 0 }; } function Tf3() { let a = "mul_"; return { body: ` float ${a}(float a, float b) { return a * b; } vec4 ${a}(vec4 v1, vec4 v2) { return v1 * v2; } `, name: a, type: 0 }; } function vf3() { let a = "sub_"; return { body: ` float ${a}(float a, float b) { return a - b; } vec4 ${a}(vec4 v1, vec4 v2) { return v1 - v2; } `, name: a, type: 0 }; } function wf3() { let a = "equal_"; return { body: ` float ${a}(float a, float b) { return float(a == b); } vec4 ${a}(vec4 v1, vec4 v2) { return vec4(equal(v1, v2)); } `, name: a, type: 0 }; } function If4() { let a = "greater_"; return { body: ` float ${a}(float a, float b) { return float(a > b); } vec4 ${a}(vec4 v1, vec4 v2) { return vec4( v1.r > v2.r , v1.g > v2.g, v1.b > v2.b, v1.a > v2.a ); } `, name: a, type: 0 }; } function _f3() { let a = "less_"; return { body: ` float ${a}(float a, float b) { return float(a < b); } vec4 ${a}(vec4 v1, vec4 v2) { return vec4( v1.r < v2.r , v1.g < v2.g, v1.b < v2.b, v1.a < v2.a ); } `, name: a, type: 0 }; } function Sf3() { let a = "and_"; return { body: ` float ${a}(float a, float b) { return float( bool(a) && bool(b) ); } vec4 ${a}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r && b2.r , b1.g && b2.g, b1.b && b2.b, b1.a && b2.a ); } `, name: a, type: 0 }; } function Of3() { let a = "or_"; return { body: ` float ${a}(float a, float b) { return float( bool(a) || bool(b) ); } vec4 ${a}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r || b2.r , b1.g || b2.g, b1.b || b2.b, b1.a || b2.a ); } `, name: a, type: 0 }; } function Af3() { let a = "xor_"; return { body: ` float ${a}(float a, float b) { return float( bool(a) ^^ bool(b) ); } vec4 ${a}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r ^^ b2.r , b1.g ^^ b2.g, b1.b ^^ b2.b, b1.a ^^ b2.a ); } `, name: a, type: 0 }; } function Pf3() { return Df2("pow"); } function Ef3() { let a = "prelu_"; return { body: ` float ${a}(float a, float b) { return a < 0.0 ? a * b: a; } vec4 ${a}(vec4 v1, vec4 v2) { return vec4( v1.r < 0.0 ? v1.r * v2.r: v1.r, v1.g < 0.0 ? v1.g * v2.g: v1.g, v1.b < 0.0 ? v1.b * v2.b: v1.b, v1.a < 0.0 ? v1.a * v2.a: v1.a ); } `, name: a, type: 0 }; } function Df2(a) { let e = `${a}_`; return { body: ` float ${e}(float a, float b) { return ${a}(a, b); } vec4 ${e}(vec4 v1, vec4 v2) { return ${a}(v1, v2); } `, name: e, type: 0 }; } function Uf3() { return gt3("abs"); } function Wf3() { return gt3("acos"); } function Hf3() { return gt3("asin"); } function qf3() { return gt3("atan"); } function jf3() { return gt3("ceil"); } function Kf3() { return gt3("cos"); } function Xf3(a) { let e = "elu"; return { body: ` const float alpha = float(${a}); float ${e}_(float a) { return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; } vec4 ${e}_(vec4 v) { return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); } `, name: e, type: 0 }; } function Jf3() { return gt3("exp"); } function Zf3() { return gt3("floor"); } function pn3(a, e) { let o = "clip"; return { body: ` const float min = float(${a}); const float max = float(${e}); float ${o}_(float a) { return clamp(a, min, max); } vec4 ${o}_(vec4 v) { return clamp(v, min, max); } `, name: o, type: 0 }; } function Yf3() { let a = "indentity"; return { body: ` float ${a}_(float a) { return a; } vec4 ${a}_(vec4 v) { return v; } `, name: a, type: 0 }; } function Qf3(a) { let e = "leakyRelu"; return { body: ` const float alpha = float(${a}); float ${e}_(float a) { return a < 0.0 ? a * alpha : a; } vec4 ${e}_(vec4 v) { return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w)); } `, name: e, type: 0 }; } function tc2() { return gt3("log"); } function ec2() { let a = "neg"; return { body: ` float ${a}_(float a) { return -a; } vec4 ${a}_(vec4 v) { return -v; } `, name: a, type: 0 }; } function rc2() { let a = "not"; return { body: ` float ${a}_(float a) { return float( ! bool(a) ); } bool ${a}_(bool a) { return !a; } vec4 ${a}_(vec4 v) { return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); } bvec4 ${a}_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } `, name: a, type: 0 }; } function nc2() { return gt3("sin"); } function dn3() { let a = "relu"; return { body: ` float ${a}_(float a) { return max( a, 0.0 ); } vec4 ${a}_(vec4 v) { return max( v, 0.0 ); } `, name: a, type: 0 }; } function hn2() { let a = "sigmoid"; return { body: ` float ${a}_(float a) { return 1.0 / (1.0 + exp(-a)); } vec4 ${a}_(vec4 v) { return 1.0 / (1.0 + exp(-v)); } `, name: a, type: 0 }; } function oc2() { return gt3("sqrt"); } function ic2() { return gt3("tan"); } function ac2() { let a = "tanh"; return { body: ` float ${a}_(float a) { a = clamp(a, -10., 10.); a = exp(2.*a); return (a - 1.) / (a + 1.); } vec4 ${a}_(vec4 v) { v = clamp(v, -10., 10.); v = exp(2.*v); return (v - 1.) / (v + 1.); } `, name: a, type: 0 }; } function gt3(a) { return { body: ` float ${a}_(float a) { return ${a}(a); } vec4 ${a}_(vec4 v) { return ${a}(v); } `, name: a, type: 0 }; } function Dt(a) { let e; switch (a.activation) { case "Relu": e = dn3(); break; case "Sigmoid": e = hn2(); break; case "Clip": e = pn3(a.clipMin, a.clipMax); break; default: return { activationFunction: "", applyActivation: "" }; } let o = e.name, t = e.body, n = `value = ${o}_(value);`; return { activationFunction: t, applyActivation: n }; } function mc2(a, e, o) { let t = e[0].dims, n = e[1].dims, r = it2.calcShape(t, n, true); if (!r) throw new Error("Can't use matmul on the given tensors"); let s = at2(r.length), i = St2(), { activationFunction: u, applyActivation: l } = Dt(o), f = e.length > 2, p = f ? "value += getBiasForMatmul();" : "", d = f ? `${xn2(s, i, e[2].dims, r, false)}` : "", b = r.length, g = t.length, y = n.length, v = t[t.length - 1], _ = ` ${u} ${d} float process(int indices[${b}]) { int a[${g}]; int b[${y}]; bcastMatmulIndices_A(indices, a); bcastMatmulIndices_B(indices, b); float value; for (int k=0; k<${v}; ++k) { a[${g - 1}] = k; b[${y - 2}] = k; value += _A(a) * _B(b); } ${p} ${l} return value; }`; return { ...a, output: { dims: r, type: e[0].type, textureType: 0 }, shaderSource: _ }; } function gn2(a, e) { let o = hc2(a.length > 2, e.activationCacheKey); return { ...o, get: () => mc2(o, a, e) }; } function xn2(a, e, o, t, n) { let r = "", s = o.length, i = t.length, u = i - s; i < 2 && s > 0 ? r = "coords" : r = o.map((y, v) => `coords.${e[v + u]}`).join(", "); let f = it2.getBroadcastDims(o, t).map((y) => `coords.${e[y + u]} = 0;`).join(` `), d = A.size(o) === 1, b = "vec4(outputValue.xx, outputValue.yy)"; return d && (b = "vec4(outputValue.x)"), n ? ` vec4 getBiasForMatmul() { ${a} coords = getOutputCoords(); ${f} vec4 outputValue = getBias(${r}); return ${b}; }` : ` float getBiasForMatmul() { ${a} coords = getOutputCoords(); ${f} return getBias(coords.x); }`; } function xc2(a, e, o, t) { let n = [], r = [], s = o[0].dims, i = o[1].dims, u = s.length, l = i.length, f = t.length, p = f - u, d = f - l; n = s.map((S, C) => `coords.${e[C + p]}`), n[u - 1] = "i*2", n.join(", "), r = i.map((S, C) => `coords.${e[C + d]}`), r[l - 2] = "i*2", r.join(", "); let b = it2.getBroadcastDims(s, t), g = it2.getBroadcastDims(i, t), y = b.map((S) => `coords.${e[S + p]} = 0;`).join(` `), v = g.map((S) => `coords.${e[S + d]} = 0;`).join(` `), _ = `int lastDim = coords.${e[f - 1]}; coords.${e[f - 1]} = coords.${e[f - 2]}; coords.${e[f - 2]} = lastDim;`; return ` vec4 getAAtOutCoordsMatmul(int i) { ${a} coords = getOutputCoords(); ${_} ${y} vec4 outputValue = getA(${n}); return outputValue; } vec4 getBAtOutCoordsMatmul(int i) { ${a} coords = getOutputCoords(); ${_} ${v} vec4 outputValue = getB(${r}); return outputValue; }`; } function Tc2(a, e) { let o = ""; for (let t = 0; t < e - 2; t++) o += `rc.${a[t]}, `; return o += `rc.${a[e - 2]}, i*2`, o; } function vc2(a, e) { let o = ""; for (let t = 0; t < e - 2; t++) o += `rc.${a[t]}, `; return o += `i*2, rc.${a[e - 1]}`, o; } function cp3(a, e) { let o = a[0].dims[1], t = a[0].dims.length, n = -Math.floor((e.size - 1) / 2), r = Math.ceil((e.size - 1) / 2), s = `float(${e.alpha}) / float(${e.size})`, i = `float(${e.bias})`, u = `float(${e.beta})`, l = ` float process(int indices[${t}]) { int c = indices[1]; float x = _X(indices); float square_sum = 0.0; for (int i = ${n}; i <= ${r}; i++) { int idx = c + i; if (c >= 0 && c < ${o}) { indices[1] = idx; float j = _X(indices); square_sum += j * j; } } return x / pow(${i} + ${s} * square_sum, ${u}); }`; return { ...Gs3, cacheHint: e.cacheKey, output: { dims: a[0].dims, type: a[0].type, textureType: 0 }, shaderSource: l }; } function pp3(a, e) { return { ...Gs3, cacheHint: e.cacheKey, get: () => cp3(a, e) }; } function Qu3(a) { let e = {}, o; for (; (o = Yu3.exec(a)) !== null; ) { let t = o[3].split(",").map((n) => { let r = n.trim().split(" "); return r && r.length === 2 ? { type: r[0], name: r[1] } : null; }).filter((n) => n !== null); e[o[2]] = { params: t, body: o[4] }; } for (let t in e) { let n = Jp3.replace("__FUNC__", t), r = new RegExp(n, "gm"); for (; (o = r.exec(a)) !== null; ) { let s = o[1], i = o[2], u = o[3].split(","), l = s ? `${s} ${i};` : "", f = e[t].body, p = ""; e[t].params.forEach((b, g) => { b && (p += `${b.type} ${b.name} = ${u[g]}; `); }), f = `${p} ${f}`, f = f.replace("return", `${i} = `); let d = ` ${l} { ${f} } `; a = a.replace(o[0], d); } } return a = a.replace(Yu3, ""), a; } function he2(a, e) { let o = [], t = [], n = e != null && Array.isArray(e) && e.length === 0, r = e == null || n ? null : Zp3(e, a).sort(), s = 0; for (let i = 0; i < a.length; ++i) { if (r != null) { if (r[s] === i && a[i] !== 1) throw new Error(`Can't squeeze axis ${i} since its dim '${a[i]}' is not 1`); (r[s] == null || r[s] > i) && a[i] === 1 && (o.push(a[i]), t.push(i)), r[s] <= i && s++; } a[i] !== 1 && (o.push(a[i]), t.push(i)); } return { newShape: o, keptDims: t }; } function Zp3(a, e) { let o = e.length; return a = a == null ? e.map((t, n) => n) : [].concat(a), ue2(a.every((t) => t >= -o && t < o), () => `All values in axis param must be in range [-${o}, ${o}) but got axis ${a}`), ue2(a.every(Yp3), () => `All values in axis param must be integers but got axis ${a}`), a.map((t) => t < 0 ? o + t : t); } function Yp3(a) { return a % 1 === 0; } function Qp3(a) { if (a.length === 0) return 1; let e = a[0]; for (let o = 1; o < a.length; o++) e *= a[o]; return e; } function el3(a) { let e = Math.ceil(Math.sqrt(a)); return [e, Math.ceil(a / e)]; } function td3(a) { let e = 0; for (; e < a.length && a[e](); ++e) ; return e - 1; } function Cn2(a) { let e; if ((!a || a === "webgl2") && "webgl2" in me2 ? e = me2.webgl2 : (!a || a === "webgl") && "webgl" in me2 && (e = me2.webgl), !e) try { let t = rd3(); e = dl3(t, a); } catch { let n = ed3(); e = dl3(n, a); } a = a || e.version === 1 ? "webgl" : "webgl2"; let o = e.gl; return me2[a] = e, o.isContextLost() ? (delete me2[a], Cn2(a)) : (o.disable(o.DEPTH_TEST), o.disable(o.STENCIL_TEST), o.disable(o.BLEND), o.disable(o.DITHER), o.disable(o.POLYGON_OFFSET_FILL), o.disable(o.SAMPLE_COVERAGE), o.enable(o.SCISSOR_TEST), o.enable(o.CULL_FACE), o.cullFace(o.BACK), e); } function dl3(a, e) { let o = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false }, t, n = o; if ((!e || e === "webgl2") && (t = a.getContext("webgl2", n), t)) try { return new De2(t, 2); } catch (r) { M2.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${r}`); } if ((!e || e === "webgl") && (t = a.getContext("webgl", n) || a.getContext("experimental-webgl", n), t)) try { return new De2(t, 1); } catch (r) { M2.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${r}`); } throw new Error("WebGL is not supported"); } function ed3() { if (typeof document > "u") throw new TypeError("failed to create canvas: document is not supported"); let a = document.createElement("canvas"); return a.width = 1, a.height = 1, a; } function rd3() { if (typeof OffscreenCanvas > "u") throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported"); return new OffscreenCanvas(1, 1); } async function Gn3(a) { if (a) { let e = typeof a == "string" ? [a] : a; for (let o of e) { let t = bl3.get(o); if (t) return t; let n = await od3(o); if (n) return n; } } else return Gn3(["webgl"]); throw new Error("no available backend to use"); } async function od3(a) { let e = nd3; if (typeof e[a] < "u" && id3(e[a])) { let o = e[a], t = o.initialize(); if (typeof t == "object" && "then" in t && (t = await t), t) return bl3.set(a, o), o; } } function id3(a) { let e = a; return "initialize" in e && typeof e.initialize == "function" && "createSessionHandler" in e && typeof e.createSessionHandler == "function" && "dispose" in e && typeof e.dispose == "function"; } var Al3, ke2, Pl3, El3, Dl3, Ll2, x, Z, Wn3, Hn3, ne, $l3, Be3, Ut3, Fe2, kl3, Ne2, Ce3, qn3, jn3, Kn3, Xn3, ct, Br3, j2, Jn3, Zn3, Yn3, Qn3, Fr3, to3, eo3, ro3, no3, oo3, Wt3, be3, io3, ao3, so3, uo3, lo3, fo3, nt2, Ge3, ot3, Re, co3, po3, Ve3, ze2, Nr3, Me3, ho3, Bl3, mo3, bo3, yo3, go3, xo3, Fl2, Ue3, To2, Nl2, vo2, Cr3, Ft3, Gr3, Rr3, Io2, Cl3, _o2, ye, M2, qe2, je2, Ke3, He3, pt, Oo, Ao2, dt3, Eo2, Do, Xe3, Lo, zl3, ie2, Bo2, $o2, ko2, Tt3, $t3, oe, Fo2, zr3, No2, Co3, ut, T2, kt3, Ur3, m, Je, P, ge2, Ro2, Uo2, Ho, Yo, Qo, ei2, ni2, ii2, Gt2, Yr2, hi2, en2, Ii2, Si2, Ai2, Ei2, $i2, Bi2, se, H2, Kt3, nn3, it2, er2, et, ft, A, we, Xt3, Jt3, Zt2, z2, Gi2, k3, on3, Y2, Yt3, Ql2, tf3, q2, N, Pt3, Qt2, Wi2, rf3, Hi2, qi2, sf3, uf2, ji2, Xi3, ln3, Ji3, Zi3, cf3, Yi3, Qi3, nr3, _e2, or3, Se, Oe3, ta2, fn2, ea2, hf3, ir3, na2, cn3, $, tt3, oa2, ia2, aa2, mf3, bf3, sa2, ar, bt2, I, Ae2, sr2, Bt, yt2, Lf3, ua2, la2, fa2, ca2, pa2, da2, ha2, ma2, ba2, ya2, ga2, xa2, Ta2, va2, wa2, kf3, Ia2, Bf3, Ff3, _a2, ur2, Sa2, Oa2, Nf3, Cf3, Gf3, Aa2, Rf3, Vf3, zf3, Pa2, Mf3, Ea2, sc2, J2, Da2, La2, $a2, ka2, mn2, Ba2, Fa2, uc2, Na2, Ca2, Ga2, Ra2, Va2, za2, bn2, Ma2, Ua2, Wa2, Ha2, qa, ja2, Ka2, Xa2, Ja2, Za3, Ya2, yn2, pe, te2, fc2, cc2, Qa3, ts3, pc2, dc2, es3, rs3, ns3, os3, hc2, bc2, fr2, yc2, gc2, cr2, Tn, is3, as3, wc2, Ic2, ss3, vn, wn, _c2, Sc2, us3, ls3, de, In, Oc2, Ac2, Pc2, Ec2, _n2, Dc2, lr2, Lc2, $c2, kc2, fs5, Bc2, Fc2, Nc2, Cc2, Gc2, Rc2, cs3, Vc2, ps3, ds3, ee2, hs3, zc2, ms3, Mc2, Uc2, Wc2, pr2, bs3, ys3, Hc2, gs3, xs3, Ts3, qc2, vs3, Vt2, Pe2, ws3, Is3, jc2, Kc2, Xc2, Jc2, _s3, Sn2, Ss3, Os3, As3, Zc2, Yc2, Qc2, Ps3, Es3, Ds3, tp2, ep2, rp2, np2, op3, Ls3, ks3, Bs3, $s3, ip3, ap3, sp3, up3, lp3, fp3, Fs3, Ns3, Cs3, Gs3, dp3, Rs3, hp3, On2, Vs3, zs3, Ms3, mp3, bp3, yp3, gp3, xp3, Tp3, vp3, wp3, Us3, Hs3, qs2, js2, Ks3, Xs2, Js2, Zs2, Ys3, Qs2, Ip3, Ws2, tu2, hr2, eu2, dr2, _p3, ru2, re, zt, Sp3, Op3, nu2, ou3, iu3, au2, su3, uu2, lu3, fu2, cu2, pu2, du2, An2, hu2, mu2, Ee2, Ap3, Pn2, mr2, En2, Dn2, Ln3, bu2, yu2, Pp3, Ep3, Dp3, Lp3, gu2, xu2, $p3, Tu3, $n2, vu2, wu2, Iu2, kp3, _u2, Bp3, Fp3, Su2, Ou2, Au2, Pu2, Eu3, Du2, Lu3, $u2, ku3, Np3, Cp3, Gp3, Bu2, Fu3, Nu2, Cu2, Gu2, Rp3, Vp3, zp3, Ru3, kn2, Vu3, zu3, Mp3, Up3, Mu3, Uu2, Wp3, Hp3, Wu3, Hu3, qp3, jp3, qu3, Bn2, ju3, Ku3, Kp3, Xp3, Xu3, Ju3, Zu3, Yu3, Jp3, tl3, br3, Fn3, yr2, rl3, gr, nl3, xr3, ol3, Tr3, il3, vr2, al3, Nn3, sl3, wr2, ul2, Ir2, ll3, _r2, fl3, Sr3, cl3, De2, pl3, me2, hl3, Or3, ml3, bl3, nd3, yl3, Rn3, Ar3, gl3, B2, xt2, Le2, xl3, zn2, Pr3, Mn3, Lt2, Er2, Vn3, Tl3, vl3, ad3, Dr2, wl3, Lr2, Il3, $r3, _l3, Sl3, Un3, sd3, Ol3, wo2, zv; var init_ort_webgl_min = __esm({ "node_modules/gliner/node_modules/onnxruntime-web/dist/ort.webgl.min.mjs"() { Al3 = Object.create; ke2 = Object.defineProperty; Pl3 = Object.getOwnPropertyDescriptor; El3 = Object.getOwnPropertyNames; Dl3 = Object.getPrototypeOf; Ll2 = Object.prototype.hasOwnProperty; x = (a, e) => () => (a && (e = a(a = 0)), e); Z = (a, e) => () => (e || a((e = { exports: {} }).exports, e), e.exports); Wn3 = (a, e) => { for (var o in e) ke2(a, o, { get: e[o], enumerable: true }); }; Hn3 = (a, e, o, t) => { if (e && typeof e == "object" || typeof e == "function") for (let n of El3(e)) !Ll2.call(a, n) && n !== o && ke2(a, n, { get: () => e[n], enumerable: !(t = Pl3(e, n)) || t.enumerable }); return a; }; ne = (a, e, o) => (o = a != null ? Al3(Dl3(a)) : {}, Hn3(e || !a || !a.__esModule ? ke2(o, "default", { value: a, enumerable: true }) : o, a)); $l3 = (a) => Hn3(ke2({}, "__esModule", { value: true }), a); Ce3 = x(() => { "use strict"; Be3 = /* @__PURE__ */ new Map(), Ut3 = [], Fe2 = (a, e, o) => { if (e && typeof e.init == "function" && typeof e.createInferenceSessionHandler == "function") { let t = Be3.get(a); if (t === void 0) Be3.set(a, { backend: e, priority: o }); else { if (t.priority > o) return; if (t.priority === o && t.backend !== e) throw new Error(`cannot register backend "${a}" using priority ${o}`); } if (o >= 0) { let n = Ut3.indexOf(a); n !== -1 && Ut3.splice(n, 1); for (let r = 0; r < Ut3.length; r++) if (Be3.get(Ut3[r]).priority <= o) { Ut3.splice(r, 0, a); return; } Ut3.push(a); } return; } throw new TypeError("not a valid backend"); }, kl3 = async (a) => { let e = Be3.get(a); if (!e) return "backend not found."; if (e.initialized) return e.backend; if (e.aborted) return e.error; { let o = !!e.initPromise; try { return o || (e.initPromise = e.backend.init(a)), await e.initPromise, e.initialized = true, e.backend; } catch (t) { return o || (e.error = `${t}`, e.aborted = true), e.error; } finally { delete e.initPromise; } } }, Ne2 = async (a) => { let e = a.executionProviders || [], o = e.map((u) => typeof u == "string" ? u : u.name), t = o.length === 0 ? Ut3 : o, n, r = [], s = /* @__PURE__ */ new Set(); for (let u of t) { let l = await kl3(u); typeof l == "string" ? r.push({ name: u, err: l }) : (n || (n = l), n === l && s.add(u)); } if (!n) throw new Error(`no available backend found. ERR: ${r.map((u) => `[${u.name}] ${u.err}`).join(", ")}`); for (let { name: u, err: l } of r) o.includes(u) && console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${l}`); let i = e.filter((u) => s.has(typeof u == "string" ? u : u.name)); return [n, new Proxy(a, { get: (u, l) => l === "executionProviders" ? i : Reflect.get(u, l) })]; }; }); qn3 = x(() => { "use strict"; Ce3(); }); Kn3 = x(() => { "use strict"; jn3 = "1.19.2"; }); Br3 = x(() => { "use strict"; Kn3(); Xn3 = "warning", ct = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: jn3 }, set logLevel(a) { if (a !== void 0) { if (typeof a != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(a) === -1) throw new Error(`Unsupported logging level: ${a}`); Xn3 = a; } }, get logLevel() { return Xn3; } }; Object.defineProperty(ct, "logLevel", { enumerable: true }); }); Jn3 = x(() => { "use strict"; Br3(); j2 = ct; }); Qn3 = x(() => { "use strict"; Zn3 = (a, e) => { let o = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); o.width = a.dims[3], o.height = a.dims[2]; let t = o.getContext("2d"); if (t != null) { let n, r; e?.tensorLayout !== void 0 && e.tensorLayout === "NHWC" ? (n = a.dims[2], r = a.dims[3]) : (n = a.dims[3], r = a.dims[2]); let s = e?.format !== void 0 ? e.format : "RGB", i = e?.norm, u, l; i === void 0 || i.mean === void 0 ? u = [255, 255, 255, 255] : typeof i.mean == "number" ? u = [i.mean, i.mean, i.mean, i.mean] : (u = [i.mean[0], i.mean[1], i.mean[2], 0], i.mean[3] !== void 0 && (u[3] = i.mean[3])), i === void 0 || i.bias === void 0 ? l = [0, 0, 0, 0] : typeof i.bias == "number" ? l = [i.bias, i.bias, i.bias, i.bias] : (l = [i.bias[0], i.bias[1], i.bias[2], 0], i.bias[3] !== void 0 && (l[3] = i.bias[3])); let f = r * n, p = 0, d = f, b = f * 2, g = -1; s === "RGBA" ? (p = 0, d = f, b = f * 2, g = f * 3) : s === "RGB" ? (p = 0, d = f, b = f * 2) : s === "RBG" && (p = 0, b = f, d = f * 2); for (let y = 0; y < r; y++) for (let v = 0; v < n; v++) { let _ = (a.data[p++] - l[0]) * u[0], O2 = (a.data[d++] - l[1]) * u[1], S = (a.data[b++] - l[2]) * u[2], C = g === -1 ? 255 : (a.data[g++] - l[3]) * u[3]; t.fillStyle = "rgba(" + _ + "," + O2 + "," + S + "," + C + ")", t.fillRect(v, y, 1, 1); } if ("toDataURL" in o) return o.toDataURL(); throw new Error("toDataURL is not supported"); } else throw new Error("Can not access image data"); }, Yn3 = (a, e) => { let o = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), t; if (o != null) { let n, r, s; e?.tensorLayout !== void 0 && e.tensorLayout === "NHWC" ? (n = a.dims[2], r = a.dims[1], s = a.dims[3]) : (n = a.dims[3], r = a.dims[2], s = a.dims[1]); let i = e !== void 0 && e.format !== void 0 ? e.format : "RGB", u = e?.norm, l, f; u === void 0 || u.mean === void 0 ? l = [255, 255, 255, 255] : typeof u.mean == "number" ? l = [u.mean, u.mean, u.mean, u.mean] : (l = [u.mean[0], u.mean[1], u.mean[2], 255], u.mean[3] !== void 0 && (l[3] = u.mean[3])), u === void 0 || u.bias === void 0 ? f = [0, 0, 0, 0] : typeof u.bias == "number" ? f = [u.bias, u.bias, u.bias, u.bias] : (f = [u.bias[0], u.bias[1], u.bias[2], 0], u.bias[3] !== void 0 && (f[3] = u.bias[3])); let p = r * n; if (e !== void 0 && (e.format !== void 0 && s === 4 && e.format !== "RGBA" || s === 3 && e.format !== "RGB" && e.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); let d = 4, b = 0, g = 1, y = 2, v = 3, _ = 0, O2 = p, S = p * 2, C = -1; i === "RGBA" ? (_ = 0, O2 = p, S = p * 2, C = p * 3) : i === "RGB" ? (_ = 0, O2 = p, S = p * 2) : i === "RBG" && (_ = 0, S = p, O2 = p * 2), t = o.createImageData(n, r); for (let F2 = 0; F2 < r * n; b += d, g += d, y += d, v += d, F2++) t.data[b] = (a.data[_++] - f[0]) * l[0], t.data[g] = (a.data[O2++] - f[1]) * l[1], t.data[y] = (a.data[S++] - f[2]) * l[2], t.data[v] = C === -1 ? 255 : (a.data[C++] - f[3]) * l[3]; } else throw new Error("Can not access image data"); return t; }; }); oo3 = x(() => { "use strict"; Ge3(); Fr3 = (a, e) => { if (a === void 0) throw new Error("Image buffer must be defined"); if (e.height === void 0 || e.width === void 0) throw new Error("Image height and width must be defined"); if (e.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet"); let { height: o, width: t } = e, n = e.norm ?? { mean: 255, bias: 0 }, r, s; typeof n.mean == "number" ? r = [n.mean, n.mean, n.mean, n.mean] : r = [n.mean[0], n.mean[1], n.mean[2], n.mean[3] ?? 255], typeof n.bias == "number" ? s = [n.bias, n.bias, n.bias, n.bias] : s = [n.bias[0], n.bias[1], n.bias[2], n.bias[3] ?? 0]; let i = e.format !== void 0 ? e.format : "RGBA", u = e.tensorFormat !== void 0 && e.tensorFormat !== void 0 ? e.tensorFormat : "RGB", l = o * t, f = u === "RGBA" ? new Float32Array(l * 4) : new Float32Array(l * 3), p = 4, d = 0, b = 1, g = 2, y = 3, v = 0, _ = l, O2 = l * 2, S = -1; i === "RGB" && (p = 3, d = 0, b = 1, g = 2, y = -1), u === "RGBA" ? S = l * 3 : u === "RBG" ? (v = 0, O2 = l, _ = l * 2) : u === "BGR" && (O2 = 0, _ = l, v = l * 2); for (let F2 = 0; F2 < l; F2++, d += p, g += p, b += p, y += p) f[v++] = (a[d] + s[0]) / r[0], f[_++] = (a[b] + s[1]) / r[1], f[O2++] = (a[g] + s[2]) / r[2], S !== -1 && y !== -1 && (f[S++] = (a[y] + s[3]) / r[3]); return u === "RGBA" ? new nt2("float32", f, [1, 4, o, t]) : new nt2("float32", f, [1, 3, o, t]); }, to3 = async (a, e) => { let o = typeof HTMLImageElement < "u" && a instanceof HTMLImageElement, t = typeof ImageData < "u" && a instanceof ImageData, n = typeof ImageBitmap < "u" && a instanceof ImageBitmap, r = typeof a == "string", s, i = e ?? {}, u = () => { if (typeof document < "u") return document.createElement("canvas"); if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); throw new Error("Canvas is not supported"); }, l = (f) => f instanceof HTMLCanvasElement || f instanceof OffscreenCanvas ? f.getContext("2d") : null; if (o) { let f = u(); f.width = a.width, f.height = a.height; let p = l(f); if (p != null) { let d = a.height, b = a.width; if (e !== void 0 && e.resizedHeight !== void 0 && e.resizedWidth !== void 0 && (d = e.resizedHeight, b = e.resizedWidth), e !== void 0) { if (i = e, e.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); i.tensorFormat = "RGBA", i.height = d, i.width = b; } else i.tensorFormat = "RGBA", i.height = d, i.width = b; p.drawImage(a, 0, 0), s = p.getImageData(0, 0, b, d).data; } else throw new Error("Can not access image data"); } else if (t) { let f, p; if (e !== void 0 && e.resizedWidth !== void 0 && e.resizedHeight !== void 0 ? (f = e.resizedHeight, p = e.resizedWidth) : (f = a.height, p = a.width), e !== void 0 && (i = e), i.format = "RGBA", i.height = f, i.width = p, e !== void 0) { let d = u(); d.width = p, d.height = f; let b = l(d); if (b != null) b.putImageData(a, 0, 0), s = b.getImageData(0, 0, p, f).data; else throw new Error("Can not access image data"); } else s = a.data; } else if (n) { if (e === void 0) throw new Error("Please provide image config with format for Imagebitmap"); let f = u(); f.width = a.width, f.height = a.height; let p = l(f); if (p != null) { let d = a.height, b = a.width; return p.drawImage(a, 0, 0, b, d), s = p.getImageData(0, 0, b, d).data, i.height = d, i.width = b, Fr3(s, i); } else throw new Error("Can not access image data"); } else { if (r) return new Promise((f, p) => { let d = u(), b = l(d); if (!a || !b) return p(); let g = new Image(); g.crossOrigin = "Anonymous", g.src = a, g.onload = () => { d.width = g.width, d.height = g.height, b.drawImage(g, 0, 0, d.width, d.height); let y = b.getImageData(0, 0, d.width, d.height); i.height = d.height, i.width = d.width, f(Fr3(y.data, i)); }; }); throw new Error("Input data provided is not supported - aborted tensor creation"); } if (s !== void 0) return Fr3(s, i); throw new Error("Input data provided is not supported - aborted tensor creation"); }, eo3 = (a, e) => { let { width: o, height: t, download: n, dispose: r } = e, s = [1, t, o, 4]; return new nt2({ location: "texture", type: "float32", texture: a, dims: s, download: n, dispose: r }); }, ro3 = (a, e) => { let { dataType: o, dims: t, download: n, dispose: r } = e; return new nt2({ location: "gpu-buffer", type: o ?? "float32", gpuBuffer: a, dims: t, download: n, dispose: r }); }, no3 = (a, e, o) => new nt2({ location: "cpu-pinned", type: a, data: e, dims: o ?? [e.length] }); }); so3 = x(() => { "use strict"; Wt3 = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array]]), be3 = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), io3 = false, ao3 = () => { if (!io3) { io3 = true; let a = typeof BigInt64Array < "u" && BigInt64Array.from, e = typeof BigUint64Array < "u" && BigUint64Array.from, o = typeof Float16Array < "u" && Float16Array.from; a && (Wt3.set("int64", BigInt64Array), be3.set(BigInt64Array, "int64")), e && (Wt3.set("uint64", BigUint64Array), be3.set(BigUint64Array, "uint64")), o ? (Wt3.set("float16", Float16Array), be3.set(Float16Array, "float16")) : Wt3.set("float16", Uint16Array); } }; }); fo3 = x(() => { "use strict"; Ge3(); uo3 = (a) => { let e = 1; for (let o = 0; o < a.length; o++) { let t = a[o]; if (typeof t != "number" || !Number.isSafeInteger(t)) throw new TypeError(`dims[${o}] must be an integer, got: ${t}`); if (t < 0) throw new RangeError(`dims[${o}] must be a non-negative integer, got: ${t}`); e *= t; } return e; }, lo3 = (a, e) => { switch (a.location) { case "cpu": return new nt2(a.type, a.data, e); case "cpu-pinned": return new nt2({ location: "cpu-pinned", data: a.data, type: a.type, dims: e }); case "texture": return new nt2({ location: "texture", texture: a.texture, type: a.type, dims: e }); case "gpu-buffer": return new nt2({ location: "gpu-buffer", gpuBuffer: a.gpuBuffer, type: a.type, dims: e }); default: throw new Error(`tensorReshape: tensor location ${a.location} is not supported`); } }; }); Ge3 = x(() => { "use strict"; Qn3(); oo3(); so3(); fo3(); nt2 = class { constructor(e, o, t) { ao3(); let n, r; if (typeof e == "object" && "location" in e) switch (this.dataLocation = e.location, n = e.type, r = e.dims, e.location) { case "cpu-pinned": { let i = Wt3.get(n); if (!i) throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`); if (!(e.data instanceof i)) throw new TypeError(`buffer should be of type ${i.name}`); this.cpuData = e.data; break; } case "texture": { if (n !== "float32") throw new TypeError(`unsupported type "${n}" to create tensor from texture`); this.gpuTextureData = e.texture, this.downloader = e.download, this.disposer = e.dispose; break; } case "gpu-buffer": { if (n !== "float32" && n !== "float16" && n !== "int32" && n !== "int64" && n !== "uint32" && n !== "uint8" && n !== "bool") throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`); this.gpuBufferData = e.gpuBuffer, this.downloader = e.download, this.disposer = e.dispose; break; } default: throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); } else { let i, u; if (typeof e == "string") if (n = e, u = t, e === "string") { if (!Array.isArray(o)) throw new TypeError("A string tensor's data must be a string array."); i = o; } else { let l = Wt3.get(e); if (l === void 0) throw new TypeError(`Unsupported tensor type: ${e}.`); if (Array.isArray(o)) { if (e === "float16" && l === Uint16Array) throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data."); e === "uint64" || e === "int64" ? i = l.from(o, BigInt) : i = l.from(o); } else if (o instanceof l) i = o; else throw new TypeError(`A ${n} tensor's data must be type of ${l}`); } else if (u = o, Array.isArray(e)) { if (e.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); let l = typeof e[0]; if (l === "string") n = "string", i = e; else if (l === "boolean") n = "bool", i = Uint8Array.from(e); else throw new TypeError(`Invalid element type of data array: ${l}.`); } else { let l = be3.get(e.constructor); if (l === void 0) throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`); n = l, i = e; } if (u === void 0) u = [i.length]; else if (!Array.isArray(u)) throw new TypeError("A tensor's dims must be a number array"); r = u, this.cpuData = i, this.dataLocation = "cpu"; } let s = uo3(r); if (this.cpuData && s !== this.cpuData.length) throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`); this.type = n, this.dims = r, this.size = s; } static async fromImage(e, o) { return to3(e, o); } static fromTexture(e, o) { return eo3(e, o); } static fromGpuBuffer(e, o) { return ro3(e, o); } static fromPinnedBuffer(e, o, t) { return no3(e, o, t); } toDataURL(e) { return Zn3(this, e); } toImageData(e) { return Yn3(this, e); } get data() { if (this.ensureValid(), !this.cpuData) throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly."); return this.cpuData; } get location() { return this.dataLocation; } get texture() { if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture."); return this.gpuTextureData; } get gpuBuffer() { if (this.ensureValid(), !this.gpuBufferData) throw new Error("The data is not stored as a WebGPU buffer."); return this.gpuBufferData; } async getData(e) { switch (this.ensureValid(), this.dataLocation) { case "cpu": case "cpu-pinned": return this.data; case "texture": case "gpu-buffer": { if (!this.downloader) throw new Error("The current tensor is not created with a specified data downloader."); if (this.isDownloading) throw new Error("The current tensor is being downloaded."); try { this.isDownloading = true; let o = await this.downloader(); return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = o, e && this.disposer && (this.disposer(), this.disposer = void 0), o; } finally { this.isDownloading = false; } } default: throw new Error(`cannot get data from location: ${this.dataLocation}`); } } dispose() { if (this.isDownloading) throw new Error("The current tensor is being downloaded."); this.disposer && (this.disposer(), this.disposer = void 0), this.cpuData = void 0, this.gpuTextureData = void 0, this.gpuBufferData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none"; } ensureValid() { if (this.dataLocation === "none") throw new Error("The tensor is disposed."); } reshape(e) { if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource."); return lo3(this, e); } }; }); Re = x(() => { "use strict"; Ge3(); ot3 = nt2; }); Nr3 = x(() => { "use strict"; Br3(); co3 = (a, e) => { (typeof ct.trace > "u" ? !ct.wasm.trace : !ct.trace) || console.timeStamp(`${a}::ORT::${e}`); }, po3 = (a, e) => { let o = new Error().stack?.split(/\r\n|\r|\n/g) || [], t = false; for (let n = 0; n < o.length; n++) { if (t && !o[n].includes("TRACE_FUNC")) { let r = `FUNC_${a}::${o[n].trim().split(" ")[1]}`; e && (r += `::${e}`), co3("CPU", r); return; } o[n].includes("TRACE_FUNC") && (t = true); } }, Ve3 = (a) => { (typeof ct.trace > "u" ? !ct.wasm.trace : !ct.trace) || po3("BEGIN", a); }, ze2 = (a) => { (typeof ct.trace > "u" ? !ct.wasm.trace : !ct.trace) || po3("END", a); }; }); ho3 = x(() => { "use strict"; Ce3(); Re(); Nr3(); Me3 = class a { constructor(e) { this.handler = e; } async run(e, o, t) { Ve3(); let n = {}, r = {}; if (typeof e != "object" || e === null || e instanceof ot3 || Array.isArray(e)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let s = true; if (typeof o == "object") { if (o === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (o instanceof ot3) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(o)) { if (o.length === 0) throw new TypeError("'fetches' cannot be an empty array."); s = false; for (let l of o) { if (typeof l != "string") throw new TypeError("'fetches' must be a string array or an object."); if (this.outputNames.indexOf(l) === -1) throw new RangeError(`'fetches' contains invalid output name: ${l}.`); n[l] = null; } if (typeof t == "object" && t !== null) r = t; else if (typeof t < "u") throw new TypeError("'options' must be an object."); } else { let l = false, f = Object.getOwnPropertyNames(o); for (let p of this.outputNames) if (f.indexOf(p) !== -1) { let d = o[p]; (d === null || d instanceof ot3) && (l = true, s = false, n[p] = d); } if (l) { if (typeof t == "object" && t !== null) r = t; else if (typeof t < "u") throw new TypeError("'options' must be an object."); } else r = o; } } else if (typeof o < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let l of this.inputNames) if (typeof e[l] > "u") throw new Error(`input '${l}' is missing in 'feeds'.`); if (s) for (let l of this.outputNames) n[l] = null; let i = await this.handler.run(e, n, r), u = {}; for (let l in i) if (Object.hasOwnProperty.call(i, l)) { let f = i[l]; f instanceof ot3 ? u[l] = f : u[l] = new ot3(f.type, f.data, f.dims); } return ze2(), u; } async release() { return this.handler.dispose(); } static async create(e, o, t, n) { Ve3(); let r, s = {}; if (typeof e == "string") { if (r = e, typeof o == "object" && o !== null) s = o; else if (typeof o < "u") throw new TypeError("'options' must be an object."); } else if (e instanceof Uint8Array) { if (r = e, typeof o == "object" && o !== null) s = o; else if (typeof o < "u") throw new TypeError("'options' must be an object."); } else if (e instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && e instanceof SharedArrayBuffer) { let f = e, p = 0, d = e.byteLength; if (typeof o == "object" && o !== null) s = o; else if (typeof o == "number") { if (p = o, !Number.isSafeInteger(p)) throw new RangeError("'byteOffset' must be an integer."); if (p < 0 || p >= f.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${f.byteLength}).`); if (d = e.byteLength - p, typeof t == "number") { if (d = t, !Number.isSafeInteger(d)) throw new RangeError("'byteLength' must be an integer."); if (d <= 0 || p + d > f.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${f.byteLength - p}].`); if (typeof n == "object" && n !== null) s = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else if (typeof t < "u") throw new TypeError("'byteLength' must be a number."); } else if (typeof o < "u") throw new TypeError("'options' must be an object."); r = new Uint8Array(f, p, d); } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); let [i, u] = await Ne2(s), l = await i.createInferenceSessionHandler(r, u); return ze2(), new a(l); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } }; }); mo3 = x(() => { "use strict"; ho3(); Bl3 = Me3; }); bo3 = x(() => { "use strict"; }); yo3 = x(() => { "use strict"; }); go3 = x(() => { "use strict"; }); xo3 = x(() => { "use strict"; }); To2 = x(() => { "use strict"; Ce3(); Re(); Fl2 = "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.", Ue3 = class a { constructor(e, o, t) { this.handler = e, this.hasOptimizerModel = o, this.hasEvalModel = t; } get trainingInputNames() { return this.handler.inputNames; } get trainingOutputNames() { return this.handler.outputNames; } get evalInputNames() { if (this.hasEvalModel) return this.handler.evalInputNames; throw new Error("This training session has no evalModel loaded."); } get evalOutputNames() { if (this.hasEvalModel) return this.handler.evalOutputNames; throw new Error("This training session has no evalModel loaded."); } static async create(e, o) { let t = e.evalModel || "", n = e.optimizerModel || "", r = o || {}, [s, i] = await Ne2(r); if (s.createTrainingSessionHandler) { let u = await s.createTrainingSessionHandler(e.checkpointState, e.trainModel, t, n, i); return new a(u, !!e.optimizerModel, !!e.evalModel); } else throw new Error(Fl2); } typeNarrowingForRunStep(e, o, t, n, r) { let s = {}, i = {}; if (typeof t != "object" || t === null || t instanceof ot3 || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let u = true; if (typeof n == "object") { if (n === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (n instanceof ot3) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(n)) { if (n.length === 0) throw new TypeError("'fetches' cannot be an empty array."); u = false; for (let l of n) { if (typeof l != "string") throw new TypeError("'fetches' must be a string array or an object."); if (o.indexOf(l) === -1) throw new RangeError(`'fetches' contains invalid output name: ${l}.`); s[l] = null; } if (typeof r == "object" && r !== null) i = r; else if (typeof r < "u") throw new TypeError("'options' must be an object."); } else { let l = false, f = Object.getOwnPropertyNames(n); for (let p of o) if (f.indexOf(p) !== -1) { let d = n[p]; (d === null || d instanceof ot3) && (l = true, u = false, s[p] = d); } if (l) { if (typeof r == "object" && r !== null) i = r; else if (typeof r < "u") throw new TypeError("'options' must be an object."); } else i = n; } } else if (typeof n < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let l of e) if (typeof t[l] > "u") throw new Error(`input '${l}' is missing in 'feeds'.`); if (u) for (let l of o) s[l] = null; return [s, i]; } convertHandlerReturnTypeToMapOfTensors(e) { let o = {}; for (let t in e) if (Object.hasOwnProperty.call(e, t)) { let n = e[t]; n instanceof ot3 ? o[t] = n : o[t] = new ot3(n.type, n.data, n.dims); } return o; } async lazyResetGrad() { await this.handler.lazyResetGrad(); } async runTrainStep(e, o, t) { let [n, r] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, e, o, t), s = await this.handler.runTrainStep(e, n, r); return this.convertHandlerReturnTypeToMapOfTensors(s); } async runOptimizerStep(e) { if (this.hasOptimizerModel) await this.handler.runOptimizerStep(e || {}); else throw new Error("This TrainingSession has no OptimizerModel loaded."); } async runEvalStep(e, o, t) { if (this.hasEvalModel) { let [n, r] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, e, o, t), s = await this.handler.runEvalStep(e, n, r); return this.convertHandlerReturnTypeToMapOfTensors(s); } else throw new Error("This TrainingSession has no EvalModel loaded."); } async getParametersSize(e = true) { return this.handler.getParametersSize(e); } async loadParametersBuffer(e, o = true) { let t = await this.getParametersSize(o); if (e.length !== 4 * t) throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check."); return this.handler.loadParametersBuffer(e, o); } async getContiguousParameters(e = true) { return this.handler.getContiguousParameters(e); } async release() { return this.handler.dispose(); } }; }); vo2 = x(() => { "use strict"; To2(); Nl2 = Ue3; }); Cr3 = {}; Wn3(Cr3, { InferenceSession: () => Bl3, TRACE: () => co3, TRACE_FUNC_BEGIN: () => Ve3, TRACE_FUNC_END: () => ze2, Tensor: () => ot3, TrainingSession: () => Nl2, env: () => j2, registerBackend: () => Fe2 }); Ft3 = x(() => { "use strict"; qn3(); Jn3(); mo3(); Re(); bo3(); yo3(); Nr3(); go3(); xo3(); vo2(); }); pt = x(() => { "use strict"; Gr3 = class { log(e, o, t) { } }, Rr3 = class { log(e, o, t) { console.log(`${this.color(e)} ${t ? "\x1B[35m" + t + "\x1B[0m " : ""}${o}`); } color(e) { switch (e) { case "verbose": return "\x1B[34;40mv\x1B[0m"; case "info": return "\x1B[32mi\x1B[0m"; case "warning": return "\x1B[30;43mw\x1B[0m"; case "error": return "\x1B[31;40me\x1B[0m"; case "fatal": return "\x1B[101mf\x1B[0m"; default: throw new Error(`unsupported severity: ${e}`); } } }, Io2 = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, Cl3 = { none: new Gr3(), console: new Rr3() }, _o2 = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false }, ye = { "": _o2 }; ((u) => { function a(l, f) { u("verbose", l, f); } u.verbose = a; function e(l, f) { u("info", l, f); } u.info = e; function o(l, f) { u("warning", l, f); } u.warning = o; function t(l, f) { u("error", l, f); } u.error = t; function n(l, f) { u("fatal", l, f); } u.fatal = n; function r(l) { ye = {}, s("", l || {}); } u.reset = r; function s(l, f) { if (l === "*") r(f); else { let p = ye[l] || _o2; ye[l] = { provider: f.provider || p.provider, minimalSeverity: f.minimalSeverity || p.minimalSeverity, logDateTime: f.logDateTime === void 0 ? p.logDateTime : f.logDateTime, logSourceLocation: f.logSourceLocation === void 0 ? p.logSourceLocation : f.logSourceLocation }; } } u.set = s; function i(l) { let f = {}; l.logLevel && (f.minimalSeverity = l.logLevel), s("", f); } u.setWithEnv = i; })(Nt3 ||= {}); M2 = Nt3, qe2 = class { constructor(e, o, t, n, r, s) { this.category = e; this.name = o; this.startTime = t; this.endCallback = n; this.timer = r; this.ctx = s; } async end() { return this.endCallback(this); } async checkTimer() { if (this.ctx === void 0 || this.timer === void 0) throw new Error("No webgl timer found"); return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer); } }, je2 = class { constructor(e, o, t, n) { this.category = e; this.name = o; this.startTime = t; this.endTime = n; } }, Ke3 = class { constructor(e, o, t) { this._started = false; this._flushPointer = 0; this._started = false, this._maxNumberEvents = e === void 0 ? 1e4 : e, this._flushBatchSize = o === void 0 ? 10 : o, this._flushIntervalInMilliseconds = t === void 0 ? 5e3 : t; } static create(e) { return e === void 0 ? new this() : new this(e.maxNumberEvents, e.flushBatchSize, e.flushIntervalInMilliseconds); } start() { this._started = true, this._timingEvents = [], this._flushTime = He3(), this._flushPointer = 0; } stop() { for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); } event(e, o, t, n) { let r = this._started ? this.begin(e, o, n) : void 0, s = false, i = t(); if (i && typeof i.then == "function") return s = true, new Promise((u, l) => { i.then(async (f) => { r && await r.end(), u(f); }, async (f) => { r && await r.end(), l(f); }); }); if (!s && r) { let u = r.end(); if (u && typeof u.then == "function") return new Promise((l, f) => { u.then(() => { l(i); }, (p) => { f(p); }); }); } return i; } begin(e, o, t) { if (!this._started) throw new Error("profiler is not started yet"); if (t === void 0) { let n = He3(); return this.flush(n), new qe2(e, o, n, (r) => this.endSync(r)); } else { let n = t.beginTimer(); return new qe2(e, o, 0, async (r) => this.end(r), n, t); } } async end(e) { let o = await e.checkTimer(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new je2(e.category, e.name, e.startTime, o)), this.flush(o)); } endSync(e) { let o = He3(); this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new je2(e.category, e.name, e.startTime, o)), this.flush(o)); } logOneEvent(e) { M2.verbose(`Profiler.${e.category}`, `${(e.endTime - e.startTime).toFixed(2)}ms on event '${e.name}' at ${e.endTime.toFixed(2)}`); } flush(e) { if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || e - this._flushTime >= this._flushIntervalInMilliseconds) { for (let o = this._flushPointer; this._flushPointer < o + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]); this._flushTime = He3(); } } get started() { return this._started; } }, He3 = typeof performance < "u" && performance.now ? () => performance.now() : Date.now; }); Oo = x(() => { "use strict"; }); Ao2 = Z((Vr3) => { "use strict"; Vr3.__esModule = true; var Vl3 = (function() { function a(e) { if (!e) throw new TypeError("Invalid argument; `value` has no value."); this.value = a.EMPTY, e && a.isGuid(e) && (this.value = e); } return a.isGuid = function(e) { var o = e.toString(); return e && (e instanceof a || a.validator.test(o)); }, a.create = function() { return new a([a.gen(2), a.gen(1), a.gen(1), a.gen(1), a.gen(3)].join("-")); }, a.createEmpty = function() { return new a("emptyguid"); }, a.parse = function(e) { return new a(e); }, a.raw = function() { return [a.gen(2), a.gen(1), a.gen(1), a.gen(1), a.gen(3)].join("-"); }, a.gen = function(e) { for (var o = "", t = 0; t < e; t++) o += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1); return o; }, a.prototype.equals = function(e) { return a.isGuid(e) && this.value === e.toString(); }, a.prototype.isEmpty = function() { return this.value === a.EMPTY; }, a.prototype.toString = function() { return this.value; }, a.prototype.toJSON = function() { return { value: this.value }; }, a.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), a.EMPTY = "00000000-0000-0000-0000-000000000000", a; })(); Vr3.Guid = Vl3; }); Ur3 = x(() => { dt3 = null; try { dt3 = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; } catch { } U2.prototype.__isLong__; Object.defineProperty(U2.prototype, "__isLong__", { value: true }); U2.isLong = rt3; Eo2 = {}, Do = {}; U2.fromInt = Ht3; U2.fromNumber = ht3; U2.fromBits = V2; Xe3 = Math.pow; U2.fromString = Mr3; U2.fromValue = vt2; Lo = 65536, zl3 = 1 << 24, ie2 = Lo * Lo, Bo2 = ie2 * ie2, $o2 = Bo2 / 2, ko2 = Ht3(zl3), Tt3 = Ht3(0); U2.ZERO = Tt3; $t3 = Ht3(0, true); U2.UZERO = $t3; oe = Ht3(1); U2.ONE = oe; Fo2 = Ht3(1, true); U2.UONE = Fo2; zr3 = Ht3(-1); U2.NEG_ONE = zr3; No2 = V2(-1, 2147483647, false); U2.MAX_VALUE = No2; Co3 = V2(-1, -1, true); U2.MAX_UNSIGNED_VALUE = Co3; ut = V2(0, -2147483648, false); U2.MIN_VALUE = ut; T2 = U2.prototype; T2.toInt = function() { return this.unsigned ? this.low >>> 0 : this.low; }; T2.toNumber = function() { return this.unsigned ? (this.high >>> 0) * ie2 + (this.low >>> 0) : this.high * ie2 + (this.low >>> 0); }; T2.toString = function(e) { if (e = e || 10, e < 2 || 36 < e) throw RangeError("radix"); if (this.isZero()) return "0"; if (this.isNegative()) if (this.eq(ut)) { var o = ht3(e), t = this.div(o), n = t.mul(o).sub(this); return t.toString(e) + n.toInt().toString(e); } else return "-" + this.neg().toString(e); for (var r = ht3(Xe3(e, 6), this.unsigned), s = this, i = ""; ; ) { var u = s.div(r), l = s.sub(u.mul(r)).toInt() >>> 0, f = l.toString(e); if (s = u, s.isZero()) return f + i; for (; f.length < 6; ) f = "0" + f; i = "" + f + i; } }; T2.getHighBits = function() { return this.high; }; T2.getHighBitsUnsigned = function() { return this.high >>> 0; }; T2.getLowBits = function() { return this.low; }; T2.getLowBitsUnsigned = function() { return this.low >>> 0; }; T2.getNumBitsAbs = function() { if (this.isNegative()) return this.eq(ut) ? 64 : this.neg().getNumBitsAbs(); for (var e = this.high != 0 ? this.high : this.low, o = 31; o > 0 && !(e & 1 << o); o--) ; return this.high != 0 ? o + 33 : o + 1; }; T2.isZero = function() { return this.high === 0 && this.low === 0; }; T2.eqz = T2.isZero; T2.isNegative = function() { return !this.unsigned && this.high < 0; }; T2.isPositive = function() { return this.unsigned || this.high >= 0; }; T2.isOdd = function() { return (this.low & 1) === 1; }; T2.isEven = function() { return (this.low & 1) === 0; }; T2.equals = function(e) { return rt3(e) || (e = vt2(e)), this.unsigned !== e.unsigned && this.high >>> 31 === 1 && e.high >>> 31 === 1 ? false : this.high === e.high && this.low === e.low; }; T2.eq = T2.equals; T2.notEquals = function(e) { return !this.eq(e); }; T2.neq = T2.notEquals; T2.ne = T2.notEquals; T2.lessThan = function(e) { return this.comp(e) < 0; }; T2.lt = T2.lessThan; T2.lessThanOrEqual = function(e) { return this.comp(e) <= 0; }; T2.lte = T2.lessThanOrEqual; T2.le = T2.lessThanOrEqual; T2.greaterThan = function(e) { return this.comp(e) > 0; }; T2.gt = T2.greaterThan; T2.greaterThanOrEqual = function(e) { return this.comp(e) >= 0; }; T2.gte = T2.greaterThanOrEqual; T2.ge = T2.greaterThanOrEqual; T2.compare = function(e) { if (rt3(e) || (e = vt2(e)), this.eq(e)) return 0; var o = this.isNegative(), t = e.isNegative(); return o && !t ? -1 : !o && t ? 1 : this.unsigned ? e.high >>> 0 > this.high >>> 0 || e.high === this.high && e.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(e).isNegative() ? -1 : 1; }; T2.comp = T2.compare; T2.negate = function() { return !this.unsigned && this.eq(ut) ? ut : this.not().add(oe); }; T2.neg = T2.negate; T2.add = function(e) { rt3(e) || (e = vt2(e)); var o = this.high >>> 16, t = this.high & 65535, n = this.low >>> 16, r = this.low & 65535, s = e.high >>> 16, i = e.high & 65535, u = e.low >>> 16, l = e.low & 65535, f = 0, p = 0, d = 0, b = 0; return b += r + l, d += b >>> 16, b &= 65535, d += n + u, p += d >>> 16, d &= 65535, p += t + i, f += p >>> 16, p &= 65535, f += o + s, f &= 65535, V2(d << 16 | b, f << 16 | p, this.unsigned); }; T2.subtract = function(e) { return rt3(e) || (e = vt2(e)), this.add(e.neg()); }; T2.sub = T2.subtract; T2.multiply = function(e) { if (this.isZero()) return this; if (rt3(e) || (e = vt2(e)), dt3) { var o = dt3.mul(this.low, this.high, e.low, e.high); return V2(o, dt3.get_high(), this.unsigned); } if (e.isZero()) return this.unsigned ? $t3 : Tt3; if (this.eq(ut)) return e.isOdd() ? ut : Tt3; if (e.eq(ut)) return this.isOdd() ? ut : Tt3; if (this.isNegative()) return e.isNegative() ? this.neg().mul(e.neg()) : this.neg().mul(e).neg(); if (e.isNegative()) return this.mul(e.neg()).neg(); if (this.lt(ko2) && e.lt(ko2)) return ht3(this.toNumber() * e.toNumber(), this.unsigned); var t = this.high >>> 16, n = this.high & 65535, r = this.low >>> 16, s = this.low & 65535, i = e.high >>> 16, u = e.high & 65535, l = e.low >>> 16, f = e.low & 65535, p = 0, d = 0, b = 0, g = 0; return g += s * f, b += g >>> 16, g &= 65535, b += r * f, d += b >>> 16, b &= 65535, b += s * l, d += b >>> 16, b &= 65535, d += n * f, p += d >>> 16, d &= 65535, d += r * l, p += d >>> 16, d &= 65535, d += s * u, p += d >>> 16, d &= 65535, p += t * f + n * l + r * u + s * i, p &= 65535, V2(b << 16 | g, p << 16 | d, this.unsigned); }; T2.mul = T2.multiply; T2.divide = function(e) { if (rt3(e) || (e = vt2(e)), e.isZero()) throw Error("division by zero"); if (dt3) { if (!this.unsigned && this.high === -2147483648 && e.low === -1 && e.high === -1) return this; var o = (this.unsigned ? dt3.div_u : dt3.div_s)(this.low, this.high, e.low, e.high); return V2(o, dt3.get_high(), this.unsigned); } if (this.isZero()) return this.unsigned ? $t3 : Tt3; var t, n, r; if (this.unsigned) { if (e.unsigned || (e = e.toUnsigned()), e.gt(this)) return $t3; if (e.gt(this.shru(1))) return Fo2; r = $t3; } else { if (this.eq(ut)) { if (e.eq(oe) || e.eq(zr3)) return ut; if (e.eq(ut)) return oe; var s = this.shr(1); return t = s.div(e).shl(1), t.eq(Tt3) ? e.isNegative() ? oe : zr3 : (n = this.sub(e.mul(t)), r = t.add(n.div(e)), r); } else if (e.eq(ut)) return this.unsigned ? $t3 : Tt3; if (this.isNegative()) return e.isNegative() ? this.neg().div(e.neg()) : this.neg().div(e).neg(); if (e.isNegative()) return this.div(e.neg()).neg(); r = Tt3; } for (n = this; n.gte(e); ) { t = Math.max(1, Math.floor(n.toNumber() / e.toNumber())); for (var i = Math.ceil(Math.log(t) / Math.LN2), u = i <= 48 ? 1 : Xe3(2, i - 48), l = ht3(t), f = l.mul(e); f.isNegative() || f.gt(n); ) t -= u, l = ht3(t, this.unsigned), f = l.mul(e); l.isZero() && (l = oe), r = r.add(l), n = n.sub(f); } return r; }; T2.div = T2.divide; T2.modulo = function(e) { if (rt3(e) || (e = vt2(e)), dt3) { var o = (this.unsigned ? dt3.rem_u : dt3.rem_s)(this.low, this.high, e.low, e.high); return V2(o, dt3.get_high(), this.unsigned); } return this.sub(this.div(e).mul(e)); }; T2.mod = T2.modulo; T2.rem = T2.modulo; T2.not = function() { return V2(~this.low, ~this.high, this.unsigned); }; T2.countLeadingZeros = function() { return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; }; T2.clz = T2.countLeadingZeros; T2.countTrailingZeros = function() { return this.low ? Po(this.low) : Po(this.high) + 32; }; T2.ctz = T2.countTrailingZeros; T2.and = function(e) { return rt3(e) || (e = vt2(e)), V2(this.low & e.low, this.high & e.high, this.unsigned); }; T2.or = function(e) { return rt3(e) || (e = vt2(e)), V2(this.low | e.low, this.high | e.high, this.unsigned); }; T2.xor = function(e) { return rt3(e) || (e = vt2(e)), V2(this.low ^ e.low, this.high ^ e.high, this.unsigned); }; T2.shiftLeft = function(e) { return rt3(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? V2(this.low << e, this.high << e | this.low >>> 32 - e, this.unsigned) : V2(0, this.low << e - 32, this.unsigned); }; T2.shl = T2.shiftLeft; T2.shiftRight = function(e) { return rt3(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? V2(this.low >>> e | this.high << 32 - e, this.high >> e, this.unsigned) : V2(this.high >> e - 32, this.high >= 0 ? 0 : -1, this.unsigned); }; T2.shr = T2.shiftRight; T2.shiftRightUnsigned = function(e) { return rt3(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? V2(this.low >>> e | this.high << 32 - e, this.high >>> e, this.unsigned) : e === 32 ? V2(this.high, 0, this.unsigned) : V2(this.high >>> e - 32, 0, this.unsigned); }; T2.shru = T2.shiftRightUnsigned; T2.shr_u = T2.shiftRightUnsigned; T2.rotateLeft = function(e) { var o; return rt3(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e === 32 ? V2(this.high, this.low, this.unsigned) : e < 32 ? (o = 32 - e, V2(this.low << e | this.high >>> o, this.high << e | this.low >>> o, this.unsigned)) : (e -= 32, o = 32 - e, V2(this.high << e | this.low >>> o, this.low << e | this.high >>> o, this.unsigned)); }; T2.rotl = T2.rotateLeft; T2.rotateRight = function(e) { var o; return rt3(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e === 32 ? V2(this.high, this.low, this.unsigned) : e < 32 ? (o = 32 - e, V2(this.high << o | this.low >>> e, this.low << o | this.high >>> e, this.unsigned)) : (e -= 32, o = 32 - e, V2(this.low << o | this.high >>> e, this.high << o | this.low >>> e, this.unsigned)); }; T2.rotr = T2.rotateRight; T2.toSigned = function() { return this.unsigned ? V2(this.low, this.high, false) : this; }; T2.toUnsigned = function() { return this.unsigned ? this : V2(this.low, this.high, true); }; T2.toBytes = function(e) { return e ? this.toBytesLE() : this.toBytesBE(); }; T2.toBytesLE = function() { var e = this.high, o = this.low; return [o & 255, o >>> 8 & 255, o >>> 16 & 255, o >>> 24, e & 255, e >>> 8 & 255, e >>> 16 & 255, e >>> 24]; }; T2.toBytesBE = function() { var e = this.high, o = this.low; return [e >>> 24, e >>> 16 & 255, e >>> 8 & 255, e & 255, o >>> 24, o >>> 16 & 255, o >>> 8 & 255, o & 255]; }; U2.fromBytes = function(e, o, t) { return t ? U2.fromBytesLE(e, o) : U2.fromBytesBE(e, o); }; U2.fromBytesLE = function(e, o) { return new U2(e[0] | e[1] << 8 | e[2] << 16 | e[3] << 24, e[4] | e[5] << 8 | e[6] << 16 | e[7] << 24, o); }; U2.fromBytesBE = function(e, o) { return new U2(e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7], e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], o); }; kt3 = U2; }); Je = x(() => { m = {}; m.Offset; m.Table; m.SIZEOF_SHORT = 2; m.SIZEOF_INT = 4; m.FILE_IDENTIFIER_LENGTH = 4; m.SIZE_PREFIX_LENGTH = 4; m.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }; m.int32 = new Int32Array(2); m.float32 = new Float32Array(m.int32.buffer); m.float64 = new Float64Array(m.int32.buffer); m.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1; m.Long = function(a, e) { this.low = a | 0, this.high = e | 0; }; m.Long.create = function(a, e) { return a == 0 && e == 0 ? m.Long.ZERO : new m.Long(a, e); }; m.Long.prototype.toFloat64 = function() { return (this.low >>> 0) + this.high * 4294967296; }; m.Long.prototype.equals = function(a) { return this.low == a.low && this.high == a.high; }; m.Long.ZERO = new m.Long(0, 0); m.Builder = function(a) { if (a) var e = a; else var e = 1024; this.bb = m.ByteBuffer.allocate(e), this.space = e, this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }; m.Builder.prototype.clear = function() { this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false; }; m.Builder.prototype.forceDefaults = function(a) { this.force_defaults = a; }; m.Builder.prototype.dataBuffer = function() { return this.bb; }; m.Builder.prototype.asUint8Array = function() { return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); }; m.Builder.prototype.prep = function(a, e) { a > this.minalign && (this.minalign = a); for (var o = ~(this.bb.capacity() - this.space + e) + 1 & a - 1; this.space < o + a + e; ) { var t = this.bb.capacity(); this.bb = m.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - t; } this.pad(o); }; m.Builder.prototype.pad = function(a) { for (var e = 0; e < a; e++) this.bb.writeInt8(--this.space, 0); }; m.Builder.prototype.writeInt8 = function(a) { this.bb.writeInt8(this.space -= 1, a); }; m.Builder.prototype.writeInt16 = function(a) { this.bb.writeInt16(this.space -= 2, a); }; m.Builder.prototype.writeInt32 = function(a) { this.bb.writeInt32(this.space -= 4, a); }; m.Builder.prototype.writeInt64 = function(a) { this.bb.writeInt64(this.space -= 8, a); }; m.Builder.prototype.writeFloat32 = function(a) { this.bb.writeFloat32(this.space -= 4, a); }; m.Builder.prototype.writeFloat64 = function(a) { this.bb.writeFloat64(this.space -= 8, a); }; m.Builder.prototype.addInt8 = function(a) { this.prep(1, 0), this.writeInt8(a); }; m.Builder.prototype.addInt16 = function(a) { this.prep(2, 0), this.writeInt16(a); }; m.Builder.prototype.addInt32 = function(a) { this.prep(4, 0), this.writeInt32(a); }; m.Builder.prototype.addInt64 = function(a) { this.prep(8, 0), this.writeInt64(a); }; m.Builder.prototype.addFloat32 = function(a) { this.prep(4, 0), this.writeFloat32(a); }; m.Builder.prototype.addFloat64 = function(a) { this.prep(8, 0), this.writeFloat64(a); }; m.Builder.prototype.addFieldInt8 = function(a, e, o) { (this.force_defaults || e != o) && (this.addInt8(e), this.slot(a)); }; m.Builder.prototype.addFieldInt16 = function(a, e, o) { (this.force_defaults || e != o) && (this.addInt16(e), this.slot(a)); }; m.Builder.prototype.addFieldInt32 = function(a, e, o) { (this.force_defaults || e != o) && (this.addInt32(e), this.slot(a)); }; m.Builder.prototype.addFieldInt64 = function(a, e, o) { (this.force_defaults || !e.equals(o)) && (this.addInt64(e), this.slot(a)); }; m.Builder.prototype.addFieldFloat32 = function(a, e, o) { (this.force_defaults || e != o) && (this.addFloat32(e), this.slot(a)); }; m.Builder.prototype.addFieldFloat64 = function(a, e, o) { (this.force_defaults || e != o) && (this.addFloat64(e), this.slot(a)); }; m.Builder.prototype.addFieldOffset = function(a, e, o) { (this.force_defaults || e != o) && (this.addOffset(e), this.slot(a)); }; m.Builder.prototype.addFieldStruct = function(a, e, o) { e != o && (this.nested(e), this.slot(a)); }; m.Builder.prototype.nested = function(a) { if (a != this.offset()) throw new Error("FlatBuffers: struct must be serialized inline."); }; m.Builder.prototype.notNested = function() { if (this.isNested) throw new Error("FlatBuffers: object serialization must not be nested."); }; m.Builder.prototype.slot = function(a) { this.vtable[a] = this.offset(); }; m.Builder.prototype.offset = function() { return this.bb.capacity() - this.space; }; m.Builder.growByteBuffer = function(a) { var e = a.capacity(); if (e & 3221225472) throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); var o = e << 1, t = m.ByteBuffer.allocate(o); return t.setPosition(o - e), t.bytes().set(a.bytes(), o - e), t; }; m.Builder.prototype.addOffset = function(a) { this.prep(m.SIZEOF_INT, 0), this.writeInt32(this.offset() - a + m.SIZEOF_INT); }; m.Builder.prototype.startObject = function(a) { this.notNested(), this.vtable == null && (this.vtable = []), this.vtable_in_use = a; for (var e = 0; e < a; e++) this.vtable[e] = 0; this.isNested = true, this.object_start = this.offset(); }; m.Builder.prototype.endObject = function() { if (this.vtable == null || !this.isNested) throw new Error("FlatBuffers: endObject called without startObject"); this.addInt32(0); for (var a = this.offset(), e = this.vtable_in_use - 1; e >= 0 && this.vtable[e] == 0; e--) ; for (var o = e + 1; e >= 0; e--) this.addInt16(this.vtable[e] != 0 ? a - this.vtable[e] : 0); var t = 2; this.addInt16(a - this.object_start); var n = (o + t) * m.SIZEOF_SHORT; this.addInt16(n); var r = 0, s = this.space; t: for (e = 0; e < this.vtables.length; e++) { var i = this.bb.capacity() - this.vtables[e]; if (n == this.bb.readInt16(i)) { for (var u = m.SIZEOF_SHORT; u < n; u += m.SIZEOF_SHORT) if (this.bb.readInt16(s + u) != this.bb.readInt16(i + u)) continue t; r = this.vtables[e]; break; } } return r ? (this.space = this.bb.capacity() - a, this.bb.writeInt32(this.space, r - a)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - a, this.offset() - a)), this.isNested = false, a; }; m.Builder.prototype.finish = function(a, e, o) { var t = o ? m.SIZE_PREFIX_LENGTH : 0; if (e) { var n = e; if (this.prep(this.minalign, m.SIZEOF_INT + m.FILE_IDENTIFIER_LENGTH + t), n.length != m.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + m.FILE_IDENTIFIER_LENGTH); for (var r = m.FILE_IDENTIFIER_LENGTH - 1; r >= 0; r--) this.writeInt8(n.charCodeAt(r)); } this.prep(this.minalign, m.SIZEOF_INT + t), this.addOffset(a), t && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space); }; m.Builder.prototype.finishSizePrefixed = function(a, e) { this.finish(a, e, true); }; m.Builder.prototype.requiredField = function(a, e) { var o = this.bb.capacity() - a, t = o - this.bb.readInt32(o), n = this.bb.readInt16(t + e) != 0; if (!n) throw new Error("FlatBuffers: field " + e + " must be set"); }; m.Builder.prototype.startVector = function(a, e, o) { this.notNested(), this.vector_num_elems = e, this.prep(m.SIZEOF_INT, a * e), this.prep(o, a * e); }; m.Builder.prototype.endVector = function() { return this.writeInt32(this.vector_num_elems), this.offset(); }; m.Builder.prototype.createString = function(a) { if (a instanceof Uint8Array) var e = a; else for (var e = [], o = 0; o < a.length; ) { var t, n = a.charCodeAt(o++); if (n < 55296 || n >= 56320) t = n; else { var r = a.charCodeAt(o++); t = (n << 10) + r + (65536 - 56623104 - 56320); } t < 128 ? e.push(t) : (t < 2048 ? e.push(t >> 6 & 31 | 192) : (t < 65536 ? e.push(t >> 12 & 15 | 224) : e.push(t >> 18 & 7 | 240, t >> 12 & 63 | 128), e.push(t >> 6 & 63 | 128)), e.push(t & 63 | 128)); } this.addInt8(0), this.startVector(1, e.length, 1), this.bb.setPosition(this.space -= e.length); for (var o = 0, s = this.space, i = this.bb.bytes(); o < e.length; o++) i[s++] = e[o]; return this.endVector(); }; m.Builder.prototype.createLong = function(a, e) { return m.Long.create(a, e); }; m.ByteBuffer = function(a) { this.bytes_ = a, this.position_ = 0; }; m.ByteBuffer.allocate = function(a) { return new m.ByteBuffer(new Uint8Array(a)); }; m.ByteBuffer.prototype.clear = function() { this.position_ = 0; }; m.ByteBuffer.prototype.bytes = function() { return this.bytes_; }; m.ByteBuffer.prototype.position = function() { return this.position_; }; m.ByteBuffer.prototype.setPosition = function(a) { this.position_ = a; }; m.ByteBuffer.prototype.capacity = function() { return this.bytes_.length; }; m.ByteBuffer.prototype.readInt8 = function(a) { return this.readUint8(a) << 24 >> 24; }; m.ByteBuffer.prototype.readUint8 = function(a) { return this.bytes_[a]; }; m.ByteBuffer.prototype.readInt16 = function(a) { return this.readUint16(a) << 16 >> 16; }; m.ByteBuffer.prototype.readUint16 = function(a) { return this.bytes_[a] | this.bytes_[a + 1] << 8; }; m.ByteBuffer.prototype.readInt32 = function(a) { return this.bytes_[a] | this.bytes_[a + 1] << 8 | this.bytes_[a + 2] << 16 | this.bytes_[a + 3] << 24; }; m.ByteBuffer.prototype.readUint32 = function(a) { return this.readInt32(a) >>> 0; }; m.ByteBuffer.prototype.readInt64 = function(a) { return new m.Long(this.readInt32(a), this.readInt32(a + 4)); }; m.ByteBuffer.prototype.readUint64 = function(a) { return new m.Long(this.readUint32(a), this.readUint32(a + 4)); }; m.ByteBuffer.prototype.readFloat32 = function(a) { return m.int32[0] = this.readInt32(a), m.float32[0]; }; m.ByteBuffer.prototype.readFloat64 = function(a) { return m.int32[m.isLittleEndian ? 0 : 1] = this.readInt32(a), m.int32[m.isLittleEndian ? 1 : 0] = this.readInt32(a + 4), m.float64[0]; }; m.ByteBuffer.prototype.writeInt8 = function(a, e) { this.bytes_[a] = e; }; m.ByteBuffer.prototype.writeUint8 = function(a, e) { this.bytes_[a] = e; }; m.ByteBuffer.prototype.writeInt16 = function(a, e) { this.bytes_[a] = e, this.bytes_[a + 1] = e >> 8; }; m.ByteBuffer.prototype.writeUint16 = function(a, e) { this.bytes_[a] = e, this.bytes_[a + 1] = e >> 8; }; m.ByteBuffer.prototype.writeInt32 = function(a, e) { this.bytes_[a] = e, this.bytes_[a + 1] = e >> 8, this.bytes_[a + 2] = e >> 16, this.bytes_[a + 3] = e >> 24; }; m.ByteBuffer.prototype.writeUint32 = function(a, e) { this.bytes_[a] = e, this.bytes_[a + 1] = e >> 8, this.bytes_[a + 2] = e >> 16, this.bytes_[a + 3] = e >> 24; }; m.ByteBuffer.prototype.writeInt64 = function(a, e) { this.writeInt32(a, e.low), this.writeInt32(a + 4, e.high); }; m.ByteBuffer.prototype.writeUint64 = function(a, e) { this.writeUint32(a, e.low), this.writeUint32(a + 4, e.high); }; m.ByteBuffer.prototype.writeFloat32 = function(a, e) { m.float32[0] = e, this.writeInt32(a, m.int32[0]); }; m.ByteBuffer.prototype.writeFloat64 = function(a, e) { m.float64[0] = e, this.writeInt32(a, m.int32[m.isLittleEndian ? 0 : 1]), this.writeInt32(a + 4, m.int32[m.isLittleEndian ? 1 : 0]); }; m.ByteBuffer.prototype.getBufferIdentifier = function() { if (this.bytes_.length < this.position_ + m.SIZEOF_INT + m.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier."); for (var a = "", e = 0; e < m.FILE_IDENTIFIER_LENGTH; e++) a += String.fromCharCode(this.readInt8(this.position_ + m.SIZEOF_INT + e)); return a; }; m.ByteBuffer.prototype.__offset = function(a, e) { var o = a - this.readInt32(a); return e < this.readInt16(o) ? this.readInt16(o + e) : 0; }; m.ByteBuffer.prototype.__union = function(a, e) { return a.bb_pos = e + this.readInt32(e), a.bb = this, a; }; m.ByteBuffer.prototype.__string = function(a, e) { a += this.readInt32(a); var o = this.readInt32(a), t = "", n = 0; if (a += m.SIZEOF_INT, e === m.Encoding.UTF8_BYTES) return this.bytes_.subarray(a, a + o); for (; n < o; ) { var r, s = this.readUint8(a + n++); if (s < 192) r = s; else { var i = this.readUint8(a + n++); if (s < 224) r = (s & 31) << 6 | i & 63; else { var u = this.readUint8(a + n++); if (s < 240) r = (s & 15) << 12 | (i & 63) << 6 | u & 63; else { var l = this.readUint8(a + n++); r = (s & 7) << 18 | (i & 63) << 12 | (u & 63) << 6 | l & 63; } } } r < 65536 ? t += String.fromCharCode(r) : (r -= 65536, t += String.fromCharCode((r >> 10) + 55296, (r & 1024 - 1) + 56320)); } return t; }; m.ByteBuffer.prototype.__indirect = function(a) { return a + this.readInt32(a); }; m.ByteBuffer.prototype.__vector = function(a) { return a + this.readInt32(a) + m.SIZEOF_INT; }; m.ByteBuffer.prototype.__vector_len = function(a) { return this.readInt32(a + this.readInt32(a)); }; m.ByteBuffer.prototype.__has_identifier = function(a) { if (a.length != m.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + m.FILE_IDENTIFIER_LENGTH); for (var e = 0; e < m.FILE_IDENTIFIER_LENGTH; e++) if (a.charCodeAt(e) != this.readInt8(this.position_ + m.SIZEOF_INT + e)) return false; return true; }; m.ByteBuffer.prototype.createLong = function(a, e) { return m.Long.create(a, e); }; }); ge2 = x(() => { "use strict"; Je(); ((e) => { let a; ((t) => { let o; ((r) => { let n; ((S) => (S[S.UNDEFINED = 0] = "UNDEFINED", S[S.FLOAT = 1] = "FLOAT", S[S.INT = 2] = "INT", S[S.STRING = 3] = "STRING", S[S.TENSOR = 4] = "TENSOR", S[S.GRAPH = 5] = "GRAPH", S[S.FLOATS = 6] = "FLOATS", S[S.INTS = 7] = "INTS", S[S.STRINGS = 8] = "STRINGS", S[S.TENSORS = 9] = "TENSORS", S[S.GRAPHS = 10] = "GRAPHS", S[S.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", S[S.SPARSE_TENSORS = 12] = "SPARSE_TENSORS"))(n = r.AttributeType ||= {}); })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { let n; ((l) => (l[l.UNKNOWN = 0] = "UNKNOWN", l[l.VALUE = 1] = "VALUE", l[l.PARAM = 2] = "PARAM"))(n = r.DimensionValueType ||= {}); })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { let n; ((L) => (L[L.UNDEFINED = 0] = "UNDEFINED", L[L.FLOAT = 1] = "FLOAT", L[L.UINT8 = 2] = "UINT8", L[L.INT8 = 3] = "INT8", L[L.UINT16 = 4] = "UINT16", L[L.INT16 = 5] = "INT16", L[L.INT32 = 6] = "INT32", L[L.INT64 = 7] = "INT64", L[L.STRING = 8] = "STRING", L[L.BOOL = 9] = "BOOL", L[L.FLOAT16 = 10] = "FLOAT16", L[L.DOUBLE = 11] = "DOUBLE", L[L.UINT32 = 12] = "UINT32", L[L.UINT64 = 13] = "UINT64", L[L.COMPLEX64 = 14] = "COMPLEX64", L[L.COMPLEX128 = 15] = "COMPLEX128", L[L.BFLOAT16 = 16] = "BFLOAT16", L[L.FLOAT8E4M3FN = 17] = "FLOAT8E4M3FN", L[L.FLOAT8E4M3FNUZ = 18] = "FLOAT8E4M3FNUZ", L[L.FLOAT8E5M2 = 19] = "FLOAT8E5M2", L[L.FLOAT8E5M2FNUZ = 20] = "FLOAT8E5M2FNUZ"))(n = r.TensorDataType ||= {}); })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { let n; ((u) => (u[u.Primitive = 0] = "Primitive", u[u.Fused = 1] = "Fused"))(n = r.NodeType ||= {}); })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { let n; ((f) => (f[f.NONE = 0] = "NONE", f[f.tensor_type = 1] = "tensor_type", f[f.sequence_type = 2] = "sequence_type", f[f.map_type = 3] = "map_type"))(n = r.TypeInfoValue ||= {}); })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsShape(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsShape(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } dim(i, u) { let l = this.bb.__offset(this.bb_pos, 4); return l ? (u || new e.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } dimLength() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startShape(i) { i.startObject(1); } static addDim(i, u) { i.addFieldOffset(0, u, 0); } static createDimVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startDimVector(i, u) { i.startVector(4, u, 4); } static endShape(i) { return i.endObject(); } static createShape(i, u) { return n.startShape(i), n.addDim(i, u), n.endShape(i); } } r.Shape = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsDimension(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsDimension(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } value(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (i || new e.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } denotation(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, i) : null; } static startDimension(i) { i.startObject(2); } static addValue(i, u) { i.addFieldOffset(0, u, 0); } static addDenotation(i, u) { i.addFieldOffset(1, u, 0); } static endDimension(i) { return i.endObject(); } static createDimension(i, u, l) { return n.startDimension(i), n.addValue(i, u), n.addDenotation(i, l), n.endDimension(i); } } r.Dimension = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsDimensionValue(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsDimensionValue(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } dimType() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.readInt8(this.bb_pos + i) : 0; } dimValue() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.readInt64(this.bb_pos + i) : this.bb.createLong(0, 0); } dimParam(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, i) : null; } static startDimensionValue(i) { i.startObject(3); } static addDimType(i, u) { i.addFieldInt8(0, u, 0); } static addDimValue(i, u) { i.addFieldInt64(1, u, i.createLong(0, 0)); } static addDimParam(i, u) { i.addFieldOffset(2, u, 0); } static endDimensionValue(i) { return i.endObject(); } static createDimensionValue(i, u, l, f) { return n.startDimensionValue(i), n.addDimType(i, u), n.addDimValue(i, l), n.addDimParam(i, f), n.endDimensionValue(i); } } r.DimensionValue = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsTensorTypeAndShape(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsTensorTypeAndShape(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } elemType() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } shape(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (i || new e.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startTensorTypeAndShape(i) { i.startObject(2); } static addElemType(i, u) { i.addFieldInt32(0, u, 0); } static addShape(i, u) { i.addFieldOffset(1, u, 0); } static endTensorTypeAndShape(i) { return i.endObject(); } static createTensorTypeAndShape(i, u, l) { return n.startTensorTypeAndShape(i), n.addElemType(i, u), n.addShape(i, l), n.endTensorTypeAndShape(i); } } r.TensorTypeAndShape = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsMapType(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsMapType(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } keyType() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } valueType(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (i || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startMapType(i) { i.startObject(2); } static addKeyType(i, u) { i.addFieldInt32(0, u, 0); } static addValueType(i, u) { i.addFieldOffset(1, u, 0); } static endMapType(i) { return i.endObject(); } static createMapType(i, u, l) { return n.startMapType(i), n.addKeyType(i, u), n.addValueType(i, l), n.endMapType(i); } } r.MapType = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsSequenceType(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsSequenceType(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } elemType(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (i || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startSequenceType(i) { i.startObject(1); } static addElemType(i, u) { i.addFieldOffset(0, u, 0); } static endSequenceType(i) { return i.endObject(); } static createSequenceType(i, u) { return n.startSequenceType(i), n.addElemType(i, u), n.endSequenceType(i); } } r.SequenceType = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } nodeIndex() { return this.bb.readUint32(this.bb_pos); } srcArgIndex() { return this.bb.readInt32(this.bb_pos + 4); } dstArgIndex() { return this.bb.readInt32(this.bb_pos + 8); } static createEdgeEnd(i, u, l, f) { return i.prep(4, 12), i.writeInt32(f), i.writeInt32(l), i.writeInt32(u), i.offset(); } } r.EdgeEnd = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsNodeEdge(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsNodeEdge(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } nodeIndex() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.readUint32(this.bb_pos + i) : 0; } inputEdges(i, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + l) + i * 12, this.bb) : null; } inputEdgesLength() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } outputEdges(i, u) { let l = this.bb.__offset(this.bb_pos, 8); return l ? (u || new e.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + l) + i * 12, this.bb) : null; } outputEdgesLength() { let i = this.bb.__offset(this.bb_pos, 8); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startNodeEdge(i) { i.startObject(3); } static addNodeIndex(i, u) { i.addFieldInt32(0, u, 0); } static addInputEdges(i, u) { i.addFieldOffset(1, u, 0); } static startInputEdgesVector(i, u) { i.startVector(12, u, 4); } static addOutputEdges(i, u) { i.addFieldOffset(2, u, 0); } static startOutputEdgesVector(i, u) { i.startVector(12, u, 4); } static endNodeEdge(i) { return i.endObject(); } static createNodeEdge(i, u, l, f) { return n.startNodeEdge(i), n.addNodeIndex(i, u), n.addInputEdges(i, l), n.addOutputEdges(i, f), n.endNodeEdge(i); } } r.NodeEdge = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsNode(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsNode(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } name(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } docString(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, i) : null; } domain(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, i) : null; } sinceVersion() { let i = this.bb.__offset(this.bb_pos, 10); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } index() { let i = this.bb.__offset(this.bb_pos, 12); return i ? this.bb.readUint32(this.bb_pos + i) : 0; } opType(i) { let u = this.bb.__offset(this.bb_pos, 14); return u ? this.bb.__string(this.bb_pos + u, i) : null; } type() { let i = this.bb.__offset(this.bb_pos, 16); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } executionProviderType(i) { let u = this.bb.__offset(this.bb_pos, 18); return u ? this.bb.__string(this.bb_pos + u, i) : null; } inputs(i, u) { let l = this.bb.__offset(this.bb_pos, 20); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } inputsLength() { let i = this.bb.__offset(this.bb_pos, 20); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } outputs(i, u) { let l = this.bb.__offset(this.bb_pos, 22); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } outputsLength() { let i = this.bb.__offset(this.bb_pos, 22); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } attributes(i, u) { let l = this.bb.__offset(this.bb_pos, 24); return l ? (u || new e.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } attributesLength() { let i = this.bb.__offset(this.bb_pos, 24); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } inputArgCounts(i) { let u = this.bb.__offset(this.bb_pos, 26); return u ? this.bb.readInt32(this.bb.__vector(this.bb_pos + u) + i * 4) : 0; } inputArgCountsLength() { let i = this.bb.__offset(this.bb_pos, 26); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } inputArgCountsArray() { let i = this.bb.__offset(this.bb_pos, 26); return i ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + i), this.bb.__vector_len(this.bb_pos + i)) : null; } implicitInputs(i, u) { let l = this.bb.__offset(this.bb_pos, 28); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } implicitInputsLength() { let i = this.bb.__offset(this.bb_pos, 28); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startNode(i) { i.startObject(13); } static addName(i, u) { i.addFieldOffset(0, u, 0); } static addDocString(i, u) { i.addFieldOffset(1, u, 0); } static addDomain(i, u) { i.addFieldOffset(2, u, 0); } static addSinceVersion(i, u) { i.addFieldInt32(3, u, 0); } static addIndex(i, u) { i.addFieldInt32(4, u, 0); } static addOpType(i, u) { i.addFieldOffset(5, u, 0); } static addType(i, u) { i.addFieldInt32(6, u, 0); } static addExecutionProviderType(i, u) { i.addFieldOffset(7, u, 0); } static addInputs(i, u) { i.addFieldOffset(8, u, 0); } static createInputsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startInputsVector(i, u) { i.startVector(4, u, 4); } static addOutputs(i, u) { i.addFieldOffset(9, u, 0); } static createOutputsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startOutputsVector(i, u) { i.startVector(4, u, 4); } static addAttributes(i, u) { i.addFieldOffset(10, u, 0); } static createAttributesVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startAttributesVector(i, u) { i.startVector(4, u, 4); } static addInputArgCounts(i, u) { i.addFieldOffset(11, u, 0); } static createInputArgCountsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addInt32(u[l]); return i.endVector(); } static startInputArgCountsVector(i, u) { i.startVector(4, u, 4); } static addImplicitInputs(i, u) { i.addFieldOffset(12, u, 0); } static createImplicitInputsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startImplicitInputsVector(i, u) { i.startVector(4, u, 4); } static endNode(i) { return i.endObject(); } static createNode(i, u, l, f, p, d, b, g, y, v, _, O2, S, C) { return n.startNode(i), n.addName(i, u), n.addDocString(i, l), n.addDomain(i, f), n.addSinceVersion(i, p), n.addIndex(i, d), n.addOpType(i, b), n.addType(i, g), n.addExecutionProviderType(i, y), n.addInputs(i, v), n.addOutputs(i, _), n.addAttributes(i, O2), n.addInputArgCounts(i, S), n.addImplicitInputs(i, C), n.endNode(i); } } r.Node = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsValueInfo(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsValueInfo(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } name(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } docString(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, i) : null; } type(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? (i || new e.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startValueInfo(i) { i.startObject(3); } static addName(i, u) { i.addFieldOffset(0, u, 0); } static addDocString(i, u) { i.addFieldOffset(1, u, 0); } static addType(i, u) { i.addFieldOffset(2, u, 0); } static endValueInfo(i) { return i.endObject(); } static createValueInfo(i, u, l, f) { return n.startValueInfo(i), n.addName(i, u), n.addDocString(i, l), n.addType(i, f), n.endValueInfo(i); } } r.ValueInfo = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsTypeInfo(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsTypeInfo(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } denotation(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } valueType() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.readUint8(this.bb_pos + i) : 0; } value(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__union(i, this.bb_pos + u) : null; } static startTypeInfo(i) { i.startObject(3); } static addDenotation(i, u) { i.addFieldOffset(0, u, 0); } static addValueType(i, u) { i.addFieldInt8(1, u, 0); } static addValue(i, u) { i.addFieldOffset(2, u, 0); } static endTypeInfo(i) { return i.endObject(); } static createTypeInfo(i, u, l, f) { return n.startTypeInfo(i), n.addDenotation(i, u), n.addValueType(i, l), n.addValue(i, f), n.endTypeInfo(i); } } r.TypeInfo = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsOperatorSetId(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsOperatorSetId(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } domain(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } version() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.readInt64(this.bb_pos + i) : this.bb.createLong(0, 0); } static startOperatorSetId(i) { i.startObject(2); } static addDomain(i, u) { i.addFieldOffset(0, u, 0); } static addVersion(i, u) { i.addFieldInt64(1, u, i.createLong(0, 0)); } static endOperatorSetId(i) { return i.endObject(); } static createOperatorSetId(i, u, l) { return n.startOperatorSetId(i), n.addDomain(i, u), n.addVersion(i, l), n.endOperatorSetId(i); } } r.OperatorSetId = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsTensor(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsTensor(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } name(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } docString(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, i) : null; } dims(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + i * 8) : this.bb.createLong(0, 0); } dimsLength() { let i = this.bb.__offset(this.bb_pos, 8); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } dataType() { let i = this.bb.__offset(this.bb_pos, 10); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } rawData(i) { let u = this.bb.__offset(this.bb_pos, 12); return u ? this.bb.readUint8(this.bb.__vector(this.bb_pos + u) + i) : 0; } rawDataLength() { let i = this.bb.__offset(this.bb_pos, 12); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } rawDataArray() { let i = this.bb.__offset(this.bb_pos, 12); return i ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + i), this.bb.__vector_len(this.bb_pos + i)) : null; } stringData(i, u) { let l = this.bb.__offset(this.bb_pos, 14); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } stringDataLength() { let i = this.bb.__offset(this.bb_pos, 14); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startTensor(i) { i.startObject(6); } static addName(i, u) { i.addFieldOffset(0, u, 0); } static addDocString(i, u) { i.addFieldOffset(1, u, 0); } static addDims(i, u) { i.addFieldOffset(2, u, 0); } static createDimsVector(i, u) { i.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) i.addInt64(u[l]); return i.endVector(); } static startDimsVector(i, u) { i.startVector(8, u, 8); } static addDataType(i, u) { i.addFieldInt32(3, u, 0); } static addRawData(i, u) { i.addFieldOffset(4, u, 0); } static createRawDataVector(i, u) { i.startVector(1, u.length, 1); for (let l = u.length - 1; l >= 0; l--) i.addInt8(u[l]); return i.endVector(); } static startRawDataVector(i, u) { i.startVector(1, u, 1); } static addStringData(i, u) { i.addFieldOffset(5, u, 0); } static createStringDataVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startStringDataVector(i, u) { i.startVector(4, u, 4); } static endTensor(i) { return i.endObject(); } static createTensor(i, u, l, f, p, d, b) { return n.startTensor(i), n.addName(i, u), n.addDocString(i, l), n.addDims(i, f), n.addDataType(i, p), n.addRawData(i, d), n.addStringData(i, b), n.endTensor(i); } } r.Tensor = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsSparseTensor(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsSparseTensor(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } values(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (i || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } indices(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (i || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } dims(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + i * 8) : this.bb.createLong(0, 0); } dimsLength() { let i = this.bb.__offset(this.bb_pos, 8); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startSparseTensor(i) { i.startObject(3); } static addValues(i, u) { i.addFieldOffset(0, u, 0); } static addIndices(i, u) { i.addFieldOffset(1, u, 0); } static addDims(i, u) { i.addFieldOffset(2, u, 0); } static createDimsVector(i, u) { i.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) i.addInt64(u[l]); return i.endVector(); } static startDimsVector(i, u) { i.startVector(8, u, 8); } static endSparseTensor(i) { return i.endObject(); } static createSparseTensor(i, u, l, f) { return n.startSparseTensor(i), n.addValues(i, u), n.addIndices(i, l), n.addDims(i, f), n.endSparseTensor(i); } } r.SparseTensor = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsAttribute(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsAttribute(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } name(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } docString(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.__string(this.bb_pos + u, i) : null; } type() { let i = this.bb.__offset(this.bb_pos, 8); return i ? this.bb.readInt32(this.bb_pos + i) : 0; } f() { let i = this.bb.__offset(this.bb_pos, 10); return i ? this.bb.readFloat32(this.bb_pos + i) : 0; } i() { let i = this.bb.__offset(this.bb_pos, 12); return i ? this.bb.readInt64(this.bb_pos + i) : this.bb.createLong(0, 0); } s(i) { let u = this.bb.__offset(this.bb_pos, 14); return u ? this.bb.__string(this.bb_pos + u, i) : null; } t(i) { let u = this.bb.__offset(this.bb_pos, 16); return u ? (i || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } g(i) { let u = this.bb.__offset(this.bb_pos, 18); return u ? (i || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } floats(i) { let u = this.bb.__offset(this.bb_pos, 20); return u ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + u) + i * 4) : 0; } floatsLength() { let i = this.bb.__offset(this.bb_pos, 20); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } floatsArray() { let i = this.bb.__offset(this.bb_pos, 20); return i ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + i), this.bb.__vector_len(this.bb_pos + i)) : null; } ints(i) { let u = this.bb.__offset(this.bb_pos, 22); return u ? this.bb.readInt64(this.bb.__vector(this.bb_pos + u) + i * 8) : this.bb.createLong(0, 0); } intsLength() { let i = this.bb.__offset(this.bb_pos, 22); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } strings(i, u) { let l = this.bb.__offset(this.bb_pos, 24); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } stringsLength() { let i = this.bb.__offset(this.bb_pos, 24); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } tensors(i, u) { let l = this.bb.__offset(this.bb_pos, 26); return l ? (u || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } tensorsLength() { let i = this.bb.__offset(this.bb_pos, 26); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } graphs(i, u) { let l = this.bb.__offset(this.bb_pos, 28); return l ? (u || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } graphsLength() { let i = this.bb.__offset(this.bb_pos, 28); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startAttribute(i) { i.startObject(13); } static addName(i, u) { i.addFieldOffset(0, u, 0); } static addDocString(i, u) { i.addFieldOffset(1, u, 0); } static addType(i, u) { i.addFieldInt32(2, u, 0); } static addF(i, u) { i.addFieldFloat32(3, u, 0); } static addI(i, u) { i.addFieldInt64(4, u, i.createLong(0, 0)); } static addS(i, u) { i.addFieldOffset(5, u, 0); } static addT(i, u) { i.addFieldOffset(6, u, 0); } static addG(i, u) { i.addFieldOffset(7, u, 0); } static addFloats(i, u) { i.addFieldOffset(8, u, 0); } static createFloatsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addFloat32(u[l]); return i.endVector(); } static startFloatsVector(i, u) { i.startVector(4, u, 4); } static addInts(i, u) { i.addFieldOffset(9, u, 0); } static createIntsVector(i, u) { i.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) i.addInt64(u[l]); return i.endVector(); } static startIntsVector(i, u) { i.startVector(8, u, 8); } static addStrings(i, u) { i.addFieldOffset(10, u, 0); } static createStringsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startStringsVector(i, u) { i.startVector(4, u, 4); } static addTensors(i, u) { i.addFieldOffset(11, u, 0); } static createTensorsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startTensorsVector(i, u) { i.startVector(4, u, 4); } static addGraphs(i, u) { i.addFieldOffset(12, u, 0); } static createGraphsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startGraphsVector(i, u) { i.startVector(4, u, 4); } static endAttribute(i) { return i.endObject(); } static createAttribute(i, u, l, f, p, d, b, g, y, v, _, O2, S, C) { return n.startAttribute(i), n.addName(i, u), n.addDocString(i, l), n.addType(i, f), n.addF(i, p), n.addI(i, d), n.addS(i, b), n.addT(i, g), n.addG(i, y), n.addFloats(i, v), n.addInts(i, _), n.addStrings(i, O2), n.addTensors(i, S), n.addGraphs(i, C), n.endAttribute(i); } } r.Attribute = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsGraph(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsGraph(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } initializers(i, u) { let l = this.bb.__offset(this.bb_pos, 4); return l ? (u || new e.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } initializersLength() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } nodeArgs(i, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } nodeArgsLength() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } nodes(i, u) { let l = this.bb.__offset(this.bb_pos, 8); return l ? (u || new e.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } nodesLength() { let i = this.bb.__offset(this.bb_pos, 8); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } maxNodeIndex() { let i = this.bb.__offset(this.bb_pos, 10); return i ? this.bb.readUint32(this.bb_pos + i) : 0; } nodeEdges(i, u) { let l = this.bb.__offset(this.bb_pos, 12); return l ? (u || new e.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } nodeEdgesLength() { let i = this.bb.__offset(this.bb_pos, 12); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } inputs(i, u) { let l = this.bb.__offset(this.bb_pos, 14); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } inputsLength() { let i = this.bb.__offset(this.bb_pos, 14); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } outputs(i, u) { let l = this.bb.__offset(this.bb_pos, 16); return l ? this.bb.__string(this.bb.__vector(this.bb_pos + l) + i * 4, u) : null; } outputsLength() { let i = this.bb.__offset(this.bb_pos, 16); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } sparseInitializers(i, u) { let l = this.bb.__offset(this.bb_pos, 18); return l ? (u || new e.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } sparseInitializersLength() { let i = this.bb.__offset(this.bb_pos, 18); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startGraph(i) { i.startObject(8); } static addInitializers(i, u) { i.addFieldOffset(0, u, 0); } static createInitializersVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startInitializersVector(i, u) { i.startVector(4, u, 4); } static addNodeArgs(i, u) { i.addFieldOffset(1, u, 0); } static createNodeArgsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startNodeArgsVector(i, u) { i.startVector(4, u, 4); } static addNodes(i, u) { i.addFieldOffset(2, u, 0); } static createNodesVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startNodesVector(i, u) { i.startVector(4, u, 4); } static addMaxNodeIndex(i, u) { i.addFieldInt32(3, u, 0); } static addNodeEdges(i, u) { i.addFieldOffset(4, u, 0); } static createNodeEdgesVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startNodeEdgesVector(i, u) { i.startVector(4, u, 4); } static addInputs(i, u) { i.addFieldOffset(5, u, 0); } static createInputsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startInputsVector(i, u) { i.startVector(4, u, 4); } static addOutputs(i, u) { i.addFieldOffset(6, u, 0); } static createOutputsVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startOutputsVector(i, u) { i.startVector(4, u, 4); } static addSparseInitializers(i, u) { i.addFieldOffset(7, u, 0); } static createSparseInitializersVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startSparseInitializersVector(i, u) { i.startVector(4, u, 4); } static endGraph(i) { return i.endObject(); } static createGraph(i, u, l, f, p, d, b, g, y) { return n.startGraph(i), n.addInitializers(i, u), n.addNodeArgs(i, l), n.addNodes(i, f), n.addMaxNodeIndex(i, p), n.addNodeEdges(i, d), n.addInputs(i, b), n.addOutputs(i, g), n.addSparseInitializers(i, y), n.endGraph(i); } } r.Graph = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsModel(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsModel(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } irVersion() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.readInt64(this.bb_pos + i) : this.bb.createLong(0, 0); } opsetImport(i, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } opsetImportLength() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } producerName(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? this.bb.__string(this.bb_pos + u, i) : null; } producerVersion(i) { let u = this.bb.__offset(this.bb_pos, 10); return u ? this.bb.__string(this.bb_pos + u, i) : null; } domain(i) { let u = this.bb.__offset(this.bb_pos, 12); return u ? this.bb.__string(this.bb_pos + u, i) : null; } modelVersion() { let i = this.bb.__offset(this.bb_pos, 14); return i ? this.bb.readInt64(this.bb_pos + i) : this.bb.createLong(0, 0); } docString(i) { let u = this.bb.__offset(this.bb_pos, 16); return u ? this.bb.__string(this.bb_pos + u, i) : null; } graph(i) { let u = this.bb.__offset(this.bb_pos, 18); return u ? (i || new e.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } graphDocString(i) { let u = this.bb.__offset(this.bb_pos, 20); return u ? this.bb.__string(this.bb_pos + u, i) : null; } static startModel(i) { i.startObject(9); } static addIrVersion(i, u) { i.addFieldInt64(0, u, i.createLong(0, 0)); } static addOpsetImport(i, u) { i.addFieldOffset(1, u, 0); } static createOpsetImportVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startOpsetImportVector(i, u) { i.startVector(4, u, 4); } static addProducerName(i, u) { i.addFieldOffset(2, u, 0); } static addProducerVersion(i, u) { i.addFieldOffset(3, u, 0); } static addDomain(i, u) { i.addFieldOffset(4, u, 0); } static addModelVersion(i, u) { i.addFieldInt64(5, u, i.createLong(0, 0)); } static addDocString(i, u) { i.addFieldOffset(6, u, 0); } static addGraph(i, u) { i.addFieldOffset(7, u, 0); } static addGraphDocString(i, u) { i.addFieldOffset(8, u, 0); } static endModel(i) { return i.endObject(); } static createModel(i, u, l, f, p, d, b, g, y, v) { return n.startModel(i), n.addIrVersion(i, u), n.addOpsetImport(i, l), n.addProducerName(i, f), n.addProducerVersion(i, p), n.addDomain(i, d), n.addModelVersion(i, b), n.addDocString(i, g), n.addGraph(i, y), n.addGraphDocString(i, v), n.endModel(i); } } r.Model = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsKernelCreateInfos(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsKernelCreateInfos(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } nodeIndices(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.readUint32(this.bb.__vector(this.bb_pos + u) + i * 4) : 0; } nodeIndicesLength() { let i = this.bb.__offset(this.bb_pos, 4); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } nodeIndicesArray() { let i = this.bb.__offset(this.bb_pos, 4); return i ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + i), this.bb.__vector_len(this.bb_pos + i)) : null; } kernelDefHashes(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? this.bb.readUint64(this.bb.__vector(this.bb_pos + u) + i * 8) : this.bb.createLong(0, 0); } kernelDefHashesLength() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startKernelCreateInfos(i) { i.startObject(2); } static addNodeIndices(i, u) { i.addFieldOffset(0, u, 0); } static createNodeIndicesVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addInt32(u[l]); return i.endVector(); } static startNodeIndicesVector(i, u) { i.startVector(4, u, 4); } static addKernelDefHashes(i, u) { i.addFieldOffset(1, u, 0); } static createKernelDefHashesVector(i, u) { i.startVector(8, u.length, 8); for (let l = u.length - 1; l >= 0; l--) i.addInt64(u[l]); return i.endVector(); } static startKernelDefHashesVector(i, u) { i.startVector(8, u, 8); } static endKernelCreateInfos(i) { return i.endObject(); } static createKernelCreateInfos(i, u, l) { return n.startKernelCreateInfos(i), n.addNodeIndices(i, u), n.addKernelDefHashes(i, l), n.endKernelCreateInfos(i); } } r.KernelCreateInfos = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsSubGraphSessionState(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsSubGraphSessionState(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } graphId(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } sessionState(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (i || new e.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startSubGraphSessionState(i) { i.startObject(2); } static addGraphId(i, u) { i.addFieldOffset(0, u, 0); } static addSessionState(i, u) { i.addFieldOffset(1, u, 0); } static endSubGraphSessionState(i) { let u = i.endObject(); return i.requiredField(u, 4), u; } static createSubGraphSessionState(i, u, l) { return n.startSubGraphSessionState(i), n.addGraphId(i, u), n.addSessionState(i, l), n.endSubGraphSessionState(i); } } r.SubGraphSessionState = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsSessionState(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsSessionState(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } kernels(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? (i || new e.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } subGraphSessionStates(i, u) { let l = this.bb.__offset(this.bb_pos, 6); return l ? (u || new e.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + l) + i * 4), this.bb) : null; } subGraphSessionStatesLength() { let i = this.bb.__offset(this.bb_pos, 6); return i ? this.bb.__vector_len(this.bb_pos + i) : 0; } static startSessionState(i) { i.startObject(2); } static addKernels(i, u) { i.addFieldOffset(0, u, 0); } static addSubGraphSessionStates(i, u) { i.addFieldOffset(1, u, 0); } static createSubGraphSessionStatesVector(i, u) { i.startVector(4, u.length, 4); for (let l = u.length - 1; l >= 0; l--) i.addOffset(u[l]); return i.endVector(); } static startSubGraphSessionStatesVector(i, u) { i.startVector(4, u, 4); } static endSessionState(i) { return i.endObject(); } static createSessionState(i, u, l) { return n.startSessionState(i), n.addKernels(i, u), n.addSubGraphSessionStates(i, l), n.endSessionState(i); } } r.SessionState = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); ((e) => { let a; ((t) => { let o; ((r) => { class n { constructor() { this.bb = null; this.bb_pos = 0; } __init(i, u) { return this.bb_pos = i, this.bb = u, this; } static getRootAsInferenceSession(i, u) { return (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static getSizePrefixedRootAsInferenceSession(i, u) { return i.setPosition(i.position() + m.SIZE_PREFIX_LENGTH), (u || new n()).__init(i.readInt32(i.position()) + i.position(), i); } static bufferHasIdentifier(i) { return i.__has_identifier("ORTM"); } ortVersion(i) { let u = this.bb.__offset(this.bb_pos, 4); return u ? this.bb.__string(this.bb_pos + u, i) : null; } model(i) { let u = this.bb.__offset(this.bb_pos, 6); return u ? (i || new e.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } sessionState(i) { let u = this.bb.__offset(this.bb_pos, 8); return u ? (i || new e.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + u), this.bb) : null; } static startInferenceSession(i) { i.startObject(3); } static addOrtVersion(i, u) { i.addFieldOffset(0, u, 0); } static addModel(i, u) { i.addFieldOffset(1, u, 0); } static addSessionState(i, u) { i.addFieldOffset(2, u, 0); } static endInferenceSession(i) { return i.endObject(); } static finishInferenceSessionBuffer(i, u) { i.finish(u, "ORTM"); } static finishSizePrefixedInferenceSessionBuffer(i, u) { i.finish(u, "ORTM", true); } static createInferenceSession(i, u, l, f) { return n.startInferenceSession(i), n.addOrtVersion(i, u), n.addModel(i, l), n.addSessionState(i, f), n.endInferenceSession(i); } } r.InferenceSession = n; })(o = t.fbs ||= {}); })(a = e.experimental ||= {}); })(P ||= {}); }); Ro2 = Z((sh2, Go2) => { "use strict"; Go2.exports = Ml3; function Ml3(a, e) { for (var o = new Array(arguments.length - 1), t = 0, n = 2, r = true; n < arguments.length; ) o[t++] = arguments[n++]; return new Promise(function(i, u) { o[t] = function(f) { if (r) if (r = false, f) u(f); else { for (var p = new Array(arguments.length - 1), d = 0; d < p.length; ) p[d++] = arguments[d]; i.apply(null, p); } }; try { a.apply(e || null, o); } catch (l) { r && (r = false, u(l)); } }); } }); Uo2 = Z((Mo) => { "use strict"; var Ze = Mo; Ze.length = function(e) { var o = e.length; if (!o) return 0; for (var t = 0; --o % 4 > 1 && e.charAt(o) === "="; ) ++t; return Math.ceil(e.length * 3) / 4 - t; }; var ae2 = new Array(64), zo2 = new Array(123); for (wt = 0; wt < 64; ) zo2[ae2[wt] = wt < 26 ? wt + 65 : wt < 52 ? wt + 71 : wt < 62 ? wt - 4 : wt - 59 | 43] = wt++; var wt; Ze.encode = function(e, o, t) { for (var n = null, r = [], s = 0, i = 0, u; o < t; ) { var l = e[o++]; switch (i) { case 0: r[s++] = ae2[l >> 2], u = (l & 3) << 4, i = 1; break; case 1: r[s++] = ae2[u | l >> 4], u = (l & 15) << 2, i = 2; break; case 2: r[s++] = ae2[u | l >> 6], r[s++] = ae2[l & 63], i = 0; break; } s > 8191 && ((n || (n = [])).push(String.fromCharCode.apply(String, r)), s = 0); } return i && (r[s++] = ae2[u], r[s++] = 61, i === 1 && (r[s++] = 61)), n ? (s && n.push(String.fromCharCode.apply(String, r.slice(0, s))), n.join("")) : String.fromCharCode.apply(String, r.slice(0, s)); }; var Vo2 = "invalid encoding"; Ze.decode = function(e, o, t) { for (var n = t, r = 0, s, i = 0; i < e.length; ) { var u = e.charCodeAt(i++); if (u === 61 && r > 1) break; if ((u = zo2[u]) === void 0) throw Error(Vo2); switch (r) { case 0: s = u, r = 1; break; case 1: o[t++] = s << 2 | (u & 48) >> 4, s = u, r = 2; break; case 2: o[t++] = (s & 15) << 4 | (u & 60) >> 2, s = u, r = 3; break; case 3: o[t++] = (s & 3) << 6 | u, r = 0; break; } } if (r === 1) throw Error(Vo2); return t - n; }; Ze.test = function(e) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e); }; }); Ho = Z((lh2, Wo) => { "use strict"; Wo.exports = Ye2; function Ye2() { this._listeners = {}; } Ye2.prototype.on = function(e, o, t) { return (this._listeners[e] || (this._listeners[e] = [])).push({ fn: o, ctx: t || this }), this; }; Ye2.prototype.off = function(e, o) { if (e === void 0) this._listeners = {}; else if (o === void 0) this._listeners[e] = []; else for (var t = this._listeners[e], n = 0; n < t.length; ) t[n].fn === o ? t.splice(n, 1) : ++n; return this; }; Ye2.prototype.emit = function(e) { var o = this._listeners[e]; if (o) { for (var t = [], n = 1; n < arguments.length; ) t.push(arguments[n++]); for (n = 0; n < o.length; ) o[n].fn.apply(o[n++].ctx, t); } return this; }; }); Yo = Z((fh2, Zo2) => { "use strict"; Zo2.exports = qo(qo); function qo(a) { return typeof Float32Array < "u" ? (function() { var e = new Float32Array([-0]), o = new Uint8Array(e.buffer), t = o[3] === 128; function n(u, l, f) { e[0] = u, l[f] = o[0], l[f + 1] = o[1], l[f + 2] = o[2], l[f + 3] = o[3]; } function r(u, l, f) { e[0] = u, l[f] = o[3], l[f + 1] = o[2], l[f + 2] = o[1], l[f + 3] = o[0]; } a.writeFloatLE = t ? n : r, a.writeFloatBE = t ? r : n; function s(u, l) { return o[0] = u[l], o[1] = u[l + 1], o[2] = u[l + 2], o[3] = u[l + 3], e[0]; } function i(u, l) { return o[3] = u[l], o[2] = u[l + 1], o[1] = u[l + 2], o[0] = u[l + 3], e[0]; } a.readFloatLE = t ? s : i, a.readFloatBE = t ? i : s; })() : (function() { function e(t, n, r, s) { var i = n < 0 ? 1 : 0; if (i && (n = -n), n === 0) t(1 / n > 0 ? 0 : 2147483648, r, s); else if (isNaN(n)) t(2143289344, r, s); else if (n > 34028234663852886e22) t((i << 31 | 2139095040) >>> 0, r, s); else if (n < 11754943508222875e-54) t((i << 31 | Math.round(n / 1401298464324817e-60)) >>> 0, r, s); else { var u = Math.floor(Math.log(n) / Math.LN2), l = Math.round(n * Math.pow(2, -u) * 8388608) & 8388607; t((i << 31 | u + 127 << 23 | l) >>> 0, r, s); } } a.writeFloatLE = e.bind(null, jo), a.writeFloatBE = e.bind(null, Ko); function o(t, n, r) { var s = t(n, r), i = (s >> 31) * 2 + 1, u = s >>> 23 & 255, l = s & 8388607; return u === 255 ? l ? NaN : i * (1 / 0) : u === 0 ? i * 1401298464324817e-60 * l : i * Math.pow(2, u - 150) * (l + 8388608); } a.readFloatLE = o.bind(null, Xo), a.readFloatBE = o.bind(null, Jo); })(), typeof Float64Array < "u" ? (function() { var e = new Float64Array([-0]), o = new Uint8Array(e.buffer), t = o[7] === 128; function n(u, l, f) { e[0] = u, l[f] = o[0], l[f + 1] = o[1], l[f + 2] = o[2], l[f + 3] = o[3], l[f + 4] = o[4], l[f + 5] = o[5], l[f + 6] = o[6], l[f + 7] = o[7]; } function r(u, l, f) { e[0] = u, l[f] = o[7], l[f + 1] = o[6], l[f + 2] = o[5], l[f + 3] = o[4], l[f + 4] = o[3], l[f + 5] = o[2], l[f + 6] = o[1], l[f + 7] = o[0]; } a.writeDoubleLE = t ? n : r, a.writeDoubleBE = t ? r : n; function s(u, l) { return o[0] = u[l], o[1] = u[l + 1], o[2] = u[l + 2], o[3] = u[l + 3], o[4] = u[l + 4], o[5] = u[l + 5], o[6] = u[l + 6], o[7] = u[l + 7], e[0]; } function i(u, l) { return o[7] = u[l], o[6] = u[l + 1], o[5] = u[l + 2], o[4] = u[l + 3], o[3] = u[l + 4], o[2] = u[l + 5], o[1] = u[l + 6], o[0] = u[l + 7], e[0]; } a.readDoubleLE = t ? s : i, a.readDoubleBE = t ? i : s; })() : (function() { function e(t, n, r, s, i, u) { var l = s < 0 ? 1 : 0; if (l && (s = -s), s === 0) t(0, i, u + n), t(1 / s > 0 ? 0 : 2147483648, i, u + r); else if (isNaN(s)) t(0, i, u + n), t(2146959360, i, u + r); else if (s > 17976931348623157e292) t(0, i, u + n), t((l << 31 | 2146435072) >>> 0, i, u + r); else { var f; if (s < 22250738585072014e-324) f = s / 5e-324, t(f >>> 0, i, u + n), t((l << 31 | f / 4294967296) >>> 0, i, u + r); else { var p = Math.floor(Math.log(s) / Math.LN2); p === 1024 && (p = 1023), f = s * Math.pow(2, -p), t(f * 4503599627370496 >>> 0, i, u + n), t((l << 31 | p + 1023 << 20 | f * 1048576 & 1048575) >>> 0, i, u + r); } } } a.writeDoubleLE = e.bind(null, jo, 0, 4), a.writeDoubleBE = e.bind(null, Ko, 4, 0); function o(t, n, r, s, i) { var u = t(s, i + n), l = t(s, i + r), f = (l >> 31) * 2 + 1, p = l >>> 20 & 2047, d = 4294967296 * (l & 1048575) + u; return p === 2047 ? d ? NaN : f * (1 / 0) : p === 0 ? f * 5e-324 * d : f * Math.pow(2, p - 1075) * (d + 4503599627370496); } a.readDoubleLE = o.bind(null, Xo, 0, 4), a.readDoubleBE = o.bind(null, Jo, 4, 0); })(), a; } function jo(a, e, o) { e[o] = a & 255, e[o + 1] = a >>> 8 & 255, e[o + 2] = a >>> 16 & 255, e[o + 3] = a >>> 24; } function Ko(a, e, o) { e[o] = a >>> 24, e[o + 1] = a >>> 16 & 255, e[o + 2] = a >>> 8 & 255, e[o + 3] = a & 255; } function Xo(a, e) { return (a[e] | a[e + 1] << 8 | a[e + 2] << 16 | a[e + 3] << 24) >>> 0; } function Jo(a, e) { return (a[e] << 24 | a[e + 1] << 16 | a[e + 2] << 8 | a[e + 3]) >>> 0; } }); Qo = Z((exports, module) => { "use strict"; module.exports = inquire; function inquire(moduleName) { try { var mod = eval("quire".replace(/^/, "re"))(moduleName); if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (a) { } return null; } }); ei2 = Z((ti) => { "use strict"; var Wr3 = ti; Wr3.length = function(e) { for (var o = 0, t = 0, n = 0; n < e.length; ++n) t = e.charCodeAt(n), t < 128 ? o += 1 : t < 2048 ? o += 2 : (t & 64512) === 55296 && (e.charCodeAt(n + 1) & 64512) === 56320 ? (++n, o += 4) : o += 3; return o; }; Wr3.read = function(e, o, t) { var n = t - o; if (n < 1) return ""; for (var r = null, s = [], i = 0, u; o < t; ) u = e[o++], u < 128 ? s[i++] = u : u > 191 && u < 224 ? s[i++] = (u & 31) << 6 | e[o++] & 63 : u > 239 && u < 365 ? (u = ((u & 7) << 18 | (e[o++] & 63) << 12 | (e[o++] & 63) << 6 | e[o++] & 63) - 65536, s[i++] = 55296 + (u >> 10), s[i++] = 56320 + (u & 1023)) : s[i++] = (u & 15) << 12 | (e[o++] & 63) << 6 | e[o++] & 63, i > 8191 && ((r || (r = [])).push(String.fromCharCode.apply(String, s)), i = 0); return r ? (i && r.push(String.fromCharCode.apply(String, s.slice(0, i))), r.join("")) : String.fromCharCode.apply(String, s.slice(0, i)); }; Wr3.write = function(e, o, t) { for (var n = t, r, s, i = 0; i < e.length; ++i) r = e.charCodeAt(i), r < 128 ? o[t++] = r : r < 2048 ? (o[t++] = r >> 6 | 192, o[t++] = r & 63 | 128) : (r & 64512) === 55296 && ((s = e.charCodeAt(i + 1)) & 64512) === 56320 ? (r = 65536 + ((r & 1023) << 10) + (s & 1023), ++i, o[t++] = r >> 18 | 240, o[t++] = r >> 12 & 63 | 128, o[t++] = r >> 6 & 63 | 128, o[t++] = r & 63 | 128) : (o[t++] = r >> 12 | 224, o[t++] = r >> 6 & 63 | 128, o[t++] = r & 63 | 128); return t - n; }; }); ni2 = Z((ph3, ri) => { "use strict"; ri.exports = Ul3; function Ul3(a, e, o) { var t = o || 8192, n = t >>> 1, r = null, s = t; return function(u) { if (u < 1 || u > n) return a(u); s + u > t && (r = a(t), s = 0); var l = e.call(r, s, s += u); return s & 7 && (s = (s | 7) + 1), l; }; } }); ii2 = Z((dh3, oi2) => { "use strict"; oi2.exports = Q2; var xe = Gt2(); function Q2(a, e) { this.lo = a >>> 0, this.hi = e >>> 0; } var qt3 = Q2.zero = new Q2(0, 0); qt3.toNumber = function() { return 0; }; qt3.zzEncode = qt3.zzDecode = function() { return this; }; qt3.length = function() { return 1; }; var Wl2 = Q2.zeroHash = "\0\0\0\0\0\0\0\0"; Q2.fromNumber = function(e) { if (e === 0) return qt3; var o = e < 0; o && (e = -e); var t = e >>> 0, n = (e - t) / 4294967296 >>> 0; return o && (n = ~n >>> 0, t = ~t >>> 0, ++t > 4294967295 && (t = 0, ++n > 4294967295 && (n = 0))), new Q2(t, n); }; Q2.from = function(e) { if (typeof e == "number") return Q2.fromNumber(e); if (xe.isString(e)) if (xe.Long) e = xe.Long.fromString(e); else return Q2.fromNumber(parseInt(e, 10)); return e.low || e.high ? new Q2(e.low >>> 0, e.high >>> 0) : qt3; }; Q2.prototype.toNumber = function(e) { if (!e && this.hi >>> 31) { var o = ~this.lo + 1 >>> 0, t = ~this.hi >>> 0; return o || (t = t + 1 >>> 0), -(o + t * 4294967296); } return this.lo + this.hi * 4294967296; }; Q2.prototype.toLong = function(e) { return xe.Long ? new xe.Long(this.lo | 0, this.hi | 0, !!e) : { low: this.lo | 0, high: this.hi | 0, unsigned: !!e }; }; var Ct2 = String.prototype.charCodeAt; Q2.fromHash = function(e) { return e === Wl2 ? qt3 : new Q2((Ct2.call(e, 0) | Ct2.call(e, 1) << 8 | Ct2.call(e, 2) << 16 | Ct2.call(e, 3) << 24) >>> 0, (Ct2.call(e, 4) | Ct2.call(e, 5) << 8 | Ct2.call(e, 6) << 16 | Ct2.call(e, 7) << 24) >>> 0); }; Q2.prototype.toHash = function() { return String.fromCharCode(this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24); }; Q2.prototype.zzEncode = function() { var e = this.hi >> 31; return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ e) >>> 0, this.lo = (this.lo << 1 ^ e) >>> 0, this; }; Q2.prototype.zzDecode = function() { var e = -(this.lo & 1); return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ e) >>> 0, this.hi = (this.hi >>> 1 ^ e) >>> 0, this; }; Q2.prototype.length = function() { var e = this.lo, o = (this.lo >>> 28 | this.hi << 4) >>> 0, t = this.hi >>> 24; return t === 0 ? o === 0 ? e < 16384 ? e < 128 ? 1 : 2 : e < 2097152 ? 3 : 4 : o < 16384 ? o < 128 ? 5 : 6 : o < 2097152 ? 7 : 8 : t < 128 ? 9 : 10; }; }); Gt2 = Z((Hr3) => { "use strict"; var E2 = Hr3; E2.asPromise = Ro2(); E2.base64 = Uo2(); E2.EventEmitter = Ho(); E2.float = Yo(); E2.inquire = Qo(); E2.utf8 = ei2(); E2.pool = ni2(); E2.LongBits = ii2(); E2.isNode = !!(typeof global < "u" && global && global.process && global.process.versions && global.process.versions.node); E2.global = E2.isNode && global || typeof window < "u" && window || typeof self < "u" && self || Hr3; E2.emptyArray = Object.freeze ? Object.freeze([]) : []; E2.emptyObject = Object.freeze ? Object.freeze({}) : {}; E2.isInteger = Number.isInteger || function(e) { return typeof e == "number" && isFinite(e) && Math.floor(e) === e; }; E2.isString = function(e) { return typeof e == "string" || e instanceof String; }; E2.isObject = function(e) { return e && typeof e == "object"; }; E2.isset = E2.isSet = function(e, o) { var t = e[o]; return t != null && e.hasOwnProperty(o) ? typeof t != "object" || (Array.isArray(t) ? t.length : Object.keys(t).length) > 0 : false; }; E2.Buffer = (function() { try { var a = E2.inquire("buffer").Buffer; return a.prototype.utf8Write ? a : null; } catch { return null; } })(); E2._Buffer_from = null; E2._Buffer_allocUnsafe = null; E2.newBuffer = function(e) { return typeof e == "number" ? E2.Buffer ? E2._Buffer_allocUnsafe(e) : new E2.Array(e) : E2.Buffer ? E2._Buffer_from(e) : typeof Uint8Array > "u" ? e : new Uint8Array(e); }; E2.Array = typeof Uint8Array < "u" ? Uint8Array : Array; E2.Long = E2.global.dcodeIO && E2.global.dcodeIO.Long || E2.global.Long || E2.inquire("long"); E2.key2Re = /^true|false|0|1$/; E2.key32Re = /^-?(?:0|[1-9][0-9]*)$/; E2.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; E2.longToHash = function(e) { return e ? E2.LongBits.from(e).toHash() : E2.LongBits.zeroHash; }; E2.longFromHash = function(e, o) { var t = E2.LongBits.fromHash(e); return E2.Long ? E2.Long.fromBits(t.lo, t.hi, o) : t.toNumber(!!o); }; function ai2(a, e, o) { for (var t = Object.keys(e), n = 0; n < t.length; ++n) (a[t[n]] === void 0 || !o) && (a[t[n]] = e[t[n]]); return a; } E2.merge = ai2; E2.lcFirst = function(e) { return e.charAt(0).toLowerCase() + e.substring(1); }; function si2(a) { function e(o, t) { if (!(this instanceof e)) return new e(o, t); Object.defineProperty(this, "message", { get: function() { return o; } }), Error.captureStackTrace ? Error.captureStackTrace(this, e) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), t && ai2(this, t); } return e.prototype = Object.create(Error.prototype, { constructor: { value: e, writable: true, enumerable: false, configurable: true }, name: { get: function() { return a; }, set: void 0, enumerable: false, configurable: true }, toString: { value: function() { return this.name + ": " + this.message; }, writable: true, enumerable: false, configurable: true } }), e; } E2.newError = si2; E2.ProtocolError = si2("ProtocolError"); E2.oneOfGetter = function(e) { for (var o = {}, t = 0; t < e.length; ++t) o[e[t]] = 1; return function() { for (var n = Object.keys(this), r = n.length - 1; r > -1; --r) if (o[n[r]] === 1 && this[n[r]] !== void 0 && this[n[r]] !== null) return n[r]; }; }; E2.oneOfSetter = function(e) { return function(o) { for (var t = 0; t < e.length; ++t) e[t] !== o && delete this[e[t]]; }; }; E2.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }; E2._configure = function() { var a = E2.Buffer; if (!a) { E2._Buffer_from = E2._Buffer_allocUnsafe = null; return; } E2._Buffer_from = a.from !== Uint8Array.from && a.from || function(o, t) { return new a(o, t); }, E2._Buffer_allocUnsafe = a.allocUnsafe || function(o) { return new a(o); }; }; }); Yr2 = Z((mh3, ci2) => { "use strict"; ci2.exports = G3; var mt2 = Gt2(), qr3, Qe = mt2.LongBits, ui2 = mt2.base64, li2 = mt2.utf8; function Te2(a, e, o) { this.fn = a, this.len = e, this.next = void 0, this.val = o; } function Kr2() { } function Hl2(a) { this.head = a.head, this.tail = a.tail, this.len = a.len, this.next = a.states; } function G3() { this.len = 0, this.head = new Te2(Kr2, 0, 0), this.tail = this.head, this.states = null; } var fi2 = function() { return mt2.Buffer ? function() { return (G3.create = function() { return new qr3(); })(); } : function() { return new G3(); }; }; G3.create = fi2(); G3.alloc = function(e) { return new mt2.Array(e); }; mt2.Array !== Array && (G3.alloc = mt2.pool(G3.alloc, mt2.Array.prototype.subarray)); G3.prototype._push = function(e, o, t) { return this.tail = this.tail.next = new Te2(e, o, t), this.len += o, this; }; function Xr2(a, e, o) { e[o] = a & 255; } function ql2(a, e, o) { for (; a > 127; ) e[o++] = a & 127 | 128, a >>>= 7; e[o] = a; } function Jr2(a, e) { this.len = a, this.next = void 0, this.val = e; } Jr2.prototype = Object.create(Te2.prototype); Jr2.prototype.fn = ql2; G3.prototype.uint32 = function(e) { return this.len += (this.tail = this.tail.next = new Jr2((e = e >>> 0) < 128 ? 1 : e < 16384 ? 2 : e < 2097152 ? 3 : e < 268435456 ? 4 : 5, e)).len, this; }; G3.prototype.int32 = function(e) { return e < 0 ? this._push(Zr2, 10, Qe.fromNumber(e)) : this.uint32(e); }; G3.prototype.sint32 = function(e) { return this.uint32((e << 1 ^ e >> 31) >>> 0); }; function Zr2(a, e, o) { for (; a.hi; ) e[o++] = a.lo & 127 | 128, a.lo = (a.lo >>> 7 | a.hi << 25) >>> 0, a.hi >>>= 7; for (; a.lo > 127; ) e[o++] = a.lo & 127 | 128, a.lo = a.lo >>> 7; e[o++] = a.lo; } G3.prototype.uint64 = function(e) { var o = Qe.from(e); return this._push(Zr2, o.length(), o); }; G3.prototype.int64 = G3.prototype.uint64; G3.prototype.sint64 = function(e) { var o = Qe.from(e).zzEncode(); return this._push(Zr2, o.length(), o); }; G3.prototype.bool = function(e) { return this._push(Xr2, 1, e ? 1 : 0); }; function jr2(a, e, o) { e[o] = a & 255, e[o + 1] = a >>> 8 & 255, e[o + 2] = a >>> 16 & 255, e[o + 3] = a >>> 24; } G3.prototype.fixed32 = function(e) { return this._push(jr2, 4, e >>> 0); }; G3.prototype.sfixed32 = G3.prototype.fixed32; G3.prototype.fixed64 = function(e) { var o = Qe.from(e); return this._push(jr2, 4, o.lo)._push(jr2, 4, o.hi); }; G3.prototype.sfixed64 = G3.prototype.fixed64; G3.prototype.float = function(e) { return this._push(mt2.float.writeFloatLE, 4, e); }; G3.prototype.double = function(e) { return this._push(mt2.float.writeDoubleLE, 8, e); }; var jl2 = mt2.Array.prototype.set ? function(e, o, t) { o.set(e, t); } : function(e, o, t) { for (var n = 0; n < e.length; ++n) o[t + n] = e[n]; }; G3.prototype.bytes = function(e) { var o = e.length >>> 0; if (!o) return this._push(Xr2, 1, 0); if (mt2.isString(e)) { var t = G3.alloc(o = ui2.length(e)); ui2.decode(e, t, 0), e = t; } return this.uint32(o)._push(jl2, o, e); }; G3.prototype.string = function(e) { var o = li2.length(e); return o ? this.uint32(o)._push(li2.write, o, e) : this._push(Xr2, 1, 0); }; G3.prototype.fork = function() { return this.states = new Hl2(this), this.head = this.tail = new Te2(Kr2, 0, 0), this.len = 0, this; }; G3.prototype.reset = function() { return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new Te2(Kr2, 0, 0), this.len = 0), this; }; G3.prototype.ldelim = function() { var e = this.head, o = this.tail, t = this.len; return this.reset().uint32(t), t && (this.tail.next = e.next, this.tail = o, this.len += t), this; }; G3.prototype.finish = function() { for (var e = this.head.next, o = this.constructor.alloc(this.len), t = 0; e; ) e.fn(e.val, o, t), t += e.len, e = e.next; return o; }; G3._configure = function(a) { qr3 = a, G3.create = fi2(), qr3._configure(); }; }); hi2 = Z((bh3, di2) => { "use strict"; di2.exports = At2; var pi2 = Yr2(); (At2.prototype = Object.create(pi2.prototype)).constructor = At2; var Rt2 = Gt2(); function At2() { pi2.call(this); } At2._configure = function() { At2.alloc = Rt2._Buffer_allocUnsafe, At2.writeBytesBuffer = Rt2.Buffer && Rt2.Buffer.prototype instanceof Uint8Array && Rt2.Buffer.prototype.set.name === "set" ? function(e, o, t) { o.set(e, t); } : function(e, o, t) { if (e.copy) e.copy(o, t, 0, e.length); else for (var n = 0; n < e.length; ) o[t++] = e[n++]; }; }; At2.prototype.bytes = function(e) { Rt2.isString(e) && (e = Rt2._Buffer_from(e, "base64")); var o = e.length >>> 0; return this.uint32(o), o && this._push(At2.writeBytesBuffer, o, e), this; }; function Kl2(a, e, o) { a.length < 40 ? Rt2.utf8.write(a, e, o) : e.utf8Write ? e.utf8Write(a, o) : e.write(a, o); } At2.prototype.string = function(e) { var o = Rt2.Buffer.byteLength(e); return this.uint32(o), o && this._push(Kl2, o, e), this; }; At2._configure(); }); en2 = Z((yh3, xi2) => { "use strict"; xi2.exports = K; var It2 = Gt2(), tn2, yi2 = It2.LongBits, Xl2 = It2.utf8; function _t3(a, e) { return RangeError("index out of range: " + a.pos + " + " + (e || 1) + " > " + a.len); } function K(a) { this.buf = a, this.pos = 0, this.len = a.length; } var mi2 = typeof Uint8Array < "u" ? function(e) { if (e instanceof Uint8Array || Array.isArray(e)) return new K(e); throw Error("illegal buffer"); } : function(e) { if (Array.isArray(e)) return new K(e); throw Error("illegal buffer"); }, gi2 = function() { return It2.Buffer ? function(o) { return (K.create = function(n) { return It2.Buffer.isBuffer(n) ? new tn2(n) : mi2(n); })(o); } : mi2; }; K.create = gi2(); K.prototype._slice = It2.Array.prototype.subarray || It2.Array.prototype.slice; K.prototype.uint32 = /* @__PURE__ */ (function() { var e = 4294967295; return function() { if (e = (this.buf[this.pos] & 127) >>> 0, this.buf[this.pos++] < 128 || (e = (e | (this.buf[this.pos] & 127) << 7) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 127) << 14) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 127) << 21) >>> 0, this.buf[this.pos++] < 128) || (e = (e | (this.buf[this.pos] & 15) << 28) >>> 0, this.buf[this.pos++] < 128)) return e; if ((this.pos += 5) > this.len) throw this.pos = this.len, _t3(this, 10); return e; }; })(); K.prototype.int32 = function() { return this.uint32() | 0; }; K.prototype.sint32 = function() { var e = this.uint32(); return e >>> 1 ^ -(e & 1) | 0; }; function Qr2() { var a = new yi2(0, 0), e = 0; if (this.len - this.pos > 4) { for (; e < 4; ++e) if (a.lo = (a.lo | (this.buf[this.pos] & 127) << e * 7) >>> 0, this.buf[this.pos++] < 128) return a; if (a.lo = (a.lo | (this.buf[this.pos] & 127) << 28) >>> 0, a.hi = (a.hi | (this.buf[this.pos] & 127) >> 4) >>> 0, this.buf[this.pos++] < 128) return a; e = 0; } else { for (; e < 3; ++e) { if (this.pos >= this.len) throw _t3(this); if (a.lo = (a.lo | (this.buf[this.pos] & 127) << e * 7) >>> 0, this.buf[this.pos++] < 128) return a; } return a.lo = (a.lo | (this.buf[this.pos++] & 127) << e * 7) >>> 0, a; } if (this.len - this.pos > 4) { for (; e < 5; ++e) if (a.hi = (a.hi | (this.buf[this.pos] & 127) << e * 7 + 3) >>> 0, this.buf[this.pos++] < 128) return a; } else for (; e < 5; ++e) { if (this.pos >= this.len) throw _t3(this); if (a.hi = (a.hi | (this.buf[this.pos] & 127) << e * 7 + 3) >>> 0, this.buf[this.pos++] < 128) return a; } throw Error("invalid varint encoding"); } K.prototype.bool = function() { return this.uint32() !== 0; }; function tr2(a, e) { return (a[e - 4] | a[e - 3] << 8 | a[e - 2] << 16 | a[e - 1] << 24) >>> 0; } K.prototype.fixed32 = function() { if (this.pos + 4 > this.len) throw _t3(this, 4); return tr2(this.buf, this.pos += 4); }; K.prototype.sfixed32 = function() { if (this.pos + 4 > this.len) throw _t3(this, 4); return tr2(this.buf, this.pos += 4) | 0; }; function bi2() { if (this.pos + 8 > this.len) throw _t3(this, 8); return new yi2(tr2(this.buf, this.pos += 4), tr2(this.buf, this.pos += 4)); } K.prototype.float = function() { if (this.pos + 4 > this.len) throw _t3(this, 4); var e = It2.float.readFloatLE(this.buf, this.pos); return this.pos += 4, e; }; K.prototype.double = function() { if (this.pos + 8 > this.len) throw _t3(this, 4); var e = It2.float.readDoubleLE(this.buf, this.pos); return this.pos += 8, e; }; K.prototype.bytes = function() { var e = this.uint32(), o = this.pos, t = this.pos + e; if (t > this.len) throw _t3(this, e); if (this.pos += e, Array.isArray(this.buf)) return this.buf.slice(o, t); if (o === t) { var n = It2.Buffer; return n ? n.alloc(0) : new this.buf.constructor(0); } return this._slice.call(this.buf, o, t); }; K.prototype.string = function() { var e = this.bytes(); return Xl2.read(e, 0, e.length); }; K.prototype.skip = function(e) { if (typeof e == "number") { if (this.pos + e > this.len) throw _t3(this, e); this.pos += e; } else do if (this.pos >= this.len) throw _t3(this); while (this.buf[this.pos++] & 128); return this; }; K.prototype.skipType = function(a) { switch (a) { case 0: this.skip(); break; case 1: this.skip(8); break; case 2: this.skip(this.uint32()); break; case 3: for (; (a = this.uint32() & 7) !== 4; ) this.skipType(a); break; case 5: this.skip(4); break; default: throw Error("invalid wire type " + a + " at offset " + this.pos); } return this; }; K._configure = function(a) { tn2 = a, K.create = gi2(), tn2._configure(); var e = It2.Long ? "toLong" : "toNumber"; It2.merge(K.prototype, { int64: function() { return Qr2.call(this)[e](false); }, uint64: function() { return Qr2.call(this)[e](true); }, sint64: function() { return Qr2.call(this).zzDecode()[e](false); }, fixed64: function() { return bi2.call(this)[e](true); }, sfixed64: function() { return bi2.call(this)[e](false); } }); }; }); Ii2 = Z((gh3, wi2) => { "use strict"; wi2.exports = jt3; var vi2 = en2(); (jt3.prototype = Object.create(vi2.prototype)).constructor = jt3; var Ti2 = Gt2(); function jt3(a) { vi2.call(this, a); } jt3._configure = function() { Ti2.Buffer && (jt3.prototype._slice = Ti2.Buffer.prototype.slice); }; jt3.prototype.string = function() { var e = this.uint32(); return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + e, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + e, this.len)); }; jt3._configure(); }); Si2 = Z((xh3, _i2) => { "use strict"; _i2.exports = ve2; var rn2 = Gt2(); (ve2.prototype = Object.create(rn2.EventEmitter.prototype)).constructor = ve2; function ve2(a, e, o) { if (typeof a != "function") throw TypeError("rpcImpl must be a function"); rn2.EventEmitter.call(this), this.rpcImpl = a, this.requestDelimited = !!e, this.responseDelimited = !!o; } ve2.prototype.rpcCall = function a(e, o, t, n, r) { if (!n) throw TypeError("request must be specified"); var s = this; if (!r) return rn2.asPromise(a, s, e, o, t, n); if (!s.rpcImpl) { setTimeout(function() { r(Error("already ended")); }, 0); return; } try { return s.rpcImpl(e, o[s.requestDelimited ? "encodeDelimited" : "encode"](n).finish(), function(u, l) { if (u) return s.emit("error", u, e), r(u); if (l === null) { s.end(true); return; } if (!(l instanceof t)) try { l = t[s.responseDelimited ? "decodeDelimited" : "decode"](l); } catch (f) { return s.emit("error", f, e), r(f); } return s.emit("data", l, e), r(null, l); }); } catch (i) { s.emit("error", i, e), setTimeout(function() { r(i); }, 0); return; } }; ve2.prototype.end = function(e) { return this.rpcImpl && (e || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this; }; }); Ai2 = Z((Oi2) => { "use strict"; var Jl2 = Oi2; Jl2.Service = Si2(); }); Ei2 = Z((vh2, Pi2) => { "use strict"; Pi2.exports = {}; }); $i2 = Z((Li2) => { "use strict"; var lt2 = Li2; lt2.build = "minimal"; lt2.Writer = Yr2(); lt2.BufferWriter = hi2(); lt2.Reader = en2(); lt2.BufferReader = Ii2(); lt2.util = Gt2(); lt2.rpc = Ai2(); lt2.roots = Ei2(); lt2.configure = Di2; function Di2() { lt2.util._configure(), lt2.Writer._configure(lt2.BufferWriter), lt2.Reader._configure(lt2.BufferReader); } Di2(); }); Bi2 = Z((Ih2, ki2) => { "use strict"; ki2.exports = $i2(); }); se = Z((_h3, Fi2) => { "use strict"; var W2 = Bi2(), w = W2.Reader, X = W2.Writer, h = W2.util, c = W2.roots.default || (W2.roots.default = {}); c.onnx = (function() { var a = {}; return a.Version = (function() { var e = {}, o = Object.create(e); return o[e[0] = "_START_VERSION"] = 0, o[e[1] = "IR_VERSION_2017_10_10"] = 1, o[e[2] = "IR_VERSION_2017_10_30"] = 2, o[e[3] = "IR_VERSION_2017_11_3"] = 3, o[e[4] = "IR_VERSION_2019_1_22"] = 4, o[e[5] = "IR_VERSION_2019_3_18"] = 5, o[e[6] = "IR_VERSION_2019_9_19"] = 6, o[e[7] = "IR_VERSION_2020_5_8"] = 7, o[e[8] = "IR_VERSION_2021_7_30"] = 8, o[e[9] = "IR_VERSION"] = 9, o; })(), a.AttributeProto = (function() { function e(o) { if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], this.sparseTensors = [], this.typeProtos = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.name = "", e.prototype.refAttrName = "", e.prototype.docString = "", e.prototype.type = 0, e.prototype.f = 0, e.prototype.i = h.Long ? h.Long.fromBits(0, 0, false) : 0, e.prototype.s = h.newBuffer([]), e.prototype.t = null, e.prototype.g = null, e.prototype.sparseTensor = null, e.prototype.tp = null, e.prototype.floats = h.emptyArray, e.prototype.ints = h.emptyArray, e.prototype.strings = h.emptyArray, e.prototype.tensors = h.emptyArray, e.prototype.graphs = h.emptyArray, e.prototype.sparseTensors = h.emptyArray, e.prototype.typeProtos = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(10).string(t.name), t.f != null && Object.hasOwnProperty.call(t, "f") && n.uint32(21).float(t.f), t.i != null && Object.hasOwnProperty.call(t, "i") && n.uint32(24).int64(t.i), t.s != null && Object.hasOwnProperty.call(t, "s") && n.uint32(34).bytes(t.s), t.t != null && Object.hasOwnProperty.call(t, "t") && c.onnx.TensorProto.encode(t.t, n.uint32(42).fork()).ldelim(), t.g != null && Object.hasOwnProperty.call(t, "g") && c.onnx.GraphProto.encode(t.g, n.uint32(50).fork()).ldelim(), t.floats != null && t.floats.length) { n.uint32(58).fork(); for (var r = 0; r < t.floats.length; ++r) n.float(t.floats[r]); n.ldelim(); } if (t.ints != null && t.ints.length) { n.uint32(66).fork(); for (var r = 0; r < t.ints.length; ++r) n.int64(t.ints[r]); n.ldelim(); } if (t.strings != null && t.strings.length) for (var r = 0; r < t.strings.length; ++r) n.uint32(74).bytes(t.strings[r]); if (t.tensors != null && t.tensors.length) for (var r = 0; r < t.tensors.length; ++r) c.onnx.TensorProto.encode(t.tensors[r], n.uint32(82).fork()).ldelim(); if (t.graphs != null && t.graphs.length) for (var r = 0; r < t.graphs.length; ++r) c.onnx.GraphProto.encode(t.graphs[r], n.uint32(90).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(106).string(t.docString), t.tp != null && Object.hasOwnProperty.call(t, "tp") && c.onnx.TypeProto.encode(t.tp, n.uint32(114).fork()).ldelim(), t.typeProtos != null && t.typeProtos.length) for (var r = 0; r < t.typeProtos.length; ++r) c.onnx.TypeProto.encode(t.typeProtos[r], n.uint32(122).fork()).ldelim(); if (t.type != null && Object.hasOwnProperty.call(t, "type") && n.uint32(160).int32(t.type), t.refAttrName != null && Object.hasOwnProperty.call(t, "refAttrName") && n.uint32(170).string(t.refAttrName), t.sparseTensor != null && Object.hasOwnProperty.call(t, "sparseTensor") && c.onnx.SparseTensorProto.encode(t.sparseTensor, n.uint32(178).fork()).ldelim(), t.sparseTensors != null && t.sparseTensors.length) for (var r = 0; r < t.sparseTensors.length; ++r) c.onnx.SparseTensorProto.encode(t.sparseTensors[r], n.uint32(186).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.AttributeProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.name = t.string(); break; } case 21: { s.refAttrName = t.string(); break; } case 13: { s.docString = t.string(); break; } case 20: { s.type = t.int32(); break; } case 2: { s.f = t.float(); break; } case 3: { s.i = t.int64(); break; } case 4: { s.s = t.bytes(); break; } case 5: { s.t = c.onnx.TensorProto.decode(t, t.uint32()); break; } case 6: { s.g = c.onnx.GraphProto.decode(t, t.uint32()); break; } case 22: { s.sparseTensor = c.onnx.SparseTensorProto.decode(t, t.uint32()); break; } case 14: { s.tp = c.onnx.TypeProto.decode(t, t.uint32()); break; } case 7: { if (s.floats && s.floats.length || (s.floats = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.floats.push(t.float()); else s.floats.push(t.float()); break; } case 8: { if (s.ints && s.ints.length || (s.ints = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.ints.push(t.int64()); else s.ints.push(t.int64()); break; } case 9: { s.strings && s.strings.length || (s.strings = []), s.strings.push(t.bytes()); break; } case 10: { s.tensors && s.tensors.length || (s.tensors = []), s.tensors.push(c.onnx.TensorProto.decode(t, t.uint32())); break; } case 11: { s.graphs && s.graphs.length || (s.graphs = []), s.graphs.push(c.onnx.GraphProto.decode(t, t.uint32())); break; } case 23: { s.sparseTensors && s.sparseTensors.length || (s.sparseTensors = []), s.sparseTensors.push(c.onnx.SparseTensorProto.decode(t, t.uint32())); break; } case 15: { s.typeProtos && s.typeProtos.length || (s.typeProtos = []), s.typeProtos.push(c.onnx.TypeProto.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.refAttrName != null && t.hasOwnProperty("refAttrName") && !h.isString(t.refAttrName)) return "refAttrName: string expected"; if (t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString)) return "docString: string expected"; if (t.type != null && t.hasOwnProperty("type")) switch (t.type) { default: return "type: enum value expected"; case 0: case 1: case 2: case 3: case 4: case 5: case 11: case 13: case 6: case 7: case 8: case 9: case 10: case 12: case 14: break; } if (t.f != null && t.hasOwnProperty("f") && typeof t.f != "number") return "f: number expected"; if (t.i != null && t.hasOwnProperty("i") && !h.isInteger(t.i) && !(t.i && h.isInteger(t.i.low) && h.isInteger(t.i.high))) return "i: integer|Long expected"; if (t.s != null && t.hasOwnProperty("s") && !(t.s && typeof t.s.length == "number" || h.isString(t.s))) return "s: buffer expected"; if (t.t != null && t.hasOwnProperty("t")) { var n = c.onnx.TensorProto.verify(t.t); if (n) return "t." + n; } if (t.g != null && t.hasOwnProperty("g")) { var n = c.onnx.GraphProto.verify(t.g); if (n) return "g." + n; } if (t.sparseTensor != null && t.hasOwnProperty("sparseTensor")) { var n = c.onnx.SparseTensorProto.verify(t.sparseTensor); if (n) return "sparseTensor." + n; } if (t.tp != null && t.hasOwnProperty("tp")) { var n = c.onnx.TypeProto.verify(t.tp); if (n) return "tp." + n; } if (t.floats != null && t.hasOwnProperty("floats")) { if (!Array.isArray(t.floats)) return "floats: array expected"; for (var r = 0; r < t.floats.length; ++r) if (typeof t.floats[r] != "number") return "floats: number[] expected"; } if (t.ints != null && t.hasOwnProperty("ints")) { if (!Array.isArray(t.ints)) return "ints: array expected"; for (var r = 0; r < t.ints.length; ++r) if (!h.isInteger(t.ints[r]) && !(t.ints[r] && h.isInteger(t.ints[r].low) && h.isInteger(t.ints[r].high))) return "ints: integer|Long[] expected"; } if (t.strings != null && t.hasOwnProperty("strings")) { if (!Array.isArray(t.strings)) return "strings: array expected"; for (var r = 0; r < t.strings.length; ++r) if (!(t.strings[r] && typeof t.strings[r].length == "number" || h.isString(t.strings[r]))) return "strings: buffer[] expected"; } if (t.tensors != null && t.hasOwnProperty("tensors")) { if (!Array.isArray(t.tensors)) return "tensors: array expected"; for (var r = 0; r < t.tensors.length; ++r) { var n = c.onnx.TensorProto.verify(t.tensors[r]); if (n) return "tensors." + n; } } if (t.graphs != null && t.hasOwnProperty("graphs")) { if (!Array.isArray(t.graphs)) return "graphs: array expected"; for (var r = 0; r < t.graphs.length; ++r) { var n = c.onnx.GraphProto.verify(t.graphs[r]); if (n) return "graphs." + n; } } if (t.sparseTensors != null && t.hasOwnProperty("sparseTensors")) { if (!Array.isArray(t.sparseTensors)) return "sparseTensors: array expected"; for (var r = 0; r < t.sparseTensors.length; ++r) { var n = c.onnx.SparseTensorProto.verify(t.sparseTensors[r]); if (n) return "sparseTensors." + n; } } if (t.typeProtos != null && t.hasOwnProperty("typeProtos")) { if (!Array.isArray(t.typeProtos)) return "typeProtos: array expected"; for (var r = 0; r < t.typeProtos.length; ++r) { var n = c.onnx.TypeProto.verify(t.typeProtos[r]); if (n) return "typeProtos." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.AttributeProto) return t; var n = new c.onnx.AttributeProto(); switch (t.name != null && (n.name = String(t.name)), t.refAttrName != null && (n.refAttrName = String(t.refAttrName)), t.docString != null && (n.docString = String(t.docString)), t.type) { default: if (typeof t.type == "number") { n.type = t.type; break; } break; case "UNDEFINED": case 0: n.type = 0; break; case "FLOAT": case 1: n.type = 1; break; case "INT": case 2: n.type = 2; break; case "STRING": case 3: n.type = 3; break; case "TENSOR": case 4: n.type = 4; break; case "GRAPH": case 5: n.type = 5; break; case "SPARSE_TENSOR": case 11: n.type = 11; break; case "TYPE_PROTO": case 13: n.type = 13; break; case "FLOATS": case 6: n.type = 6; break; case "INTS": case 7: n.type = 7; break; case "STRINGS": case 8: n.type = 8; break; case "TENSORS": case 9: n.type = 9; break; case "GRAPHS": case 10: n.type = 10; break; case "SPARSE_TENSORS": case 12: n.type = 12; break; case "TYPE_PROTOS": case 14: n.type = 14; break; } if (t.f != null && (n.f = Number(t.f)), t.i != null && (h.Long ? (n.i = h.Long.fromValue(t.i)).unsigned = false : typeof t.i == "string" ? n.i = parseInt(t.i, 10) : typeof t.i == "number" ? n.i = t.i : typeof t.i == "object" && (n.i = new h.LongBits(t.i.low >>> 0, t.i.high >>> 0).toNumber())), t.s != null && (typeof t.s == "string" ? h.base64.decode(t.s, n.s = h.newBuffer(h.base64.length(t.s)), 0) : t.s.length >= 0 && (n.s = t.s)), t.t != null) { if (typeof t.t != "object") throw TypeError(".onnx.AttributeProto.t: object expected"); n.t = c.onnx.TensorProto.fromObject(t.t); } if (t.g != null) { if (typeof t.g != "object") throw TypeError(".onnx.AttributeProto.g: object expected"); n.g = c.onnx.GraphProto.fromObject(t.g); } if (t.sparseTensor != null) { if (typeof t.sparseTensor != "object") throw TypeError(".onnx.AttributeProto.sparseTensor: object expected"); n.sparseTensor = c.onnx.SparseTensorProto.fromObject(t.sparseTensor); } if (t.tp != null) { if (typeof t.tp != "object") throw TypeError(".onnx.AttributeProto.tp: object expected"); n.tp = c.onnx.TypeProto.fromObject(t.tp); } if (t.floats) { if (!Array.isArray(t.floats)) throw TypeError(".onnx.AttributeProto.floats: array expected"); n.floats = []; for (var r = 0; r < t.floats.length; ++r) n.floats[r] = Number(t.floats[r]); } if (t.ints) { if (!Array.isArray(t.ints)) throw TypeError(".onnx.AttributeProto.ints: array expected"); n.ints = []; for (var r = 0; r < t.ints.length; ++r) h.Long ? (n.ints[r] = h.Long.fromValue(t.ints[r])).unsigned = false : typeof t.ints[r] == "string" ? n.ints[r] = parseInt(t.ints[r], 10) : typeof t.ints[r] == "number" ? n.ints[r] = t.ints[r] : typeof t.ints[r] == "object" && (n.ints[r] = new h.LongBits(t.ints[r].low >>> 0, t.ints[r].high >>> 0).toNumber()); } if (t.strings) { if (!Array.isArray(t.strings)) throw TypeError(".onnx.AttributeProto.strings: array expected"); n.strings = []; for (var r = 0; r < t.strings.length; ++r) typeof t.strings[r] == "string" ? h.base64.decode(t.strings[r], n.strings[r] = h.newBuffer(h.base64.length(t.strings[r])), 0) : t.strings[r].length >= 0 && (n.strings[r] = t.strings[r]); } if (t.tensors) { if (!Array.isArray(t.tensors)) throw TypeError(".onnx.AttributeProto.tensors: array expected"); n.tensors = []; for (var r = 0; r < t.tensors.length; ++r) { if (typeof t.tensors[r] != "object") throw TypeError(".onnx.AttributeProto.tensors: object expected"); n.tensors[r] = c.onnx.TensorProto.fromObject(t.tensors[r]); } } if (t.graphs) { if (!Array.isArray(t.graphs)) throw TypeError(".onnx.AttributeProto.graphs: array expected"); n.graphs = []; for (var r = 0; r < t.graphs.length; ++r) { if (typeof t.graphs[r] != "object") throw TypeError(".onnx.AttributeProto.graphs: object expected"); n.graphs[r] = c.onnx.GraphProto.fromObject(t.graphs[r]); } } if (t.sparseTensors) { if (!Array.isArray(t.sparseTensors)) throw TypeError(".onnx.AttributeProto.sparseTensors: array expected"); n.sparseTensors = []; for (var r = 0; r < t.sparseTensors.length; ++r) { if (typeof t.sparseTensors[r] != "object") throw TypeError(".onnx.AttributeProto.sparseTensors: object expected"); n.sparseTensors[r] = c.onnx.SparseTensorProto.fromObject(t.sparseTensors[r]); } } if (t.typeProtos) { if (!Array.isArray(t.typeProtos)) throw TypeError(".onnx.AttributeProto.typeProtos: array expected"); n.typeProtos = []; for (var r = 0; r < t.typeProtos.length; ++r) { if (typeof t.typeProtos[r] != "object") throw TypeError(".onnx.AttributeProto.typeProtos: object expected"); n.typeProtos[r] = c.onnx.TypeProto.fromObject(t.typeProtos[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.floats = [], r.ints = [], r.strings = [], r.tensors = [], r.graphs = [], r.typeProtos = [], r.sparseTensors = []), n.defaults) { if (r.name = "", r.f = 0, h.Long) { var s = new h.Long(0, 0, false); r.i = n.longs === String ? s.toString() : n.longs === Number ? s.toNumber() : s; } else r.i = n.longs === String ? "0" : 0; n.bytes === String ? r.s = "" : (r.s = [], n.bytes !== Array && (r.s = h.newBuffer(r.s))), r.t = null, r.g = null, r.docString = "", r.tp = null, r.type = n.enums === String ? "UNDEFINED" : 0, r.refAttrName = "", r.sparseTensor = null; } if (t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.f != null && t.hasOwnProperty("f") && (r.f = n.json && !isFinite(t.f) ? String(t.f) : t.f), t.i != null && t.hasOwnProperty("i") && (typeof t.i == "number" ? r.i = n.longs === String ? String(t.i) : t.i : r.i = n.longs === String ? h.Long.prototype.toString.call(t.i) : n.longs === Number ? new h.LongBits(t.i.low >>> 0, t.i.high >>> 0).toNumber() : t.i), t.s != null && t.hasOwnProperty("s") && (r.s = n.bytes === String ? h.base64.encode(t.s, 0, t.s.length) : n.bytes === Array ? Array.prototype.slice.call(t.s) : t.s), t.t != null && t.hasOwnProperty("t") && (r.t = c.onnx.TensorProto.toObject(t.t, n)), t.g != null && t.hasOwnProperty("g") && (r.g = c.onnx.GraphProto.toObject(t.g, n)), t.floats && t.floats.length) { r.floats = []; for (var i = 0; i < t.floats.length; ++i) r.floats[i] = n.json && !isFinite(t.floats[i]) ? String(t.floats[i]) : t.floats[i]; } if (t.ints && t.ints.length) { r.ints = []; for (var i = 0; i < t.ints.length; ++i) typeof t.ints[i] == "number" ? r.ints[i] = n.longs === String ? String(t.ints[i]) : t.ints[i] : r.ints[i] = n.longs === String ? h.Long.prototype.toString.call(t.ints[i]) : n.longs === Number ? new h.LongBits(t.ints[i].low >>> 0, t.ints[i].high >>> 0).toNumber() : t.ints[i]; } if (t.strings && t.strings.length) { r.strings = []; for (var i = 0; i < t.strings.length; ++i) r.strings[i] = n.bytes === String ? h.base64.encode(t.strings[i], 0, t.strings[i].length) : n.bytes === Array ? Array.prototype.slice.call(t.strings[i]) : t.strings[i]; } if (t.tensors && t.tensors.length) { r.tensors = []; for (var i = 0; i < t.tensors.length; ++i) r.tensors[i] = c.onnx.TensorProto.toObject(t.tensors[i], n); } if (t.graphs && t.graphs.length) { r.graphs = []; for (var i = 0; i < t.graphs.length; ++i) r.graphs[i] = c.onnx.GraphProto.toObject(t.graphs[i], n); } if (t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.tp != null && t.hasOwnProperty("tp") && (r.tp = c.onnx.TypeProto.toObject(t.tp, n)), t.typeProtos && t.typeProtos.length) { r.typeProtos = []; for (var i = 0; i < t.typeProtos.length; ++i) r.typeProtos[i] = c.onnx.TypeProto.toObject(t.typeProtos[i], n); } if (t.type != null && t.hasOwnProperty("type") && (r.type = n.enums === String ? c.onnx.AttributeProto.AttributeType[t.type] === void 0 ? t.type : c.onnx.AttributeProto.AttributeType[t.type] : t.type), t.refAttrName != null && t.hasOwnProperty("refAttrName") && (r.refAttrName = t.refAttrName), t.sparseTensor != null && t.hasOwnProperty("sparseTensor") && (r.sparseTensor = c.onnx.SparseTensorProto.toObject(t.sparseTensor, n)), t.sparseTensors && t.sparseTensors.length) { r.sparseTensors = []; for (var i = 0; i < t.sparseTensors.length; ++i) r.sparseTensors[i] = c.onnx.SparseTensorProto.toObject(t.sparseTensors[i], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.AttributeProto"; }, e.AttributeType = (function() { var o = {}, t = Object.create(o); return t[o[0] = "UNDEFINED"] = 0, t[o[1] = "FLOAT"] = 1, t[o[2] = "INT"] = 2, t[o[3] = "STRING"] = 3, t[o[4] = "TENSOR"] = 4, t[o[5] = "GRAPH"] = 5, t[o[11] = "SPARSE_TENSOR"] = 11, t[o[13] = "TYPE_PROTO"] = 13, t[o[6] = "FLOATS"] = 6, t[o[7] = "INTS"] = 7, t[o[8] = "STRINGS"] = 8, t[o[9] = "TENSORS"] = 9, t[o[10] = "GRAPHS"] = 10, t[o[12] = "SPARSE_TENSORS"] = 12, t[o[14] = "TYPE_PROTOS"] = 14, t; })(), e; })(), a.ValueInfoProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.name = "", e.prototype.type = null, e.prototype.docString = "", e.create = function(t) { return new e(t); }, e.encode = function(t, n) { return n || (n = X.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(10).string(t.name), t.type != null && Object.hasOwnProperty.call(t, "type") && c.onnx.TypeProto.encode(t.type, n.uint32(18).fork()).ldelim(), t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(26).string(t.docString), n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.ValueInfoProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.name = t.string(); break; } case 2: { s.type = c.onnx.TypeProto.decode(t, t.uint32()); break; } case 3: { s.docString = t.string(); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.type != null && t.hasOwnProperty("type")) { var n = c.onnx.TypeProto.verify(t.type); if (n) return "type." + n; } return t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString) ? "docString: string expected" : null; }, e.fromObject = function(t) { if (t instanceof c.onnx.ValueInfoProto) return t; var n = new c.onnx.ValueInfoProto(); if (t.name != null && (n.name = String(t.name)), t.type != null) { if (typeof t.type != "object") throw TypeError(".onnx.ValueInfoProto.type: object expected"); n.type = c.onnx.TypeProto.fromObject(t.type); } return t.docString != null && (n.docString = String(t.docString)), n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; return n.defaults && (r.name = "", r.type = null, r.docString = ""), t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.type != null && t.hasOwnProperty("type") && (r.type = c.onnx.TypeProto.toObject(t.type, n)), t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.ValueInfoProto"; }, e; })(), a.NodeProto = (function() { function e(o) { if (this.input = [], this.output = [], this.attribute = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.input = h.emptyArray, e.prototype.output = h.emptyArray, e.prototype.name = "", e.prototype.opType = "", e.prototype.domain = "", e.prototype.attribute = h.emptyArray, e.prototype.docString = "", e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.input != null && t.input.length) for (var r = 0; r < t.input.length; ++r) n.uint32(10).string(t.input[r]); if (t.output != null && t.output.length) for (var r = 0; r < t.output.length; ++r) n.uint32(18).string(t.output[r]); if (t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(26).string(t.name), t.opType != null && Object.hasOwnProperty.call(t, "opType") && n.uint32(34).string(t.opType), t.attribute != null && t.attribute.length) for (var r = 0; r < t.attribute.length; ++r) c.onnx.AttributeProto.encode(t.attribute[r], n.uint32(42).fork()).ldelim(); return t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(50).string(t.docString), t.domain != null && Object.hasOwnProperty.call(t, "domain") && n.uint32(58).string(t.domain), n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.NodeProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.input && s.input.length || (s.input = []), s.input.push(t.string()); break; } case 2: { s.output && s.output.length || (s.output = []), s.output.push(t.string()); break; } case 3: { s.name = t.string(); break; } case 4: { s.opType = t.string(); break; } case 7: { s.domain = t.string(); break; } case 5: { s.attribute && s.attribute.length || (s.attribute = []), s.attribute.push(c.onnx.AttributeProto.decode(t, t.uint32())); break; } case 6: { s.docString = t.string(); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var n = 0; n < t.input.length; ++n) if (!h.isString(t.input[n])) return "input: string[] expected"; } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var n = 0; n < t.output.length; ++n) if (!h.isString(t.output[n])) return "output: string[] expected"; } if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.opType != null && t.hasOwnProperty("opType") && !h.isString(t.opType)) return "opType: string expected"; if (t.domain != null && t.hasOwnProperty("domain") && !h.isString(t.domain)) return "domain: string expected"; if (t.attribute != null && t.hasOwnProperty("attribute")) { if (!Array.isArray(t.attribute)) return "attribute: array expected"; for (var n = 0; n < t.attribute.length; ++n) { var r = c.onnx.AttributeProto.verify(t.attribute[n]); if (r) return "attribute." + r; } } return t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString) ? "docString: string expected" : null; }, e.fromObject = function(t) { if (t instanceof c.onnx.NodeProto) return t; var n = new c.onnx.NodeProto(); if (t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.NodeProto.input: array expected"); n.input = []; for (var r = 0; r < t.input.length; ++r) n.input[r] = String(t.input[r]); } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.NodeProto.output: array expected"); n.output = []; for (var r = 0; r < t.output.length; ++r) n.output[r] = String(t.output[r]); } if (t.name != null && (n.name = String(t.name)), t.opType != null && (n.opType = String(t.opType)), t.domain != null && (n.domain = String(t.domain)), t.attribute) { if (!Array.isArray(t.attribute)) throw TypeError(".onnx.NodeProto.attribute: array expected"); n.attribute = []; for (var r = 0; r < t.attribute.length; ++r) { if (typeof t.attribute[r] != "object") throw TypeError(".onnx.NodeProto.attribute: object expected"); n.attribute[r] = c.onnx.AttributeProto.fromObject(t.attribute[r]); } } return t.docString != null && (n.docString = String(t.docString)), n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.input = [], r.output = [], r.attribute = []), n.defaults && (r.name = "", r.opType = "", r.docString = "", r.domain = ""), t.input && t.input.length) { r.input = []; for (var s = 0; s < t.input.length; ++s) r.input[s] = t.input[s]; } if (t.output && t.output.length) { r.output = []; for (var s = 0; s < t.output.length; ++s) r.output[s] = t.output[s]; } if (t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.opType != null && t.hasOwnProperty("opType") && (r.opType = t.opType), t.attribute && t.attribute.length) { r.attribute = []; for (var s = 0; s < t.attribute.length; ++s) r.attribute[s] = c.onnx.AttributeProto.toObject(t.attribute[s], n); } return t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.domain != null && t.hasOwnProperty("domain") && (r.domain = t.domain), r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.NodeProto"; }, e; })(), a.TrainingInfoProto = (function() { function e(o) { if (this.initializationBinding = [], this.updateBinding = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.initialization = null, e.prototype.algorithm = null, e.prototype.initializationBinding = h.emptyArray, e.prototype.updateBinding = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.initialization != null && Object.hasOwnProperty.call(t, "initialization") && c.onnx.GraphProto.encode(t.initialization, n.uint32(10).fork()).ldelim(), t.algorithm != null && Object.hasOwnProperty.call(t, "algorithm") && c.onnx.GraphProto.encode(t.algorithm, n.uint32(18).fork()).ldelim(), t.initializationBinding != null && t.initializationBinding.length) for (var r = 0; r < t.initializationBinding.length; ++r) c.onnx.StringStringEntryProto.encode(t.initializationBinding[r], n.uint32(26).fork()).ldelim(); if (t.updateBinding != null && t.updateBinding.length) for (var r = 0; r < t.updateBinding.length; ++r) c.onnx.StringStringEntryProto.encode(t.updateBinding[r], n.uint32(34).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.TrainingInfoProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.initialization = c.onnx.GraphProto.decode(t, t.uint32()); break; } case 2: { s.algorithm = c.onnx.GraphProto.decode(t, t.uint32()); break; } case 3: { s.initializationBinding && s.initializationBinding.length || (s.initializationBinding = []), s.initializationBinding.push(c.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 4: { s.updateBinding && s.updateBinding.length || (s.updateBinding = []), s.updateBinding.push(c.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.initialization != null && t.hasOwnProperty("initialization")) { var n = c.onnx.GraphProto.verify(t.initialization); if (n) return "initialization." + n; } if (t.algorithm != null && t.hasOwnProperty("algorithm")) { var n = c.onnx.GraphProto.verify(t.algorithm); if (n) return "algorithm." + n; } if (t.initializationBinding != null && t.hasOwnProperty("initializationBinding")) { if (!Array.isArray(t.initializationBinding)) return "initializationBinding: array expected"; for (var r = 0; r < t.initializationBinding.length; ++r) { var n = c.onnx.StringStringEntryProto.verify(t.initializationBinding[r]); if (n) return "initializationBinding." + n; } } if (t.updateBinding != null && t.hasOwnProperty("updateBinding")) { if (!Array.isArray(t.updateBinding)) return "updateBinding: array expected"; for (var r = 0; r < t.updateBinding.length; ++r) { var n = c.onnx.StringStringEntryProto.verify(t.updateBinding[r]); if (n) return "updateBinding." + n; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.TrainingInfoProto) return t; var n = new c.onnx.TrainingInfoProto(); if (t.initialization != null) { if (typeof t.initialization != "object") throw TypeError(".onnx.TrainingInfoProto.initialization: object expected"); n.initialization = c.onnx.GraphProto.fromObject(t.initialization); } if (t.algorithm != null) { if (typeof t.algorithm != "object") throw TypeError(".onnx.TrainingInfoProto.algorithm: object expected"); n.algorithm = c.onnx.GraphProto.fromObject(t.algorithm); } if (t.initializationBinding) { if (!Array.isArray(t.initializationBinding)) throw TypeError(".onnx.TrainingInfoProto.initializationBinding: array expected"); n.initializationBinding = []; for (var r = 0; r < t.initializationBinding.length; ++r) { if (typeof t.initializationBinding[r] != "object") throw TypeError(".onnx.TrainingInfoProto.initializationBinding: object expected"); n.initializationBinding[r] = c.onnx.StringStringEntryProto.fromObject(t.initializationBinding[r]); } } if (t.updateBinding) { if (!Array.isArray(t.updateBinding)) throw TypeError(".onnx.TrainingInfoProto.updateBinding: array expected"); n.updateBinding = []; for (var r = 0; r < t.updateBinding.length; ++r) { if (typeof t.updateBinding[r] != "object") throw TypeError(".onnx.TrainingInfoProto.updateBinding: object expected"); n.updateBinding[r] = c.onnx.StringStringEntryProto.fromObject(t.updateBinding[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.initializationBinding = [], r.updateBinding = []), n.defaults && (r.initialization = null, r.algorithm = null), t.initialization != null && t.hasOwnProperty("initialization") && (r.initialization = c.onnx.GraphProto.toObject(t.initialization, n)), t.algorithm != null && t.hasOwnProperty("algorithm") && (r.algorithm = c.onnx.GraphProto.toObject(t.algorithm, n)), t.initializationBinding && t.initializationBinding.length) { r.initializationBinding = []; for (var s = 0; s < t.initializationBinding.length; ++s) r.initializationBinding[s] = c.onnx.StringStringEntryProto.toObject(t.initializationBinding[s], n); } if (t.updateBinding && t.updateBinding.length) { r.updateBinding = []; for (var s = 0; s < t.updateBinding.length; ++s) r.updateBinding[s] = c.onnx.StringStringEntryProto.toObject(t.updateBinding[s], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TrainingInfoProto"; }, e; })(), a.ModelProto = (function() { function e(o) { if (this.opsetImport = [], this.metadataProps = [], this.trainingInfo = [], this.functions = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.irVersion = h.Long ? h.Long.fromBits(0, 0, false) : 0, e.prototype.opsetImport = h.emptyArray, e.prototype.producerName = "", e.prototype.producerVersion = "", e.prototype.domain = "", e.prototype.modelVersion = h.Long ? h.Long.fromBits(0, 0, false) : 0, e.prototype.docString = "", e.prototype.graph = null, e.prototype.metadataProps = h.emptyArray, e.prototype.trainingInfo = h.emptyArray, e.prototype.functions = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.irVersion != null && Object.hasOwnProperty.call(t, "irVersion") && n.uint32(8).int64(t.irVersion), t.producerName != null && Object.hasOwnProperty.call(t, "producerName") && n.uint32(18).string(t.producerName), t.producerVersion != null && Object.hasOwnProperty.call(t, "producerVersion") && n.uint32(26).string(t.producerVersion), t.domain != null && Object.hasOwnProperty.call(t, "domain") && n.uint32(34).string(t.domain), t.modelVersion != null && Object.hasOwnProperty.call(t, "modelVersion") && n.uint32(40).int64(t.modelVersion), t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(50).string(t.docString), t.graph != null && Object.hasOwnProperty.call(t, "graph") && c.onnx.GraphProto.encode(t.graph, n.uint32(58).fork()).ldelim(), t.opsetImport != null && t.opsetImport.length) for (var r = 0; r < t.opsetImport.length; ++r) c.onnx.OperatorSetIdProto.encode(t.opsetImport[r], n.uint32(66).fork()).ldelim(); if (t.metadataProps != null && t.metadataProps.length) for (var r = 0; r < t.metadataProps.length; ++r) c.onnx.StringStringEntryProto.encode(t.metadataProps[r], n.uint32(114).fork()).ldelim(); if (t.trainingInfo != null && t.trainingInfo.length) for (var r = 0; r < t.trainingInfo.length; ++r) c.onnx.TrainingInfoProto.encode(t.trainingInfo[r], n.uint32(162).fork()).ldelim(); if (t.functions != null && t.functions.length) for (var r = 0; r < t.functions.length; ++r) c.onnx.FunctionProto.encode(t.functions[r], n.uint32(202).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.ModelProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.irVersion = t.int64(); break; } case 8: { s.opsetImport && s.opsetImport.length || (s.opsetImport = []), s.opsetImport.push(c.onnx.OperatorSetIdProto.decode(t, t.uint32())); break; } case 2: { s.producerName = t.string(); break; } case 3: { s.producerVersion = t.string(); break; } case 4: { s.domain = t.string(); break; } case 5: { s.modelVersion = t.int64(); break; } case 6: { s.docString = t.string(); break; } case 7: { s.graph = c.onnx.GraphProto.decode(t, t.uint32()); break; } case 14: { s.metadataProps && s.metadataProps.length || (s.metadataProps = []), s.metadataProps.push(c.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 20: { s.trainingInfo && s.trainingInfo.length || (s.trainingInfo = []), s.trainingInfo.push(c.onnx.TrainingInfoProto.decode(t, t.uint32())); break; } case 25: { s.functions && s.functions.length || (s.functions = []), s.functions.push(c.onnx.FunctionProto.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.irVersion != null && t.hasOwnProperty("irVersion") && !h.isInteger(t.irVersion) && !(t.irVersion && h.isInteger(t.irVersion.low) && h.isInteger(t.irVersion.high))) return "irVersion: integer|Long expected"; if (t.opsetImport != null && t.hasOwnProperty("opsetImport")) { if (!Array.isArray(t.opsetImport)) return "opsetImport: array expected"; for (var n = 0; n < t.opsetImport.length; ++n) { var r = c.onnx.OperatorSetIdProto.verify(t.opsetImport[n]); if (r) return "opsetImport." + r; } } if (t.producerName != null && t.hasOwnProperty("producerName") && !h.isString(t.producerName)) return "producerName: string expected"; if (t.producerVersion != null && t.hasOwnProperty("producerVersion") && !h.isString(t.producerVersion)) return "producerVersion: string expected"; if (t.domain != null && t.hasOwnProperty("domain") && !h.isString(t.domain)) return "domain: string expected"; if (t.modelVersion != null && t.hasOwnProperty("modelVersion") && !h.isInteger(t.modelVersion) && !(t.modelVersion && h.isInteger(t.modelVersion.low) && h.isInteger(t.modelVersion.high))) return "modelVersion: integer|Long expected"; if (t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString)) return "docString: string expected"; if (t.graph != null && t.hasOwnProperty("graph")) { var r = c.onnx.GraphProto.verify(t.graph); if (r) return "graph." + r; } if (t.metadataProps != null && t.hasOwnProperty("metadataProps")) { if (!Array.isArray(t.metadataProps)) return "metadataProps: array expected"; for (var n = 0; n < t.metadataProps.length; ++n) { var r = c.onnx.StringStringEntryProto.verify(t.metadataProps[n]); if (r) return "metadataProps." + r; } } if (t.trainingInfo != null && t.hasOwnProperty("trainingInfo")) { if (!Array.isArray(t.trainingInfo)) return "trainingInfo: array expected"; for (var n = 0; n < t.trainingInfo.length; ++n) { var r = c.onnx.TrainingInfoProto.verify(t.trainingInfo[n]); if (r) return "trainingInfo." + r; } } if (t.functions != null && t.hasOwnProperty("functions")) { if (!Array.isArray(t.functions)) return "functions: array expected"; for (var n = 0; n < t.functions.length; ++n) { var r = c.onnx.FunctionProto.verify(t.functions[n]); if (r) return "functions." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.ModelProto) return t; var n = new c.onnx.ModelProto(); if (t.irVersion != null && (h.Long ? (n.irVersion = h.Long.fromValue(t.irVersion)).unsigned = false : typeof t.irVersion == "string" ? n.irVersion = parseInt(t.irVersion, 10) : typeof t.irVersion == "number" ? n.irVersion = t.irVersion : typeof t.irVersion == "object" && (n.irVersion = new h.LongBits(t.irVersion.low >>> 0, t.irVersion.high >>> 0).toNumber())), t.opsetImport) { if (!Array.isArray(t.opsetImport)) throw TypeError(".onnx.ModelProto.opsetImport: array expected"); n.opsetImport = []; for (var r = 0; r < t.opsetImport.length; ++r) { if (typeof t.opsetImport[r] != "object") throw TypeError(".onnx.ModelProto.opsetImport: object expected"); n.opsetImport[r] = c.onnx.OperatorSetIdProto.fromObject(t.opsetImport[r]); } } if (t.producerName != null && (n.producerName = String(t.producerName)), t.producerVersion != null && (n.producerVersion = String(t.producerVersion)), t.domain != null && (n.domain = String(t.domain)), t.modelVersion != null && (h.Long ? (n.modelVersion = h.Long.fromValue(t.modelVersion)).unsigned = false : typeof t.modelVersion == "string" ? n.modelVersion = parseInt(t.modelVersion, 10) : typeof t.modelVersion == "number" ? n.modelVersion = t.modelVersion : typeof t.modelVersion == "object" && (n.modelVersion = new h.LongBits(t.modelVersion.low >>> 0, t.modelVersion.high >>> 0).toNumber())), t.docString != null && (n.docString = String(t.docString)), t.graph != null) { if (typeof t.graph != "object") throw TypeError(".onnx.ModelProto.graph: object expected"); n.graph = c.onnx.GraphProto.fromObject(t.graph); } if (t.metadataProps) { if (!Array.isArray(t.metadataProps)) throw TypeError(".onnx.ModelProto.metadataProps: array expected"); n.metadataProps = []; for (var r = 0; r < t.metadataProps.length; ++r) { if (typeof t.metadataProps[r] != "object") throw TypeError(".onnx.ModelProto.metadataProps: object expected"); n.metadataProps[r] = c.onnx.StringStringEntryProto.fromObject(t.metadataProps[r]); } } if (t.trainingInfo) { if (!Array.isArray(t.trainingInfo)) throw TypeError(".onnx.ModelProto.trainingInfo: array expected"); n.trainingInfo = []; for (var r = 0; r < t.trainingInfo.length; ++r) { if (typeof t.trainingInfo[r] != "object") throw TypeError(".onnx.ModelProto.trainingInfo: object expected"); n.trainingInfo[r] = c.onnx.TrainingInfoProto.fromObject(t.trainingInfo[r]); } } if (t.functions) { if (!Array.isArray(t.functions)) throw TypeError(".onnx.ModelProto.functions: array expected"); n.functions = []; for (var r = 0; r < t.functions.length; ++r) { if (typeof t.functions[r] != "object") throw TypeError(".onnx.ModelProto.functions: object expected"); n.functions[r] = c.onnx.FunctionProto.fromObject(t.functions[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.opsetImport = [], r.metadataProps = [], r.trainingInfo = [], r.functions = []), n.defaults) { if (h.Long) { var s = new h.Long(0, 0, false); r.irVersion = n.longs === String ? s.toString() : n.longs === Number ? s.toNumber() : s; } else r.irVersion = n.longs === String ? "0" : 0; if (r.producerName = "", r.producerVersion = "", r.domain = "", h.Long) { var s = new h.Long(0, 0, false); r.modelVersion = n.longs === String ? s.toString() : n.longs === Number ? s.toNumber() : s; } else r.modelVersion = n.longs === String ? "0" : 0; r.docString = "", r.graph = null; } if (t.irVersion != null && t.hasOwnProperty("irVersion") && (typeof t.irVersion == "number" ? r.irVersion = n.longs === String ? String(t.irVersion) : t.irVersion : r.irVersion = n.longs === String ? h.Long.prototype.toString.call(t.irVersion) : n.longs === Number ? new h.LongBits(t.irVersion.low >>> 0, t.irVersion.high >>> 0).toNumber() : t.irVersion), t.producerName != null && t.hasOwnProperty("producerName") && (r.producerName = t.producerName), t.producerVersion != null && t.hasOwnProperty("producerVersion") && (r.producerVersion = t.producerVersion), t.domain != null && t.hasOwnProperty("domain") && (r.domain = t.domain), t.modelVersion != null && t.hasOwnProperty("modelVersion") && (typeof t.modelVersion == "number" ? r.modelVersion = n.longs === String ? String(t.modelVersion) : t.modelVersion : r.modelVersion = n.longs === String ? h.Long.prototype.toString.call(t.modelVersion) : n.longs === Number ? new h.LongBits(t.modelVersion.low >>> 0, t.modelVersion.high >>> 0).toNumber() : t.modelVersion), t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.graph != null && t.hasOwnProperty("graph") && (r.graph = c.onnx.GraphProto.toObject(t.graph, n)), t.opsetImport && t.opsetImport.length) { r.opsetImport = []; for (var i = 0; i < t.opsetImport.length; ++i) r.opsetImport[i] = c.onnx.OperatorSetIdProto.toObject(t.opsetImport[i], n); } if (t.metadataProps && t.metadataProps.length) { r.metadataProps = []; for (var i = 0; i < t.metadataProps.length; ++i) r.metadataProps[i] = c.onnx.StringStringEntryProto.toObject(t.metadataProps[i], n); } if (t.trainingInfo && t.trainingInfo.length) { r.trainingInfo = []; for (var i = 0; i < t.trainingInfo.length; ++i) r.trainingInfo[i] = c.onnx.TrainingInfoProto.toObject(t.trainingInfo[i], n); } if (t.functions && t.functions.length) { r.functions = []; for (var i = 0; i < t.functions.length; ++i) r.functions[i] = c.onnx.FunctionProto.toObject(t.functions[i], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.ModelProto"; }, e; })(), a.StringStringEntryProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.key = "", e.prototype.value = "", e.create = function(t) { return new e(t); }, e.encode = function(t, n) { return n || (n = X.create()), t.key != null && Object.hasOwnProperty.call(t, "key") && n.uint32(10).string(t.key), t.value != null && Object.hasOwnProperty.call(t, "value") && n.uint32(18).string(t.value), n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.StringStringEntryProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.key = t.string(); break; } case 2: { s.value = t.string(); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { return typeof t != "object" || t === null ? "object expected" : t.key != null && t.hasOwnProperty("key") && !h.isString(t.key) ? "key: string expected" : t.value != null && t.hasOwnProperty("value") && !h.isString(t.value) ? "value: string expected" : null; }, e.fromObject = function(t) { if (t instanceof c.onnx.StringStringEntryProto) return t; var n = new c.onnx.StringStringEntryProto(); return t.key != null && (n.key = String(t.key)), t.value != null && (n.value = String(t.value)), n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; return n.defaults && (r.key = "", r.value = ""), t.key != null && t.hasOwnProperty("key") && (r.key = t.key), t.value != null && t.hasOwnProperty("value") && (r.value = t.value), r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.StringStringEntryProto"; }, e; })(), a.TensorAnnotation = (function() { function e(o) { if (this.quantParameterTensorNames = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.tensorName = "", e.prototype.quantParameterTensorNames = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.tensorName != null && Object.hasOwnProperty.call(t, "tensorName") && n.uint32(10).string(t.tensorName), t.quantParameterTensorNames != null && t.quantParameterTensorNames.length) for (var r = 0; r < t.quantParameterTensorNames.length; ++r) c.onnx.StringStringEntryProto.encode(t.quantParameterTensorNames[r], n.uint32(18).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.TensorAnnotation(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.tensorName = t.string(); break; } case 2: { s.quantParameterTensorNames && s.quantParameterTensorNames.length || (s.quantParameterTensorNames = []), s.quantParameterTensorNames.push(c.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.tensorName != null && t.hasOwnProperty("tensorName") && !h.isString(t.tensorName)) return "tensorName: string expected"; if (t.quantParameterTensorNames != null && t.hasOwnProperty("quantParameterTensorNames")) { if (!Array.isArray(t.quantParameterTensorNames)) return "quantParameterTensorNames: array expected"; for (var n = 0; n < t.quantParameterTensorNames.length; ++n) { var r = c.onnx.StringStringEntryProto.verify(t.quantParameterTensorNames[n]); if (r) return "quantParameterTensorNames." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.TensorAnnotation) return t; var n = new c.onnx.TensorAnnotation(); if (t.tensorName != null && (n.tensorName = String(t.tensorName)), t.quantParameterTensorNames) { if (!Array.isArray(t.quantParameterTensorNames)) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected"); n.quantParameterTensorNames = []; for (var r = 0; r < t.quantParameterTensorNames.length; ++r) { if (typeof t.quantParameterTensorNames[r] != "object") throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected"); n.quantParameterTensorNames[r] = c.onnx.StringStringEntryProto.fromObject(t.quantParameterTensorNames[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.quantParameterTensorNames = []), n.defaults && (r.tensorName = ""), t.tensorName != null && t.hasOwnProperty("tensorName") && (r.tensorName = t.tensorName), t.quantParameterTensorNames && t.quantParameterTensorNames.length) { r.quantParameterTensorNames = []; for (var s = 0; s < t.quantParameterTensorNames.length; ++s) r.quantParameterTensorNames[s] = c.onnx.StringStringEntryProto.toObject(t.quantParameterTensorNames[s], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorAnnotation"; }, e; })(), a.GraphProto = (function() { function e(o) { if (this.node = [], this.initializer = [], this.sparseInitializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.node = h.emptyArray, e.prototype.name = "", e.prototype.initializer = h.emptyArray, e.prototype.sparseInitializer = h.emptyArray, e.prototype.docString = "", e.prototype.input = h.emptyArray, e.prototype.output = h.emptyArray, e.prototype.valueInfo = h.emptyArray, e.prototype.quantizationAnnotation = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.node != null && t.node.length) for (var r = 0; r < t.node.length; ++r) c.onnx.NodeProto.encode(t.node[r], n.uint32(10).fork()).ldelim(); if (t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(18).string(t.name), t.initializer != null && t.initializer.length) for (var r = 0; r < t.initializer.length; ++r) c.onnx.TensorProto.encode(t.initializer[r], n.uint32(42).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(82).string(t.docString), t.input != null && t.input.length) for (var r = 0; r < t.input.length; ++r) c.onnx.ValueInfoProto.encode(t.input[r], n.uint32(90).fork()).ldelim(); if (t.output != null && t.output.length) for (var r = 0; r < t.output.length; ++r) c.onnx.ValueInfoProto.encode(t.output[r], n.uint32(98).fork()).ldelim(); if (t.valueInfo != null && t.valueInfo.length) for (var r = 0; r < t.valueInfo.length; ++r) c.onnx.ValueInfoProto.encode(t.valueInfo[r], n.uint32(106).fork()).ldelim(); if (t.quantizationAnnotation != null && t.quantizationAnnotation.length) for (var r = 0; r < t.quantizationAnnotation.length; ++r) c.onnx.TensorAnnotation.encode(t.quantizationAnnotation[r], n.uint32(114).fork()).ldelim(); if (t.sparseInitializer != null && t.sparseInitializer.length) for (var r = 0; r < t.sparseInitializer.length; ++r) c.onnx.SparseTensorProto.encode(t.sparseInitializer[r], n.uint32(122).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.GraphProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.node && s.node.length || (s.node = []), s.node.push(c.onnx.NodeProto.decode(t, t.uint32())); break; } case 2: { s.name = t.string(); break; } case 5: { s.initializer && s.initializer.length || (s.initializer = []), s.initializer.push(c.onnx.TensorProto.decode(t, t.uint32())); break; } case 15: { s.sparseInitializer && s.sparseInitializer.length || (s.sparseInitializer = []), s.sparseInitializer.push(c.onnx.SparseTensorProto.decode(t, t.uint32())); break; } case 10: { s.docString = t.string(); break; } case 11: { s.input && s.input.length || (s.input = []), s.input.push(c.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 12: { s.output && s.output.length || (s.output = []), s.output.push(c.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 13: { s.valueInfo && s.valueInfo.length || (s.valueInfo = []), s.valueInfo.push(c.onnx.ValueInfoProto.decode(t, t.uint32())); break; } case 14: { s.quantizationAnnotation && s.quantizationAnnotation.length || (s.quantizationAnnotation = []), s.quantizationAnnotation.push(c.onnx.TensorAnnotation.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.node != null && t.hasOwnProperty("node")) { if (!Array.isArray(t.node)) return "node: array expected"; for (var n = 0; n < t.node.length; ++n) { var r = c.onnx.NodeProto.verify(t.node[n]); if (r) return "node." + r; } } if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.initializer != null && t.hasOwnProperty("initializer")) { if (!Array.isArray(t.initializer)) return "initializer: array expected"; for (var n = 0; n < t.initializer.length; ++n) { var r = c.onnx.TensorProto.verify(t.initializer[n]); if (r) return "initializer." + r; } } if (t.sparseInitializer != null && t.hasOwnProperty("sparseInitializer")) { if (!Array.isArray(t.sparseInitializer)) return "sparseInitializer: array expected"; for (var n = 0; n < t.sparseInitializer.length; ++n) { var r = c.onnx.SparseTensorProto.verify(t.sparseInitializer[n]); if (r) return "sparseInitializer." + r; } } if (t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString)) return "docString: string expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var n = 0; n < t.input.length; ++n) { var r = c.onnx.ValueInfoProto.verify(t.input[n]); if (r) return "input." + r; } } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var n = 0; n < t.output.length; ++n) { var r = c.onnx.ValueInfoProto.verify(t.output[n]); if (r) return "output." + r; } } if (t.valueInfo != null && t.hasOwnProperty("valueInfo")) { if (!Array.isArray(t.valueInfo)) return "valueInfo: array expected"; for (var n = 0; n < t.valueInfo.length; ++n) { var r = c.onnx.ValueInfoProto.verify(t.valueInfo[n]); if (r) return "valueInfo." + r; } } if (t.quantizationAnnotation != null && t.hasOwnProperty("quantizationAnnotation")) { if (!Array.isArray(t.quantizationAnnotation)) return "quantizationAnnotation: array expected"; for (var n = 0; n < t.quantizationAnnotation.length; ++n) { var r = c.onnx.TensorAnnotation.verify(t.quantizationAnnotation[n]); if (r) return "quantizationAnnotation." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.GraphProto) return t; var n = new c.onnx.GraphProto(); if (t.node) { if (!Array.isArray(t.node)) throw TypeError(".onnx.GraphProto.node: array expected"); n.node = []; for (var r = 0; r < t.node.length; ++r) { if (typeof t.node[r] != "object") throw TypeError(".onnx.GraphProto.node: object expected"); n.node[r] = c.onnx.NodeProto.fromObject(t.node[r]); } } if (t.name != null && (n.name = String(t.name)), t.initializer) { if (!Array.isArray(t.initializer)) throw TypeError(".onnx.GraphProto.initializer: array expected"); n.initializer = []; for (var r = 0; r < t.initializer.length; ++r) { if (typeof t.initializer[r] != "object") throw TypeError(".onnx.GraphProto.initializer: object expected"); n.initializer[r] = c.onnx.TensorProto.fromObject(t.initializer[r]); } } if (t.sparseInitializer) { if (!Array.isArray(t.sparseInitializer)) throw TypeError(".onnx.GraphProto.sparseInitializer: array expected"); n.sparseInitializer = []; for (var r = 0; r < t.sparseInitializer.length; ++r) { if (typeof t.sparseInitializer[r] != "object") throw TypeError(".onnx.GraphProto.sparseInitializer: object expected"); n.sparseInitializer[r] = c.onnx.SparseTensorProto.fromObject(t.sparseInitializer[r]); } } if (t.docString != null && (n.docString = String(t.docString)), t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.GraphProto.input: array expected"); n.input = []; for (var r = 0; r < t.input.length; ++r) { if (typeof t.input[r] != "object") throw TypeError(".onnx.GraphProto.input: object expected"); n.input[r] = c.onnx.ValueInfoProto.fromObject(t.input[r]); } } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.GraphProto.output: array expected"); n.output = []; for (var r = 0; r < t.output.length; ++r) { if (typeof t.output[r] != "object") throw TypeError(".onnx.GraphProto.output: object expected"); n.output[r] = c.onnx.ValueInfoProto.fromObject(t.output[r]); } } if (t.valueInfo) { if (!Array.isArray(t.valueInfo)) throw TypeError(".onnx.GraphProto.valueInfo: array expected"); n.valueInfo = []; for (var r = 0; r < t.valueInfo.length; ++r) { if (typeof t.valueInfo[r] != "object") throw TypeError(".onnx.GraphProto.valueInfo: object expected"); n.valueInfo[r] = c.onnx.ValueInfoProto.fromObject(t.valueInfo[r]); } } if (t.quantizationAnnotation) { if (!Array.isArray(t.quantizationAnnotation)) throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected"); n.quantizationAnnotation = []; for (var r = 0; r < t.quantizationAnnotation.length; ++r) { if (typeof t.quantizationAnnotation[r] != "object") throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected"); n.quantizationAnnotation[r] = c.onnx.TensorAnnotation.fromObject(t.quantizationAnnotation[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.node = [], r.initializer = [], r.input = [], r.output = [], r.valueInfo = [], r.quantizationAnnotation = [], r.sparseInitializer = []), n.defaults && (r.name = "", r.docString = ""), t.node && t.node.length) { r.node = []; for (var s = 0; s < t.node.length; ++s) r.node[s] = c.onnx.NodeProto.toObject(t.node[s], n); } if (t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.initializer && t.initializer.length) { r.initializer = []; for (var s = 0; s < t.initializer.length; ++s) r.initializer[s] = c.onnx.TensorProto.toObject(t.initializer[s], n); } if (t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.input && t.input.length) { r.input = []; for (var s = 0; s < t.input.length; ++s) r.input[s] = c.onnx.ValueInfoProto.toObject(t.input[s], n); } if (t.output && t.output.length) { r.output = []; for (var s = 0; s < t.output.length; ++s) r.output[s] = c.onnx.ValueInfoProto.toObject(t.output[s], n); } if (t.valueInfo && t.valueInfo.length) { r.valueInfo = []; for (var s = 0; s < t.valueInfo.length; ++s) r.valueInfo[s] = c.onnx.ValueInfoProto.toObject(t.valueInfo[s], n); } if (t.quantizationAnnotation && t.quantizationAnnotation.length) { r.quantizationAnnotation = []; for (var s = 0; s < t.quantizationAnnotation.length; ++s) r.quantizationAnnotation[s] = c.onnx.TensorAnnotation.toObject(t.quantizationAnnotation[s], n); } if (t.sparseInitializer && t.sparseInitializer.length) { r.sparseInitializer = []; for (var s = 0; s < t.sparseInitializer.length; ++s) r.sparseInitializer[s] = c.onnx.SparseTensorProto.toObject(t.sparseInitializer[s], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.GraphProto"; }, e; })(), a.TensorProto = (function() { function e(o) { if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.dims = h.emptyArray, e.prototype.dataType = 0, e.prototype.segment = null, e.prototype.floatData = h.emptyArray, e.prototype.int32Data = h.emptyArray, e.prototype.stringData = h.emptyArray, e.prototype.int64Data = h.emptyArray, e.prototype.name = "", e.prototype.docString = "", e.prototype.rawData = h.newBuffer([]), e.prototype.externalData = h.emptyArray, e.prototype.dataLocation = 0, e.prototype.doubleData = h.emptyArray, e.prototype.uint64Data = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.dims != null && t.dims.length) { n.uint32(10).fork(); for (var r = 0; r < t.dims.length; ++r) n.int64(t.dims[r]); n.ldelim(); } if (t.dataType != null && Object.hasOwnProperty.call(t, "dataType") && n.uint32(16).int32(t.dataType), t.segment != null && Object.hasOwnProperty.call(t, "segment") && c.onnx.TensorProto.Segment.encode(t.segment, n.uint32(26).fork()).ldelim(), t.floatData != null && t.floatData.length) { n.uint32(34).fork(); for (var r = 0; r < t.floatData.length; ++r) n.float(t.floatData[r]); n.ldelim(); } if (t.int32Data != null && t.int32Data.length) { n.uint32(42).fork(); for (var r = 0; r < t.int32Data.length; ++r) n.int32(t.int32Data[r]); n.ldelim(); } if (t.stringData != null && t.stringData.length) for (var r = 0; r < t.stringData.length; ++r) n.uint32(50).bytes(t.stringData[r]); if (t.int64Data != null && t.int64Data.length) { n.uint32(58).fork(); for (var r = 0; r < t.int64Data.length; ++r) n.int64(t.int64Data[r]); n.ldelim(); } if (t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(66).string(t.name), t.rawData != null && Object.hasOwnProperty.call(t, "rawData") && n.uint32(74).bytes(t.rawData), t.doubleData != null && t.doubleData.length) { n.uint32(82).fork(); for (var r = 0; r < t.doubleData.length; ++r) n.double(t.doubleData[r]); n.ldelim(); } if (t.uint64Data != null && t.uint64Data.length) { n.uint32(90).fork(); for (var r = 0; r < t.uint64Data.length; ++r) n.uint64(t.uint64Data[r]); n.ldelim(); } if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(98).string(t.docString), t.externalData != null && t.externalData.length) for (var r = 0; r < t.externalData.length; ++r) c.onnx.StringStringEntryProto.encode(t.externalData[r], n.uint32(106).fork()).ldelim(); return t.dataLocation != null && Object.hasOwnProperty.call(t, "dataLocation") && n.uint32(112).int32(t.dataLocation), n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.TensorProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { if (s.dims && s.dims.length || (s.dims = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.dims.push(t.int64()); else s.dims.push(t.int64()); break; } case 2: { s.dataType = t.int32(); break; } case 3: { s.segment = c.onnx.TensorProto.Segment.decode(t, t.uint32()); break; } case 4: { if (s.floatData && s.floatData.length || (s.floatData = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.floatData.push(t.float()); else s.floatData.push(t.float()); break; } case 5: { if (s.int32Data && s.int32Data.length || (s.int32Data = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.int32Data.push(t.int32()); else s.int32Data.push(t.int32()); break; } case 6: { s.stringData && s.stringData.length || (s.stringData = []), s.stringData.push(t.bytes()); break; } case 7: { if (s.int64Data && s.int64Data.length || (s.int64Data = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.int64Data.push(t.int64()); else s.int64Data.push(t.int64()); break; } case 8: { s.name = t.string(); break; } case 12: { s.docString = t.string(); break; } case 9: { s.rawData = t.bytes(); break; } case 13: { s.externalData && s.externalData.length || (s.externalData = []), s.externalData.push(c.onnx.StringStringEntryProto.decode(t, t.uint32())); break; } case 14: { s.dataLocation = t.int32(); break; } case 10: { if (s.doubleData && s.doubleData.length || (s.doubleData = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.doubleData.push(t.double()); else s.doubleData.push(t.double()); break; } case 11: { if (s.uint64Data && s.uint64Data.length || (s.uint64Data = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.uint64Data.push(t.uint64()); else s.uint64Data.push(t.uint64()); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.dims != null && t.hasOwnProperty("dims")) { if (!Array.isArray(t.dims)) return "dims: array expected"; for (var n = 0; n < t.dims.length; ++n) if (!h.isInteger(t.dims[n]) && !(t.dims[n] && h.isInteger(t.dims[n].low) && h.isInteger(t.dims[n].high))) return "dims: integer|Long[] expected"; } if (t.dataType != null && t.hasOwnProperty("dataType") && !h.isInteger(t.dataType)) return "dataType: integer expected"; if (t.segment != null && t.hasOwnProperty("segment")) { var r = c.onnx.TensorProto.Segment.verify(t.segment); if (r) return "segment." + r; } if (t.floatData != null && t.hasOwnProperty("floatData")) { if (!Array.isArray(t.floatData)) return "floatData: array expected"; for (var n = 0; n < t.floatData.length; ++n) if (typeof t.floatData[n] != "number") return "floatData: number[] expected"; } if (t.int32Data != null && t.hasOwnProperty("int32Data")) { if (!Array.isArray(t.int32Data)) return "int32Data: array expected"; for (var n = 0; n < t.int32Data.length; ++n) if (!h.isInteger(t.int32Data[n])) return "int32Data: integer[] expected"; } if (t.stringData != null && t.hasOwnProperty("stringData")) { if (!Array.isArray(t.stringData)) return "stringData: array expected"; for (var n = 0; n < t.stringData.length; ++n) if (!(t.stringData[n] && typeof t.stringData[n].length == "number" || h.isString(t.stringData[n]))) return "stringData: buffer[] expected"; } if (t.int64Data != null && t.hasOwnProperty("int64Data")) { if (!Array.isArray(t.int64Data)) return "int64Data: array expected"; for (var n = 0; n < t.int64Data.length; ++n) if (!h.isInteger(t.int64Data[n]) && !(t.int64Data[n] && h.isInteger(t.int64Data[n].low) && h.isInteger(t.int64Data[n].high))) return "int64Data: integer|Long[] expected"; } if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString)) return "docString: string expected"; if (t.rawData != null && t.hasOwnProperty("rawData") && !(t.rawData && typeof t.rawData.length == "number" || h.isString(t.rawData))) return "rawData: buffer expected"; if (t.externalData != null && t.hasOwnProperty("externalData")) { if (!Array.isArray(t.externalData)) return "externalData: array expected"; for (var n = 0; n < t.externalData.length; ++n) { var r = c.onnx.StringStringEntryProto.verify(t.externalData[n]); if (r) return "externalData." + r; } } if (t.dataLocation != null && t.hasOwnProperty("dataLocation")) switch (t.dataLocation) { default: return "dataLocation: enum value expected"; case 0: case 1: break; } if (t.doubleData != null && t.hasOwnProperty("doubleData")) { if (!Array.isArray(t.doubleData)) return "doubleData: array expected"; for (var n = 0; n < t.doubleData.length; ++n) if (typeof t.doubleData[n] != "number") return "doubleData: number[] expected"; } if (t.uint64Data != null && t.hasOwnProperty("uint64Data")) { if (!Array.isArray(t.uint64Data)) return "uint64Data: array expected"; for (var n = 0; n < t.uint64Data.length; ++n) if (!h.isInteger(t.uint64Data[n]) && !(t.uint64Data[n] && h.isInteger(t.uint64Data[n].low) && h.isInteger(t.uint64Data[n].high))) return "uint64Data: integer|Long[] expected"; } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.TensorProto) return t; var n = new c.onnx.TensorProto(); if (t.dims) { if (!Array.isArray(t.dims)) throw TypeError(".onnx.TensorProto.dims: array expected"); n.dims = []; for (var r = 0; r < t.dims.length; ++r) h.Long ? (n.dims[r] = h.Long.fromValue(t.dims[r])).unsigned = false : typeof t.dims[r] == "string" ? n.dims[r] = parseInt(t.dims[r], 10) : typeof t.dims[r] == "number" ? n.dims[r] = t.dims[r] : typeof t.dims[r] == "object" && (n.dims[r] = new h.LongBits(t.dims[r].low >>> 0, t.dims[r].high >>> 0).toNumber()); } if (t.dataType != null && (n.dataType = t.dataType | 0), t.segment != null) { if (typeof t.segment != "object") throw TypeError(".onnx.TensorProto.segment: object expected"); n.segment = c.onnx.TensorProto.Segment.fromObject(t.segment); } if (t.floatData) { if (!Array.isArray(t.floatData)) throw TypeError(".onnx.TensorProto.floatData: array expected"); n.floatData = []; for (var r = 0; r < t.floatData.length; ++r) n.floatData[r] = Number(t.floatData[r]); } if (t.int32Data) { if (!Array.isArray(t.int32Data)) throw TypeError(".onnx.TensorProto.int32Data: array expected"); n.int32Data = []; for (var r = 0; r < t.int32Data.length; ++r) n.int32Data[r] = t.int32Data[r] | 0; } if (t.stringData) { if (!Array.isArray(t.stringData)) throw TypeError(".onnx.TensorProto.stringData: array expected"); n.stringData = []; for (var r = 0; r < t.stringData.length; ++r) typeof t.stringData[r] == "string" ? h.base64.decode(t.stringData[r], n.stringData[r] = h.newBuffer(h.base64.length(t.stringData[r])), 0) : t.stringData[r].length >= 0 && (n.stringData[r] = t.stringData[r]); } if (t.int64Data) { if (!Array.isArray(t.int64Data)) throw TypeError(".onnx.TensorProto.int64Data: array expected"); n.int64Data = []; for (var r = 0; r < t.int64Data.length; ++r) h.Long ? (n.int64Data[r] = h.Long.fromValue(t.int64Data[r])).unsigned = false : typeof t.int64Data[r] == "string" ? n.int64Data[r] = parseInt(t.int64Data[r], 10) : typeof t.int64Data[r] == "number" ? n.int64Data[r] = t.int64Data[r] : typeof t.int64Data[r] == "object" && (n.int64Data[r] = new h.LongBits(t.int64Data[r].low >>> 0, t.int64Data[r].high >>> 0).toNumber()); } if (t.name != null && (n.name = String(t.name)), t.docString != null && (n.docString = String(t.docString)), t.rawData != null && (typeof t.rawData == "string" ? h.base64.decode(t.rawData, n.rawData = h.newBuffer(h.base64.length(t.rawData)), 0) : t.rawData.length >= 0 && (n.rawData = t.rawData)), t.externalData) { if (!Array.isArray(t.externalData)) throw TypeError(".onnx.TensorProto.externalData: array expected"); n.externalData = []; for (var r = 0; r < t.externalData.length; ++r) { if (typeof t.externalData[r] != "object") throw TypeError(".onnx.TensorProto.externalData: object expected"); n.externalData[r] = c.onnx.StringStringEntryProto.fromObject(t.externalData[r]); } } switch (t.dataLocation) { default: if (typeof t.dataLocation == "number") { n.dataLocation = t.dataLocation; break; } break; case "DEFAULT": case 0: n.dataLocation = 0; break; case "EXTERNAL": case 1: n.dataLocation = 1; break; } if (t.doubleData) { if (!Array.isArray(t.doubleData)) throw TypeError(".onnx.TensorProto.doubleData: array expected"); n.doubleData = []; for (var r = 0; r < t.doubleData.length; ++r) n.doubleData[r] = Number(t.doubleData[r]); } if (t.uint64Data) { if (!Array.isArray(t.uint64Data)) throw TypeError(".onnx.TensorProto.uint64Data: array expected"); n.uint64Data = []; for (var r = 0; r < t.uint64Data.length; ++r) h.Long ? (n.uint64Data[r] = h.Long.fromValue(t.uint64Data[r])).unsigned = true : typeof t.uint64Data[r] == "string" ? n.uint64Data[r] = parseInt(t.uint64Data[r], 10) : typeof t.uint64Data[r] == "number" ? n.uint64Data[r] = t.uint64Data[r] : typeof t.uint64Data[r] == "object" && (n.uint64Data[r] = new h.LongBits(t.uint64Data[r].low >>> 0, t.uint64Data[r].high >>> 0).toNumber(true)); } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.dims = [], r.floatData = [], r.int32Data = [], r.stringData = [], r.int64Data = [], r.doubleData = [], r.uint64Data = [], r.externalData = []), n.defaults && (r.dataType = 0, r.segment = null, r.name = "", n.bytes === String ? r.rawData = "" : (r.rawData = [], n.bytes !== Array && (r.rawData = h.newBuffer(r.rawData))), r.docString = "", r.dataLocation = n.enums === String ? "DEFAULT" : 0), t.dims && t.dims.length) { r.dims = []; for (var s = 0; s < t.dims.length; ++s) typeof t.dims[s] == "number" ? r.dims[s] = n.longs === String ? String(t.dims[s]) : t.dims[s] : r.dims[s] = n.longs === String ? h.Long.prototype.toString.call(t.dims[s]) : n.longs === Number ? new h.LongBits(t.dims[s].low >>> 0, t.dims[s].high >>> 0).toNumber() : t.dims[s]; } if (t.dataType != null && t.hasOwnProperty("dataType") && (r.dataType = t.dataType), t.segment != null && t.hasOwnProperty("segment") && (r.segment = c.onnx.TensorProto.Segment.toObject(t.segment, n)), t.floatData && t.floatData.length) { r.floatData = []; for (var s = 0; s < t.floatData.length; ++s) r.floatData[s] = n.json && !isFinite(t.floatData[s]) ? String(t.floatData[s]) : t.floatData[s]; } if (t.int32Data && t.int32Data.length) { r.int32Data = []; for (var s = 0; s < t.int32Data.length; ++s) r.int32Data[s] = t.int32Data[s]; } if (t.stringData && t.stringData.length) { r.stringData = []; for (var s = 0; s < t.stringData.length; ++s) r.stringData[s] = n.bytes === String ? h.base64.encode(t.stringData[s], 0, t.stringData[s].length) : n.bytes === Array ? Array.prototype.slice.call(t.stringData[s]) : t.stringData[s]; } if (t.int64Data && t.int64Data.length) { r.int64Data = []; for (var s = 0; s < t.int64Data.length; ++s) typeof t.int64Data[s] == "number" ? r.int64Data[s] = n.longs === String ? String(t.int64Data[s]) : t.int64Data[s] : r.int64Data[s] = n.longs === String ? h.Long.prototype.toString.call(t.int64Data[s]) : n.longs === Number ? new h.LongBits(t.int64Data[s].low >>> 0, t.int64Data[s].high >>> 0).toNumber() : t.int64Data[s]; } if (t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.rawData != null && t.hasOwnProperty("rawData") && (r.rawData = n.bytes === String ? h.base64.encode(t.rawData, 0, t.rawData.length) : n.bytes === Array ? Array.prototype.slice.call(t.rawData) : t.rawData), t.doubleData && t.doubleData.length) { r.doubleData = []; for (var s = 0; s < t.doubleData.length; ++s) r.doubleData[s] = n.json && !isFinite(t.doubleData[s]) ? String(t.doubleData[s]) : t.doubleData[s]; } if (t.uint64Data && t.uint64Data.length) { r.uint64Data = []; for (var s = 0; s < t.uint64Data.length; ++s) typeof t.uint64Data[s] == "number" ? r.uint64Data[s] = n.longs === String ? String(t.uint64Data[s]) : t.uint64Data[s] : r.uint64Data[s] = n.longs === String ? h.Long.prototype.toString.call(t.uint64Data[s]) : n.longs === Number ? new h.LongBits(t.uint64Data[s].low >>> 0, t.uint64Data[s].high >>> 0).toNumber(true) : t.uint64Data[s]; } if (t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.externalData && t.externalData.length) { r.externalData = []; for (var s = 0; s < t.externalData.length; ++s) r.externalData[s] = c.onnx.StringStringEntryProto.toObject(t.externalData[s], n); } return t.dataLocation != null && t.hasOwnProperty("dataLocation") && (r.dataLocation = n.enums === String ? c.onnx.TensorProto.DataLocation[t.dataLocation] === void 0 ? t.dataLocation : c.onnx.TensorProto.DataLocation[t.dataLocation] : t.dataLocation), r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorProto"; }, e.DataType = (function() { var o = {}, t = Object.create(o); return t[o[0] = "UNDEFINED"] = 0, t[o[1] = "FLOAT"] = 1, t[o[2] = "UINT8"] = 2, t[o[3] = "INT8"] = 3, t[o[4] = "UINT16"] = 4, t[o[5] = "INT16"] = 5, t[o[6] = "INT32"] = 6, t[o[7] = "INT64"] = 7, t[o[8] = "STRING"] = 8, t[o[9] = "BOOL"] = 9, t[o[10] = "FLOAT16"] = 10, t[o[11] = "DOUBLE"] = 11, t[o[12] = "UINT32"] = 12, t[o[13] = "UINT64"] = 13, t[o[14] = "COMPLEX64"] = 14, t[o[15] = "COMPLEX128"] = 15, t[o[16] = "BFLOAT16"] = 16, t[o[17] = "FLOAT8E4M3FN"] = 17, t[o[18] = "FLOAT8E4M3FNUZ"] = 18, t[o[19] = "FLOAT8E5M2"] = 19, t[o[20] = "FLOAT8E5M2FNUZ"] = 20, t; })(), e.Segment = (function() { function o(t) { if (t) for (var n = Object.keys(t), r = 0; r < n.length; ++r) t[n[r]] != null && (this[n[r]] = t[n[r]]); } return o.prototype.begin = h.Long ? h.Long.fromBits(0, 0, false) : 0, o.prototype.end = h.Long ? h.Long.fromBits(0, 0, false) : 0, o.create = function(n) { return new o(n); }, o.encode = function(n, r) { return r || (r = X.create()), n.begin != null && Object.hasOwnProperty.call(n, "begin") && r.uint32(8).int64(n.begin), n.end != null && Object.hasOwnProperty.call(n, "end") && r.uint32(16).int64(n.end), r; }, o.encodeDelimited = function(n, r) { return this.encode(n, r).ldelim(); }, o.decode = function(n, r) { n instanceof w || (n = w.create(n)); for (var s = r === void 0 ? n.len : n.pos + r, i = new c.onnx.TensorProto.Segment(); n.pos < s; ) { var u = n.uint32(); switch (u >>> 3) { case 1: { i.begin = n.int64(); break; } case 2: { i.end = n.int64(); break; } default: n.skipType(u & 7); break; } } return i; }, o.decodeDelimited = function(n) { return n instanceof w || (n = new w(n)), this.decode(n, n.uint32()); }, o.verify = function(n) { return typeof n != "object" || n === null ? "object expected" : n.begin != null && n.hasOwnProperty("begin") && !h.isInteger(n.begin) && !(n.begin && h.isInteger(n.begin.low) && h.isInteger(n.begin.high)) ? "begin: integer|Long expected" : n.end != null && n.hasOwnProperty("end") && !h.isInteger(n.end) && !(n.end && h.isInteger(n.end.low) && h.isInteger(n.end.high)) ? "end: integer|Long expected" : null; }, o.fromObject = function(n) { if (n instanceof c.onnx.TensorProto.Segment) return n; var r = new c.onnx.TensorProto.Segment(); return n.begin != null && (h.Long ? (r.begin = h.Long.fromValue(n.begin)).unsigned = false : typeof n.begin == "string" ? r.begin = parseInt(n.begin, 10) : typeof n.begin == "number" ? r.begin = n.begin : typeof n.begin == "object" && (r.begin = new h.LongBits(n.begin.low >>> 0, n.begin.high >>> 0).toNumber())), n.end != null && (h.Long ? (r.end = h.Long.fromValue(n.end)).unsigned = false : typeof n.end == "string" ? r.end = parseInt(n.end, 10) : typeof n.end == "number" ? r.end = n.end : typeof n.end == "object" && (r.end = new h.LongBits(n.end.low >>> 0, n.end.high >>> 0).toNumber())), r; }, o.toObject = function(n, r) { r || (r = {}); var s = {}; if (r.defaults) { if (h.Long) { var i = new h.Long(0, 0, false); s.begin = r.longs === String ? i.toString() : r.longs === Number ? i.toNumber() : i; } else s.begin = r.longs === String ? "0" : 0; if (h.Long) { var i = new h.Long(0, 0, false); s.end = r.longs === String ? i.toString() : r.longs === Number ? i.toNumber() : i; } else s.end = r.longs === String ? "0" : 0; } return n.begin != null && n.hasOwnProperty("begin") && (typeof n.begin == "number" ? s.begin = r.longs === String ? String(n.begin) : n.begin : s.begin = r.longs === String ? h.Long.prototype.toString.call(n.begin) : r.longs === Number ? new h.LongBits(n.begin.low >>> 0, n.begin.high >>> 0).toNumber() : n.begin), n.end != null && n.hasOwnProperty("end") && (typeof n.end == "number" ? s.end = r.longs === String ? String(n.end) : n.end : s.end = r.longs === String ? h.Long.prototype.toString.call(n.end) : r.longs === Number ? new h.LongBits(n.end.low >>> 0, n.end.high >>> 0).toNumber() : n.end), s; }, o.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, o.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TensorProto.Segment"; }, o; })(), e.DataLocation = (function() { var o = {}, t = Object.create(o); return t[o[0] = "DEFAULT"] = 0, t[o[1] = "EXTERNAL"] = 1, t; })(), e; })(), a.SparseTensorProto = (function() { function e(o) { if (this.dims = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.values = null, e.prototype.indices = null, e.prototype.dims = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.values != null && Object.hasOwnProperty.call(t, "values") && c.onnx.TensorProto.encode(t.values, n.uint32(10).fork()).ldelim(), t.indices != null && Object.hasOwnProperty.call(t, "indices") && c.onnx.TensorProto.encode(t.indices, n.uint32(18).fork()).ldelim(), t.dims != null && t.dims.length) { n.uint32(26).fork(); for (var r = 0; r < t.dims.length; ++r) n.int64(t.dims[r]); n.ldelim(); } return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.SparseTensorProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.values = c.onnx.TensorProto.decode(t, t.uint32()); break; } case 2: { s.indices = c.onnx.TensorProto.decode(t, t.uint32()); break; } case 3: { if (s.dims && s.dims.length || (s.dims = []), (i & 7) === 2) for (var u = t.uint32() + t.pos; t.pos < u; ) s.dims.push(t.int64()); else s.dims.push(t.int64()); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.values != null && t.hasOwnProperty("values")) { var n = c.onnx.TensorProto.verify(t.values); if (n) return "values." + n; } if (t.indices != null && t.hasOwnProperty("indices")) { var n = c.onnx.TensorProto.verify(t.indices); if (n) return "indices." + n; } if (t.dims != null && t.hasOwnProperty("dims")) { if (!Array.isArray(t.dims)) return "dims: array expected"; for (var r = 0; r < t.dims.length; ++r) if (!h.isInteger(t.dims[r]) && !(t.dims[r] && h.isInteger(t.dims[r].low) && h.isInteger(t.dims[r].high))) return "dims: integer|Long[] expected"; } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.SparseTensorProto) return t; var n = new c.onnx.SparseTensorProto(); if (t.values != null) { if (typeof t.values != "object") throw TypeError(".onnx.SparseTensorProto.values: object expected"); n.values = c.onnx.TensorProto.fromObject(t.values); } if (t.indices != null) { if (typeof t.indices != "object") throw TypeError(".onnx.SparseTensorProto.indices: object expected"); n.indices = c.onnx.TensorProto.fromObject(t.indices); } if (t.dims) { if (!Array.isArray(t.dims)) throw TypeError(".onnx.SparseTensorProto.dims: array expected"); n.dims = []; for (var r = 0; r < t.dims.length; ++r) h.Long ? (n.dims[r] = h.Long.fromValue(t.dims[r])).unsigned = false : typeof t.dims[r] == "string" ? n.dims[r] = parseInt(t.dims[r], 10) : typeof t.dims[r] == "number" ? n.dims[r] = t.dims[r] : typeof t.dims[r] == "object" && (n.dims[r] = new h.LongBits(t.dims[r].low >>> 0, t.dims[r].high >>> 0).toNumber()); } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.dims = []), n.defaults && (r.values = null, r.indices = null), t.values != null && t.hasOwnProperty("values") && (r.values = c.onnx.TensorProto.toObject(t.values, n)), t.indices != null && t.hasOwnProperty("indices") && (r.indices = c.onnx.TensorProto.toObject(t.indices, n)), t.dims && t.dims.length) { r.dims = []; for (var s = 0; s < t.dims.length; ++s) typeof t.dims[s] == "number" ? r.dims[s] = n.longs === String ? String(t.dims[s]) : t.dims[s] : r.dims[s] = n.longs === String ? h.Long.prototype.toString.call(t.dims[s]) : n.longs === Number ? new h.LongBits(t.dims[s].low >>> 0, t.dims[s].high >>> 0).toNumber() : t.dims[s]; } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.SparseTensorProto"; }, e; })(), a.TensorShapeProto = (function() { function e(o) { if (this.dim = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.dim = h.emptyArray, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.dim != null && t.dim.length) for (var r = 0; r < t.dim.length; ++r) c.onnx.TensorShapeProto.Dimension.encode(t.dim[r], n.uint32(10).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.TensorShapeProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.dim && s.dim.length || (s.dim = []), s.dim.push(c.onnx.TensorShapeProto.Dimension.decode(t, t.uint32())); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.dim != null && t.hasOwnProperty("dim")) { if (!Array.isArray(t.dim)) return "dim: array expected"; for (var n = 0; n < t.dim.length; ++n) { var r = c.onnx.TensorShapeProto.Dimension.verify(t.dim[n]); if (r) return "dim." + r; } } return null; }, e.fromObject = function(t) { if (t instanceof c.onnx.TensorShapeProto) return t; var n = new c.onnx.TensorShapeProto(); if (t.dim) { if (!Array.isArray(t.dim)) throw TypeError(".onnx.TensorShapeProto.dim: array expected"); n.dim = []; for (var r = 0; r < t.dim.length; ++r) { if (typeof t.dim[r] != "object") throw TypeError(".onnx.TensorShapeProto.dim: object expected"); n.dim[r] = c.onnx.TensorShapeProto.Dimension.fromObject(t.dim[r]); } } return n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.dim = []), t.dim && t.dim.length) { r.dim = []; for (var s = 0; s < t.dim.length; ++s) r.dim[s] = c.onnx.TensorShapeProto.Dimension.toObject(t.dim[s], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.TensorShapeProto"; }, e.Dimension = (function() { function o(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } o.prototype.dimValue = null, o.prototype.dimParam = null, o.prototype.denotation = ""; var t; return Object.defineProperty(o.prototype, "value", { get: h.oneOfGetter(t = ["dimValue", "dimParam"]), set: h.oneOfSetter(t) }), o.create = function(r) { return new o(r); }, o.encode = function(r, s) { return s || (s = X.create()), r.dimValue != null && Object.hasOwnProperty.call(r, "dimValue") && s.uint32(8).int64(r.dimValue), r.dimParam != null && Object.hasOwnProperty.call(r, "dimParam") && s.uint32(18).string(r.dimParam), r.denotation != null && Object.hasOwnProperty.call(r, "denotation") && s.uint32(26).string(r.denotation), s; }, o.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, o.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TensorShapeProto.Dimension(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.dimValue = r.int64(); break; } case 2: { u.dimParam = r.string(); break; } case 3: { u.denotation = r.string(); break; } default: r.skipType(l & 7); break; } } return u; }, o.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, o.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; var s = {}; if (r.dimValue != null && r.hasOwnProperty("dimValue") && (s.value = 1, !h.isInteger(r.dimValue) && !(r.dimValue && h.isInteger(r.dimValue.low) && h.isInteger(r.dimValue.high)))) return "dimValue: integer|Long expected"; if (r.dimParam != null && r.hasOwnProperty("dimParam")) { if (s.value === 1) return "value: multiple values"; if (s.value = 1, !h.isString(r.dimParam)) return "dimParam: string expected"; } return r.denotation != null && r.hasOwnProperty("denotation") && !h.isString(r.denotation) ? "denotation: string expected" : null; }, o.fromObject = function(r) { if (r instanceof c.onnx.TensorShapeProto.Dimension) return r; var s = new c.onnx.TensorShapeProto.Dimension(); return r.dimValue != null && (h.Long ? (s.dimValue = h.Long.fromValue(r.dimValue)).unsigned = false : typeof r.dimValue == "string" ? s.dimValue = parseInt(r.dimValue, 10) : typeof r.dimValue == "number" ? s.dimValue = r.dimValue : typeof r.dimValue == "object" && (s.dimValue = new h.LongBits(r.dimValue.low >>> 0, r.dimValue.high >>> 0).toNumber())), r.dimParam != null && (s.dimParam = String(r.dimParam)), r.denotation != null && (s.denotation = String(r.denotation)), s; }, o.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.denotation = ""), r.dimValue != null && r.hasOwnProperty("dimValue") && (typeof r.dimValue == "number" ? i.dimValue = s.longs === String ? String(r.dimValue) : r.dimValue : i.dimValue = s.longs === String ? h.Long.prototype.toString.call(r.dimValue) : s.longs === Number ? new h.LongBits(r.dimValue.low >>> 0, r.dimValue.high >>> 0).toNumber() : r.dimValue, s.oneofs && (i.value = "dimValue")), r.dimParam != null && r.hasOwnProperty("dimParam") && (i.dimParam = r.dimParam, s.oneofs && (i.value = "dimParam")), r.denotation != null && r.hasOwnProperty("denotation") && (i.denotation = r.denotation), i; }, o.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, o.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TensorShapeProto.Dimension"; }, o; })(), e; })(), a.TypeProto = (function() { function e(t) { if (t) for (var n = Object.keys(t), r = 0; r < n.length; ++r) t[n[r]] != null && (this[n[r]] = t[n[r]]); } e.prototype.tensorType = null, e.prototype.sequenceType = null, e.prototype.mapType = null, e.prototype.optionalType = null, e.prototype.sparseTensorType = null, e.prototype.denotation = ""; var o; return Object.defineProperty(e.prototype, "value", { get: h.oneOfGetter(o = ["tensorType", "sequenceType", "mapType", "optionalType", "sparseTensorType"]), set: h.oneOfSetter(o) }), e.create = function(n) { return new e(n); }, e.encode = function(n, r) { return r || (r = X.create()), n.tensorType != null && Object.hasOwnProperty.call(n, "tensorType") && c.onnx.TypeProto.Tensor.encode(n.tensorType, r.uint32(10).fork()).ldelim(), n.sequenceType != null && Object.hasOwnProperty.call(n, "sequenceType") && c.onnx.TypeProto.Sequence.encode(n.sequenceType, r.uint32(34).fork()).ldelim(), n.mapType != null && Object.hasOwnProperty.call(n, "mapType") && c.onnx.TypeProto.Map.encode(n.mapType, r.uint32(42).fork()).ldelim(), n.denotation != null && Object.hasOwnProperty.call(n, "denotation") && r.uint32(50).string(n.denotation), n.sparseTensorType != null && Object.hasOwnProperty.call(n, "sparseTensorType") && c.onnx.TypeProto.SparseTensor.encode(n.sparseTensorType, r.uint32(66).fork()).ldelim(), n.optionalType != null && Object.hasOwnProperty.call(n, "optionalType") && c.onnx.TypeProto.Optional.encode(n.optionalType, r.uint32(74).fork()).ldelim(), r; }, e.encodeDelimited = function(n, r) { return this.encode(n, r).ldelim(); }, e.decode = function(n, r) { n instanceof w || (n = w.create(n)); for (var s = r === void 0 ? n.len : n.pos + r, i = new c.onnx.TypeProto(); n.pos < s; ) { var u = n.uint32(); switch (u >>> 3) { case 1: { i.tensorType = c.onnx.TypeProto.Tensor.decode(n, n.uint32()); break; } case 4: { i.sequenceType = c.onnx.TypeProto.Sequence.decode(n, n.uint32()); break; } case 5: { i.mapType = c.onnx.TypeProto.Map.decode(n, n.uint32()); break; } case 9: { i.optionalType = c.onnx.TypeProto.Optional.decode(n, n.uint32()); break; } case 8: { i.sparseTensorType = c.onnx.TypeProto.SparseTensor.decode(n, n.uint32()); break; } case 6: { i.denotation = n.string(); break; } default: n.skipType(u & 7); break; } } return i; }, e.decodeDelimited = function(n) { return n instanceof w || (n = new w(n)), this.decode(n, n.uint32()); }, e.verify = function(n) { if (typeof n != "object" || n === null) return "object expected"; var r = {}; if (n.tensorType != null && n.hasOwnProperty("tensorType")) { r.value = 1; { var s = c.onnx.TypeProto.Tensor.verify(n.tensorType); if (s) return "tensorType." + s; } } if (n.sequenceType != null && n.hasOwnProperty("sequenceType")) { if (r.value === 1) return "value: multiple values"; r.value = 1; { var s = c.onnx.TypeProto.Sequence.verify(n.sequenceType); if (s) return "sequenceType." + s; } } if (n.mapType != null && n.hasOwnProperty("mapType")) { if (r.value === 1) return "value: multiple values"; r.value = 1; { var s = c.onnx.TypeProto.Map.verify(n.mapType); if (s) return "mapType." + s; } } if (n.optionalType != null && n.hasOwnProperty("optionalType")) { if (r.value === 1) return "value: multiple values"; r.value = 1; { var s = c.onnx.TypeProto.Optional.verify(n.optionalType); if (s) return "optionalType." + s; } } if (n.sparseTensorType != null && n.hasOwnProperty("sparseTensorType")) { if (r.value === 1) return "value: multiple values"; r.value = 1; { var s = c.onnx.TypeProto.SparseTensor.verify(n.sparseTensorType); if (s) return "sparseTensorType." + s; } } return n.denotation != null && n.hasOwnProperty("denotation") && !h.isString(n.denotation) ? "denotation: string expected" : null; }, e.fromObject = function(n) { if (n instanceof c.onnx.TypeProto) return n; var r = new c.onnx.TypeProto(); if (n.tensorType != null) { if (typeof n.tensorType != "object") throw TypeError(".onnx.TypeProto.tensorType: object expected"); r.tensorType = c.onnx.TypeProto.Tensor.fromObject(n.tensorType); } if (n.sequenceType != null) { if (typeof n.sequenceType != "object") throw TypeError(".onnx.TypeProto.sequenceType: object expected"); r.sequenceType = c.onnx.TypeProto.Sequence.fromObject(n.sequenceType); } if (n.mapType != null) { if (typeof n.mapType != "object") throw TypeError(".onnx.TypeProto.mapType: object expected"); r.mapType = c.onnx.TypeProto.Map.fromObject(n.mapType); } if (n.optionalType != null) { if (typeof n.optionalType != "object") throw TypeError(".onnx.TypeProto.optionalType: object expected"); r.optionalType = c.onnx.TypeProto.Optional.fromObject(n.optionalType); } if (n.sparseTensorType != null) { if (typeof n.sparseTensorType != "object") throw TypeError(".onnx.TypeProto.sparseTensorType: object expected"); r.sparseTensorType = c.onnx.TypeProto.SparseTensor.fromObject(n.sparseTensorType); } return n.denotation != null && (r.denotation = String(n.denotation)), r; }, e.toObject = function(n, r) { r || (r = {}); var s = {}; return r.defaults && (s.denotation = ""), n.tensorType != null && n.hasOwnProperty("tensorType") && (s.tensorType = c.onnx.TypeProto.Tensor.toObject(n.tensorType, r), r.oneofs && (s.value = "tensorType")), n.sequenceType != null && n.hasOwnProperty("sequenceType") && (s.sequenceType = c.onnx.TypeProto.Sequence.toObject(n.sequenceType, r), r.oneofs && (s.value = "sequenceType")), n.mapType != null && n.hasOwnProperty("mapType") && (s.mapType = c.onnx.TypeProto.Map.toObject(n.mapType, r), r.oneofs && (s.value = "mapType")), n.denotation != null && n.hasOwnProperty("denotation") && (s.denotation = n.denotation), n.sparseTensorType != null && n.hasOwnProperty("sparseTensorType") && (s.sparseTensorType = c.onnx.TypeProto.SparseTensor.toObject(n.sparseTensorType, r), r.oneofs && (s.value = "sparseTensorType")), n.optionalType != null && n.hasOwnProperty("optionalType") && (s.optionalType = c.onnx.TypeProto.Optional.toObject(n.optionalType, r), r.oneofs && (s.value = "optionalType")), s; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(n) { return n === void 0 && (n = "type.googleapis.com"), n + "/onnx.TypeProto"; }, e.Tensor = (function() { function t(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } return t.prototype.elemType = 0, t.prototype.shape = null, t.create = function(r) { return new t(r); }, t.encode = function(r, s) { return s || (s = X.create()), r.elemType != null && Object.hasOwnProperty.call(r, "elemType") && s.uint32(8).int32(r.elemType), r.shape != null && Object.hasOwnProperty.call(r, "shape") && c.onnx.TensorShapeProto.encode(r.shape, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, t.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TypeProto.Tensor(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.elemType = r.int32(); break; } case 2: { u.shape = c.onnx.TensorShapeProto.decode(r, r.uint32()); break; } default: r.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, t.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; if (r.elemType != null && r.hasOwnProperty("elemType") && !h.isInteger(r.elemType)) return "elemType: integer expected"; if (r.shape != null && r.hasOwnProperty("shape")) { var s = c.onnx.TensorShapeProto.verify(r.shape); if (s) return "shape." + s; } return null; }, t.fromObject = function(r) { if (r instanceof c.onnx.TypeProto.Tensor) return r; var s = new c.onnx.TypeProto.Tensor(); if (r.elemType != null && (s.elemType = r.elemType | 0), r.shape != null) { if (typeof r.shape != "object") throw TypeError(".onnx.TypeProto.Tensor.shape: object expected"); s.shape = c.onnx.TensorShapeProto.fromObject(r.shape); } return s; }, t.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.elemType = 0, i.shape = null), r.elemType != null && r.hasOwnProperty("elemType") && (i.elemType = r.elemType), r.shape != null && r.hasOwnProperty("shape") && (i.shape = c.onnx.TensorShapeProto.toObject(r.shape, s)), i; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, t.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto.Tensor"; }, t; })(), e.Sequence = (function() { function t(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } return t.prototype.elemType = null, t.create = function(r) { return new t(r); }, t.encode = function(r, s) { return s || (s = X.create()), r.elemType != null && Object.hasOwnProperty.call(r, "elemType") && c.onnx.TypeProto.encode(r.elemType, s.uint32(10).fork()).ldelim(), s; }, t.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, t.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TypeProto.Sequence(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.elemType = c.onnx.TypeProto.decode(r, r.uint32()); break; } default: r.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, t.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; if (r.elemType != null && r.hasOwnProperty("elemType")) { var s = c.onnx.TypeProto.verify(r.elemType); if (s) return "elemType." + s; } return null; }, t.fromObject = function(r) { if (r instanceof c.onnx.TypeProto.Sequence) return r; var s = new c.onnx.TypeProto.Sequence(); if (r.elemType != null) { if (typeof r.elemType != "object") throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected"); s.elemType = c.onnx.TypeProto.fromObject(r.elemType); } return s; }, t.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.elemType = null), r.elemType != null && r.hasOwnProperty("elemType") && (i.elemType = c.onnx.TypeProto.toObject(r.elemType, s)), i; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, t.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto.Sequence"; }, t; })(), e.Map = (function() { function t(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } return t.prototype.keyType = 0, t.prototype.valueType = null, t.create = function(r) { return new t(r); }, t.encode = function(r, s) { return s || (s = X.create()), r.keyType != null && Object.hasOwnProperty.call(r, "keyType") && s.uint32(8).int32(r.keyType), r.valueType != null && Object.hasOwnProperty.call(r, "valueType") && c.onnx.TypeProto.encode(r.valueType, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, t.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TypeProto.Map(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.keyType = r.int32(); break; } case 2: { u.valueType = c.onnx.TypeProto.decode(r, r.uint32()); break; } default: r.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, t.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; if (r.keyType != null && r.hasOwnProperty("keyType") && !h.isInteger(r.keyType)) return "keyType: integer expected"; if (r.valueType != null && r.hasOwnProperty("valueType")) { var s = c.onnx.TypeProto.verify(r.valueType); if (s) return "valueType." + s; } return null; }, t.fromObject = function(r) { if (r instanceof c.onnx.TypeProto.Map) return r; var s = new c.onnx.TypeProto.Map(); if (r.keyType != null && (s.keyType = r.keyType | 0), r.valueType != null) { if (typeof r.valueType != "object") throw TypeError(".onnx.TypeProto.Map.valueType: object expected"); s.valueType = c.onnx.TypeProto.fromObject(r.valueType); } return s; }, t.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.keyType = 0, i.valueType = null), r.keyType != null && r.hasOwnProperty("keyType") && (i.keyType = r.keyType), r.valueType != null && r.hasOwnProperty("valueType") && (i.valueType = c.onnx.TypeProto.toObject(r.valueType, s)), i; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, t.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto.Map"; }, t; })(), e.Optional = (function() { function t(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } return t.prototype.elemType = null, t.create = function(r) { return new t(r); }, t.encode = function(r, s) { return s || (s = X.create()), r.elemType != null && Object.hasOwnProperty.call(r, "elemType") && c.onnx.TypeProto.encode(r.elemType, s.uint32(10).fork()).ldelim(), s; }, t.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, t.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TypeProto.Optional(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.elemType = c.onnx.TypeProto.decode(r, r.uint32()); break; } default: r.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, t.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; if (r.elemType != null && r.hasOwnProperty("elemType")) { var s = c.onnx.TypeProto.verify(r.elemType); if (s) return "elemType." + s; } return null; }, t.fromObject = function(r) { if (r instanceof c.onnx.TypeProto.Optional) return r; var s = new c.onnx.TypeProto.Optional(); if (r.elemType != null) { if (typeof r.elemType != "object") throw TypeError(".onnx.TypeProto.Optional.elemType: object expected"); s.elemType = c.onnx.TypeProto.fromObject(r.elemType); } return s; }, t.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.elemType = null), r.elemType != null && r.hasOwnProperty("elemType") && (i.elemType = c.onnx.TypeProto.toObject(r.elemType, s)), i; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, t.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto.Optional"; }, t; })(), e.SparseTensor = (function() { function t(n) { if (n) for (var r = Object.keys(n), s = 0; s < r.length; ++s) n[r[s]] != null && (this[r[s]] = n[r[s]]); } return t.prototype.elemType = 0, t.prototype.shape = null, t.create = function(r) { return new t(r); }, t.encode = function(r, s) { return s || (s = X.create()), r.elemType != null && Object.hasOwnProperty.call(r, "elemType") && s.uint32(8).int32(r.elemType), r.shape != null && Object.hasOwnProperty.call(r, "shape") && c.onnx.TensorShapeProto.encode(r.shape, s.uint32(18).fork()).ldelim(), s; }, t.encodeDelimited = function(r, s) { return this.encode(r, s).ldelim(); }, t.decode = function(r, s) { r instanceof w || (r = w.create(r)); for (var i = s === void 0 ? r.len : r.pos + s, u = new c.onnx.TypeProto.SparseTensor(); r.pos < i; ) { var l = r.uint32(); switch (l >>> 3) { case 1: { u.elemType = r.int32(); break; } case 2: { u.shape = c.onnx.TensorShapeProto.decode(r, r.uint32()); break; } default: r.skipType(l & 7); break; } } return u; }, t.decodeDelimited = function(r) { return r instanceof w || (r = new w(r)), this.decode(r, r.uint32()); }, t.verify = function(r) { if (typeof r != "object" || r === null) return "object expected"; if (r.elemType != null && r.hasOwnProperty("elemType") && !h.isInteger(r.elemType)) return "elemType: integer expected"; if (r.shape != null && r.hasOwnProperty("shape")) { var s = c.onnx.TensorShapeProto.verify(r.shape); if (s) return "shape." + s; } return null; }, t.fromObject = function(r) { if (r instanceof c.onnx.TypeProto.SparseTensor) return r; var s = new c.onnx.TypeProto.SparseTensor(); if (r.elemType != null && (s.elemType = r.elemType | 0), r.shape != null) { if (typeof r.shape != "object") throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected"); s.shape = c.onnx.TensorShapeProto.fromObject(r.shape); } return s; }, t.toObject = function(r, s) { s || (s = {}); var i = {}; return s.defaults && (i.elemType = 0, i.shape = null), r.elemType != null && r.hasOwnProperty("elemType") && (i.elemType = r.elemType), r.shape != null && r.hasOwnProperty("shape") && (i.shape = c.onnx.TensorShapeProto.toObject(r.shape, s)), i; }, t.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, t.getTypeUrl = function(r) { return r === void 0 && (r = "type.googleapis.com"), r + "/onnx.TypeProto.SparseTensor"; }, t; })(), e; })(), a.OperatorSetIdProto = (function() { function e(o) { if (o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.domain = "", e.prototype.version = h.Long ? h.Long.fromBits(0, 0, false) : 0, e.create = function(t) { return new e(t); }, e.encode = function(t, n) { return n || (n = X.create()), t.domain != null && Object.hasOwnProperty.call(t, "domain") && n.uint32(10).string(t.domain), t.version != null && Object.hasOwnProperty.call(t, "version") && n.uint32(16).int64(t.version), n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.OperatorSetIdProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.domain = t.string(); break; } case 2: { s.version = t.int64(); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { return typeof t != "object" || t === null ? "object expected" : t.domain != null && t.hasOwnProperty("domain") && !h.isString(t.domain) ? "domain: string expected" : t.version != null && t.hasOwnProperty("version") && !h.isInteger(t.version) && !(t.version && h.isInteger(t.version.low) && h.isInteger(t.version.high)) ? "version: integer|Long expected" : null; }, e.fromObject = function(t) { if (t instanceof c.onnx.OperatorSetIdProto) return t; var n = new c.onnx.OperatorSetIdProto(); return t.domain != null && (n.domain = String(t.domain)), t.version != null && (h.Long ? (n.version = h.Long.fromValue(t.version)).unsigned = false : typeof t.version == "string" ? n.version = parseInt(t.version, 10) : typeof t.version == "number" ? n.version = t.version : typeof t.version == "object" && (n.version = new h.LongBits(t.version.low >>> 0, t.version.high >>> 0).toNumber())), n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if (n.defaults) if (r.domain = "", h.Long) { var s = new h.Long(0, 0, false); r.version = n.longs === String ? s.toString() : n.longs === Number ? s.toNumber() : s; } else r.version = n.longs === String ? "0" : 0; return t.domain != null && t.hasOwnProperty("domain") && (r.domain = t.domain), t.version != null && t.hasOwnProperty("version") && (typeof t.version == "number" ? r.version = n.longs === String ? String(t.version) : t.version : r.version = n.longs === String ? h.Long.prototype.toString.call(t.version) : n.longs === Number ? new h.LongBits(t.version.low >>> 0, t.version.high >>> 0).toNumber() : t.version), r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.OperatorSetIdProto"; }, e; })(), a.OperatorStatus = (function() { var e = {}, o = Object.create(e); return o[e[0] = "EXPERIMENTAL"] = 0, o[e[1] = "STABLE"] = 1, o; })(), a.FunctionProto = (function() { function e(o) { if (this.input = [], this.output = [], this.attribute = [], this.attributeProto = [], this.node = [], this.opsetImport = [], o) for (var t = Object.keys(o), n = 0; n < t.length; ++n) o[t[n]] != null && (this[t[n]] = o[t[n]]); } return e.prototype.name = "", e.prototype.input = h.emptyArray, e.prototype.output = h.emptyArray, e.prototype.attribute = h.emptyArray, e.prototype.attributeProto = h.emptyArray, e.prototype.node = h.emptyArray, e.prototype.docString = "", e.prototype.opsetImport = h.emptyArray, e.prototype.domain = "", e.create = function(t) { return new e(t); }, e.encode = function(t, n) { if (n || (n = X.create()), t.name != null && Object.hasOwnProperty.call(t, "name") && n.uint32(10).string(t.name), t.input != null && t.input.length) for (var r = 0; r < t.input.length; ++r) n.uint32(34).string(t.input[r]); if (t.output != null && t.output.length) for (var r = 0; r < t.output.length; ++r) n.uint32(42).string(t.output[r]); if (t.attribute != null && t.attribute.length) for (var r = 0; r < t.attribute.length; ++r) n.uint32(50).string(t.attribute[r]); if (t.node != null && t.node.length) for (var r = 0; r < t.node.length; ++r) c.onnx.NodeProto.encode(t.node[r], n.uint32(58).fork()).ldelim(); if (t.docString != null && Object.hasOwnProperty.call(t, "docString") && n.uint32(66).string(t.docString), t.opsetImport != null && t.opsetImport.length) for (var r = 0; r < t.opsetImport.length; ++r) c.onnx.OperatorSetIdProto.encode(t.opsetImport[r], n.uint32(74).fork()).ldelim(); if (t.domain != null && Object.hasOwnProperty.call(t, "domain") && n.uint32(82).string(t.domain), t.attributeProto != null && t.attributeProto.length) for (var r = 0; r < t.attributeProto.length; ++r) c.onnx.AttributeProto.encode(t.attributeProto[r], n.uint32(90).fork()).ldelim(); return n; }, e.encodeDelimited = function(t, n) { return this.encode(t, n).ldelim(); }, e.decode = function(t, n) { t instanceof w || (t = w.create(t)); for (var r = n === void 0 ? t.len : t.pos + n, s = new c.onnx.FunctionProto(); t.pos < r; ) { var i = t.uint32(); switch (i >>> 3) { case 1: { s.name = t.string(); break; } case 4: { s.input && s.input.length || (s.input = []), s.input.push(t.string()); break; } case 5: { s.output && s.output.length || (s.output = []), s.output.push(t.string()); break; } case 6: { s.attribute && s.attribute.length || (s.attribute = []), s.attribute.push(t.string()); break; } case 11: { s.attributeProto && s.attributeProto.length || (s.attributeProto = []), s.attributeProto.push(c.onnx.AttributeProto.decode(t, t.uint32())); break; } case 7: { s.node && s.node.length || (s.node = []), s.node.push(c.onnx.NodeProto.decode(t, t.uint32())); break; } case 8: { s.docString = t.string(); break; } case 9: { s.opsetImport && s.opsetImport.length || (s.opsetImport = []), s.opsetImport.push(c.onnx.OperatorSetIdProto.decode(t, t.uint32())); break; } case 10: { s.domain = t.string(); break; } default: t.skipType(i & 7); break; } } return s; }, e.decodeDelimited = function(t) { return t instanceof w || (t = new w(t)), this.decode(t, t.uint32()); }, e.verify = function(t) { if (typeof t != "object" || t === null) return "object expected"; if (t.name != null && t.hasOwnProperty("name") && !h.isString(t.name)) return "name: string expected"; if (t.input != null && t.hasOwnProperty("input")) { if (!Array.isArray(t.input)) return "input: array expected"; for (var n = 0; n < t.input.length; ++n) if (!h.isString(t.input[n])) return "input: string[] expected"; } if (t.output != null && t.hasOwnProperty("output")) { if (!Array.isArray(t.output)) return "output: array expected"; for (var n = 0; n < t.output.length; ++n) if (!h.isString(t.output[n])) return "output: string[] expected"; } if (t.attribute != null && t.hasOwnProperty("attribute")) { if (!Array.isArray(t.attribute)) return "attribute: array expected"; for (var n = 0; n < t.attribute.length; ++n) if (!h.isString(t.attribute[n])) return "attribute: string[] expected"; } if (t.attributeProto != null && t.hasOwnProperty("attributeProto")) { if (!Array.isArray(t.attributeProto)) return "attributeProto: array expected"; for (var n = 0; n < t.attributeProto.length; ++n) { var r = c.onnx.AttributeProto.verify(t.attributeProto[n]); if (r) return "attributeProto." + r; } } if (t.node != null && t.hasOwnProperty("node")) { if (!Array.isArray(t.node)) return "node: array expected"; for (var n = 0; n < t.node.length; ++n) { var r = c.onnx.NodeProto.verify(t.node[n]); if (r) return "node." + r; } } if (t.docString != null && t.hasOwnProperty("docString") && !h.isString(t.docString)) return "docString: string expected"; if (t.opsetImport != null && t.hasOwnProperty("opsetImport")) { if (!Array.isArray(t.opsetImport)) return "opsetImport: array expected"; for (var n = 0; n < t.opsetImport.length; ++n) { var r = c.onnx.OperatorSetIdProto.verify(t.opsetImport[n]); if (r) return "opsetImport." + r; } } return t.domain != null && t.hasOwnProperty("domain") && !h.isString(t.domain) ? "domain: string expected" : null; }, e.fromObject = function(t) { if (t instanceof c.onnx.FunctionProto) return t; var n = new c.onnx.FunctionProto(); if (t.name != null && (n.name = String(t.name)), t.input) { if (!Array.isArray(t.input)) throw TypeError(".onnx.FunctionProto.input: array expected"); n.input = []; for (var r = 0; r < t.input.length; ++r) n.input[r] = String(t.input[r]); } if (t.output) { if (!Array.isArray(t.output)) throw TypeError(".onnx.FunctionProto.output: array expected"); n.output = []; for (var r = 0; r < t.output.length; ++r) n.output[r] = String(t.output[r]); } if (t.attribute) { if (!Array.isArray(t.attribute)) throw TypeError(".onnx.FunctionProto.attribute: array expected"); n.attribute = []; for (var r = 0; r < t.attribute.length; ++r) n.attribute[r] = String(t.attribute[r]); } if (t.attributeProto) { if (!Array.isArray(t.attributeProto)) throw TypeError(".onnx.FunctionProto.attributeProto: array expected"); n.attributeProto = []; for (var r = 0; r < t.attributeProto.length; ++r) { if (typeof t.attributeProto[r] != "object") throw TypeError(".onnx.FunctionProto.attributeProto: object expected"); n.attributeProto[r] = c.onnx.AttributeProto.fromObject(t.attributeProto[r]); } } if (t.node) { if (!Array.isArray(t.node)) throw TypeError(".onnx.FunctionProto.node: array expected"); n.node = []; for (var r = 0; r < t.node.length; ++r) { if (typeof t.node[r] != "object") throw TypeError(".onnx.FunctionProto.node: object expected"); n.node[r] = c.onnx.NodeProto.fromObject(t.node[r]); } } if (t.docString != null && (n.docString = String(t.docString)), t.opsetImport) { if (!Array.isArray(t.opsetImport)) throw TypeError(".onnx.FunctionProto.opsetImport: array expected"); n.opsetImport = []; for (var r = 0; r < t.opsetImport.length; ++r) { if (typeof t.opsetImport[r] != "object") throw TypeError(".onnx.FunctionProto.opsetImport: object expected"); n.opsetImport[r] = c.onnx.OperatorSetIdProto.fromObject(t.opsetImport[r]); } } return t.domain != null && (n.domain = String(t.domain)), n; }, e.toObject = function(t, n) { n || (n = {}); var r = {}; if ((n.arrays || n.defaults) && (r.input = [], r.output = [], r.attribute = [], r.node = [], r.opsetImport = [], r.attributeProto = []), n.defaults && (r.name = "", r.docString = "", r.domain = ""), t.name != null && t.hasOwnProperty("name") && (r.name = t.name), t.input && t.input.length) { r.input = []; for (var s = 0; s < t.input.length; ++s) r.input[s] = t.input[s]; } if (t.output && t.output.length) { r.output = []; for (var s = 0; s < t.output.length; ++s) r.output[s] = t.output[s]; } if (t.attribute && t.attribute.length) { r.attribute = []; for (var s = 0; s < t.attribute.length; ++s) r.attribute[s] = t.attribute[s]; } if (t.node && t.node.length) { r.node = []; for (var s = 0; s < t.node.length; ++s) r.node[s] = c.onnx.NodeProto.toObject(t.node[s], n); } if (t.docString != null && t.hasOwnProperty("docString") && (r.docString = t.docString), t.opsetImport && t.opsetImport.length) { r.opsetImport = []; for (var s = 0; s < t.opsetImport.length; ++s) r.opsetImport[s] = c.onnx.OperatorSetIdProto.toObject(t.opsetImport[s], n); } if (t.domain != null && t.hasOwnProperty("domain") && (r.domain = t.domain), t.attributeProto && t.attributeProto.length) { r.attributeProto = []; for (var s = 0; s < t.attributeProto.length; ++s) r.attributeProto[s] = c.onnx.AttributeProto.toObject(t.attributeProto[s], n); } return r; }, e.prototype.toJSON = function() { return this.constructor.toObject(this, W2.util.toJSONOptions); }, e.getTypeUrl = function(t) { return t === void 0 && (t = "type.googleapis.com"), t + "/onnx.FunctionProto"; }, e; })(), a; })(); Fi2.exports = c; }); z2 = x(() => { "use strict"; Je(); Ur3(); H2 = ne(se()); Yt3(); Kt3 = class { static arraysEqual(e, o) { if (e.length !== o.length) return false; for (let t = 0; t < e.length; t++) if (e[t] !== o[t]) return false; return true; } }, nn3 = class { static preprocessInputShapes(e, o) { let t = e.length === 1 ? [1, e[0]] : e, n = o.length === 1 ? [o[0], 1] : o; return [t, n]; } static postprocessOutputShape(e, o, t) { o === 1 && e.splice(e.length - 2, 1), t === 1 && e.pop(); } static calcMatMulShape(e, o) { return e[1] !== o[0] ? void 0 : [e[0], o[1]]; } }, it2 = class a { static calcShape(e, o, t = false) { let n = e.length, r = o.length; if (n === 0) return o; if (r === 0) return e; let s = Math.max(e.length, o.length), i = new Array(s); if (t) { if (n < 2 || r < 2) return; let u = nn3.calcMatMulShape([e[n - 2], e[n - 1]], [o[r - 2], o[r - 1]]); if (u === void 0) return; [i[s - 2], i[s - 1]] = u; } for (let u = t ? 3 : 1; u <= s; u++) { let l = n - u < 0 ? 1 : e[n - u], f = r - u < 0 ? 1 : o[r - u]; if (l !== f && l > 1 && f > 1) return; i[s - u] = Math.max(l, f); } return i; } static index(e, o) { let t = new Array(o.length); return a.fillIndex(e, o, t), t; } static fillIndex(e, o, t) { let n = e.length - o.length; for (let r = 0; r < o.length; r++) t[r] = e[n + r] % o[r]; } static calc(e, o, t, n, r) { let s = a.calcShape(e.dims, o.dims); if (s) { if (n && !A.areEqual(s, e.dims)) return; let i = A.size(s), u = n ? e : new Y2(s, r || e.type); if (s.length === 0) u.set([], t(e.get([]), o.get([]))); else { let l = new Array(s.length), f = new Array(e.dims.length), p = new Array(o.dims.length), d = 0, b = 0, g = false, y = false; e.dims.length === 0 && (d = e.get([]), g = true), o.dims.length === 0 && (b = o.get([]), y = true); let v; for (let _ = 0; _ < i; _++) { v = _; for (let O2 = s.length - 1; O2 >= 0; O2--) l[O2] = v % s[O2], v = Math.floor(v / s[O2]); g || (a.fillIndex(l, e.dims, f), d = e.get(f)), y || (a.fillIndex(l, o.dims, p), b = o.get(p)), u.set(l, t(d, b)); } } return u; } } static isValidBroadcast(e, o) { let t = e.length, n = o.length; if (t > n) return false; for (let r = 1; r <= t; r++) if (e[t - r] !== 1 && e[t - r] !== o[n - r]) return false; return true; } static getBroadcastDims(e, o) { let t = e.length, n = []; for (let r = 0; r < t; r++) { let s = t - 1 - r, i = e[s] || 1; (o[o.length - 1 - r] || 1) > 1 && i === 1 && n.unshift(s); } return n; } }, er2 = class { static getShapeOfGemmResult(e, o, t, n, r) { if (e.length !== 2 || t.length !== 2) throw new Error("shape need to be of size 2"); let s, i, u; o ? (s = e[1], i = e[0]) : (s = e[0], i = e[1]); let l = -1; if (n ? (u = t[0], l = 1) : (u = t[1], l = 0), t[l] !== i) throw new Error("dimension mismatch"); if (s <= 0 || u <= 0 || i <= 0) throw new Error("invalid shape specified"); if (r && !it2.isValidBroadcast(r, [s, u])) throw new Error("gemm: invalid bias shape for broadcast"); return [s, u, i]; } }, et = class a { static tensorDataTypeFromProto(e) { switch (e) { case H2.onnx.TensorProto.DataType.INT8: return "int8"; case H2.onnx.TensorProto.DataType.UINT8: return "uint8"; case H2.onnx.TensorProto.DataType.BOOL: return "bool"; case H2.onnx.TensorProto.DataType.INT16: return "int16"; case H2.onnx.TensorProto.DataType.UINT16: return "uint16"; case H2.onnx.TensorProto.DataType.INT32: return "int32"; case H2.onnx.TensorProto.DataType.UINT32: return "uint32"; case H2.onnx.TensorProto.DataType.FLOAT: return "float32"; case H2.onnx.TensorProto.DataType.DOUBLE: return "float64"; case H2.onnx.TensorProto.DataType.STRING: return "string"; case H2.onnx.TensorProto.DataType.INT64: return "int32"; case H2.onnx.TensorProto.DataType.UINT64: return "uint32"; default: throw new Error(`unsupported data type: ${H2.onnx.TensorProto.DataType[e]}`); } } static tensorDataTypeStringToEnum(e) { switch (e) { case "int8": return H2.onnx.TensorProto.DataType.INT8; case "uint8": return H2.onnx.TensorProto.DataType.UINT8; case "bool": return H2.onnx.TensorProto.DataType.BOOL; case "int16": return H2.onnx.TensorProto.DataType.INT16; case "uint16": return H2.onnx.TensorProto.DataType.UINT16; case "int32": return H2.onnx.TensorProto.DataType.INT32; case "uint32": return H2.onnx.TensorProto.DataType.UINT32; case "float32": return H2.onnx.TensorProto.DataType.FLOAT; case "float64": return H2.onnx.TensorProto.DataType.DOUBLE; case "string": return H2.onnx.TensorProto.DataType.STRING; case "int64": return H2.onnx.TensorProto.DataType.INT64; case "uint64": return H2.onnx.TensorProto.DataType.UINT64; default: throw new Error(`unsupported data type: ${e}`); } } static tensorDimsFromProto(e) { return e.map((o) => kt3.isLong(o) ? o.toNumber() : o); } static tensorValueTypeFromProto(e) { return { tensorType: a.tensorDataTypeFromProto(e.elemType), shape: { dims: a.tensorDimsFromProto(e.shape.dim.map((o) => o.dimValue)) } }; } static tensorDimsFromORTFormat(e) { let o = []; for (let t = 0; t < e.dimsLength(); t++) o.push(ft.longToNumber(e.dims(t))); return o; } static tensorAttributesFromORTFormat(e) { let o = []; for (let t = 0; t < e.attributesLength(); t++) o.push(e.attributes(t)); return o; } }, ft = class { static longToNumber(e, o) { return kt3.isLong(e) ? e.toNumber() : e instanceof m.Long ? kt3.fromValue({ low: e.low, high: e.high, unsigned: o ?? false }).toNumber() : e; } static isLong(e) { return kt3.isLong(e) || e instanceof m.Long; } }, A = class a { static size(e) { return a.getSizeFromDimensionRange(e, 0, e.length); } static sizeFromDimension(e, o) { if (o < 0 || o > e.length) throw new Error(`invalid dimension of ${o} for sizeFromDimension as Tensor has ${e.length} dimensions.`); return a.getSizeFromDimensionRange(e, o, e.length); } static sizeToDimension(e, o) { if (o < 0 || o > e.length) throw new Error(`invalid dimension of ${o} for sizeToDimension as Tensor has ${e.length} dimensions.`); return a.getSizeFromDimensionRange(e, 0, o); } static getSizeFromDimensionRange(e, o, t) { let n = 1; for (let r = o; r < t; r++) { if (e[r] <= 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them."); n *= e[r]; } return n; } static computeStrides(e) { let o = e.length; if (o === 0) return []; if (o === 1) return [1]; let t = new Array(o); t[o - 1] = 1, t[o - 2] = e[o - 1]; for (let n = o - 3; n >= 0; --n) t[n] = t[n + 1] * e[n + 1]; return t; } static transpose(e) { return e.slice().reverse(); } static indicesToOffset(e, o, t) { t === void 0 && (t = e.length); let n = 0; for (let r = 0; r < t; ++r) n += o[r] * e[r]; return n; } static offsetToIndices(e, o) { let t = o.length; if (t === 0) return []; if (t === 1) return [e * o[0]]; let n = new Array(o.length); for (let r = 0; r < n.length - 1; ++r) n[r] = Math.floor(e / o[r]), e -= n[r] * o[r]; return n[n.length - 1] = e, n; } static normalizeAxis(e, o) { if (e < -o && e >= o) throw new Error("unsupported axis for this operation."); return e < 0 ? e + o : e; } static normalizeAxes(e, o) { return e.map((t) => this.normalizeAxis(t, o)); } static incrementIndex(e, o, t) { if (o.length === 0 || e.length === 0) throw new Error("Index incrementing unsupported for scalar Tensor"); if (t === void 0) t = o.length; else if (t <= 0 || t > o.length) throw new Error("Incorrect axis to increment on"); for (let n = t - 1; n >= 0 && (e[n]++, !(e[n] < o[n])); --n) e[n] = 0; } static calculateReshapedDims(e, o) { if (o.length === 0) { if (e.length === 0 || a.size(e) === 1) return []; throw new Error("cannot reshape to a scalar Tensor"); } let t = o.length, n = new Array(t), r = -1, s = 1; for (let u = 0; u < t; u++) { if (o[u] < -1) throw new Error("a dimension in shape hints cannot be less than -1"); if (o[u] === -1) { if (r !== -1) throw new Error("at most one dimension in shape hints can be -1"); r = u; } else { if (o[u] === 0) { if (u >= e.length) throw new Error("the dimension with value zero exceeds the dimension size of the input tensor"); n[u] = e[u]; } else n[u] = o[u]; s *= n[u]; } } let i = a.size(e); if (r !== -1) { if (i % s !== 0) throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${o}]`); n[r] = i / s; } else if (s !== i) throw new Error("reshapedDims and originalDims don't have matching sizes"); return n; } static sortBasedOnPerm(e, o) { return o ? o.map((t) => e[t]) : e.slice().reverse(); } static padShape(e, o) { let t = e.length; return e.map((n, r) => n + o[r] + o[r + t]); } static areEqual(e, o) { return e.length !== o.length ? false : e.every((t, n) => t === o[n]); } static validateDimsAndCalcSize(e) { if (e.length > 6) throw new TypeError("Only rank 0 to 6 is supported for tensor shape."); let o = 1; for (let t of e) { if (!Number.isInteger(t)) throw new TypeError(`Invalid shape: ${t} is not an integer`); if (t < 0 || t > 2147483647) throw new TypeError(`Invalid shape: length ${t} is not allowed`); o *= t; } return o; } static flattenShape(e, o) { o < 0 && (o += e.length); let t = e.reduce((s, i) => s * i, 1), n = e.slice(o).reduce((s, i) => s * i, 1); return [t / n, n]; } static squeezeShape(e, o) { let t = new Array(); o = a.normalizeAxes(o, e.length); for (let n = 0; n < e.length; n++) { let r = o.indexOf(n) >= 0; if (r && e[n] !== 1) throw new Error("squeeze an axis of size different than 1"); (o.length === 0 && e[n] > 1 || o.length > 0 && !r) && t.push(e[n]); } return t; } static unsqueezeShape(e, o) { let t = new Array(e.length + o.length); t.fill(0); for (let r = 0; r < o.length; r++) { let s = a.normalizeAxis(o[r], t.length); if (s >= t.length) throw new Error("'axes' has an out of range axis"); if (t[s] !== 0) throw new Error("'axes' has a duplicate axis"); t[s] = 1; } let n = 0; for (let r = 0; r < t.length; r++) t[r] === 0 && (t[r] = e[n++]); if (n !== e.length) throw new Error("the unsqueezed dimension could not be established"); return t; } }, we = class a { static splitShape(e, o, t, n) { if (t.length === 0) { if (!n) throw new Error("need to know number of outputs when the 'split' attribute is not specified"); a.determineSplit(e[o], n, t); } let r = [], s = [0]; for (let i = 0; i < t.length; ++i) { i !== 0 && s.push(s[i - 1] + t[i - 1]); let u = e.slice(); u[o] = t[i], r.push(u); } return [r, s]; } static determineSplit(e, o, t) { if (e % o !== 0) throw new Error("cannot split tensor to equal sized parts"); for (let n = 0; n < o; ++n) t.push(e / o); } }, Xt3 = class a { static adjustPoolAttributes(e, o, t, n, r, s) { if (!e && t.length !== o.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); if (e) for (let i = 0; i < o.length - 2; i++) i >= t.length ? t.push(o[i + 2]) : t[i] = o[i + 2]; for (let i = 0; i < t.length; i++) if (i < n.length) { if (n[i] < 0) throw new Error("strides should be greater than or equal to 1"); } else n.push(1); for (let i = 0; i < t.length; i++) if (i < r.length) { if (r[i] < 0) throw new Error("dilations should be greater than or equal to 1"); } else r.push(1); for (let i = 0; i < t.length * 2; i++) if (i < s.length) { if (s[i] < 0) throw new Error("pad should be greater than or equal to 1"); } else s.push(0); for (let i = 0; i < t.length; i++) { if (t[i] <= 0) throw new Error("kernel shapes need to be greater than 0"); if (s[i] >= t[i] || s[i + t.length] >= t[i]) throw new Error("pads should be smaller than kernel"); } } static adjustPadsBasedOnAutoPad(e, o, t, n, r, s) { if (s) { if (r.length !== 2 * (e.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); if (o.length !== e.length - 2) throw new Error("length of strides should be the length of data dimensions"); if (n.length !== e.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions"); for (let i = 0; i < e.length - 2; i++) a.adjustPadAndReturnShape(e[i + 2], o[i], t[i], n[i], r, i, i + e.length - 2, s); } } static computePoolOutputShape(e, o, t, n, r, s, i) { if (o.length <= 0) throw new Error("input shape must be of size greater than 0"); let u = [o[0], o[1]]; return a.computeShapeHelper(e, o, u, t, n, r, s, i), u; } static computeConvOutputShape(e, o, t, n, r, s, i) { if (e.length <= 0 || o.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); let u = [e[0], o[0]]; return a.computeShapeHelper(false, e, u, t, n, r, s, i), u; } static computeShapeHelper(e, o, t, n, r, s, i, u) { if (e) for (let l = 0; l < o.length - 2; l++) t.push(1); else for (let l = 0; l < o.length - 2; l++) t.push(a.adjustPadAndReturnShape(o[l + 2], n[l], r[l], s[l], i, l, l + o.length - 2, u)); } static adjustPadAndReturnShape(e, o, t, n, r, s, i, u) { let l = t * (n - 1) + 1; if (u && u !== "NOTSET") switch (u) { case "VALID": return r[s] = 0, r[i] = 0, Math.floor((e - l) / o + 1); case "SAME_LOWER": case "SAME_UPPER": if (t !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); { let p = ((e + o - 1) / o - 1) * o + n - e; return r[s] = Math.floor(u === "SAME_LOWER" ? (p + 1) / 2 : p / 2), r[i] = p - r[s], Math.floor((e + p - n) / o + 1); } default: throw new Error("Unsupported AutoPad type"); } else return Math.floor((e + r[s] + r[i] - l) / o + 1); } }, Jt3 = -34028234663852886e22, Zt2 = 34028234663852886e22; }); Yt3 = x(() => { "use strict"; Gi2 = ne(Ao2()); Ur3(); ge2(); k3 = ne(se()); z2(); on3 = P.experimental.fbs, Y2 = class a { constructor(e, o, t, n, r, s = Gi2.Guid.create()) { this.dims = e; this.type = o; this.dataProvider = t; this.asyncDataProvider = n; this.cache = r; this.dataId = s; this.size = A.validateDimsAndCalcSize(e); let i = this.size, u = t === void 0 && n === void 0 && r === void 0; if (r !== void 0 && r.length !== i) throw new RangeError("Input dims doesn't match data length."); if (o === "string") { if (r !== void 0 && (!Array.isArray(r) || !r.every((l) => typeof l == "string"))) throw new TypeError("cache should be a string array"); u && (this.cache = new Array(i)); } else { if (r !== void 0) { let l = Ri2(o); if (!(r instanceof l)) throw new TypeError(`cache should be type ${l.name}`); } if (u) { let l = new ArrayBuffer(i * Zl2(o)); this.cache = Yl2(l, o); } } } get data() { if (this.cache === void 0) { let e = this.dataProvider(this.dataId); if (e.length !== this.size) throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor."); this.cache = e; } return this.cache; } get stringData() { if (this.type !== "string") throw new TypeError("data type is not string"); return this.data; } get integerData() { switch (this.type) { case "uint8": case "int8": case "uint16": case "int16": case "int32": case "uint32": case "bool": return this.data; default: throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)"); } } get floatData() { switch (this.type) { case "float32": case "float64": return this.data; default: throw new TypeError("data type is not float (float32, float64)"); } } get numberData() { if (this.type !== "string") return this.data; throw new TypeError("type cannot be non-number (string)"); } get(e) { return this.data[A.indicesToOffset(e, this.strides)]; } set(e, o) { this.data[A.indicesToOffset(e, this.strides)] = o; } async getData() { return this.cache === void 0 && (this.cache = await this.asyncDataProvider(this.dataId)), this.cache; } get strides() { return this._strides || (this._strides = A.computeStrides(this.dims)), this._strides; } static fromProto(e) { if (!e) throw new Error("cannot construct Value from an empty tensor"); let o = et.tensorDataTypeFromProto(e.dataType), t = et.tensorDimsFromProto(e.dims), n = new a(t, o); if (o === "string") e.stringData.forEach((r, s) => { n.data[s] = Ie3(r); }); else if (e.rawData && typeof e.rawData.byteLength == "number" && e.rawData.byteLength > 0) { let r = n.data, s = new DataView(e.rawData.buffer, e.rawData.byteOffset, e.rawData.byteLength), i = Ni2(e.dataType), u = e.rawData.byteLength / i; if (e.rawData.byteLength % i !== 0) throw new Error("invalid buffer length"); if (r.length !== u) throw new Error("buffer length mismatch"); for (let l = 0; l < u; l++) { let f = Ci2(s, e.dataType, l * i); r[l] = f; } } else { let r; switch (e.dataType) { case k3.onnx.TensorProto.DataType.FLOAT: r = e.floatData; break; case k3.onnx.TensorProto.DataType.INT32: case k3.onnx.TensorProto.DataType.INT16: case k3.onnx.TensorProto.DataType.UINT16: case k3.onnx.TensorProto.DataType.INT8: case k3.onnx.TensorProto.DataType.UINT8: case k3.onnx.TensorProto.DataType.BOOL: r = e.int32Data; break; case k3.onnx.TensorProto.DataType.INT64: r = e.int64Data; break; case k3.onnx.TensorProto.DataType.DOUBLE: r = e.doubleData; break; case k3.onnx.TensorProto.DataType.UINT32: case k3.onnx.TensorProto.DataType.UINT64: r = e.uint64Data; break; default: throw new Error("unspecific error"); } if (r == null) throw new Error("failed to populate data from a tensorproto value"); let s = n.data; if (s.length !== r.length) throw new Error("array length mismatch"); for (let i = 0; i < r.length; i++) { let u = r[i]; kt3.isLong(u) ? s[i] = an3(u, e.dataType) : s[i] = u; } } return n; } static fromData(e, o, t) { return new a(o, t, void 0, void 0, e); } static fromOrtTensor(e) { if (!e) throw new Error("cannot construct Value from an empty tensor"); let o = et.tensorDimsFromORTFormat(e), t = et.tensorDataTypeFromProto(e.dataType()), n = new a(o, t); if (t === "string") for (let r = 0; r < e.stringDataLength(); r++) n.data[r] = e.stringData(r); else if (e.rawDataArray() && typeof e.rawDataLength() == "number" && e.rawDataLength() > 0) { let r = n.data, s = new DataView(e.rawDataArray().buffer, e.rawDataArray().byteOffset, e.rawDataLength()), i = Ni2(e.dataType()), u = e.rawDataLength() / i; if (e.rawDataLength() % i !== 0) throw new Error("invalid buffer length"); if (r.length !== u) throw new Error("buffer length mismatch"); for (let l = 0; l < u; l++) { let f = Ci2(s, e.dataType(), l * i); r[l] = f; } } return n; } }; }); q2 = x(() => { "use strict"; Ql2 = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, tf3 = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" }; }); N = x(() => { "use strict"; }); Pt3 = x(() => { "use strict"; z2(); }); Qt2 = x(() => { "use strict"; Pt3(); }); qi2 = x(() => { "use strict"; q2(); N(); Pt3(); Qt2(); Wi2 = { name: "pack", inputNames: ["A"], inputTypes: [1] }, rf3 = (a, e) => { let o = D2(a.session.backend.glContext.version), t = e.dims, n = t.length, r = e.dims.length, s = at2(r), i = ce2("rc", r), u = af3(r, i, t[t.length - 2], t[t.length - 1]), l; n === 0 ? l = [1, 1] : n === 1 ? l = [t[0], 1] : l = [t[r - 1], t[r - 2]]; let f = nf3(r, l, i), p = of3(t, i), d = ` void main() { ${s} rc = getOutputCoords(); if(${f}) { ${o.output} = vec4(0); } else { ${u} ${o.output} = vec4(${p}); } } `; return { ...Wi2, hasMain: true, output: { dims: e.dims, type: e.type, textureType: 2 }, shaderSource: d }; }, Hi2 = (a, e) => ({ ...Wi2, get: () => rf3(a, e) }); }); Xi3 = x(() => { "use strict"; z2(); q2(); N(); Qt2(); sf3 = (a) => ({ name: "Reshape (packed)", inputTypes: [2], inputNames: ["A"], cacheHint: `${a}` }), uf2 = (a, e, o, t) => { let n = e.dims, r = t, s = ""; for (let l = 0; l < 4; l++) { let f = ""; switch (l) { case 0: f = "outputCoords = rc;"; break; case 1: f = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);"; break; case 2: f = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);"; break; case 3: f = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);"; break; default: throw new Error(); } s += ` ${f} ${l > 0 ? "if(outputCoords.y < rows && outputCoords.z < cols){" : ""} int flattenedIndex = getFlattenedIndex(outputCoords); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); result[${l}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); ${l > 0 ? "}" : ""} `; } let i = D2(a.session.backend.glContext.version), u = ` ${lf3(n)} ${ff3(r)} ${Et2()} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.0); ivec3 outputCoords; int rows = ${r[2]}; int cols = ${r[1]}; ${s} ${i.output} = result; } `; return { ...o, output: { dims: r, type: e.type, textureType: 2 }, shaderSource: u, hasMain: true }; }, ji2 = (a, e, o) => { let t = sf3(o); return { ...t, get: () => uf2(a, e, t, o) }; }; }); Ji3 = x(() => { "use strict"; q2(); N(); ln3 = (a, e) => { let o = e.shape, t = D2(a.session.backend.glContext.version), n = ` const float FLOAT_MAX = 1.70141184e38; const float FLOAT_MIN = 1.17549435e-38; bool isNaN(float val) { return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; } highp vec4 encodeAsUint8(highp float v) { if (isNaN(v)) { return vec4(255, 255, 255, 255); } highp float av = abs(v); if(av < FLOAT_MIN) { return vec4(0.0, 0.0, 0.0, 0.0); } else if(v > FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; } else if(v < -FLOAT_MAX) { return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; } highp vec4 c = vec4(0,0,0,0); highp float e = floor(log2(av)); highp float m = exp2(fract(log2(av))) - 1.0; c[2] = floor(128.0 * m); m -= c[2] / 128.0; c[1] = floor(32768.0 * m); m -= c[1] / 32768.0; c[0] = floor(8388608.0 * m); highp float ebias = e + 127.0; c[3] = floor(ebias / 2.0); ebias -= c[3] * 2.0; c[2] += floor(ebias) * 128.0; c[3] += 128.0 * step(0.0, -v); return c / 255.0; } void main() { float value = ${t.texture2D}(X,TexCoords).r; ${t.output} = encodeAsUint8(value); }`, r = { name: "Uint8Encode", inputTypes: [0], inputNames: ["X"], output: { dims: o, type: e.tensor.type, textureType: 3 }, shaderSource: n, hasMain: true }; return a.executeProgram(r, [e.tensor]); }; }); Qi3 = x(() => { "use strict"; q2(); N(); Pt3(); Qt2(); Zi3 = { name: "unpack", inputNames: ["A"], inputTypes: [2] }, cf3 = (a, e) => { let o = e.dims.length, t = ce2("rc", o), n = t.slice(-2), r = at2(o), s = Et2(), u = e.dims.length === 0 ? "" : pf3(o, t), l = o <= 1 ? "rc" : `vec2(${n.join(",")})`, f = D2(a.session.backend.glContext.version), p = ` ${s} void main() { ${r} rc = getOutputCoords(); // Sample the texture with the coords to get the rgba channel value. vec4 packedInput = getA(${u}); ${f.output} = vec4(getChannel(packedInput, ${l}), 0, 0, 0); } `; return { ...Zi3, hasMain: true, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: p }; }, Yi3 = (a, e) => ({ ...Zi3, get: () => cf3(a, e) }); }); Se = x(() => { "use strict"; pt(); nr3 = class { constructor(e, o = 1) { if (o === 1) this.internalFormat = e.R32F, this.format = e.RED, this.textureType = e.FLOAT, this.channelSize = o; else if (o === 4) this.internalFormat = e.RGBA32F, this.format = e.RGBA, this.textureType = e.FLOAT, this.channelSize = o; else throw new Error(`Invalid number of channels: ${o}`); } encode(e, o) { let t, n; return e.constructor !== Float32Array && (M2.warning("Encoder", "data was not of type Float32; creating new Float32Array"), n = new Float32Array(e)), o * this.channelSize > e.length ? (M2.warning("Encoder", "Source data too small. Allocating larger array"), n = e, t = this.allocate(o * this.channelSize), n.forEach((r, s) => t[s] = r)) : (n = e, t = n), t; } allocate(e) { return new Float32Array(e * 4); } decode(e, o) { return this.channelSize === 1 ? e.filter((n, r) => r % 4 === 0).subarray(0, o) : e.subarray(0, o); } }, _e2 = class { constructor(e, o = 1, t) { if (o !== 1 && o !== 4) throw new Error(`Invalid number of channels: ${o}`); this.internalFormat = e.RGBA, this.format = e.RGBA, this.channelSize = o, this.textureType = t || e.FLOAT; } encode(e, o) { let t = e; return this.channelSize === 1 && (M2.verbose("Encoder", "Exploding into a larger array"), t = this.allocate(o), e.forEach((n, r) => t[r * 4] = n)), t; } allocate(e) { return new Float32Array(e * 4); } decode(e, o) { return this.channelSize === 1 ? e.filter((n, r) => r % 4 === 0).subarray(0, o) : e.subarray(0, o); } }, or3 = class { constructor(e, o = 1) { this.channelSize = 4; if (o === 1) this.internalFormat = e.ALPHA, this.format = e.ALPHA, this.textureType = e.UNSIGNED_BYTE, this.channelSize = o; else if (o === 4) this.internalFormat = e.RGBA, this.format = e.RGBA, this.textureType = e.UNSIGNED_BYTE, this.channelSize = o; else throw new Error(`Invalid number of channels: ${o}`); } encode(e, o) { return new Uint8Array(e.buffer, e.byteOffset, e.byteLength); } allocate(e) { return new Uint8Array(e * this.channelSize); } decode(e, o) { if (e instanceof Uint8Array) return e.subarray(0, o); throw new Error(`Invalid array type: ${e.constructor}`); } }; }); ea2 = x(() => { "use strict"; z2(); N(); Oe3 = (a, e, o) => { let t = o === 0 || o === 1 ? 1 : 4, n = o === 2, r = o === 1 || o === 2, s = o === 4 ? e.length - 1 : void 0, i = o === 4 ? e.map((u, l) => l === e.length - 1 ? u * 4 : u) : void 0; return fn2(a, e, t, i, { isPacked: n, reverseWH: r, breakAxis: s }); }, ta2 = (a, e, o) => { let t = Oe3(a, e, o); return [t.width, t.height]; }, fn2 = (a, e, o = 1, t, n) => { let r = !!(n && n.isPacked), [s, i] = a.computeTextureWH(r && t || e, n), u = e.length, l = e.slice(0); if (u === 0 && (l = [1]), o === 1) t = e; else if (r) { if (o !== 4) throw new Error("a packed texture must be 4-channel"); t = e, u > 0 && (l[u - 1] = Math.ceil(l[u - 1] / 2)), u > 1 && (l[u - 2] = Math.ceil(l[u - 2] / 2)); } else if (!t) throw new Error("Unpacked shape is needed when using channels > 1"); return { width: s, height: i, channels: o, isPacked: r, shape: l, strides: A.computeStrides(l), unpackedShape: t, reversedWH: n && n.reverseWH }; }; }); na2 = x(() => { "use strict"; pt(); Yt3(); z2(); qi2(); Xi3(); Ji3(); Qi3(); Se(); ea2(); N(); hf3 = (a, e) => { let o = e.map((n) => `${n.unpackedShape.join(",")};${n.width}x${n.height}`).join("_"), t = a.name; return a.cacheHint && (t += "[" + a.cacheHint + "]"), t += ":" + o, t; }, ir3 = class { constructor(e) { this.session = e; this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } calculateTextureWidthAndHeight(e, o) { return ta2(this.session.layoutStrategy, e, o); } executeProgram(e, o) { if (o.length < e.inputNames.length) throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`); if (e.inputNames.length !== e.inputTypes.length) throw new Error("input names size does not match input types"); let t = []; for (let l = 0; l < e.inputNames.length; ++l) t[l] = this.getOrCreateTextureData(o[l], e.inputTypes[l]); let n = hf3(e, t), r = this.session.programManager.getArtifact(n), s = r ? r.programInfo : typeof e.get == "function" ? e.get() : e, i = Oe3(this.session.layoutStrategy, s.output.dims, s.output.textureType), u = this.createTextureData(i, s.output.type); return r || (r = this.session.programManager.build(s, t, u), this.session.programManager.setArtifact(n, r)), this.runProgram(r, t, u), u; } run(e, o) { return this.executeProgram(e, o).tensor; } runProgram(e, o, t) { for (let n = 0; n < o.length; ++n) if (!!o[n].isPacked != (e.programInfo.inputTypes[n] === 2)) throw new Error(`input[${n}] property packed inconsistent`); if (!!t.isPacked != (e.programInfo.output.textureType === 2)) throw new Error("output property packed inconsistent"); this.session.programManager.run(e, o, t); } getOrCreateTextureData(e, o) { let t = this.getTextureData(e.dataId, o === 2); if (!t && (t = this.getTextureData(e.dataId, o !== 2), t)) return o === 2 ? this.pack(t) : this.unpack(t); if (!t) { let n = Oe3(this.session.layoutStrategy, e.dims, o); if (o === 4) { let i = e.dims; if (i.length === 4) { let u = [i[0], Math.ceil(i[1] * i[2] * i[3] / 4)], l = Oe3(this.session.layoutStrategy, u, o), f = e.numberData; if (i[1] * i[2] * i[3] % 4 !== 0) { let p = i[0], d = i[1] * i[2] * i[3], b = Math.ceil(d * 1 / 4) * 4, g = p * b; f = new Float32Array(g); for (let y = 0; y < p; ++y) { let v = y * d, _ = y * b + y % 1 * d; f.set(e.numberData.subarray(v, v + d), _); } } return this.createTextureData(l, e.type, f, e, 1); } } if (o === 2) { let r = fn2(this.session.layoutStrategy, e.dims, 1, [], { reverseWH: true }), s = this.createTextureData(r, e.type, e.numberData, e, 1); t = this.pack(s); } else t = this.createTextureData(n, e.type, e.numberData, e, 1); } return t; } createTextureDataFromLayoutBindTensor(e, o, t, n) { return this.createTextureData(e, o, t, n, 1); } createTextureData(e, o, t, n, r) { M2.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(e)}]`); let s = this.session.textureManager.createTextureFromLayout(o, e, t, r); return this.createTextureDataFromTexture(e, o, s, n); } reshapeUnpacked(e, o) { let t = this.getOrCreateTextureData(e, 0), n = { channels: t.channels, height: t.height, width: t.width, shape: o.length !== 0 ? o : [1], strides: A.computeStrides(o), unpackedShape: o }; return this.createTextureDataFromTexture(n, e.type, t.texture).tensor; } reshapePacked(e, o) { let t = this.getOrCreateTextureData(e, 2); if (Ki2(e.dims, o)) { let l = { channels: t.channels, height: t.height, width: t.width, shape: o.length !== 0 ? o : [1], strides: A.computeStrides(o), unpackedShape: o, isPacked: true }; return this.createTextureDataFromTexture(l, e.type, t.texture).tensor; } let n = un3(e.dims), r = un3(o), s = this.reshapePacked(e, n), i = this.run(ji2(this, s, r), [s]); return this.reshapePacked(i, o); } cast(e, o) { let t = this.getOrCreateTextureData(e, 0); return this.createTextureDataFromTexture(t, o, t.texture).tensor; } createTextureDataFromTexture(e, o, t, n, r) { let s = { ...e, tensor: n || new Y2(e.unpackedShape, o, (i) => this.readTexture(s), async (i) => this.readTextureAsync(s), void 0, r), texture: t }; return this.setTextureData(s.tensor.dataId, s, e.isPacked), s; } getTextureData(e, o = false) { return this.session.isInitializer(e) ? this.session.getTextureData(e, o) : o ? this.packedTextureDataCache.get(e) : this.unpackedTextureDataCache.get(e); } setTextureData(e, o, t = false) { this.session.isInitializer(e) ? this.session.setTextureData(e, o, t) : (t ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(e, o); } isTextureLayoutCached(e, o = false) { return !!this.getTextureData(e.dataId, o); } dispose() { this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((e) => this.session.textureManager.releaseTexture(e)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((e) => this.session.textureManager.releaseTexture(e)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } readTexture(e) { return e.isPacked ? this.readTexture(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat(ln3(this, e)); } async readTextureAsync(e) { return e.isPacked ? this.readTextureAsync(this.unpack(e)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(e, e.tensor.type, e.channels) : this.session.textureManager.readUint8TextureAsFloat(ln3(this, e)); } pack(e) { return this.executeProgram(Hi2(this, e.tensor), [e.tensor]); } unpack(e) { return this.executeProgram(Yi3(this, e.tensor), [e.tensor]); } }; }); tt3 = x(() => { "use strict"; cn3 = class { constructor(e) { Object.assign(this, e); } get cacheKey() { return this.key || (this.key = Object.getOwnPropertyNames(this).sort().map((e) => `${this[e]}`).join(";")), this.key; } }, $ = (a) => new cn3(a); }); sa2 = x(() => { "use strict"; tt3(); q2(); N(); oa2 = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [0, 0, 0, 0, 0] }, ia2 = (a, e, o) => (bf3(e), [a.run({ ...oa2, cacheHint: o.cacheKey, get: () => mf3(a, e, o) }, e)]), aa2 = (a) => { let e = a.attributes.getFloat("epsilon", 1e-5), o = a.attributes.getFloat("momentum", 0.9), t = a.attributes.getInt("spatial", 1); return $({ epsilon: e, momentum: o, spatial: t }); }, mf3 = (a, e, o) => { let t = D2(a.session.backend.glContext.version), n = e[0].dims.length, [r, s] = a.calculateTextureWidthAndHeight(e[1].dims, 0), i = ` float process(int[${n}] indices) { vec2 position = offsetToCoords(indices[1], ${r}, ${s}); float scale = getColorAsFloat(${t.texture2D}(Scale, position)); float mean = getColorAsFloat(${t.texture2D}(Mean, position)); float variance = getColorAsFloat(${t.texture2D}(Variance, position)); float b = getColorAsFloat(${t.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${o.epsilon})) ) + b; }`; return { ...oa2, output: { dims: e[0].dims, type: e[0].type, textureType: 0 }, shaderSource: i }; }, bf3 = (a) => { if (!a || a.length !== 5) throw new Error("BatchNormalization requires 5 inputs."); let e = a[0], o = a[1], t = a[2], n = a[3], r = a[4]; if (e.dims.length < 3 || o.dims.length !== 1 || t.dims.length !== 1 || n.dims.length !== 1 || r.dims.length !== 1) throw new Error("invalid input shape."); if (o.dims[0] !== e.dims[1] || t.dims[0] !== e.dims[1] || n.dims[0] !== e.dims[1] || r.dims[0] !== e.dims[1]) throw new Error("invalid input shape."); if (e.type !== "float32" && e.type !== "float64" || o.type !== "float32" && o.type !== "float64" || t.type !== "float32" && t.type !== "float64" || n.type !== "float32" && n.type !== "float64" || r.type !== "float32" && r.type !== "float64") throw new Error("invalid input tensor types."); }; }); Bt = x(() => { "use strict"; ar = class { constructor(e, o, t, n) { this.glContext = e; this.programInfo = o; this.inputTextureLayouts = t; this.outputTextureLayout = n; } }, bt2 = class { constructor(e) { this.context = e; } }, I = class { constructor(e, o) { this.routineBody = e; this.dependencies = o; } }, Ae2 = class { constructor(e, o, t) { this.name = e; t ? this.dependencies = t : this.dependencies = [], o && (this.routineBody = o); } addDependency(e) { e && this.dependencies.push(e); } }, sr2 = class { static returnOrderedNodes(e) { if (!e || e.length === 0) return []; if (e.length === 1) return e; let o = /* @__PURE__ */ new Set(), t = /* @__PURE__ */ new Set(), n = new Array(); return this.createOrderedNodes(e, o, t, n), n; } static createOrderedNodes(e, o, t, n) { for (let r = 0; r < e.length; ++r) this.dfsTraverse(e[r], o, t, n); } static dfsTraverse(e, o, t, n) { if (!e || t.has(e.name)) return; if (o.has(e.name)) throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader."); o.add(e.name); let r = e.dependencies; if (r && r.length > 0) for (let s = 0; s < r.length; ++s) this.dfsTraverse(r[s], o, t, n); n.push(e), t.add(e.name), o.delete(e.name); } }; }); Ta2 = x(() => { "use strict"; z2(); Bt(); q2(); N(); yt2 = (a, e, o, t = e[0].type, n) => { let r = a.session.pack ? 2 : 0; return { name: o.name, inputNames: ["A", "B"], inputTypes: [r, r], cacheHint: n, get: () => Lf3(a, e, o, t) }; }, Lf3 = (a, e, o, t = e[0].type) => { let n = a.session.pack ? 2 : 0, r = !A.areEqual(e[0].dims, e[1].dims), s = e[0].dims, i = a.session.pack; if (r) { let f = it2.calcShape(e[0].dims, e[1].dims, false); if (!f) throw new Error("Can't perform binary op on the given tensors"); s = f; let p = s.length, d = e[0].dims.length !== 0 ? e[0].dims.length : 1, b = e[1].dims.length !== 0 ? e[1].dims.length : 1, g = e[0].dims.length !== 0 ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", y = e[1].dims.length !== 0 ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", v = D2(a.session.backend.glContext.version), _ = i ? ` ${o.body} void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = ${o.name}(a, b); ${v.output} = result; }` : ` ${o.body} float process(int indices[${p}]) { int aindices[${d}]; int bindices[${b}]; ${g} ${y} return ${o.name}(_A(aindices), _B(bindices)); }`; return { name: o.name, inputNames: ["A", "B"], inputTypes: [n, n], output: { dims: s, type: t, textureType: n }, shaderSource: _, hasMain: i }; } let u = D2(a.session.backend.glContext.version), l = ` ${o.body} void main() { vec4 v1 = ${u.texture2D}(A, TexCoords); vec4 v2 = ${u.texture2D}(B, TexCoords); vec4 result = ${o.name}(v1, v2); ${u.output} = result; } `; return { name: o.name, inputNames: ["A", "B"], inputTypes: [n, n], output: { dims: e[0].dims, type: t, textureType: n }, shaderSource: l, hasMain: true }; }, ua2 = (a, e) => [a.run(yt2(a, e, gf3()), e)], la2 = (a, e) => [a.run(yt2(a, e, Sf3(), "bool"), e)], fa2 = (a, e) => [a.run(yt2(a, e, xf3()), e)], ca2 = (a, e) => [a.run(yt2(a, e, wf3(), "bool"), e)], pa2 = (a, e) => [a.run(yt2(a, e, If4(), "bool"), e)], da2 = (a, e) => [a.run(yt2(a, e, _f3(), "bool"), e)], ha2 = (a, e) => [a.run(yt2(a, e, Tf3()), e)], ma2 = (a, e) => [a.run(yt2(a, e, Of3(), "bool"), e)], ba2 = (a, e) => [a.run(yt2(a, e, Pf3()), e)], ya2 = (a, e) => [a.run(yt2(a, e, Ef3()), e)], ga2 = (a, e) => [a.run(yt2(a, e, vf3()), e)], xa2 = (a, e) => [a.run(yt2(a, e, Af3(), "bool"), e)]; }); Ia2 = x(() => { "use strict"; z2(); va2 = (a, e, o) => (kf3(e), [a.cast(e[0], o)]), wa2 = (a) => et.tensorDataTypeFromProto(a.attributes.getInt("to")), kf3 = (a) => { if (!a || a.length !== 1) throw new Error("Cast requires 1 input."); if (a[0].type === "string") throw new Error("Invalid input type."); }; }); Sa2 = x(() => { "use strict"; q2(); N(); Pt3(); Qt2(); Bf3 = (a, e) => ({ name: "Concat (packed)", inputNames: Array.from({ length: a }, (o, t) => `X${t}`), inputTypes: Array(a).fill(2), cacheHint: e }), Ff3 = (a, e, o, t) => { let n = o[0].dims.slice(); if (t >= n.length || t < -1 * n.length) throw new Error("axis specified for concat doesn't match input dimensionality"); t < 0 && (t = n.length + t); let r = n.slice(0); for (let F2 = 1; F2 < o.length; F2++) { let st2 = o[F2].dims.slice(); for (let Ot = 0; Ot < n.length; Ot++) if (Ot === t) r[t] += st2[Ot]; else if (n[Ot] !== st2[Ot]) throw new Error("non concat dimensions must match"); } let s = r.length, i = ce2("coords", s), u = at2(s), l = Et2(), f = o.map((F2) => F2.dims), p = St2(s), d = new Array(f.length - 1); d[0] = f[0][t]; for (let F2 = 1; F2 < d.length; F2++) d[F2] = d[F2 - 1] + f[F2][t]; let b = p[t], g = p.slice(-2), y = p.join(), v = `if (${b} < ${d[0]}) { return getChannel( getX0(${y}), vec2(${g.join()})); }`; for (let F2 = 1; F2 < d.length; F2++) { let st2 = d[F2 - 1]; v += ` if (${b} < ${d[F2]} && ${b} >= ${d[F2 - 1]}) { return getChannel( getX${F2}(${ur2(p, b, st2)}), vec2(${ur2(g, b, st2)})); }`; } let _ = d.length, O2 = d[d.length - 1]; v += ` return getChannel( getX${_}(${ur2(p, b, O2)}), vec2(${ur2(g, b, O2)}));`; let S = D2(a.session.backend.glContext.version), C = ` ${l} float getValue(${p.map((F2) => "int " + F2)}) { ${v} } void main() { ${u} coords = getOutputCoords(); int lastDim = coords.${p[s - 1]}; coords.${p[s - 1]} = coords.${p[s - 2]}; coords.${p[s - 2]} = lastDim; vec4 result = vec4(getValue(${i}), 0., 0., 0.); ${i[s - 1]} = ${i[s - 1]} + 1; if (${i[s - 1]} < ${r[s - 1]}) { result.g = getValue(${i}); } ${i[s - 2]} = ${i[s - 2]} + 1; if (${i[s - 2]} < ${r[s - 2]}) { result.a = getValue(${i}); } ${i[s - 1]} = ${i[s - 1]} - 1; if (${i[s - 2]} < ${r[s - 2]} && ${i[s - 1]} < ${r[s - 1]}) { result.b = getValue(${i}); } ${S.output} = result; } `; return { ...e, output: { dims: r, type: o[0].type, textureType: 2 }, shaderSource: C, hasMain: true }; }, _a2 = (a, e, o) => { let t = Bf3(e.length, o.cacheKey); return { ...t, get: () => Ff3(a, t, e, o.axis) }; }, ur2 = (a, e, o) => { let t = a.indexOf(e); return a.map((r, s) => s === t ? `${r} - ${o}` : r).join(); }; }); Ea2 = x(() => { "use strict"; tt3(); N(); Sa2(); Oa2 = (a, e, o) => (Mf3(e), a.session.pack && e[0].dims.length > 1 ? [a.run(_a2(a, e, o), e)] : [a.run(Gf3(a, e, o), e)]), Nf3 = (a, e) => ({ name: "Concat", inputNames: Array.from({ length: a }, (o, t) => `X${t}`), inputTypes: Array(a).fill(0), cacheHint: e }), Cf3 = (a, e, o, t) => { let n = o[0].dims.slice(); if (t >= n.length || t < -1 * n.length) throw new Error("axis specified for concat doesn't match input dimensionality"); t < 0 && (t = n.length + t); let r = n.slice(0); for (let b = 1; b < o.length; b++) { let g = o[b].dims.slice(); for (let y = 0; y < n.length; y++) if (y === t) r[t] += g[y]; else if (n[y] !== g[y]) throw new Error("non concat dimensions must match"); } let s = r.length, i = new Array(o.length), u = 0; for (let b = 0; b < i.length; ++b) u += o[b].dims[t], i[b] = u; let l = ""; o.length < 5 ? l = Aa2(i) : l = Rf3(i); let f = Vf3(o.length, s), p = zf3(i), d = ` ${f} ${p} ${l} float process(int indices[${s}]) { int textureIndex = getTextureWhereDataResides (indices[${t}]); if(textureIndex != 0) { indices[${t}] = indices[${t}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1))); } return fetchDataFromCorrectTexture(textureIndex, indices); }`; return { ...e, output: { dims: r, type: o[0].type, textureType: 0 }, shaderSource: d }; }, Gf3 = (a, e, o) => { let t = Nf3(e.length, o.cacheKey); return { ...t, get: () => Cf3(a, t, e, o.axis) }; }, Aa2 = (a) => `int getTextureWhereDataResides(int index) { ${a.map((o, t) => `if(index<${o}) {return ${t};} `).join("")} }`, Rf3 = (a) => Aa2(a), Vf3 = (a, e) => { let o = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`]; for (let t = 0; t < a; ++t) t === 0 ? o.push(` if (textureIndex == ${t}) { return _X${t}(indices); }`) : t === a - 1 ? o.push(` else { return _X${t}(indices); }`) : o.push(` else if (textureIndex == ${t}) { return _X${t}(indices); }`); return o.push(" }"), o.join(` `); }, zf3 = (a) => { let e = ["int getSizeInConcatAxisValueFromIndex(int index) {"]; for (let o = 0; o < a.length; ++o) o === 0 ? e.push(` if (index == ${o}) { return ${a[o]}; }`) : o === a.length - 1 ? e.push(` else { return ${a[o]}; }`) : e.push(` else if (index == ${o}) { return ${a[o]}; }`); return e.push(" }"), e.join(` `); }, Pa2 = (a) => $({ axis: a.attributes.getInt("axis") }), Mf3 = (a) => { if (!a || a.length < 1) throw new Error("too few inputs"); let e = a[0].type, o = a[0].dims.length; if (e === "string") throw new Error("string tensor is not supported yet"); for (let t of a) { if (t.type !== e) throw new Error("input tensors should be one type"); if (t.dims.length !== o) throw new Error("input tensors should have the same shape"); } }; }); yn2 = x(() => { "use strict"; tt3(); z2(); Bt(); q2(); N(); sc2 = (a, e, o, t) => { let n = a.session.pack ? 2 : 0, r = D2(a.session.backend.glContext.version); return { ...e, output: { dims: o.dims, type: o.type, textureType: n }, shaderSource: ` ${t.body} void main() { vec4 v = ${r.texture2D}(A, TexCoords); v = ${t.name}_(v); ${r.output} = v; } `, hasMain: true }; }, J2 = (a, e, o, t) => { let n = a.session.pack ? 2 : 0, r = { name: o.name, inputTypes: [n], inputNames: ["A"], cacheHint: t }; return { ...r, get: () => sc2(a, r, e, o) }; }, Da2 = (a, e) => [a.run(J2(a, e[0], Uf3()), e)], La2 = (a, e) => [a.run(J2(a, e[0], Wf3()), e)], $a2 = (a, e) => [a.run(J2(a, e[0], Hf3()), e)], ka2 = (a, e) => [a.run(J2(a, e[0], qf3()), e)], mn2 = (a, e, o) => [a.run(J2(a, e[0], pn3(o.min, o.max), o.cacheKey), e)], Ba2 = (a) => $({ min: a.attributes.getFloat("min", Jt3), max: a.attributes.getFloat("max", Zt2) }), Fa2 = (a, e) => { let o = uc2(a, e); return mn2(a, [e[0]], o); }, uc2 = (a, e) => { if (e.length >= 3 && (!a.session.isInitializer(e[1].dataId) || !a.session.isInitializer(e[2].dataId))) throw new Error("dynamic clip attributes are not allowed"); let o = e.length >= 3 ? e[1].numberData[0] : Jt3, t = e.length >= 3 ? e[2].numberData[0] : Zt2; return $({ min: o, max: t }); }, Na2 = (a, e) => [a.run(J2(a, e[0], jf3()), e)], Ca2 = (a, e) => [a.run(J2(a, e[0], Kf3()), e)], Ga2 = (a, e, o) => [a.run(J2(a, e[0], Xf3(o.alpha), o.cacheKey), e)], Ra2 = (a) => $({ alpha: a.attributes.getFloat("alpha", 1) }), Va2 = (a, e) => [a.run(J2(a, e[0], Jf3()), e)], za2 = (a, e) => [a.run(J2(a, e[0], Zf3()), e)], bn2 = (a, e) => [a.run(J2(a, e[0], Yf3()), e)], Ma2 = (a, e, o) => [a.run(J2(a, e[0], Qf3(o.alpha), o.cacheKey), e)], Ua2 = (a) => $({ alpha: a.attributes.getFloat("alpha", 0.01) }), Wa2 = (a, e) => [a.run(J2(a, e[0], tc2()), e)], Ha2 = (a, e) => [a.run(J2(a, e[0], ec2()), e)], qa = (a, e) => [a.run(J2(a, e[0], rc2()), e)], ja2 = (a, e) => [a.run(J2(a, e[0], dn3()), e)], Ka2 = (a, e) => [a.run(J2(a, e[0], hn2()), e)], Xa2 = (a, e) => [a.run(J2(a, e[0], nc2()), e)], Ja2 = (a, e) => [a.run(J2(a, e[0], oc2()), e)], Za3 = (a, e) => [a.run(J2(a, e[0], ic2()), e)], Ya2 = (a, e) => [a.run(J2(a, e[0], ac2()), e)]; }); te2 = x(() => { "use strict"; z2(); yn2(); pe = (a) => { let e = a.getString("activation", ""); if (e === "Clip") { let [o, t] = a.getFloats("activation_params", [Jt3, Zt2]); return { activation: e, clipMax: t, clipMin: o, activationCacheKey: `${e}:${o},${t}` }; } return { activation: e, activationCacheKey: e }; }; }); ts3 = x(() => { "use strict"; pt(); q2(); N(); lr2(); te2(); fc2 = (a, e) => ({ name: "GroupedConv", inputNames: a ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: a ? [0, 0, 0] : [0, 0], cacheHint: e }), cc2 = (a, e, o, t) => { let r = e.length > 2 ? "value += getBias(output_channel);" : "", s = e[0].dims.slice(), i = e[1].dims.slice(), u = i[0] / t.group; M2.verbose("GroupedConv", `autpPad:${t.autoPad}, dilations:${t.dilations}, group:${t.group}, kernelShape:${t.kernelShape}, pads:${t.pads}, strides:${t.strides}`); let l = de(s, i, t.dilations, t.pads, t.strides), f = D2(a.session.backend.glContext.version), { activationFunction: p, applyActivation: d } = Dt(t), b = ` const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); ${p} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 xRCCorner = coords.zw * strides - pads; int group_id = output_channel / ${u}; float value = 0.0; for (int wInChannel = 0; wInChannel < ${i[1]}; wInChannel++) { int input_channel = group_id * ${i[1]} + wInChannel; for (int wHeight = 0; wHeight < ${i[2]}; wHeight++) { int xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}; if (xHeight < 0 || xHeight >= ${s[2]}) { continue; } for (int wWidth = 0; wWidth < ${i[3]}; wWidth++) { int xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}; if (xWidth < 0 || xWidth >= ${s[3]}) { continue; } float xVal = getX(batch, input_channel, xWidth, xHeight); float wVal = getW(output_channel, wInChannel, wWidth, wHeight); value += xVal*wVal; } } } ${r} ${d} ${f.output} = vec4(value, .0, .0, .0); } `; return { ...o, output: { dims: l, type: e[0].type, textureType: 0 }, shaderSource: b, hasMain: true }; }, Qa3 = (a, e, o) => { let t = fc2(e.length > 2, o.cacheKey); return { ...t, get: () => cc2(a, e, t, o) }; }; }); rs3 = x(() => { "use strict"; q2(); N(); Qt2(); pc2 = (a) => ({ name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [2], cacheHint: a }), dc2 = (a, e, o, t, n, r) => { let s = o.dims, i = t.dims, u = 2, l = 3, f = n.length, p = [i[1] * i[2] * i[3], n[2] * n[3]], d = i[2] * i[3], b = Et2(), g = D2(a.session.backend.glContext.version), y = ""; for (let _ = 0; _ <= 1; _++) for (let O2 = 0; O2 <= 1; O2++) y += ` blockIndex = rc.x + ${O2}; pos = rc.y + ${_}; if(blockIndex < ${p[1]} && pos < ${p[0]}) { offsetY = int(blockIndex / (${n[f - 1]})) * ${r.strides[0]} - ${r.pads[0]}; d0 = offsetY + ${r.dilations[0]} * (imod(pos, ${d}) / ${i[2]}); if(d0 < ${s[u]} && d0 >= 0) { offsetX = imod(blockIndex, ${n[f - 1]}) * ${r.strides[1]} - ${r.pads[1]}; d1 = offsetX + ${r.dilations[1]} * imod(imod(pos, ${d}), ${i[2]}); if(d1 < ${s[l]} && d1 >= 0) { ch = int(float(pos)/ ${d}.); innerDims = vec2(d0, d1); result[${_ * 2 + O2}] = getChannel( getA(0, ch, int(innerDims.x), int(innerDims.y)), innerDims); } } } `; let v = ` ${b} void main() { ivec2 rc = getOutputCoords(); vec4 result = vec4(0.0); int blockIndex, pos, offsetY, d0, offsetX, d1, ch; vec2 innerDims; ${y} ${g.output} = result; } `; return { ...e, output: { dims: p, type: o.type, textureType: 2 }, shaderSource: v, hasMain: true }; }, es3 = (a, e, o, t, n) => { let r = pc2(n.cacheKey); return { ...r, get: () => dc2(a, r, e, o, t, n) }; }; }); fr2 = x(() => { "use strict"; z2(); N(); Pt3(); te2(); Tn(); ns3 = (a, e, o) => (bc2(e), a.session.pack ? [a.run(cr2(a, e, o), e)] : [a.run(gn2(e, o), e)]), os3 = (a) => pe(a.attributes), hc2 = (a, e) => ({ name: "MatMul", inputNames: a ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: a ? [0, 0, 0] : [0, 0], cacheHint: e }); bc2 = (a) => { if (!a || a.length !== 2) throw new Error("MatMul requires 2 inputs."); if (a[0].dims[a[0].dims.length - 1] !== a[1].dims[a[1].dims.length - 2]) throw new Error("shared dimension does not match."); if (a[0].type !== "float32" && a[0].type !== "float64" || a[1].type !== "float32" && a[1].type !== "float64") throw new Error("inputs should be float type"); if (a[0].type !== a[1].type) throw new Error("inputs types should match"); }; }); Tn = x(() => { "use strict"; z2(); q2(); N(); Pt3(); te2(); fr2(); yc2 = (a, e) => ({ name: "MatMul (packed)", inputNames: a ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: a ? [2, 2, 2] : [2, 2], cacheHint: e }), gc2 = (a, e, o, t) => { let n = o.length > 2, r = n ? "value += getBiasForMatmul();" : "", s = o[0].dims, i = o[1].dims, u = it2.calcShape(s, i, true), l = !A.areEqual(o[0].dims, o[1].dims); if (!u) throw new Error("Can't use matmul on the given tensors"); let f = s[s.length - 1], p = Math.ceil(f / 2), d = s.length, b = i.length, g = D2(a.session.backend.glContext.version), y = at2(u.length), v = u.length, _ = St2(), { activationFunction: O2, applyActivation: S } = Dt(t), C = n ? `${xn2(y, _, o[2].dims, u, true)}` : "", F2 = l ? `${xc2(y, _, o, u)}` : "", st2 = l ? "getAAtOutCoordsMatmul(i)" : `getA(${Tc2(_, d)})`, Ot = l ? "getBAtOutCoordsMatmul(i)" : `getB(${vc2(_, b)})`, kr3 = l ? "" : `${y} rc = getOutputCoords(); int lastDim = rc.${_[v - 1]}; rc.${_[v - 1]} = rc.${_[v - 2]}; rc.${_[v - 2]} = lastDim; `, Mt2 = ` ${F2} ${C} ${O2} void main() { ${kr3} vec4 value = vec4(0); for (int i = 0; i < ${p}; i++) { vec4 a = ${st2}; vec4 b = ${Ot}; value += (a.rrbb * b.rgrg); value += (a.ggaa * b.baba); } ${r} ${S} ${g.output} = value; }`; return { ...e, output: { dims: u, type: o[0].type, textureType: 2 }, shaderSource: Mt2, hasMain: true }; }, cr2 = (a, e, o) => { let t = yc2(e.length > 2, o.activationCacheKey); return { ...t, get: () => gc2(a, t, e, o) }; }; }); as3 = x(() => { "use strict"; lr2(); rs3(); Tn(); is3 = (a, e, o) => { let t = e[0].dims, n = e[1].dims, r = de(t, n, o.dilations, o.pads, o.strides), s = a.run(es3(a, e[0], e[1], r, o), [e[0]]), i = a.reshapePacked(e[1], [n[0], n[1] * n[2] * n[3]]), u = e.length === 3 ? [i, s, e[2]] : [i, s], l = a.run(cr2(a, u, o), u); return a.reshapePacked(l, r); }; }); wn = x(() => { "use strict"; N(); wc2 = (a) => ({ name: "Im2Col", inputNames: ["X"], inputTypes: [0], cacheHint: a }), Ic2 = (a, e, o, t, n, r) => { let s = o.dims, i = t.dims, u = n.length, l = vn(s, i, n, 4), f = ` const int XC = ${s[1]}; const int XH = ${s[2]}; const int XW = ${s[3]}; const int KH = ${r.kernelShape[0]}; const int KW = ${r.kernelShape[1]}; const int dilationH = ${r.dilations[0]}; const int dilationW = ${r.dilations[1]}; const int strideH = ${r.strides[0]}; const int strideW = ${r.strides[1]}; const int padH = ${r.pads[0]}; const int padW = ${r.pads[1]}; const int KHKW = KH*KW; const int XCKHKW = XC * KHKW; const int outputChannels = 4; vec4 process(int indices[${u}]) { int b = indices[0]; // batch size int oh = indices[1] * strideH - padH; //output height int ow = indices[2] * strideW - padW; //output width int p = indices[3] * outputChannels; //patch vec4 value = vec4(0.0); for(int i=0; i < outputChannels; ++i) { if(p < XCKHKW) { int patchC = p / KHKW; int patchH = (p - patchC*KHKW) / KW; int patchW = (p - patchC*KHKW) - patchH * KW; int xh2 = oh + patchH * dilationH; int xw2 = ow + patchW * dilationW; int x[${s.length}]; x[0] = b; x[1] = patchC; x[2] = xh2; x[3] = xw2; if(xh2 >= 0 && xh2 < XH && xw2 >= 0 && xw2 < XW) { value[i] = _X(x); } } ++p; } return value; } `; return { ...e, output: { dims: l, type: o.type, textureType: 4 }, shaderSource: f }; }, ss3 = (a, e, o, t, n) => { let r = wc2(n.cacheKey); return { ...r, get: () => Ic2(a, r, e, o, t, n) }; }, vn = (a, e, o, t = 4) => [o[0], o[2], o[3], Math.ceil(a[1] * e[2] * e[3] / t)]; }); ls3 = x(() => { "use strict"; z2(); q2(); N(); te2(); wn(); _c2 = (a, e) => ({ name: "ConvDotProduct", inputNames: a ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: a ? [0, 4, 0] : [0, 4], cacheKey: e.activationCacheKey }), Sc2 = (a, e, o, t, n) => { let r = o[0].dims, s = o[1].dims, i = [s[0], Math.ceil(r[1] * s[2] * s[3] / 4)], u = vn(r, s, t), [l, f] = a.calculateTextureWidthAndHeight(i, 4), p = A.computeStrides(u), [d, b] = a.calculateTextureWidthAndHeight(u, 4), g = t.length, y = o.length < 3 ? "0.0" : "_B(b)", v = Math.ceil(r[1] * s[2] * s[3] / 4), { activationFunction: _, applyActivation: O2 } = Dt(n), S = D2(a.session.backend.glContext.version), C = ` ${_} float process(int indices[${g}]) { int b[1]; b[0] = indices[1]; int im2col[4]; im2col[0] = indices[0]; im2col[1] = indices[2]; im2col[2] = indices[3]; int im2colOffset = im2col[0] * ${p[0]} + im2col[1] * ${p[1]} + im2col[2] * ${p[2]}; int kernelOffset = indices[1] * ${i[1]}; float value = ${y}; for (int i = 0; i < ${v}; ++i) { vec2 im2colCoords = offsetToCoords(im2colOffset, ${d}, ${b}); vec2 kernelCoords = offsetToCoords(kernelOffset, ${l}, ${f}); value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords)); ++im2colOffset; ++kernelOffset; } ${O2} return value; }`; return { ...e, output: { dims: t, type: o[0].type, textureType: 0 }, shaderSource: C }; }, us3 = (a, e, o, t) => { let n = _c2(e.length > 2, t); return { ...n, get: () => Sc2(a, n, e, o, t) }; }; }); lr2 = x(() => { "use strict"; tt3(); z2(); ts3(); as3(); ls3(); te2(); wn(); fr2(); de = (a, e, o, t, n) => { let r = a[0], s = a.slice(2), i = s.length, u = e[0], f = e.slice(2).map((g, y) => g + (g - 1) * (o[y] - 1)), d = s.map((g, y) => g + t[y] + t[y + i]).map((g, y) => Math.floor((g - f[y] + n[y]) / n[y])); return [r, u].concat(...d); }, In = (a, e, o) => (Dc2(e, o), Oc2(a, e, o)), Oc2 = (a, e, o) => { let t = Ec2(o, e), n = a.session.pack, r = t.kernelShape[0] === 1 && t.kernelShape[1] === 1; return t.group > 1 ? [a.run(Qa3(a, e, t), e)] : r && n ? [Ac2(a, e, t)] : n && e[0].dims.length === 4 && e[0].dims[0] === 1 && !r ? [is3(a, e, t)] : [Pc2(a, e, t)]; }, Ac2 = (a, e, o) => { let t = e[0].dims, n = e[1].dims, r = de(t, n, o.dilations, o.pads, o.strides), s = a.reshapeUnpacked(e[0], [t[1], t[2] * t[3]]), i = a.reshapeUnpacked(e[1], [n[0], n[1]]), u = e.length > 2 ? [i, s, e[2]] : [i, s], l = a.run(gn2(u, o), u); return a.reshapeUnpacked(l, r); }, Pc2 = (a, e, o) => { let t = e[0].dims, n = e[1].dims, r = de(t, n, o.dilations, o.pads, o.strides), s = a.run(ss3(a, e[0], e[1], r, o), [e[0]]), i = e.length === 3 ? [s, e[1], e[2]] : [s, e[1]]; return a.run(us3(a, e, r, o), i); }, Ec2 = (a, e) => { let o = a.kernelShape.slice(); if (a.kernelShape.length === 0) for (let r = 2; r < e[1].dims.length; ++r) o.push(e[1].dims[r]); let t = a.pads.slice(); Xt3.adjustPadsBasedOnAutoPad(e[0].dims, a.strides, a.dilations, o, t, a.autoPad); let n = Object.assign({}, a); return Object.assign(n, { kernelShape: o, pads: t, cacheKey: a.cacheKey }), n; }, _n2 = (a) => { let e = a.attributes, o = pe(e), t = e.getString("auto_pad", "NOTSET"), n = e.getInts("dilations", [1, 1]), r = e.getInt("group", 1), s = e.getInts("kernel_shape", []), i = e.getInts("pads", [0, 0, 0, 0]), u = e.getInts("strides", [1, 1]); return $({ autoPad: t, dilations: n, group: r, kernelShape: s, pads: i, strides: u, ...o }); }, Dc2 = (a, e) => { if (!a || a.length !== 2 && a.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (a[0].dims.length !== 4 || a[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv"); let o = a[0].dims[1], t = a[1].dims[1] * e.group; if (o !== t) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); if (a.length === 3 && (a[2].dims.length !== 1 || a[1].dims[0] !== a[2].dims[0])) throw new Error("invalid bias"); let n = a[0].dims.length - 2; if (e.dilations.length !== n) throw new Error(`dilations should be ${n}D`); if (e.strides.length !== n) throw new Error(`strides should be ${n}D`); if (e.pads.length !== n * 2) throw new Error(`pads should be ${n * 2}D`); if (e.kernelShape.length !== 0 && e.kernelShape.length !== a[1].dims.length - 2) throw new Error("invalid kernel shape"); if (a[0].type !== "float32" || a[1].type !== "float32") throw new Error("Conv input(X,W) should be float tensor"); if (a.length === 3 && a[2].type !== "float32") throw new Error("Conv input(bias) should be float tensor"); }; }); ps3 = x(() => { "use strict"; tt3(); q2(); N(); te2(); Lc2 = (a, e, o, t, n, r) => (a - 1) * e + o + (t - 1) * n + 1 - r, $c2 = (a, e, o, t, n) => { let r = Math.floor(a / 2); e === "SAME_UPPER" ? (o[t] = r, o[n] = a - r) : e === "SAME_LOWER" && (o[t] = a - r, o[n] = r); }, kc2 = (a, e, o, t, n, r, s, i) => { let u = a.length - 2, l = i.length === 0; for (let f = 0; f < u; ++f) { let p = l ? a[f + 2] * r[f] : i[f], d = Lc2(a[f + 2], r[f], n[f], e[f], o[f], p); $c2(d, t, n, f, f + u), l && i.push(r[f] * (a[f + 2] - 1) + s[f] + (e[f] - 1) * o[f] + 1 - n[f] - n[f + u]); } }, fs5 = (a, e, o) => (Vc2(e, o), Bc2(a, e, o)), Bc2 = (a, e, o) => { let t = Rc2(o, e); return [Gc2(a, e, t)]; }, Fc2 = (a, e) => ({ name: "ConvTranspose", inputNames: a ? ["X", "W", "B"] : ["X", "W"], inputTypes: a ? [0, 0, 0] : [0, 0], cacheHint: e }), Nc2 = (a, e, o, t) => { let r = e.length > 2 ? "getB(output_channel)" : "0.0", s = e[0].dims, i = e[1].dims, u = i[1], l = i[0] / t.group, f = [e[0].dims[0], e[1].dims[1] * t.group, ...t.outputShape], p = D2(a.session.backend.glContext.version), { activationFunction: d, applyActivation: b } = Dt(t), g = ` const ivec2 strides = ivec2(${t.strides[0]}, ${t.strides[1]}); const ivec2 pads = ivec2(${t.pads[0]}, ${t.pads[1]}); ${d} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 loc = coords.zw + pads; int group_id = output_channel / ${u}; int wOutChannel = output_channel - group_id * ${u}; float value = ${r}; for (int inChannelOffset = 0; inChannelOffset < ${l}; inChannelOffset++) { int input_channel = group_id * ${l} + inChannelOffset; for (int wWOff = 0; wWOff < ${i[2]}; wWOff++) { for (int wHOff = 0; wHOff < ${i[3]}; wHOff++) { ivec2 wOff = ivec2(wWOff * ${t.dilations[0]}, wHOff * ${t.dilations[1]}); ivec2 wLoc = loc - wOff; ivec2 wLocIn = wLoc / strides; if ( wLocIn * strides == wLoc && wLocIn.x >= 0 && wLocIn.x < ${s[2]} && wLocIn.y >= 0 && wLocIn.y < ${s[3]} ) { float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); value += xVal * wVal; } } } } ${b} ${p.output} = vec4(value, .0, .0, .0); } `; return { ...o, output: { dims: f, type: e[0].type, textureType: 0 }, shaderSource: g, hasMain: true }; }, Cc2 = (a, e, o) => { let t = Fc2(e.length > 2, o.cacheKey); return { ...t, get: () => Nc2(a, e, t, o) }; }, Gc2 = (a, e, o) => a.run(Cc2(a, e, o), e), Rc2 = (a, e) => { let o = a.kernelShape.slice(); if (a.kernelShape.length === 0) for (let i = 2; i < e[1].dims.length; ++i) o.push(e[1].dims[i]); let t = a.pads.slice(), n = a.outputShape.slice(), r = e[0].dims; kc2(r, o, a.dilations, a.autoPad, t, a.strides, a.outputPadding, n); let s = Object.assign({}, a); return Object.assign(s, { kernelShape: o, pads: t, outputShape: n, cacheKey: a.cacheKey }), s; }, cs3 = (a) => { let e = a.attributes, o = pe(e), t = e.getString("auto_pad", "NOTSET"), n = e.getInts("dilations", [1, 1]), r = e.getInt("group", 1), s = e.getInts("kernel_shape", []), i = e.getInts("output_padding", [0, 0]), u = e.getInts("output_shape", []), l = e.getInts("pads", [0, 0, 0, 0]), f = e.getInts("strides", [1, 1]); return $({ autoPad: t, dilations: n, group: r, kernelShape: s, outputPadding: i, outputShape: u, pads: l, strides: f, ...o }); }, Vc2 = (a, e) => { if (!a || a.length !== 2 && a.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); if (a[0].dims.length !== 4 || a[1].dims.length !== 4) throw new Error("currently only support 2-dimensional conv"); let o = a[0].dims[1], t = a[1].dims[0]; if (o !== t) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); let n = a[1].dims[1] * e.group; if (a.length === 3 && (a[2].dims.length !== 1 || a[2].dims[0] !== n)) throw new Error("invalid bias"); let r = a[0].dims.length - 2; if (e.dilations.length !== r) throw new Error(`dilations should be ${r}D`); if (e.strides.length !== r) throw new Error(`strides should be ${r}D`); if (e.pads.length !== r * 2) throw new Error(`pads should be ${r * 2}D`); if (e.outputPadding.length !== r) throw new Error(`output_padding should be ${r}D`); if (e.kernelShape.length !== 0 && e.kernelShape.length !== a[1].dims.length - 2) throw new Error("invalid kernel shape"); if (e.outputShape.length !== 0 && e.outputShape.length !== a[0].dims.length - 2) throw new Error("invalid output shape"); if (a[0].type !== "float32" || a[1].type !== "float32") throw new Error("ConvTranspose input(X,W) should be float tensor"); if (a.length === 3 && a[2].type !== "float32") throw new Error("ConvTranspose input(bias) should be float tensor"); }; }); pr2 = x(() => { "use strict"; tt3(); z2(); N(); ds3 = { name: "Transpose", inputNames: ["A"], inputTypes: [0] }, ee2 = (a, e, o) => (Wc2(e), [a.run({ ...ds3, cacheHint: o.cacheKey, get: () => zc2(a, e[0], o.perm) }, e)]), hs3 = (a) => $({ perm: a.attributes.getInts("perm", []) }), zc2 = (a, e, o) => { let t = e.dims; o = ms3(t, o); let n = Mc2(t, o), r = t.length, s = ` ${Uc2("perm", o, r)} float process(int indices[${r}]) { int a[${r}]; perm(a, indices); return _A(a); }`; return { ...ds3, output: { dims: n, type: e.type, textureType: 0 }, shaderSource: s }; }, ms3 = (a, e) => (e && e.length !== a.length && (e = [...a.keys()].reverse()), e), Mc2 = (a, e) => (e = ms3(a, e), A.sortBasedOnPerm(a, e)), Uc2 = (a, e, o) => { let t = []; t.push(`void ${a}(out int a[${o}], int src[${o}]) {`); for (let n = 0; n < o; ++n) t.push(` a[${e[n]}]=src[${n}];`); return t.push(" }"), t.join(` `); }, Wc2 = (a) => { if (!a || a.length !== 1) throw new Error("Transpose requires 1 input."); if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("input should be float tensor"); }; }); gs3 = x(() => { "use strict"; pr2(); bs3 = (a, e, o) => { Hc2(e); let t = o.blocksize, n = t * t, r = o.mode === "DCR" ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], s = o.mode === "DCR" ? [e[0].dims[0], t, t, e[0].dims[1] / n, e[0].dims[2], e[0].dims[3]] : [e[0].dims[0], e[0].dims[1] / n, t, t, e[0].dims[2], e[0].dims[3]], i = a.reshapeUnpacked(e[0], s), u = { perm: r, cacheKey: `${r}` }, [l] = ee2(a, [i], u), f = [e[0].dims[0], e[0].dims[1] / n, e[0].dims[2] * t, e[0].dims[3] * t]; return [a.reshapeUnpacked(l, f)]; }, ys3 = (a) => { let e = a.attributes.getInt("blocksize"); if (e < 1) throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`); let o = a.attributes.getString("mode", "DCR"); if (o !== "DCR" && o !== "CRD") throw new Error(`unrecognized mode: ${o} for DepthToSpace`); return { mode: o, blocksize: e }; }, Hc2 = (a) => { if (a.length !== 1) throw new Error(`DepthToSpace expect 1 inputs, but got ${a.length}`); if (a[0].type === "string" || a[0].dims.length !== 4) throw new TypeError("DepthToSpace input should be a 4-D numeric tensor"); }; }); vs3 = x(() => { "use strict"; z2(); xs3 = (a, e, o) => { qc2(e, o); let t = A.flattenShape(e[0].dims, o); return [a.reshapeUnpacked(e[0], t)]; }, Ts3 = (a) => a.attributes.getInt("axis", 1), qc2 = (a, e) => { if (!a || a.length !== 1) throw new Error("Flatten requires 1 input."); let o = a[0].dims.length; if (o === 0) throw new Error("scalar tensor is not supported."); if (e < -o || e > o) throw new Error("Invalid axis"); if (a[0].type === "string") throw new Error("string tensor is not supported."); }; }); Pe2 = x(() => { "use strict"; Vt2 = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"]; }); _s3 = x(() => { "use strict"; tt3(); Pe2(); z2(); N(); ws3 = (a, e, o) => (Jc2(e, o.axis), [a.run(Xc2(a, e, o), e)]), Is3 = (a) => $({ axis: a.attributes.getInt("axis", 0) }), jc2 = { name: "Gather", inputNames: ["A", "B"], inputTypes: [0, 0] }, Kc2 = (a, e, o, t) => { let n = o[0].dims.slice(), r = o[1].dims.slice(), s = new Array(n.length + r.length - 1); t = A.normalizeAxis(t, n.length); let i = []; for (let d = 0; d < s.length; d++) d < t ? (s[d] = n[d], i.push(`inputIdx[${d}] = outputIdx[${d}];`)) : d < t + r.length ? (s[d] = r[d - t], i.push(`indexDataIdx[${d - t}] = outputIdx[${d}];`)) : (s[d] = n[d - r.length + 1], i.push(`inputIdx[${d - r.length + 1}] = outputIdx[${d}];`)); let u = s.length || 1, l = n.length, f = r.length || 1, p = ` float process(int outputIdx[${u}]) { int inputIdx[${l}]; int indexDataIdx[${f}]; indexDataIdx[0] = 0; ${i.join(` `)} int idx = int(_B(indexDataIdx)); inputIdx[${t}] = idx < 0 ? idx + ${n[t]} : idx; return _A(inputIdx); }`; return { ...e, output: { dims: s, type: o[0].type, textureType: 0 }, shaderSource: p }; }, Xc2 = (a, e, o) => { let t = { ...jc2, cacheHint: o.cacheKey }; return { ...t, get: () => Kc2(a, t, e, o.axis) }; }, Jc2 = (a, e) => { if (!a || a.length !== 2) throw new Error("Gather requires 2 inputs."); let o = a[0].dims.length; if (o < 1) throw new Error("Invalid input shape."); if (e < -o || e > o - 1) throw new Error("Invalid axis."); if (Vt2.indexOf(a[0].type) === -1) throw new Error("Invaid input type."); if (a[1].type !== "int32" && a[1].type !== "int16") throw new Error("Invaid input type."); }; }); Ps3 = x(() => { "use strict"; tt3(); z2(); N(); Sn2 = (a, e, o) => (Qc2(e, o), [a.run(Zc2(e, o), e)]), Ss3 = (a, e) => { let o = a.attributes.getInt("transA", 0) !== 0, t = a.attributes.getInt("transB", 0) !== 0, n = a.attributes.getFloat("alpha", 1), r = a.attributes.getFloat("beta", 1); return $({ transA: o, transB: t, alpha: n, beta: r, isOptionalC: e }); }, Os3 = (a) => Ss3(a, false), As3 = (a) => Ss3(a, true), Zc2 = (a, e) => { let o = { name: "Gemm", inputNames: a.length === 3 ? ["A", "B", "C"] : ["A", "B"], inputTypes: a.length === 3 ? [0, 0, 0] : [0, 0], key: e.cacheKey }; return { ...o, get: () => Yc2(o, a, e) }; }, Yc2 = (a, e, o) => { let t = e[0].dims.slice(), n = e[1].dims.slice(), [r, s] = er2.getShapeOfGemmResult(t, o.transA, n, o.transB, e.length === 3 ? e[2].dims : void 0), i = [r, s]; if (!i) throw new Error("Can't use gemm on the given tensors"); let u = t[t.length - 1], l = ""; o.transA && (u = t[0]), o.transA && o.transB ? l = "value += _A_T(a) * _B_T(b);" : o.transA && !o.transB ? l = "value += _A_T(a) * _B(b);" : !o.transA && o.transB ? l = "value += _A(a) * _B_T(b);" : !o.transA && !o.transB && (l = "value += _A(a) * _B(b);"); let f = i.length, p = e.length === 3 ? `int c[${e[2].dims.length}];` : "", d = e.length === 3 ? "bcastIndices_C(indices, c);" : "", b = e.length === 3 ? "value += beta * _C(c);" : "", g = ` float process(int indices[${f}]) { int a[${f}]; int b[${f}]; ${p} copyVec(indices, a); copyVec(indices, b); ${d} float value = 0.0; for (int k=0; k<${u}; ++k) { a[${f - 1}] = k; b[${f - 2}] = k; ${l} } value = value * alpha; ${b} return value; }`; return { ...a, output: { dims: i, type: e[0].type, textureType: 0 }, variables: [{ name: "alpha", type: "float", data: o.alpha }, { name: "beta", type: "float", data: o.beta }], shaderSource: g }; }, Qc2 = (a, e) => { if (!a) throw new Error("Input is missing"); if (e.isOptionalC && (a.length < 2 || a.length > 3)) throw new Error("Invaid input shape."); if (!e.isOptionalC && a.length !== 3) throw new Error("Gemm requires 3 inputs"); if (a.length === 3 && a[2].dims.length !== 1 && a[2].dims.length !== 2) throw new Error("Invalid input shape of C"); if (a[0].type !== "float32" && a[0].type !== "float64" || a[1].type !== "float32" && a[1].type !== "float64" || a.length === 3 && a[2].type !== "float32" && a[2].type !== "float64") throw new Error("Invalid input type."); if (a[0].type !== a[1].type || a.length === 3 && a[0].type !== a[2].type) throw new Error("Input types are mismatched"); }; }); Ls3 = x(() => { "use strict"; tt3(); N(); Es3 = (a, e, o) => (op3(e), [a.run(rp2(a, e, o), e)]), Ds3 = (a) => { let e = a.attributes.getFloat("scale"), o = a.attributes.getFloats("bias"); return $({ scale: e, bias: o }); }, tp2 = { name: "ImageScaler", inputNames: ["X"], inputTypes: [0] }, ep2 = (a, e, o, t) => { let n = o[0].dims.slice(), r = n.length, i = ` ${np2(t.bias.length)} float process(int indices[${r}]) { return _X(indices) * scale + getBias(bias, indices[1]); }`; return { ...e, output: { dims: n, type: o[0].type, textureType: 0 }, variables: [{ name: "bias", type: "float", arrayLength: t.bias.length, data: t.bias }, { name: "scale", type: "float", data: t.scale }], shaderSource: i }; }, rp2 = (a, e, o) => { let t = { ...tp2, cacheHint: o.cacheKey }; return { ...t, get: () => ep2(a, t, e, o) }; }, np2 = (a) => { let e = [`float getBias(float bias[${a}], int channel) {`]; for (let o = 0; o < a; ++o) o === 0 ? e.push(` if (channel == ${o}) { return bias[${o}]; }`) : o === a - 1 ? e.push(` else { return bias[${o}]; }`) : e.push(` else if (channel == ${o}) { return bias[${o}]; }`); return e.push(" }"), e.join(` `); }, op3 = (a) => { if (!a || a.length !== 1) throw new Error("ImageScaler requires 1 input."); if (a[0].dims.length !== 4) throw new Error("Invalid input shape."); if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("Invalid input type."); }; }); Fs3 = x(() => { "use strict"; q2(); N(); ks3 = (a, e, o) => { fp3(e); let t = a.run(ap3(e[0]), e); return [a.run(lp3(a, e[0], o, t.dims), [e[0], t, e[1], e[2]])]; }, Bs3 = (a) => a.attributes.getFloat("epsilon", 1e-5), $s3 = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [0] }, ip3 = (a, e) => { let o = e.dims.slice(), t = o[1], n = o[2] * o[3], r = [o[0], t], s = ` vec4 process(int[2] indices) { vec4 v = vec4(0.0); int a[4]; a[0] = indices[0]; a[1] = indices[1]; float temp = 0.0; for(int a2=0; a2<${o[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${o[3]}; a3++) { a[3] = a3; float x = _X(a); temp += x; } } float mean = temp / float(${n}); temp = 0.0; for(int a2=0; a2<${o[2]}; a2++) { a[2] = a2; for(int a3=0; a3<${o[3]}; a3++) { a[3] = a3; float x = _X(a); temp += (x - mean) * (x - mean); } } v.r = mean; v.g = temp / float(${n}); return v; }`; return { ...a, output: { dims: r, type: e.type, textureType: 4 }, shaderSource: s }; }, ap3 = (a) => ({ ...$s3, get: () => ip3($s3, a) }), sp3 = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [0, 4, 0, 0] }, up3 = (a, e, o, t, n) => { let r = D2(a.session.backend.glContext.version), [s, i] = a.calculateTextureWidthAndHeight(n, 4), [u, l] = [s / 4, i], f = ` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); vec2 coords = offsetToCoords(offset, ${u}, ${l}); return ${r.texture2D}(MeanAndVariance, coords); } float process(int[4] indices) { int mv[2]; mv[0] = indices[0]; mv[1] = indices[1]; vec4 mean_and_variance = get_MeanAndVariance(mv); float mean = mean_and_variance.r; float variance = mean_and_variance.g; int sb[1]; sb[0] = indices[1]; float scale = _Scale(sb); float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; }`; return { ...e, output: { dims: o.dims, type: o.type, textureType: 0 }, variables: [{ name: "epsilon", type: "float", data: t }], shaderSource: f }; }, lp3 = (a, e, o, t) => { let n = { ...sp3, cacheHint: `${o}` }; return { ...n, get: () => up3(a, n, e, o, t) }; }, fp3 = (a) => { if (!a || a.length !== 3) throw new Error("InstanceNormalization requires 3 inputs."); let e = a[0], o = a[1], t = a[2]; if (e.dims.length < 3 || o.dims.length !== 1 || t.dims.length !== 1) throw new Error("Invalid input shape."); if (o.dims[0] !== e.dims[1] || t.dims[0] !== e.dims[1]) throw new Error("Input shapes are mismatched."); if (e.type !== "float32" && e.type !== "float64" || o.type !== "float32" && o.type !== "float64" || t.type !== "float32" && t.type !== "float64") throw new Error("Invalid input type."); if (a[0].dims.length !== 4) throw new Error("Only support 4-D input shape."); }; }); Rs3 = x(() => { "use strict"; tt3(); N(); Ns3 = (a, e, o) => (dp3(e), [a.run(pp3(e, o), e)]), Cs3 = (a) => { let e = a.attributes.getFloat("alpha", 1e-4), o = a.attributes.getFloat("beta", 0.75), t = a.attributes.getFloat("bias", 1), n = a.attributes.getInt("size"); return $({ alpha: e, beta: o, bias: t, size: n }); }, Gs3 = { name: "LRN", inputNames: ["X"], inputTypes: [0] }; dp3 = (a) => { if (!a || a.length !== 1) throw new Error("LRN requires 1 input."); if (a[0].dims.length !== 4) throw new Error('currently only support LRN for input with "NCHW" format'); if (a[0].type !== "float32") throw new Error("input should be float type"); }; }); Us3 = x(() => { "use strict"; tt3(); z2(); q2(); N(); hp3 = { name: "Pad", inputNames: ["A"], inputTypes: [0] }, On2 = (a, e, o) => (yp3(e), [a.run({ ...hp3, cacheHint: o.cacheKey, get: () => bp3(a, e[0], o) }, e)]), Vs3 = (a) => { let e = a.attributes.getString("mode", "constant"), o = a.attributes.getFloat("value", 0), t = a.attributes.getInts("pads"); return $({ mode: e, value: o, pads: t }); }, zs3 = (a, e, o) => { gp3(e); let t = mp3(a, e, o); return On2(a, [e[0]], t); }, Ms3 = (a) => a.attributes.getString("mode", "constant"), mp3 = (a, e, o) => { if (!a.session.isInitializer(e[1].dataId) || e.length >= 3 && !a.session.isInitializer(e[2].dataId)) throw new Error("dynamic pad attributes are not allowed"); let t = Array.from(e[1].integerData), n = e.length >= 3 ? e[2].floatData[0] : 0; return $({ mode: o, pads: t, value: n }); }, bp3 = (a, e, o) => { let t = A.padShape(e.dims.slice(), o.pads), n = t.length, s = ` ${xp3(a, e, o)} float process(int[${n}] indices) { return padA(indices); }`; return { name: "Pad", inputNames: ["A"], inputTypes: [0], output: { dims: t, type: e.type, textureType: 0 }, shaderSource: s }; }, yp3 = (a) => { if (!a || a.length !== 1) throw new Error("Pad requires 1 input"); if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("Invalid input type."); }, gp3 = (a) => { if (!a || a.length !== 2 && a.length !== 3) throw new Error("Pad requires 2 or 3 inputs"); if (a[1].type !== "int32") throw new Error("Invalid input type."); if (a.length >= 3 && a[2].type === "string") throw new Error("Invalid input type."); }, xp3 = (a, e, o) => { let t = D2(a.session.backend.glContext.version), [n, r] = a.calculateTextureWidthAndHeight(e.dims, 0), s = A.computeStrides(e.dims); switch (o.mode) { case "constant": return Tp3(t, e.dims, s, n, r, o.pads, o.value); case "reflect": return vp3(t, e.dims, s, n, r, o.pads); case "edge": return wp3(t, e.dims, s, n, r, o.pads); default: throw new Error("Invalid mode"); } }, Tp3 = (a, e, o, t, n, r, s) => { let i = e.length, u = ""; for (let l = i - 1; l >= 0; --l) u += ` k = m[${l}] - ${r[l]}; if (k < 0) return constant; if (k >= ${e[l]}) return constant; offset += k * ${o[l]}; `; return ` float padA(int m[${i}]) { const float constant = float(${s}); int offset = 0; int k = 0; ${u} vec2 coords = offsetToCoords(offset, ${t}, ${n}); float value = getColorAsFloat(${a.texture2D}(A, coords)); return value; } `; }, vp3 = (a, e, o, t, n, r) => { let s = e.length, i = ""; for (let u = s - 1; u >= 0; --u) i += ` k = m[${u}] - ${r[u]}; if (k < 0) { k = -k; } { const int _2n_1 = ${2 * (e[u] - 1)}; k = int( mod( float(k), float(_2n_1) ) ) ; if(k >= ${e[u]}) { k = _2n_1 - k; } } offset += k * ${o[u]}; `; return ` float padA(int m[${s}]) { int offset = 0; int k = 0; ${i} vec2 coords = offsetToCoords(offset, ${t}, ${n}); float value = getColorAsFloat(${a.texture2D}(A, coords)); return value; } `; }, wp3 = (a, e, o, t, n, r) => { let s = e.length, i = ""; for (let u = s - 1; u >= 0; --u) i += ` k = m[${u}] - ${r[u]}; if (k < 0) k = 0; if (k >= ${e[u]}) k = ${e[u] - 1}; offset += k * ${o[u]}; `; return ` float padA(int m[${s}]) { int offset = 0; int k = 0; ${i} vec2 coords = offsetToCoords(offset, ${t}, ${n}); float value = getColorAsFloat(${a.texture2D}(A, coords)); return value; } `; }; }); ru2 = x(() => { "use strict"; tt3(); z2(); N(); Hs3 = (a, e, o) => { hr2(e); let t = { name: "AveragePool", inputNames: ["X"], inputTypes: [0], cacheHint: o.cacheKey }; return [a.run({ ...t, get: () => js2(e, t, false, o) }, e)]; }, qs2 = (a) => { let e = a.attributes.getString("auto_pad", "NOTSET"), o = a.attributes.getInt("ceil_mode", 0), t = a.attributes.getInt("count_include_pad", 0) !== 0, n = a.attributes.getInts("kernel_shape"), r = a.attributes.getInts("strides", []), s = a.attributes.getInts("pads", []); if (o !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); return $({ autoPad: e, ceilMode: o, countIncludePad: t, kernelShape: n, strides: r, pads: s }); }, js2 = (a, e, o, t) => { let [n, r] = Qs2(a, t, o), s = A.size(n.kernelShape), i = "value += _X(x);", u = ""; n.countIncludePad ? u += `value /= float(${s});` : u += `value /= float(${s} - pad);`; let f = ` ${eu2(a[0].dims, n, i, u, "0.0")} `; return { ...e, output: { dims: r, type: a[0].type, textureType: 0 }, shaderSource: f }; }, Ks3 = (a, e, o) => { hr2(e); let t = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [0], cacheHint: `${o.countIncludePad}` }; return [a.run({ ...t, get: () => js2(e, t, true, o) }, e)]; }, Xs2 = (a) => { let e = a.attributes.getInt("count_include_pad", 0) !== 0; return $({ autoPad: "", ceilMode: 0, countIncludePad: e, kernelShape: [], strides: [], pads: [] }); }, Js2 = (a, e, o) => { hr2(e); let t = { name: "MaxPool", inputNames: ["X"], inputTypes: [0], cacheHint: o.cacheKey }; return [a.run({ ...t, get: () => Ys3(e, t, false, o) }, e)]; }, Zs2 = (a) => { let e = a.attributes.getString("auto_pad", "NOTSET"), o = a.attributes.getInt("ceil_mode", 0), t = a.attributes.getInts("kernel_shape"), n = a.attributes.getInts("strides", []), r = a.attributes.getInts("pads", []), s = a.attributes.getInt("storage_order", 0), i = a.attributes.getInts("dilations", []); if (s !== 0) throw new Error("column major storage order is not yet supported for MaxPool"); if (o !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); return $({ autoPad: e, ceilMode: o, countIncludePad: false, kernelShape: t, strides: n, pads: r, storageOrder: s, dilations: i }); }, Ys3 = (a, e, o, t) => { let [n, r] = Qs2(a, t, o), s = ` value = max(_X(x), value); `, i = "", l = ` ${eu2(a[0].dims, n, s, i, "-1e5")} `; return { ...e, output: { dims: r, type: a[0].type, textureType: 0 }, shaderSource: l }; }, Qs2 = (a, e, o) => { let t = a[0].dims.slice(), n = Object.hasOwnProperty.call(e, "dilations"), r = e.kernelShape.slice(), s = e.strides.slice(), i = n ? e.dilations.slice() : [], u = e.pads.slice(); Xt3.adjustPoolAttributes(o, t, r, s, i, u); let l = Xt3.computePoolOutputShape(o, t, s, i, r, u, e.autoPad), f = Object.assign({}, e); return n ? Object.assign(f, { kernelShape: r, strides: s, pads: u, dilations: i, cacheKey: e.cacheKey }) : Object.assign(f, { kernelShape: r, strides: s, pads: u, cacheKey: e.cacheKey }), [f, l]; }, Ip3 = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, Ws2 = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [0] }, tu2 = (a, e) => (hr2(e), [a.run({ ...Ws2, get: () => Ys3(e, Ws2, true, Ip3) }, e)]), hr2 = (a) => { if (!a || a.length !== 1) throw new Error("Pool ops requires 1 input."); if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("Invalid input type."); }, eu2 = (a, e, o, t, n) => { let r = a.length; if (e.kernelShape.length <= 2) { let s = e.kernelShape[e.kernelShape.length - 1], i = e.strides[e.strides.length - 1], u = e.pads[e.pads.length / 2 - 1], l = e.pads[e.pads.length - 1], f = a[r - 1], p = "", d = "", b = ""; if (u + l !== 0 ? p = ` for (int i = 0; i < ${s}; i++) { x[${r} - 1] = indices[${r} - 1] * ${i} - ${u} + i; if (x[${r} - 1] < 0 || x[${r} - 1] >= ${f}) { pad++; continue; } ${o} }` : p = ` for (int i = 0; i < ${s}; i++) { x[${r} - 1] = indices[${r} - 1] * ${i} - ${u} + i; ${o} }`, e.kernelShape.length === 2) { let y = e.kernelShape[e.kernelShape.length - 2], v = e.strides[e.strides.length - 2], _ = e.pads[e.pads.length / 2 - 2], O2 = e.pads[e.pads.length - 2], S = a[r - 2]; _ + O2 !== 0 ? d = ` for (int j = 0; j < ${y}; j++) { x[${r} - 2] = indices[${r} - 2] * ${v} - ${_} + j; if (x[${r} - 2] < 0 || x[${r} - 2] >= ${S}) { pad+= ${s}; continue; } ` : d = ` for (int j = 0; j < ${y}; j++) { x[${r} - 2] = indices[${r} - 2] * ${v} - ${_} + j; `, b = ` } `; } return ` float process(int indices[${r}]) { int x[${r}]; copyVec(indices, x); float value = ${n}; int pad = 0; ${d} ${p} ${b} ${t} return value; } `; } else { let s = A.size(e.kernelShape), i = A.computeStrides(e.kernelShape), u = i.length, l = e.pads.length, f = _p3(u), p = dr2(a, "inputDims"), d = dr2(e.pads, "pads"), b = dr2(i, "kernelStrides"), g = dr2(e.strides, "strides"), y = e.pads.reduce((O2, S) => O2 + S), v = ""; return y ? v = ` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; break; } } if (!isPad) { ${o} }` : v = ` } ${o} `, ` ${f} float process(int indices[${r}]) { int x[${r}]; copyVec(indices, x); int offset[${u}]; int pads[${l}]; int inputDims[${r}]; int kernelStrides[${u}]; int strides[${u}]; ${d} ${p} ${g} ${b} float value = ${n}; int pad = 0; bool isPad = false; for (int i = 0; i < ${s}; i++) { offsetToIndices(i, kernelStrides, offset); isPad = false; for (int j = ${r} - ${u}; j < ${r}; j++) { x[j] = indices[j] * strides[j - ${r} + ${u}] + offset[j - ${r} + ${u}] - pads[j - 2]; ${v} } ${t} return value; } `; } }, dr2 = (a, e) => { let o = ""; for (let t = 0; t < a.length; t++) o += ` ${e}[${t}] = ${a[t]}; `; return o; }, _p3 = (a) => ` void offsetToIndices(int offset, int[${a}] strides, out int[${a}] indices) { if (${a} == 0) { return; } for (int i = 0; i < ${a} - 1; ++i) { indices[i] = offset / strides[i]; offset -= indices[i] * strides[i]; } indices[${a} - 1] = offset; }`; }); fu2 = x(() => { "use strict"; tt3(); Pe2(); z2(); N(); re = (a, e, o, t, n) => { Op3(e); let r = { name: t, inputNames: ["A"], inputTypes: [0] }; return [a.run({ ...r, cacheHint: o.cacheKey, get: () => Sp3(a, e, o, t, n, r) }, e)]; }, zt = (a) => { let e = a.attributes.getInts("axes", []), o = a.attributes.getInt("keepdims", 1) === 1; return $({ axes: e, keepDims: o }); }, Sp3 = (a, e, o, t, n, r) => { let s = [], i = e[0].dims.length || 1, u = [], l = A.normalizeAxes(o.axes, e[0].dims.length), f = n(e, l), p = f[1]; for (let g = 0; g < e[0].dims.length; g++) l.indexOf(g) >= 0 || l.length === 0 ? (o.keepDims && s.push(1), p = ` for(int j${g} = 0; j${g} < ${e[0].dims[g]}; j${g}++) { inputIdx[${g}] = j${g}; ${p} }`) : (u.push(`inputIdx[${g}] = outputIdx[${s.length}];`), s.push(e[0].dims[g])); let b = ` float process(int outputIdx[${s.length || 1}]) { float value; // final result int inputIdx[${i}]; // addressing input data ${u.join(` `)} ${f[0]} // init ops for reduce max/min ${p} ${f[2]} // final computation for reduce mean return value; }`; return { ...r, output: { dims: s, type: e[0].type, textureType: 0 }, shaderSource: b }; }, Op3 = (a) => { if (!a || a.length !== 1) throw new Error("Reduce op requires 1 input."); if (Vt2.indexOf(a[0].type) === -1) throw new Error("Invalid input type."); }, nu2 = (a, e, o) => re(a, e, o, "ReduceSum", () => ["value = 0.0;", "value += _A(inputIdx);", ""]), ou3 = (a, e, o) => re(a, e, o, "ReduceMean", (n, r) => { let s = 1; for (let i = 0; i < n[0].dims.length; i++) (r.indexOf(i) >= 0 || r.length === 0) && (s *= n[0].dims[i]); return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${s}.;`]; }), iu3 = (a, e, o) => re(a, e, o, "ReduceMax", (n, r) => { let s = []; for (let i = 0; i < n[0].dims.length; i++) (r.indexOf(i) >= 0 || r.length === 0) && s.push(`inputIdx[${i}] = 0;`); return [`${s.join(` `)} value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""]; }), au2 = (a, e, o) => re(a, e, o, "ReduceMin", (n, r) => { let s = []; for (let i = 0; i < n[0].dims.length; i++) (r.indexOf(i) >= 0 || r.length === 0) && s.push(`inputIdx[${i}] = 0;`); return [`${s.join(` `)} value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""]; }), su3 = (a, e, o) => re(a, e, o, "ReduceProd", () => ["value = 1.0;", "value *= _A(inputIdx);", ""]), uu2 = (a, e, o) => re(a, e, o, "ReduceLogSum", () => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"]), lu3 = (a, e, o) => re(a, e, o, "ReduceLogSumSquare", () => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]); }); pu2 = x(() => { "use strict"; z2(); cu2 = (a, e) => { let o = A.calculateReshapedDims(e[0].dims, e[1].integerData); return a.session.pack ? [a.reshapePacked(e[0], o)] : [a.reshapeUnpacked(e[0], o)]; }; }); En2 = x(() => { "use strict"; tt3(); q2(); N(); du2 = { name: "Upsample", inputNames: ["X"], inputTypes: [0] }, An2 = (a, e, o) => (Pn2(e, o), [a.run({ ...du2, cacheHint: o.cacheKey, get: () => Ap3(a, e, o) }, e)]), hu2 = (a) => Ee2(a, 7), mu2 = (a) => Ee2(a, 9), Ee2 = (a, e) => { let o = e >= 10, t = a.attributes.getString("mode", "nearest"); if (t !== "nearest" && t !== "linear" && (e < 11 || t !== "cubic")) throw new Error(`unrecognized mode: ${t}`); let n = []; e < 9 && (n = a.attributes.getFloats("scales"), mr2(n, t, o)); let r = a.attributes.getFloat("extrapolation_value", 0), s = e > 10 ? a.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric"; if (["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(s) === -1) throw new Error(`coordinate_transform_mode '${s}' is not supported`); let i = s === "tf_crop_and_resize", u = i, l = t === "nearest" && e >= 11 ? a.attributes.getString("nearest_mode", "round_prefer_floor") : ""; if (["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(l) === -1) throw new Error(`nearest_mode '${l}' is not supported`); let f = a.attributes.getFloat("cubic_coeff_a", -0.75), p = a.attributes.getInt("exclude_outside", 0) !== 0; if (p && t !== "cubic") throw new Error("exclude_outside can be set to 1 only when mode is CUBIC."); let d = e < 11 ? true : t === "nearest" && s === "asymmetric" && l === "floor", b = 0, g = 0, y = 0; return e > 10 ? a.inputs.length > 2 ? (b = 1, g = 2, y = 3) : (g = 1, y = 2) : e === 9 && (g = 1), $({ opset: e, isResize: o, mode: t, scales: n, extrapolationValue: r, coordinateTransformMode: s, useExtrapolation: u, needRoiInput: i, nearestMode: l, cubicCoefficientA: f, excludeOutside: p, useNearest2xOptimization: d, roiInputIdx: b, scalesInputIdx: g, sizesInputIdx: y }); }, Ap3 = (a, e, o) => { let t = D2(a.session.backend.glContext.version), [n, r] = a.calculateTextureWidthAndHeight(e[0].dims, 0), s = e[0].dims.map((y, v) => Math.floor(y * o.scales[v])), [i, u] = a.calculateTextureWidthAndHeight(s, 0), l = s.length, f = new Array(l), p = new Array(l), d = ` int output_pitches[${l}]; int input_pitches[${l}]; `; for (let y = l - 1; y >= 0; y--) f[y] = y === l - 1 ? 1 : f[y + 1] * s[y + 1], p[y] = y === l - 1 ? 1 : p[y + 1] * e[0].dims[y + 1], d += ` output_pitches[${y}] = ${f[y]}; input_pitches[${y}] = ${p[y]}; `; let b = ` float getInputFloat(int index) { vec2 coords = offsetToCoords(index, ${n}, ${r}); float value = getColorAsFloat(${t.texture2D}(X, coords)); return value; } `, g = o.mode === "nearest" ? ` ${b} float process(int indices[${l}]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${i}, ${u}); ${d} int d, m; for (int dim = 0; dim < ${l}; ++dim) { d = output_index / output_pitches[dim]; m = output_index - d * output_pitches[dim]; output_index = m; if (scales[dim] != 1 && d > 0) { int d2 = d / scales[dim]; m = d - d2 * scales[dim]; d = d2; } input_index += input_pitches[dim] * d; } return getInputFloat(input_index); }` : l === 4 ? ` ${b} float process(int indices[4]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${i}, ${u}); ${d} int m; int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m / output_pitches[1]; m = m - index_of_dim1 * output_pitches[1]; index_of_dim2 = m / output_pitches[2]; m = m - index_of_dim2 * output_pitches[2]; index_of_dim3 = m; int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; index_of_input_dim2 = index_of_dim2 / scales[2]; y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; index_of_input_dim3 = index_of_dim3 / scales[3]; x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; input_index = index_of_dim0 * input_pitches[0] + index_of_dim1 * input_pitches[1] + index_of_input_dim2 * input_pitches[2] + index_of_input_dim3; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim2 = false; if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) { // It's the end in dimension 2 x01 = x00; end_of_dim2 = true; } else { x01 = getInputFloat(input_index + input_pitches[2]); } if (index_of_input_dim3 == (input_pitches[2] - 1)) { // It's the end in dimension 3 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); }` : ` ${b} float process(int indices[2]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${i}, ${u}); ${d} int m; int index_of_dim0, index_of_dim1; index_of_dim0 = output_index / output_pitches[0]; m = output_index - index_of_dim0 * output_pitches[0]; index_of_dim1 = m; int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; index_of_input_dim0 = index_of_dim0 / scales[0]; y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; index_of_input_dim1 = index_of_dim1 / scales[1]; x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; float x00 = getInputFloat(input_index); float x10, x01, x11; bool end_of_dim0 = false; if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) { // It's the end in dimension 0 x01 = x00; end_of_dim0 = true; } else { x01 = getInputFloat(input_index + input_pitches[0]); } if (index_of_input_dim1 == (input_pitches[0] - 1)) { // It's the end in dimension 1 x10 = x00; x11 = x01; } else { x10 = getInputFloat(input_index + 1); x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); } float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); }`; return { ...du2, output: { dims: s, type: e[0].type, textureType: 0 }, shaderSource: g, variables: [{ name: "scales", type: "int", arrayLength: o.scales.length, data: o.scales.map((y) => Math.ceil(y)) }] }; }, Pn2 = (a, e) => { if (!a || e.opset < 9 && a.length !== 1 || e.opset >= 9 && e.opset < 11 && a.length !== 2 || e.opset >= 11 && a.length < 2) throw new Error("invalid inputs."); if (e.scales.length > 0 && a[0].dims.length !== e.scales.length) throw new Error("Invalid input shape."); if (a[0].type === "string") throw new Error("Invalid input tensor types."); }, mr2 = (a, e, o) => { if (o) { for (let t of a) if (t <= 0) throw new Error("Scale value should be greater than 0."); } else for (let t of a) if (t < 1) throw new Error("Scale value should be greater than or equal to 1."); if ((e === "linear" || e === "cubic") && a.length !== 2 && (a.length !== 4 || a[0] !== 1 || a[1] !== 1)) throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${o ? "Resize" : "Upsample"} opeartor.`); }; }); gu2 = x(() => { "use strict"; q2(); N(); Pt3(); Qt2(); En2(); Dn2 = { name: "Resize", inputNames: ["A"], inputTypes: [2] }, Ln3 = (a, e, o) => (Pn2(e, o), [a.run({ ...Dn2, cacheHint: o.cacheKey, get: () => Pp3(a, e, o) }, e)]), bu2 = (a) => Ee2(a, 10), yu2 = (a) => Ee2(a, 11), Pp3 = (a, e, o) => { let t = D2(a.session.backend.glContext.version), [n, r] = Ep3(e, o); if (n.every((S) => S === 1) && o.coordinateTransformMode !== "tf_crop_and_resize") return { ...Dn2, output: { dims: r, type: e[0].type, textureType: 2 }, hasMain: true, shaderSource: `void main() { vec4 v = ${t.texture2D}(X, TexCoords); ${t.output} = v; }` }; let i = r.length; if (i < 2) throw new Error(`output dimension should be at least 2, but got ${i}`); let u = r[i - 2], l = r[i - 1], f = e[0].dims; if (i !== f.length) throw new Error(`output dimension should match input ${f.length}, but got ${i}`); let p = f[i - 2], d = f[i - 1], b = n[i - 2], g = n[i - 1], y = ""; if (o.mode !== "linear") throw new Error(`resize (packed) does not support mode: '${o.mode}'`); switch (o.coordinateTransformMode) { case "asymmetric": y = ` vec4 getSourceFracIndex(ivec4 coords) { return vec4(coords) / scaleWHWH; } `; break; case "half_pixel": y = ` vec4 getSourceFracIndex(ivec4 coords) { return (vec4(coords) + 0.5) / scaleWHWH - 0.5; } `; break; case "pytorch_half_pixel": y = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 fcoords = vec4(coords); return vec4( ${l}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, ${u}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, ${l}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, ${u}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 ); } `; break; case "align_corners": y = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 resized = vec4(${l}.0 - 1.0, ${u}.0 - 1.0, ${l}.0 - 1.0, ${u}.0 - 1.0); vec4 original = vec4(${d}.0 - 1.0, ${p}.0 - 1.0, ${d}.0 - 1.0, ${p}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `; break; default: throw new Error(`resize (packed) does not support coordinateTransformMode: '${o.coordinateTransformMode}'`); } let v = at2(i), _ = Et2(), O2 = ` const vec2 inputWH = vec2(${p}.0, ${d}.0); const vec4 scaleWHWH = vec4(float(${b}), float(${g}), float(${b}), float(${g})); ${_} ${y} float getAValue(int x10, int r, int c, int d) { return getChannel(getA(x10, r, c, d), vec2(c, d)); } void main() { ${v} rc = getOutputCoords(); int batch = rc[0]; int depth = rc[1]; // retrieve the 4 coordinates that is used in the 4 packed output values. ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); // calculate the source index in fraction vec4 sourceFrac = getSourceFracIndex(coords); // get the lower and upper bound of the 4 values that will be packed into one texel. ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); bool hasNextRow = rc.w < ${u - 1}; bool hasNextCol = rc.z < ${l - 1}; // pack x00, x01, x10, x11's top-left corner into one vec4 structure vec4 topLeft = vec4( getAValue(batch, depth, x00.x, x00.y), hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); // pack x00, x01, x10, x11's top-right corner into one vec4 structure vec4 topRight = vec4( getAValue(batch, depth, x00.x, x00.w), hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure vec4 bottomLeft = vec4( getAValue(batch, depth, x00.z, x00.y), hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure vec4 bottomRight = vec4( getAValue(batch, depth, x00.z, x00.w), hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); // calculate the interpolation fraction on u and v direction vec4 frac = vec4(sourceFrac) - floor(sourceFrac); vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); vec4 top = mix(topLeft, topRight, clampFrac.ywyw); vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); vec4 newValue = mix(top, bottom, clampFrac.xxzz); ${t.output} = vec4(newValue); } `; return { ...Dn2, output: { dims: r, type: e[0].type, textureType: 2 }, hasMain: true, shaderSource: O2 }; }, Ep3 = (a, e) => { let t = a[0].dims, n = e.scales, r; if (n.length === 0) { let i = a[e.scalesInputIdx]; if (i && i.size !== 0) { if (a[e.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); n = Dp3(i, e.mode, e.isResize); } else { let u = a[e.sizesInputIdx]; if (!u || u.size === 0) throw new Error("Either scales or sizes MUST be provided as input."); r = Array.from(u.integerData), n = Lp3(r, t, e.mode, e.isResize); } } else if (a[e.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input."); let s = r || t.map((i, u) => Math.floor(i * n[u])); return [n, s]; }, Dp3 = (a, e, o) => { let t = Array.from(a.floatData); return mr2(t, e, o), t; }, Lp3 = (a, e, o, t) => { let n = e.length, r = new Array(n); for (let s = 0, i = n; s < i; s++) if (e[s] === 0) { if (a[s] !== 0) throw new Error("Input dim is zero but required output dim is non-zero."); r[s] = 1; } else r[s] = a[s] / e[s]; return mr2(r, o, t), r; }; }); Tu3 = x(() => { "use strict"; Yt3(); xu2 = (a, e) => ($p3(e), [new Y2([e[0].dims.length], "int32", void 0, void 0, new Int32Array(e[0].dims))]), $p3 = (a) => { if (!a || a.length !== 1) throw new Error("Shape requires 1 input."); }; }); Su2 = x(() => { "use strict"; tt3(); Pe2(); z2(); N(); $n2 = { name: "Slice", inputNames: ["A"], inputTypes: [0] }, vu2 = (a, e, o) => (kp3(e), [a.run({ ...$n2, cacheHint: o.cacheKey, get: () => Iu2(a, e[0], o) }, e)]), wu2 = (a) => { let e = a.attributes.getInts("starts"), o = a.attributes.getInts("ends"), t = a.attributes.getInts("axes", []); return $({ starts: e, ends: o, axes: t }); }, Iu2 = (a, e, o) => { let t = o.axes.length === 0 ? e.dims.slice(0).map((p, d) => d) : o.axes, n = A.normalizeAxes(t, e.dims.length), r = o.starts.map((p, d) => p > e.dims[n[d]] - 1 ? e.dims[n[d]] : A.normalizeAxis(p, e.dims[n[d]])), s = o.ends.map((p, d) => p > e.dims[n[d]] - 1 ? e.dims[n[d]] : A.normalizeAxis(p, e.dims[n[d]])), i = e.dims.slice(), u = []; for (let p = 0; p < n.length; p++) i[n[p]] = s[p] - r[p], r[p] > 0 && u.push(`outputIdx[${n[p]}] += ${r[p]};`); let f = ` float process(int outputIdx[${i.length}]) { ${u.join(` `)} return _A(outputIdx); }`; return { ...$n2, output: { dims: i, type: e.type, textureType: 0 }, shaderSource: f }; }, kp3 = (a) => { if (!a || a.length !== 1) throw new Error("Slice requires 1 input."); if (Vt2.indexOf(a[0].type) === -1) throw new Error("Invalid input type."); }, _u2 = (a, e) => { Fp3(e); let o = Bp3(a, e); return [a.run({ ...$n2, cacheHint: o.cacheKey, get: () => Iu2(a, e[0], o) }, [e[0]])]; }, Bp3 = (a, e) => { if (!a.session.isInitializer(e[1].dataId) || !a.session.isInitializer(e[2].dataId) || e.length >= 4 && !a.session.isInitializer(e[3].dataId) || e.length >= 5 && !a.session.isInitializer(e[4].dataId)) throw new Error("dynamic slice attributes are not allowed"); if (e.length >= 5 && e[4].integerData.some((s) => s !== 1)) throw new Error("currently non-1 steps is not supported for Slice"); let o = Array.from(e[1].integerData), t = Array.from(e[2].integerData), n = e.length >= 4 ? Array.from(e[3].integerData) : [], r = `${n};${o};${t}`; return { starts: o, ends: t, axes: n, cacheKey: r }; }, Fp3 = (a) => { if (!a || a.length < 3 || a.length > 5) throw new Error("Invalid input number."); if (a[1].type !== "int32" || a[1].dims.length !== 1) throw new Error("Invalid input type."); if (a[2].type !== "int32" || a[2].dims.length !== 1) throw new Error("Invalid input type."); if (a.length >= 4 && (a[3].type !== "int32" || a[3].dims.length !== 1)) throw new Error("Invalid input type."); if (a.length >= 5 && (a[4].type !== "int32" || a[4].dims.length !== 1)) throw new Error("Invalid input type."); }; }); Fu3 = x(() => { "use strict"; tt3(); z2(); q2(); N(); pr2(); Ou2 = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [0] }, Au2 = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [0, 0] }, Pu2 = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [0, 0, 0] }, Eu3 = (a, e, o) => { Bu2(e); let t = e[0].dims.slice(), n = A.normalizeAxis(o.axis, t.length), r = A.sizeToDimension(t, n), s = A.sizeFromDimension(t, n); return ku3(a, e, o, r, s); }, Du2 = (a) => $({ axis: a.attributes.getInt("axis", 1) }), Lu3 = (a) => $({ axis: a.attributes.getInt("axis", -1) }), $u2 = (a, e, o) => { Bu2(e); let t = e[0].dims.slice(), n = A.normalizeAxis(o.axis, t.length), r = t.length, s = n !== r - 1, i = [], u = [], l = [], f; s && (u = Array.from({ length: r }).map((g, y) => y), u[n] = r - 1, u[r - 1] = n, u.map((g) => i.push(t[g])), f = $({ perm: u }), l = ee2(a, e, f)); let p = s ? A.sizeToDimension(i, r - 1) : A.sizeToDimension(t, r - 1), d = s ? A.sizeFromDimension(i, r - 1) : A.sizeFromDimension(t, r - 1), b = ku3(a, s ? l : e, o, p, d); return s ? ee2(a, b, f) : b; }, ku3 = (a, e, o, t, n) => { let r = Np3(a, e[0], t, n, [t]), s = a.run({ ...Ou2, cacheHint: o.cacheKey, get: () => r }, e), i = Cp3(a, e[0], t, n, r.output.dims, [t]), u = a.run({ ...Au2, cacheHint: o.cacheKey, get: () => i }, [e[0], s]), l = Gp3(a, e[0], t, n, r.output.dims, i.output.dims); return [a.run({ ...Pu2, cacheHint: o.cacheKey, get: () => l }, [e[0], s, u])]; }, Np3 = (a, e, o, t, n) => { let [r, s] = a.calculateTextureWidthAndHeight(e.dims, 0), i = n.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (n.length !== 1) throw new Error("Dimensionality of the output should be 1"); if (n[0] !== o) throw new Error("Shape of the output should be equal to logical row count"); let u = D2(a.session.backend.glContext.version), l = ` float process(int[${i}] indices) { int logical_row_start_offset = indices[0] * ${t}; float max = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset, ${r}, ${s} ))); for(int i=1; i<${t}; ++i) { float current = getColorAsFloat(${u.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${r}, ${s}))); if(current > max) max = current; } return max; }`; return { ...Ou2, output: { dims: n, type: e.type, textureType: 0 }, shaderSource: l }; }, Cp3 = (a, e, o, t, n, r) => { let [s, i] = a.calculateTextureWidthAndHeight(e.dims, 0), u = r.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (r.length !== 1) throw new Error("Dimensionality of the output should be 1"); if (r[0] !== o) throw new Error("Shape of the output should be equal to logical row count"); if (n.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1"); if (n[0] !== o) throw new Error("Shape of the intermediate results should be equal to logical row count"); let l = D2(a.session.backend.glContext.version), f = ` float process(int[${u}] indices) { int logical_row_start_offset = indices[0] * ${t}; float norm_factor = 0.0; float max = _Max(indices); for(int i=0; i<${t}; ++i) { norm_factor += exp(getColorAsFloat(${l.texture2D}(A, offsetToCoords(logical_row_start_offset + i, ${s}, ${i}))) - max); } return norm_factor; }`; return { ...Au2, output: { dims: r, type: e.type, textureType: 0 }, shaderSource: f }; }, Gp3 = (a, e, o, t, n, r) => { let [s, i] = a.calculateTextureWidthAndHeight(e.dims, 0), u = e.dims.length; if (o < 1 || t < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1"); if (n.length !== 1 || r.length !== 1) throw new Error("Dimensionality of the intermediate results should be 1"); if (n[0] !== o || r[0] !== o) throw new Error("Shape of the intermediate results should be equal to logical row count"); let l = ` float process(int[${u}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) int offset = coordsToOffset(TexCoords, ${s}, ${i}); //determine the logical row for this index int logical_row_index[1]; logical_row_index[0] = offset / ${t}; float norm_factor = _Norm(logical_row_index); // avoid possible division by 0 // if norm_facor is 0, all elements are zero // if so, return 0 if(norm_factor == 0.0) return 0.0; return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; }`; return { ...Pu2, output: { dims: e.dims, type: e.type, textureType: 0 }, shaderSource: l }; }, Bu2 = (a) => { if (!a || a.length !== 1) throw new Error("Softmax requires 1 input."); if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("Invalid input type"); }; }); Ru3 = x(() => { "use strict"; tt3(); z2(); N(); Nu2 = { name: "Split", inputNames: ["A"], inputTypes: [0] }, Cu2 = (a, e, o) => { zp3(e); let t = A.normalizeAxis(o.axis, e[0].dims.length), n = Rp3(a, e, t, o), r = []; for (let s = 0; s < n; ++s) r.push(a.run({ ...Nu2, cacheHint: `${o.cacheKey};${s}`, get: () => Vp3(a, e[0], o, t, s) }, e)); return r; }, Gu2 = (a) => { let e = a.attributes.getInt("axis", 0), o = a.attributes.getInts("split", []), t = a.outputs.length; return $({ axis: e, split: o, numOutputs: t }); }, Rp3 = (a, e, o, t) => { let [, n] = we.splitShape(e[0].dims, o, t.split, t.numOutputs); return n.length; }, Vp3 = (a, e, o, t, n) => { let [r, s] = we.splitShape(e.dims, t, o.split, o.numOutputs), i = s[n], u = r[n], f = ` float process(int indices[${u.length}]) { indices[${t}] += ${i}; return _A(indices); } `; return { ...Nu2, cacheHint: `${o.cacheKey}:${n}`, output: { dims: u, type: e.type, textureType: 0 }, shaderSource: f }; }, zp3 = (a) => { if (!a || a.length !== 1) throw new Error("Split requires one input."); if (a[0].type !== "int8" && a[0].type !== "uint8" && a[0].type !== "int16" && a[0].type !== "uint16" && a[0].type !== "int32" && a[0].type !== "uint32" && a[0].type !== "float32" && a[0].type !== "float64" && a[0].type !== "bool") throw new Error("Invalid input type."); }; }); Mu3 = x(() => { "use strict"; z2(); kn2 = (a, e, o) => { Mp3(e); let t = A.squeezeShape(e[0].dims, o); return [a.reshapeUnpacked(e[0], t)]; }, Vu3 = (a, e) => (Up3(e), kn2(a, [e[0]], Array.from(e[1].integerData))), zu3 = (a) => a.attributes.getInts("axes"), Mp3 = (a) => { if (!a || a.length !== 1) throw new Error("Squeeze requires 1 input."); if (a[0].type === "string") throw new Error("invalid input tensor types."); }, Up3 = (a) => { if (!a || a.length !== 2) throw new Error("Squeeze requires 2 inputs."); if (a[1].type !== "int32") throw new Error("Invalid input type."); }; }); Wu3 = x(() => { "use strict"; q2(); N(); Uu2 = (a, e) => { Hp3(e); let o = { name: "Sum", inputNames: e.map((n, r) => `X${r}`), inputTypes: new Array(e.length).fill(0) }; return [a.run({ ...o, get: () => Wp3(a, e, o) }, e)]; }, Wp3 = (a, e, o) => { let t = D2(a.session.backend.glContext.version), n = e[0].dims.slice(), s = ` void main() { vec4 result = ${e.map((i, u) => `${t.texture2D}(X${u},TexCoords)`).join(" + ")}; ${t.output} = result; } `; return { ...o, output: { dims: n, type: e[0].type, textureType: 0 }, hasMain: true, shaderSource: s }; }, Hp3 = (a) => { if (!a || a.length === 0) throw new Error("Sum requires inputs."); let e = a[0].dims.length; for (let o = 1; o < a.length; o++) { if (e !== a[o].dims.length) throw new Error("Input shapes are mismatched."); for (let t = 0; t < e; t++) if (a[0].dims[t] !== a[o].dims[t]) throw new Error("Input shapes are not matched."); } if (a[0].type !== "float32" && a[0].type !== "float64") throw new Error("Invalid input type."); for (let o = 1; o < a.length; o++) if (a[0].type !== a[o].type) throw new Error("Input types are not matched."); }; }); qu3 = x(() => { "use strict"; Pe2(); N(); Hu3 = (a, e) => { jp3(e); let o = { name: "Tile", inputNames: ["A"], inputTypes: [0] }; return [a.run({ ...o, get: () => qp3(a, e, o) }, e)]; }, qp3 = (a, e, o) => { let t = e[0].dims.slice(), n = new Array(t.length), r = []; for (let u = 0; u < t.length; u++) n[u] = t[u] * e[1].numberData[u], r.push(`inputIdx[${u}] = int(mod(float(outputIdx[${u}]), ${t[u]}.));`); let s = n.length, i = ` float process(int outputIdx[${s}]) { int inputIdx[${s}]; ${r.join(` `)} return _A(inputIdx); } `; return { ...o, output: { dims: n, type: e[0].type, textureType: 0 }, shaderSource: i }; }, jp3 = (a) => { if (!a || a.length !== 2) throw new Error("Tile requires 2 input."); if (a[1].dims.length !== 1) throw new Error("The second input shape must 1 dimension."); if (a[1].dims[0] !== a[0].dims.length) throw new Error("Invalid input shape."); if (Vt2.indexOf(a[0].type) === -1) throw new Error("Invalid input type."); if (a[1].type !== "int32" && a[1].type !== "int16") throw new Error("Invalid repeat type."); }; }); Xu3 = x(() => { "use strict"; z2(); Bn2 = (a, e, o) => { Kp3(e); let t = A.unsqueezeShape(e[0].dims, o); return [a.reshapeUnpacked(e[0], t)]; }, ju3 = (a, e) => (Xp3(e), Bn2(a, [e[0]], Array.from(e[1].integerData))), Ku3 = (a) => a.attributes.getInts("axes"), Kp3 = (a) => { if (!a || a.length !== 1) throw new Error("Unsqueeze requires 1 input."); if (a[0].type === "string") throw new Error("invalid input tensor types."); }, Xp3 = (a) => { if (!a || a.length !== 2) throw new Error("Unsqueeze requires 2 inputs."); if (a[1].type !== "int32") throw new Error("Invalid input type."); }; }); Zu3 = x(() => { "use strict"; sa2(); Ta2(); Ia2(); Ea2(); lr2(); ps3(); gs3(); vs3(); _s3(); Ps3(); Ls3(); Fs3(); Rs3(); fr2(); Us3(); ru2(); fu2(); pu2(); gu2(); Tu3(); Su2(); Fu3(); Ru3(); Mu3(); Wu3(); qu3(); pr2(); yn2(); Xu3(); En2(); Ju3 = [["Abs", "", "6+", Da2], ["Acos", "", "7+", La2], ["Add", "", "7+", ua2], ["And", "", "7+", la2], ["Asin", "", "7+", $a2], ["Atan", "", "7+", ka2], ["AveragePool", "", "7+", Hs3, qs2], ["BatchNormalization", "", "7+", ia2, aa2], ["Cast", "", "6+", va2, wa2], ["Ceil", "", "6+", Na2], ["Clip", "", "6-10", mn2, Ba2], ["Clip", "", "11+", Fa2], ["Concat", "", "4+", Oa2, Pa2], ["Conv", "", "1+", In, _n2], ["ConvTranspose", "", "1+", fs5, cs3], ["Cos", "", "7+", Ca2], ["Div", "", "7+", fa2], ["Dropout", "", "7+", bn2], ["DepthToSpace", "", "1+", bs3, ys3], ["Equal", "", "7+", ca2], ["Elu", "", "6+", Ga2, Ra2], ["Exp", "", "6+", Va2], ["Flatten", "", "1+", xs3, Ts3], ["Floor", "", "6+", za2], ["FusedConv", "com.microsoft", "1+", In, _n2], ["Gather", "", "1+", ws3, Is3], ["Gemm", "", "7-10", Sn2, Os3], ["Gemm", "", "11+", Sn2, As3], ["GlobalAveragePool", "", "1+", Ks3, Xs2], ["GlobalMaxPool", "", "1+", tu2], ["Greater", "", "7+", pa2], ["Identity", "", "1+", bn2], ["ImageScaler", "", "1+", Es3, Ds3], ["InstanceNormalization", "", "6+", ks3, Bs3], ["LeakyRelu", "", "6+", Ma2, Ua2], ["Less", "", "7+", da2], ["LRN", "", "1+", Ns3, Cs3], ["Log", "", "6+", Wa2], ["MatMul", "", "1+", ns3, os3], ["MaxPool", "", "1+", Js2, Zs2], ["Mul", "", "7+", ha2], ["Neg", "", "6+", Ha2], ["Not", "", "1+", qa], ["Or", "", "7+", ma2], ["Pad", "", "2-10", On2, Vs3], ["Pad", "", "11+", zs3, Ms3], ["Pow", "", "7+", ba2], ["PRelu", "", "7+", ya2], ["ReduceLogSum", "", "1+", uu2, zt], ["ReduceMax", "", "1+", iu3, zt], ["ReduceMean", "", "1+", ou3, zt], ["ReduceMin", "", "1+", au2, zt], ["ReduceProd", "", "1+", su3, zt], ["ReduceSum", "", "1-12", nu2, zt], ["ReduceSumSquare", "", "1+", lu3, zt], ["Relu", "", "6+", ja2], ["Reshape", "", "5+", cu2], ["Resize", "", "10", Ln3, bu2], ["Resize", "", "11+", Ln3, yu2], ["Shape", "", "1+", xu2], ["Sigmoid", "", "6+", Ka2], ["Sin", "", "7+", Xa2], ["Slice", "", "10+", _u2], ["Slice", "", "1-9", vu2, wu2], ["Softmax", "", "1-12", Eu3, Du2], ["Softmax", "", "13+", $u2, Lu3], ["Split", "", "2-12", Cu2, Gu2], ["Sqrt", "", "6+", Ja2], ["Squeeze", "", "1-12", kn2, zu3], ["Squeeze", "", "13+", Vu3], ["Sub", "", "7+", ga2], ["Sum", "", "6+", Uu2], ["Tan", "", "7+", Za3], ["Tanh", "", "6+", Ya2], ["Tile", "", "6+", Hu3], ["Transpose", "", "1+", ee2, hs3], ["Upsample", "", "7-8", An2, hu2], ["Upsample", "", "9", An2, mu2], ["Unsqueeze", "", "1-12", Bn2, Ku3], ["Unsqueeze", "", "13+", ju3], ["Xor", "", "7+", xa2]]; }); tl3 = x(() => { "use strict"; Yu3 = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm, Jp3 = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"; }); Fn3 = x(() => { "use strict"; pt(); z2(); br3 = class { constructor(e) { this.maxTextureSize = e; } computeTextureWH(e, o) { let t = this.computeTexture(e, o); return o && o.isPacked && (t[0] /= 2, t[1] /= 2), o && o.reverseWH ? [t[1], t[0]] : t; } computeTexture(e, o) { let t = o && o.isPacked; if (e.length === 0) return t ? [2, 2] : [1, 1]; let n = this.maxTextureSize; if (o && o.breakAxis !== void 0) { let i = o.breakAxis >= e.length ? 1 : e.slice(o.breakAxis).reduce((l, f) => l * f), u = o.breakAxis <= 0 ? 1 : e.slice(0, o.breakAxis).reduce((l, f) => l * f); if (i > n || u > n) M2.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${e}, breakAxis:${o.breakAxis}`); else return [i, u]; } let r = e.slice(0); t && (n = n * 2, r = r.map((i, u) => u >= r.length - 2 ? r[u] % 2 === 0 ? r[u] : r[u] + 1 : r[u]), r.length === 1 && (r = [2, r[0]])), r.length !== 2 && (r = he2(r).newShape); let s = Qp3(r); return r.length <= 1 && s <= n ? [1, s] : r.length === 2 && r[0] <= n && r[1] <= n ? r : r.length === 3 && r[0] * r[1] <= n && r[2] <= n ? [r[0] * r[1], r[2]] : r.length === 3 && r[0] <= n && r[1] * r[2] <= n ? [r[0], r[1] * r[2]] : r.length === 4 && r[0] * r[1] * r[2] <= n && r[3] <= n ? [r[0] * r[1] * r[2], r[3]] : r.length === 4 && r[0] <= n && r[1] * r[2] * r[3] <= n ? [r[0], r[1] * r[2] * r[3]] : t ? el3(s / 4).map((i) => i * 2) : el3(s); } }; }); rl3 = x(() => { "use strict"; z2(); Bt(); q2(); Fn3(); Pt3(); yr2 = class extends bt2 { constructor(o) { super(o); } getFunctions() { return { ...this.offsetToCoords(), ...this.coordsToOffset(), ...this.toVec(), ...this.valueFrom(), ...this.getCommonUtilFuncs(), ...this.getInputsSamplingSnippets(), ...this.getOutputSamplingSnippet() }; } getCustomTypes() { return {}; } offsetToCoords() { let o = "offsetToCoords"; return { offsetToCoords: new I(` vec2 ${o}(int offset, int width, int height) { int t = offset / width; int s = offset - t*width; vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); return coords; } `) }; } coordsToOffset() { let o = "coordsToOffset"; return { coordsToOffset: new I(` int ${o}(vec2 coords, int width, int height) { float s = coords.s * float(width); float t = coords.t * float(height); int offset = int(t) * width + int(s); return offset; } `) }; } getOutputSamplingSnippet() { let o = this.context.outputTextureLayout; return o.isPacked ? this.getPackedOutputSamplingSnippet(o) : this.getUnpackedOutputSamplingSnippet(o); } getPackedOutputSamplingSnippet(o) { let t = o.unpackedShape, n = [o.width, o.height], r = {}, s = "getOutputCoords"; switch (t.length) { case 0: r[s] = this.getOutputScalarCoords(); break; case 1: r[s] = this.getOutputPacked1DCoords(t, n); break; case 2: r[s] = this.getOutputPacked2DCoords(t, n); break; case 3: r[s] = this.getOutputPacked3DCoords(t, n); break; default: r[s] = this.getOutputPackedNDCoords(t, n); } let u = ` void setOutput(vec4 val) { ${D2(this.context.glContext.version).output} = val; } `, l = "floatTextureSetRGBA"; return r[l] = new I(u), r; } getUnpackedOutputSamplingSnippet(o) { let t = o.unpackedShape, n = [o.width, o.height], r = {}, s = "getOutputCoords"; switch (t.length) { case 0: r[s] = this.getOutputScalarCoords(); break; case 1: r[s] = this.getOutputUnpacked1DCoords(t, n); break; case 2: r[s] = this.getOutputUnpacked2DCoords(t, n); break; case 3: r[s] = this.getOutputUnpacked3DCoords(t, n); break; case 4: r[s] = this.getOutputUnpacked4DCoords(t, n); break; case 5: r[s] = this.getOutputUnpacked5DCoords(t, n); break; case 6: r[s] = this.getOutputUnpacked6DCoords(t, n); break; default: throw new Error(`Unsupported output dimensionality: ${t.length}`); } let u = ` void setOutput(float val) { ${D2(this.context.glContext.version).output} = vec4(val, 0, 0, 0); } `, l = "floatTextureSetR"; return r[l] = new I(u), r; } getOutputScalarCoords() { return new I(` int getOutputCoords() { return 0; } `); } getOutputPacked1DCoords(o, t) { let n = t, r = ""; return n[0] === 1 ? (r = ` int getOutputCoords() { return 2 * int(TexCoords.y * ${n[1]}.0); } `, new I(r)) : n[1] === 1 ? (r = ` int getOutputCoords() { return 2 * int(TexCoords.x * ${n[0]}.0); } `, new I(r)) : (r = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); return 2 * (resTexRC.y * ${n[0]} + resTexRC.x); } `, new I(r)); } getOutputPacked2DCoords(o, t) { let n = ""; if (Kt3.arraysEqual(o, t)) return n = ` ivec2 getOutputCoords() { return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); } `, new I(n); let r = t, s = Math.ceil(o[1] / 2); return n = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${r[0]}, ${r[1]})); int index = resTexRC.y * ${r[0]} + resTexRC.x; // reverse r and c order for packed texture int r = imod(index, ${s}) * 2; int c = 2 * (index / ${s}); return ivec2(r, c); } `, new I(n); } getOutputPacked3DCoords(o, t) { let n = [t[0], t[1]], r = Math.ceil(o[2] / 2), s = r * Math.ceil(o[1] / 2), i = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; int b = index / ${s}; index -= b * ${s}; // reverse r and c order for packed texture int r = imod(index, ${r}) * 2; int c = 2 * (index / ${r}); return ivec3(b, r, c); } `; return new I(i); } getOutputPackedNDCoords(o, t) { let n = [t[0], t[1]], r = Math.ceil(o[o.length - 1] / 2), s = r * Math.ceil(o[o.length - 2] / 2), i = s, u = "", l = "b, r, c"; for (let p = 2; p < o.length - 1; p++) i *= o[o.length - p - 1], u = ` int b${p} = index / ${i}; index -= b${p} * ${i}; ` + u, l = `b${p}, ` + l; let f = ` ivec${o.length} getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${n[0]}, ${n[1]})); int index = resTexRC.y * ${n[0]} + resTexRC.x; ${u} int b = index / ${s}; index -= b * ${s}; // reverse r and c order for packed texture int r = imod(index, ${r}) * 2; int c = 2 * (index / ${r}); return ivec${o.length}(${l}); } `; return new I(f); } getOutputUnpacked1DCoords(o, t) { let n = ` int getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); return resTexRC.y * ${t[0]} + resTexRC.x; } `; return new I(n); } getOutputUnpacked2DCoords(o, t) { let n = ` ivec2 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; int r = index / ${o[1]}; int c = index - r * ${o[1]}; return ivec2(r, c); } `; return new I(n); } getOutputUnpacked3DCoords(o, t) { let n = "", r = o.length, s = null; r < 2 && (s = []), s = new Array(r - 1), s[r - 2] = o[r - 1]; for (let l = r - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let i = ["r", "c", "d"], u = s.map((l, f) => { let p = `int ${i[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${i[f + 1]} = index - ${i[f]} * ${l}` : `index -= ${i[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return n = ` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec3(r, c, d); } `, new I(n); } getOutputUnpacked4DCoords(o, t) { let n = "", r = o.length, s = null; r < 2 && (s = []), s = new Array(r - 1), s[r - 2] = o[r - 1]; for (let l = r - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let i = ["r", "c", "d", "d2"], u = s.map((l, f) => { let p = `int ${i[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${i[f + 1]} = index - ${i[f]} * ${l}` : `index -= ${i[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return n = ` ivec4 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec4(r, c, d, d2); } `, new I(n); } getOutputUnpacked5DCoords(o, t) { let n = "", r = o.length, s = null; r < 2 && (s = []), s = new Array(r - 1), s[r - 2] = o[r - 1]; for (let l = r - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let i = ["r", "c", "d", "d2", "d3"], u = s.map((l, f) => { let p = `int ${i[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${i[f + 1]} = index - ${i[f]} * ${l}` : `index -= ${i[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return n = ` ivec5 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec5(r, c, d, d2, d3); } `, new I(n); } getOutputUnpacked6DCoords(o, t) { let n = "", r = o.length, s = null; r < 2 && (s = []), s = new Array(r - 1), s[r - 2] = o[r - 1]; for (let l = r - 3; l >= 0; --l) s[l] = s[l + 1] * o[l + 1]; let i = ["r", "c", "d", "d2", "d3", "d4"], u = s.map((l, f) => { let p = `int ${i[f]} = index / ${l}`, d = f === s.length - 1 ? `int ${i[f + 1]} = index - ${i[f]} * ${l}` : `index -= ${i[f]} * ${l}`; return `${p}; ${d};`; }).join(""); return n = ` ivec6 getOutputCoords() { ivec2 resTexRC = ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); int index = resTexRC.y * ${t[0]} + resTexRC.x; ${u} return ivec6(r, c, d, d2, d3, d4); } `, new I(n); } getCommonUtilFuncs() { let o = {}, t = "uvFromFlat"; o[t] = new I(` vec2 uvFromFlat(int texNumR, int texNumC, int index) { int texC = index / texNumR; int texR = index - texC * texNumR; // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to // v. return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); } `), t = "packedUVfrom1D", o[t] = new I(` vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { int texelIndex = index / 2; int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "packedUVfrom2D", o[t] = new I(` vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); int texR = texelIndex / texNumC; int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "packedUVfrom3D", o[t] = new I(` vec2 packedUVfrom3D(int texNumR, int texNumC, int texelsInBatch, int texelsInLogicalRow, int b, int row, int col) { int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); int texR = index / texNumC; int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } `), t = "sampleTexture"; let n = D2(this.context.glContext.version); return o[t] = new I(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${n.texture2D}(textureSampler, uv).r; }`), o; } getInputsSamplingSnippets() { let o = {}, t = this.context.outputTextureLayout; return this.context.programInfo.inputNames.forEach((n, r) => { let s = this.context.inputTextureLayouts[r], i = rr3(n); s.isPacked ? o[i] = this.getPackedSamplerFromInput(i, n, s) : o[i] = this.getUnpackedSamplerFromInput(i, n, s); let u = Ui2(n); s.unpackedShape.length <= t.unpackedShape.length && (s.isPacked ? o[u] = this.getPackedSamplerAtOutputCoords(u, s, t, n) : o[u] = this.getUnpackedSamplerAtOutputCoords(u, s, t, n)); }), o; } getPackedSamplerAtOutputCoords(o, t, n, r) { let s = t.unpackedShape, i = n.unpackedShape, l = rr3(r), f = s.length, p = i.length, d = it2.getBroadcastDims(s, i), b = at2(p), g = p - f, y, v = St2(); f === 0 ? y = "" : p < 2 && d.length >= 1 ? y = "coords = 0;" : y = d.map((Mt2) => `coords.${v[Mt2 + g]} = 0;`).join(` `); let _ = ""; p < 2 && f > 0 ? _ = "coords" : _ = s.map((Mt2, $e3) => `coords.${v[$e3 + g]}`).join(", "); let O2 = "return outputValue;", C = A.size(s) === 1, st2 = A.size(i) === 1; if (f === 1 && !C && !st2) O2 = ` return vec4(outputValue.xy, outputValue.xy); `; else if (C && !st2) p === 1 ? O2 = ` return vec4(outputValue.x, outputValue.x, 0., 0.); ` : O2 = ` return vec4(outputValue.x); `; else if (d.length) { let Mt2 = f - 2, $e3 = f - 1; d.indexOf(Mt2) > -1 && d.indexOf($e3) > -1 ? O2 = "return vec4(outputValue.x);" : d.indexOf(Mt2) > -1 ? O2 = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf($e3) > -1 && (O2 = "return vec4(outputValue.xx, outputValue.zz);"); } let Ot = ` int lastDim = coords.${v[p - 1]}; coords.${v[p - 1]} = coords.${v[p - 2]}; coords.${v[p - 2]} = lastDim; `, kr3 = ` vec4 ${o}() { ${b} coords = getOutputCoords(); ${Ot} ${y} vec4 outputValue = ${l}(${_}); ${O2} } `; return new I(kr3, ["coordinates.getOutputCoords"]); } getUnpackedSamplerAtOutputCoords(o, t, n, r) { let s = [n.width, n.height], i = [t.width, t.height], u = t.unpackedShape.length, l = n.unpackedShape.length, f = t.unpackedShape, p = n.unpackedShape, d = rr3(r); if (u === l && Kt3.arraysEqual(i, s)) { let C = ` float ${o}() { return sampleTexture(${r}, TexCoords); } `; return new I(C, ["coordinates.sampleTexture"]); } let b = at2(l), g = it2.getBroadcastDims(f, p), y = l - u, v, _ = St2(); u === 0 ? v = "" : l < 2 && g.length >= 1 ? v = "coords = 0;" : v = g.map((C) => `coords.${_[C + y]} = 0;`).join(` `); let O2 = ""; l < 2 && u > 0 ? O2 = "coords" : O2 = t.unpackedShape.map((C, F2) => `coords.${_[F2 + y]}`).join(", "); let S = ` float ${o}() { ${b} coords = getOutputCoords(); ${v} return ${d}(${O2}); } `; return new I(S, ["coordinates.getOutputCoords"]); } getPackedSamplerFromInput(o, t, n) { switch (n.unpackedShape.length) { case 0: return this.getPackedSamplerScalar(o, t); case 1: return this.getPackedSampler1D(o, t, n); case 2: return this.getPackedSampler2D(o, t, n); case 3: return this.getPackedSampler3D(o, t, n); default: return this.getPackedSamplerND(o, t, n); } } getUnpackedSamplerFromInput(o, t, n) { let r = n.unpackedShape; switch (r.length) { case 0: return this.getUnpackedSamplerScalar(o, t, n); case 1: return this.getUnpackedSampler1D(o, t, n); case 2: return this.getUnpackedSampler2D(o, t, n); case 3: return this.getUnpackedSampler3D(o, t, n); case 4: return this.getUnpackedSampler4D(o, t, n); case 5: return this.getUnpackedSampler5D(o, t, n); case 6: return this.getUnpackedSampler6D(o, t, n); default: throw new Error(`Unsupported dimension ${r.length}-D`); } } getPackedSamplerScalar(o, t) { let n = D2(this.context.glContext.version), r = ` vec4 ${o}() { return ${n.texture2D}(${t}, halfCR); } `; return new I(r); } getPackedSampler1D(o, t, n) { let r = [n.width, n.height], s = [r[1], r[0]], i = D2(this.context.glContext.version), l = `vec4 ${o}(int index) { vec2 uv = packedUVfrom1D( ${s[0]}, ${s[1]}, index); return ${i.texture2D}(${t}, uv); }`; return new I(l, ["coordinates.packedUVfrom1D"]); } getPackedSampler2D(o, t, n) { let r = n.unpackedShape, s = [n.width, n.height], i = D2(this.context.glContext.version), u = s[0], l = s[1]; if (s != null && Kt3.arraysEqual(r, s)) { let g = `vec4 ${o}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${u}.0); return ${i.texture2D}(${t}, uv); }`; return new I(g); } let f = s, p = Math.ceil(r[1] / 2), b = `vec4 ${o}(int row, int col) { vec2 uv = packedUVfrom2D(${f[1]}, ${f[0]}, ${p}, row, col); return ${i.texture2D}(${t}, uv); }`; return new I(b, ["coordinates.packedUVfrom2D"]); } getPackedSampler3D(o, t, n) { let r = n.unpackedShape, s = [n.width, n.height], i = [s[0], s[1]], u = D2(this.context.glContext.version); if (r[0] === 1) { let y = r.slice(1), v = [1, 2], _ = le2(r, y), O2 = ["b", "row", "col"], S = JSON.parse(JSON.stringify(n)); S.unpackedShape = _; let C = this.getPackedSamplerFromInput(o, t, S), st2 = `${C.routineBody} vec4 ${o}(int b, int row, int col) { return ${o}(${fe3(O2, v)}); } `; return new I(st2, C.dependencies); } let l = i[0], f = i[1], p = Math.ceil(r[2] / 2), d = p * Math.ceil(r[1] / 2), g = `vec4 ${o}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${f}, ${l}, ${d}, ${p}, b, row, col); return ${u.texture2D}(${t}, uv);}`; return new I(g, ["coordinates.packedUVfrom3D"]); } getPackedSamplerND(o, t, n) { let r = n.unpackedShape, s = r.length, i = [n.width, n.height], u = D2(this.context.glContext.version), l = [i[0], i[1]], f = l[1], p = l[0], d = Math.ceil(r[s - 1] / 2), b = d * Math.ceil(r[s - 2] / 2), g = "int b, int row, int col", y = `b * ${b} + (row / 2) * ${d} + (col / 2)`; for (let O2 = 2; O2 < s - 1; O2++) g = `int b${O2}, ` + g, b *= r[s - O2 - 1], y = `b${O2} * ${b} + ` + y; let _ = `vec4 ${o}(${g}) { int index = ${y}; int texR = index / ${p}; int texC = index - texR * ${p}; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${f}); return ${u.texture2D}(${t}, uv); }`; return new I(_); } getUnpackedSamplerScalar(o, t, n) { let [r, s] = [n.width, n.height]; if (r === 1 && s === 1) { let u = ` float ${o}() { return sampleTexture(${t}, halfCR); } `; return new I(u, ["coordinates.sampleTexture"]); } let i = ` float ${o}() { int offset_${t} = coordsToOffset(TexCoords, ${r}, ${s}); vec2 uv = uvFromFlat(${r}, ${s}, offset_${t}); return sampleTexture(${t}, uv); } `; return new I(i, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler1D(o, t, n) { let r = n.width, s = n.height; if (s === 1 && r === 1) { let u = ` float ${o}(int index) { return sampleTexture(${t}, halfCR); } `; return new I(u, ["coordinates.sampleTexture"]); } if (s === 1) { let u = ` float ${o}(int index) { vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5); return sampleTexture(${t}, uv); } `; return new I(u, ["coordinates.sampleTexture"]); } if (r === 1) { let u = ` float ${o}(int index) { vec2 uv = vec2(0.5, (float(index) + 0.5) / ${s}.0); return sampleTexture(${t}, uv); } `; return new I(u, ["coordinates.sampleTexture"]); } let i = ` float ${o}(int index) { vec2 uv = uvFromFlat(${r}, ${s}, index); return sampleTexture(${t}, uv); } `; return new I(i, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler2D(o, t, n) { let r = n.unpackedShape, s = [n.height, n.width]; if (s != null && Kt3.arraysEqual(r, s)) { let b = s[1], g = s[0], y = ` float ${o}(int row, int col) { vec2 uv = (vec2(row, col) + halfCR) / vec2(${b}.0, ${g}.0); return sampleTexture(${t}, uv); } `; return new I(y, ["coordinates.sampleTexture"]); } let { newShape: i, keptDims: u } = he2(r), l = i; if (l.length < r.length) { let b = le2(r, l), g = JSON.parse(JSON.stringify(n)); g.unpackedShape = b; let y = ["col", "row"], v = ` ${this.getUnpackedSamplerFromInput(o, t, g).routineBody} float ${o}(int row, int col) { return ${o}(${fe3(y, u)}); } `; return new I(v, ["coordinates.sampleTexture"]); } let f = s[1], p = s[0]; if (p === 1) { let b = ` float ${o}(int row, int col) { int offset_${t} = coordsToOffset(TexCoords, ${f}, ${p}); float index = dot(vec3(row, col, offset_${t}), vec3(${r[1]}, 1, 1)); vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0); return sampleTexture(${t}, uv); } `; return new I(b, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } if (f === 1) { let b = ` float ${o}(int row, int col) { int offset_${t} = coordsToOffset(TexCoords, ${f}, ${p}); float index = dot(vec3(row, col, offset_${t}), vec3(${r[1]}, 1, 1)); vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5); return sampleTexture(${t}, uv); } `; return new I(b, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]); } let d = ` float ${o}(int row, int col) { int index = col * ${r[1]} + row; vec2 uv = uvFromFlat(${f}, ${p}, index); return sampleTexture(${t}, uv); } `; return new I(d, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler3D(o, t, n) { let r = n.unpackedShape, s = r[1] * r[2], i = r[2], { newShape: u, keptDims: l } = he2(r), f = u; if (f.length < r.length) { let g = le2(r, f), y = ["batch", "col", "row"], v = JSON.parse(JSON.stringify(n)); v.unpackedShape = g; let _ = this.getUnpackedSamplerFromInput(o, t, v), O2 = l.reverse(), S = ` ${_.routineBody} float ${o}(int batch, int row, int col) { return ${o}(${fe3(y, O2)}); } `; return new I(S, _.dependencies); } let p = n.width, d = n.height, b = ` float ${o}(int depth, int row, int col) { // Explicitly use integer operations as dot() only works on floats. int index = depth * ${s} + col * ${i} + row; vec2 uv = uvFromFlat(${p}, ${d}, index); return sampleTexture(${t}, uv); } `; return new I(b, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } getUnpackedSampler4D(o, t, n) { let r = n.unpackedShape, s = r[3], i = r[2] * s, u = r[1] * i, l = n.width, f = n.height, p = ` float ${o}(int row, int col, int depth, int depth2) { int index = row * ${u} + col * ${i} + depth2 * ${s} + depth; vec2 uv = uvFromFlat(${l}, ${f}, index); return sampleTexture(${t}, uv); } `; return new I(p, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]); } getUnpackedSampler5D(o, t, n) { let r = n.unpackedShape, s = r[4], i = r[3] * s, u = r[2] * i, l = r[1] * u, { newShape: f, keptDims: p } = he2(r); if (f.length < r.length) { let y = le2(r, f), v = ["row", "col", "depth", "depth2", "depth3"], _ = JSON.parse(JSON.stringify(n)); _.unpackedShape = y; let O2 = ` ${this.getUnpackedSamplerFromInput(o, t, _).routineBody} float ${o}(int row, int col, int depth, int depth2, int depth3) { return ${o}(${fe3(v, p)}); } `; return new I(O2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } let d = n.width, b = n.height, g = ` float ${o}(int row, int col, int depth, int depth2, int depth3) { int index = row * ${l} + col * ${u} + depth * ${i} + depth3 * ${s} + depth2; vec2 uv = uvFromFlat(${d}, ${b}, index); return sampleTexture(${t}, uv); } `; return new I(g, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } getUnpackedSampler6D(o, t, n) { let r = n.unpackedShape, s = r[5], i = r[4] * s, u = r[3] * i, l = r[2] * u, f = r[1] * l, { newShape: p, keptDims: d } = he2(r); if (p.length < r.length) { let v = le2(r, p), _ = ["row", "col", "depth", "depth2", "depth3", "depth4"], O2 = JSON.parse(JSON.stringify(n)); O2.unpackedShape = v; let S = ` ${this.getUnpackedSamplerFromInput(o, t, O2).routineBody} float ${o}(int row, int col, int depth, int depth2, int depth3, int depth4) { return ${o}(${fe3(_, d)}); } `; return new I(S, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]); } let b = n.width, g = n.height, y = ` float ${o}(int row, int col, int depth, int depth2, int depth3, int depth4) { int index = row * ${f} + col * ${l} + depth * ${u} + depth2 * ${i} + depth3 * ${s} + depth4; vec2 uv = uvFromFlat(${b}, ${g}, index); return sampleTexture(${t}, uv); } `; return new I(y, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]); } toVec() { let o = this.context.outputTextureLayout, t = o.shape.length, n = o.strides, r = o.width, s = o.height, i = []; for (let l = 0; l < t - 1; ++l) i.push(` c[${l}] = offset / ${n[l]};`), i.push(` offset -= c[${l}] * ${n[l]};`); i.push(` c[${t - 1}] = offset;`); let u = ` void toVec(vec2 texCoords, out int c[${t}]) { int offset = coordsToOffset(texCoords, ${r}, ${s}); ${i.join("")} } void toVec(int offset, out int c[${t}]) { ${i.join("")} } `; return { toVec: new I(u, ["coordinates.coordsToOffset"]) }; } valueFrom() { let o = {}; return this.context.programInfo.inputNames.forEach((t, n) => { let r = this.context.inputTextureLayouts[n], i = (r.unpackedShape.length > 0 ? r.unpackedShape : r.shape).length, u = `_${t}`; o[u] = new I(this.getValueFromSingle(t, i, r.width, r.height, false), [`shapeUtils.indicesToOffset${u}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), u = u + "_T", o[u] = new I(this.getValueFromSingle(t, i, r.width, r.height, true), [`shapeUtils.indicesToOffset${u}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]); }), o; } getValueFromSingle(o, t, n, r, s) { let i = `_${o}`; s && (i = i + "_T"); let u = D2(this.context.glContext.version); return ` float ${i}(int m[${t}]) { int offset = indicesToOffset${i}(m); vec2 coords = offsetToCoords(offset, ${n}, ${r}); float value = getColorAsFloat(${u.texture2D}(${o}, coords)); return value; } `; } getPackedValueFrom(o, t, n, r, s) { let i = `_${o}_Pack`; s && (i = i + "_T"); let u = D2(this.context.glContext.version); return ` vec4 ${i}(int m[${t}]) { int offset = indicesToOffset_${o}(m); vec2 coords = offsetToCoords(offset, ${n}, ${r}); return ${u.texture2D}(${o}, coords); } `; } }; }); nl3 = x(() => { "use strict"; Bt(); gr = class a extends bt2 { constructor(e) { super(e); } getFunctions() { return { ...this.encodeFloat32(), ...this.decodeFloat32() }; } getCustomTypes() { return {}; } encodeFloat32() { return { encode: new I(`highp vec4 encode(highp float f) { return vec4(f, 0.0, 0.0, 0.0); } `) }; } decodeFloat32() { return { decode: new I(`highp float decode(highp vec4 rgba) { return rgba.r; } `) }; } encodeUint8() { let e = a.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { encode: new I(` highp vec4 encode(highp float f) { highp float F = abs(f); highp float Sign = step(0.0,-f); highp float Exponent = floor(log2(F)); highp float Mantissa = (exp2(- Exponent) * F); Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); highp vec4 rgba; rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); ${e} rgba = rgba / 255.0; // values need to be normalized to [0,1] return rgba; } `) }; } decodeUint8() { let e = a.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : ""; return { decode: new I(` highp float decode(highp vec4 rgba) { rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] ${e} highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); return Result; } `) }; } static isLittleEndian() { let e = new ArrayBuffer(4), o = new Uint32Array(e), t = new Uint8Array(e); if (o[0] = 3735928559, t[0] === 239) return true; if (t[0] === 222) return false; throw new Error("unknown endianness"); } }; }); ol3 = x(() => { "use strict"; Bt(); q2(); xr3 = class extends bt2 { constructor(e) { super(e); } getFunctions() { return { ...this.setFragColor(), ...this.getColorAsFloat() }; } getCustomTypes() { return {}; } setFragColor() { let e = D2(this.context.glContext.version); return { setFragColor: new I(` void setFragColor(float value) { ${e.output} = encode(value); } `, ["encoding.encode"]) }; } getColorAsFloat() { return { getColorAsFloat: new I(` float getColorAsFloat(vec4 color) { return decode(color); } `, ["encoding.decode"]) }; } }; }); il3 = x(() => { "use strict"; Bt(); Tr3 = class a extends bt2 { constructor(e) { super(e); } getFunctions() { return { ...this.bcastIndex(), ...this.bcastMatmulIndex(), ...this.offsetToIndices(), ...this.indicesToOffset(), ...this.incrementIndices() }; } getCustomTypes() { return {}; } bcastIndex() { let e = this.context.outputTextureLayout.shape.length, o = {}; return this.context.programInfo.inputNames.forEach((t, n) => { let r = this.context.inputTextureLayouts[n].unpackedShape; if (r.length <= e) { let s = r.length, i = e - s, u = `bcastIndices_${t}`, l = ""; for (let p = 0; p < s; ++p) l += ` realIndices[${p}] = int( mod(float(bcastedIndices[${i + p}]), ${r[p]}.0) ); `; let f = ` void ${u} (int bcastedIndices[${e}], out int realIndices[${s}]) { ${l} } `; o[u] = new I(f); } }), o; } bcastMatmulIndex() { let e = this.context.outputTextureLayout.shape.length, o = {}; return this.context.programInfo.inputNames.forEach((t, n) => { let r = this.context.inputTextureLayouts[n].shape; if (!(r.length < 2 || r.length > e)) { let s = r.length, i = e - s, u = `bcastMatmulIndices_${t}`, l = ""; for (let p = 0; p < s - 2; ++p) l += ` realIndices[${p}] = int( mod(float(bcastedIndices[${i + p}]), ${r[p]}.0) ); `; let f = ` void ${u}(int bcastedIndices[${e}], out int realIndices[${s}]) { ${l} realIndices[${s - 1}] = bcastedIndices[${e - 1}]; realIndices[${s - 2}] = bcastedIndices[${e - 2}]; } `; o[u] = new I(f); } }), o; } indicesToOffset() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let n = this.context.inputTextureLayouts[t].shape, r = this.context.inputTextureLayouts[t].strides, s = n.length, i = `indicesToOffset_${o}`; e[i] = new I(a.indexToOffsetSingle(i, s, r)), i = `indicesToOffset_${o}_T`, e[i] = new I(a.indexToOffsetSingle(i, s, r.slice().reverse())); }), e; } static indexToOffsetSingle(e, o, t) { let n = ""; for (let r = o - 1; r >= 0; --r) n += ` offset += indices[${r}] * ${t[r]}; `; return ` int ${e}(int indices[${o}]) { int offset = 0; ${n} return offset; } `; } offsetToIndices() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let n = this.context.inputTextureLayouts[t].shape, r = this.context.inputTextureLayouts[t].strides, s = n.length, i = `offsetToIndices_${o}`; e[i] = new I(a.offsetToIndicesSingle(i, s, r)), i = `offsetToIndices_${o}_T`, e[i] = new I(a.offsetToIndicesSingle(i, s, r.slice().reverse())); }), e; } static offsetToIndicesSingle(e, o, t) { let n = []; for (let r = 0; r < o - 1; ++r) n.push(` indices[${r}] = offset / ${t[r]};`), n.push(` offset -= indices[${r}] * ${t[r]};`); return n.push(` indices[${o - 1}] = offset;`), ` void ${e}(int offset, out int indices[${o}]) { ${n.join("")} } `; } incrementIndices() { let e = {}; return this.context.programInfo.inputNames.forEach((o, t) => { let n = this.context.inputTextureLayouts[t].shape, r = n.length, s = `incrementIndices_${o}`, i = ""; for (let l = 0; l < r; ++l) i += ` shape[${l}] = ${n[l]};`; let u = ` void ${s}(int axis, out int indices[${r}]) { int shape[${r}]; ${i}; for(int i = ${r} -1 ; i >= 0; --i) { if(i > axis) continue; indices[i] += 1; if(indices[i] < shape[i]) { break; } indices[i] = 0; } } `; e[s] = new I(u); }), e; } }; }); al3 = x(() => { "use strict"; Bt(); vr2 = class extends bt2 { constructor(e) { super(e); } getCustomTypes() { return {}; } getFunctions() { return { ...this.binaryVecFunctions(), ...this.copyVec(), ...this.setVecItem(), ...this.getVecItem() }; } binaryVecFunctions() { let o = this.context.outputTextureLayout.shape.length, t = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, n = {}; for (let r in t) { let s = `${r}Vec`, i = ""; for (let l = 0; l < o; ++l) i += ` dest[${l}] ${t[r]} src[${l}]; `; let u = ` void ${s}(int src[${o}], out int dest[${o}]) { ${i} } `; n[s] = new I(u); } return n; } copyVec() { let o = this.context.outputTextureLayout.shape.length, t = ""; for (let r = 0; r < o; ++r) t += ` dest[${r}] = src[${r}]; `; let n = ` void copyVec(int src[${o}], out int dest[${o}]) { ${t} } `; return { copyVec: new I(n) }; } setVecItem() { let o = this.context.outputTextureLayout.shape.length, t = ` if(index < 0) index =${o} + index; if (index == 0) m[0] = value; `; for (let r = 1; r < o - 1; ++r) t += ` else if (index == ${r}) m[${r}] = value; `; t += ` else m[${o - 1}] = value; `; let n = ` void setVecItem(out int m[${o}], int index, int value) { ${t} } `; return { setVecItem: new I(n) }; } getVecItem() { let o = this.context.outputTextureLayout.shape.length, t = ` if(index < 0) index = ${o} + index; if (index == 0) return m[0]; `; for (let r = 1; r < o - 1; ++r) t += ` else if (index == ${r}) return m[${r}]; `; t += ` else return m[${o - 1}]; `; let n = ` int getVecItem(int m[${o}], int index) { ${t} } `; return { getVecItem: new I(n) }; } }; }); sl3 = x(() => { "use strict"; rl3(); nl3(); ol3(); il3(); al3(); Nn3 = { encoding: gr, fragcolor: xr3, vec: vr2, shapeUtils: Tr3, coordinates: yr2 }; }); ul2 = x(() => { "use strict"; Bt(); tl3(); sl3(); q2(); wr2 = class { constructor(e, o, t, n) { this.libs = {}; this.glslLibRoutineDependencyGraph = {}; this.context = new ar(e, o, t, n), Object.keys(Nn3).forEach((s) => { let i = new Nn3[s](this.context); this.libs[s] = i; }); let r = this.glslLibRoutineDependencyGraph; for (let s in this.libs) { let u = this.libs[s].getFunctions(); for (let l in u) { let f = s + "." + l, p; r[f] ? (p = r[f], p.routineBody = u[l].routineBody) : (p = new Ae2(f, u[l].routineBody), r[f] = p); let d = u[l].dependencies; if (d) for (let b = 0; b < d.length; ++b) if (r[d[b]]) p.addDependency(r[d[b]]); else { let g = new Ae2(d[b]); r[d[b]] = g, p.addDependency(g); } } } } preprocess() { let e = this.context.programInfo, o = e.shaderSource; return this.context.programInfo.hasMain || (o = `${o} ${Mi2(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), o = Qu3(o), `${zi2(this.context.glContext.version)} ${this.getUniforms(e.inputNames, e.variables)} ${this.getImports(o)} ${o}`; } getImports(e) { let o = this.selectGlslLibRoutinesToBeIncluded(e); if (o.length === 0) return ""; let t = ""; for (let n = 0; n < o.length; ++n) if (o[n].routineBody) t += o[n].routineBody + ` `; else throw new Error(`Missing body for the Glsl Library routine: ${o[n].name}`); return t; } selectGlslLibRoutinesToBeIncluded(e) { let o = []; return Object.keys(this.glslLibRoutineDependencyGraph).forEach((t) => { let n = t.split(".")[1]; e.indexOf(n) !== -1 && o.push(this.glslLibRoutineDependencyGraph[t]); }), sr2.returnOrderedNodes(o); } getUniforms(e, o) { let t = []; if (e) for (let n of e) t.push(`uniform sampler2D ${n};`); if (o) for (let n of o) t.push(`uniform ${n.type} ${n.name}${n.arrayLength ? `[${n.arrayLength}]` : ""};`); return t.join(` `); } }; }); ll3 = x(() => { "use strict"; Ft3(); pt(); ul2(); q2(); Ir2 = class { constructor(e, o, t) { this.profiler = e; this.glContext = o; this.textureLayoutStrategy = t; this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; } getArtifact(e) { return this.repo.get(e); } setArtifact(e, o) { this.repo.set(e, o); } run(e, o, t) { this.profiler.event("op", `ProgramManager.run ${e.programInfo.name ?? "unknown kernel"}`, () => { let n = this.glContext.gl, r = e.program; n.useProgram(r); try { this.bindOutput(t), this.attributesBound || this.bindAttributes(e.attribLocations), this.bindUniforms(e.uniformLocations, e.programInfo.variables ?? [], o); } catch (s) { throw M2.error("ProgramManager", e.programInfo.shaderSource), s; } this.profiler.event("backend", "GlContext.draw()", () => { this.glContext.draw(); }); }, this.glContext); } dispose() { this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach((e) => this.glContext.deleteProgram(e.program)); } build(e, o, t) { return this.profiler.event("backend", "ProgramManager.build", () => { let n = new wr2(this.glContext, e, o, t), r = n.preprocess(), s = this.compile(r); return { programInfo: e, program: s, uniformLocations: this.getUniformLocations(s, n.context.programInfo.inputNames, n.context.programInfo.variables), attribLocations: this.getAttribLocations(s) }; }); } compile(e) { if (!this.vertexShader) { M2.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time"); let n = Vi2(this.glContext.version); this.vertexShader = this.glContext.compileShader(n, this.glContext.gl.VERTEX_SHADER); } j2.debug && M2.verbose("ProrgramManager", `FragShader: ${e} `); let o = this.glContext.compileShader(e, this.glContext.gl.FRAGMENT_SHADER), t = this.glContext.createProgram(this.vertexShader, o); return this.glContext.deleteShader(o), t; } bindOutput(e) { let o = e.width, t = e.height; M2.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${o}/${t}, shape=${e.shape}, type=${e.tensor.type}`), this.glContext.attachFramebuffer(e.texture, o, t); } bindAttributes(e) { let o = e.position, t = e.textureCoord; this.glContext.setVertexAttributes(o, t), this.attributesBound = true; } bindUniforms(e, o, t) { let n = this.glContext.gl, r = 0; for (let { name: s, type: i, location: u, arrayLength: l } of e) { let f = o.find((p) => p.name === s)?.data; if (i !== "sampler2D" && !f) throw new Error(`variable '${s}' does not have data defined in program info`); switch (i) { case "sampler2D": this.bindTexture(t[r], u, r), r++; break; case "float": l ? n.uniform1fv(u, f) : n.uniform1f(u, f); break; case "int": l ? n.uniform1iv(u, f) : n.uniform1i(u, f); break; default: throw new Error(`Uniform not implemented: ${i}`); } } } bindTexture(e, o, t) { this.glContext.bindTextureToUniform(e.texture, t, o); } getAttribLocations(e) { return { position: this.getAttribLocation(e, "position"), textureCoord: this.getAttribLocation(e, "textureCoord") }; } getUniformLocations(e, o, t) { let n = []; if (o) for (let r of o) n.push({ name: r, type: "sampler2D", location: this.getUniformLocation(e, r) }); if (t) for (let r of t) n.push({ ...r, location: this.getUniformLocation(e, r.name) }); return n; } getUniformLocation(e, o) { let n = this.glContext.gl.getUniformLocation(e, o); if (n === null) throw new Error(`Uniform ${o} not found.`); return n; } getAttribLocation(e, o) { return this.glContext.gl.getAttribLocation(e, o); } }; }); fl3 = x(() => { "use strict"; pt(); Se(); _r2 = class { constructor(e, o, t, n) { this.glContext = e; this.layoutStrategy = o; this.profiler = t; this.config = n; this.pendingRead = /* @__PURE__ */ new Map(); n.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map()); } createTextureFromLayout(e, o, t, n) { let r = this.toEncoderType(e), s = this.glContext.getEncoder(r, o.channels || 1, n); if (o.isPacked && n === 1) throw new Error("not implemented"); let i = o.width, u = o.height, l, f; if (this.config.reuseTextures) { l = `${i}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`, f = this.inUseTextures.get(l), f || (f = [], this.inUseTextures.set(l, f)); let d = this.idleTextures.get(l); if (d && d.length > 0) { let b = d.pop(); return f.push(b), n === 1 && this.glContext.updateTexture(b, i, u, s, this.toTextureData(e, t)), b; } } M2.verbose("TextureManager", `Creating new texture of size ${o.width}x${o.height}`); let p = this.glContext.allocateTexture(i, u, s, this.toTextureData(e, t)); return this.config.reuseTextures && (f.push(p), this.textureLookup.set(p, l)), p; } readTexture(e, o, t) { return t || (t = 1), this.profiler.event("backend", "TextureManager.readTexture", () => { let n = e.shape.reduce((s, i) => s * i) * t, r = this.glContext.readTexture(e.texture, e.width, e.height, n, this.toEncoderType(o), t); return this.toTensorData(o, r); }); } async readTextureAsync(e, o, t) { let n = e.tensor.dataId; if (t || (t = 1), this.pendingRead.has(n)) { let r = this.pendingRead.get(n); return new Promise((s) => r?.push(s)); } return this.profiler.event("backend", "TextureManager.readTextureAsync", async () => { this.pendingRead.set(n, []); let r = e.shape.reduce((l, f) => l * f) * t; await this.glContext.createAndWaitForFence(); let s = this.glContext.readTexture(e.texture, e.width, e.height, r, this.toEncoderType(o), t), i = this.toTensorData(o, s), u = this.pendingRead.get(n); return this.pendingRead.delete(n), u?.forEach((l) => l(i)), i; }); } readUint8TextureAsFloat(e) { return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", () => { let o = e.shape.reduce((n, r) => n * r), t = this.glContext.readTexture(e.texture, e.width, e.height, o * 4, "byte", 4); return new Float32Array(t.buffer, t.byteOffset, o); }); } releaseTexture(e, o) { let t; if (this.config.reuseTextures && (t = this.textureLookup.get(e.texture), t)) { o && this.textureLookup.delete(t); let n = this.inUseTextures.get(t); if (n) { let r = n.indexOf(e.texture); if (r !== -1) { n.splice(r, 1); let s = this.idleTextures.get(t); s || (s = [], this.idleTextures.set(t, s)), s.push(e.texture); } } } (!t || o) && (M2.verbose("TextureManager", `Deleting texture of size ${e.width}x${e.height}`), this.glContext.deleteTexture(e.texture)); } toTensorData(e, o) { switch (e) { case "int16": return o instanceof Int16Array ? o : Int16Array.from(o); case "int32": return o instanceof Int32Array ? o : Int32Array.from(o); case "int8": return o instanceof Int8Array ? o : Int8Array.from(o); case "uint16": return o instanceof Uint16Array ? o : Uint16Array.from(o); case "uint32": return o instanceof Uint32Array ? o : Uint32Array.from(o); case "uint8": case "bool": return o instanceof Uint8Array ? o : Uint8Array.from(o); case "float32": return o instanceof Float32Array ? o : Float32Array.from(o); case "float64": return o instanceof Float64Array ? o : Float64Array.from(o); default: throw new Error(`TensorData type ${e} is not supported`); } } toTextureData(e, o) { if (o) return o instanceof Float32Array ? o : new Float32Array(o); } toEncoderType(e) { return "float"; } clearActiveTextures() { this.glContext.clearActiveTextures(); } }; }); cl3 = x(() => { "use strict"; pt(); Oo(); na2(); Zu3(); ll3(); Fn3(); fl3(); Sr3 = class { constructor(e, o) { this.backend = e; this.context = o; this.layoutStrategy = new br3(e.glContext.maxTextureSize), this.programManager = new Ir2(this.context.profiler, e.glContext, this.layoutStrategy), this.textureManager = new _r2(e.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: e.textureCacheMode === "full" }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = e.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map(); } createInferenceHandler() { return new ir3(this); } onGraphInitialized(e) { let o = e.getValues().filter((t) => t.from === -1 && t.tensor).map((t) => t.tensor.dataId); this.initializers = new Set(o); } isInitializer(e) { return this.initializers ? this.initializers.has(e) : false; } addInitializer(e) { this.initializers.add(e); } getTextureData(e, o) { return o ? this.packedTextureDataCache.get(e) : this.unpackedTextureDataCache.get(e); } setTextureData(e, o, t = false) { M2.verbose("WebGLSessionHandler", "Storing Texture data in cache"), t ? this.packedTextureDataCache.set(e, o) : this.unpackedTextureDataCache.set(e, o); } dispose() { this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach((e) => this.textureManager.releaseTexture(e, true)), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach((e) => this.textureManager.releaseTexture(e, true)), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(); } resolve(e, o, t) { let n = So2(e, o, Ju3); return { impl: n.opImpl, context: n.opInit ? n.opInit(e, t) : e }; } }; }); pl3 = x(() => { "use strict"; Ft3(); Se(); Se(); Pt3(); De2 = class { constructor(e, o) { this.frameBufferBound = false; this.itemsToPoll = []; this.gl = e, this.version = o, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters(); } allocateTexture(e, o, t, n) { let r = this.gl, s = r.createTexture(); r.bindTexture(r.TEXTURE_2D, s), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MIN_FILTER, r.NEAREST), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MAG_FILTER, r.NEAREST), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_S, r.CLAMP_TO_EDGE), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_T, r.CLAMP_TO_EDGE); let i = n ? t.encode(n, e * o) : null; return r.texImage2D(r.TEXTURE_2D, 0, t.internalFormat, e, o, 0, t.format, t.textureType, i), this.checkError(), s; } updateTexture(e, o, t, n, r) { let s = this.gl; s.bindTexture(s.TEXTURE_2D, e); let i = n.encode(r, o * t); s.texSubImage2D(s.TEXTURE_2D, 0, 0, 0, o, t, n.format, n.textureType, i), this.checkError(); } attachFramebuffer(e, o, t) { let n = this.gl; n.bindTexture(n.TEXTURE_2D, e), n.bindFramebuffer(n.FRAMEBUFFER, this.framebuffer), n.framebufferTexture2D(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, e, 0), this.checkError(), n.viewport(0, 0, o, t), n.scissor(0, 0, o, t); } readTexture(e, o, t, n, r, s) { let i = this.gl; s || (s = 1), this.frameBufferBound || this.attachFramebuffer(e, o, t); let u = this.getEncoder(r, s), l = u.allocate(o * t); return i.bindTexture(i.TEXTURE_2D, e), i.framebufferTexture2D(i.FRAMEBUFFER, i.COLOR_ATTACHMENT0, i.TEXTURE_2D, e, 0), i.readPixels(0, 0, o, t, i.RGBA, u.textureType, l), this.checkError(), u.decode(l, n); } isFramebufferReady() { return true; } getActiveTexture() { let e = this.gl; return `TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE) - e.TEXTURE0}`; } getTextureBinding() { return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); } getFramebufferBinding() { return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); } setVertexAttributes(e, o) { let t = this.gl; t.vertexAttribPointer(e, 3, t.FLOAT, false, 20, 0), t.enableVertexAttribArray(e), o !== -1 && (t.vertexAttribPointer(o, 2, t.FLOAT, false, 20, 12), t.enableVertexAttribArray(o)), this.checkError(); } createProgram(e, o) { let t = this.gl, n = t.createProgram(); return t.attachShader(n, e), t.attachShader(n, o), t.linkProgram(n), n; } compileShader(e, o) { let t = this.gl, n = t.createShader(o); if (!n) throw new Error(`createShader() returned null with type ${o}`); if (t.shaderSource(n, e), t.compileShader(n), t.getShaderParameter(n, t.COMPILE_STATUS) === false) throw new Error(`Failed to compile shader: ${t.getShaderInfoLog(n)} Shader source: ${e}`); return n; } deleteShader(e) { this.gl.deleteShader(e); } bindTextureToUniform(e, o, t) { let n = this.gl; n.activeTexture(n.TEXTURE0 + o), this.checkError(), n.bindTexture(n.TEXTURE_2D, e), this.checkError(), n.uniform1i(t, o), this.checkError(); } draw() { this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError(); } checkError() { if (j2.debug) { let e = this.gl, o = e.getError(), t = ""; switch (o) { case e.NO_ERROR: return; case e.INVALID_ENUM: t = "INVALID_ENUM"; break; case e.INVALID_VALUE: t = "INVALID_VALUE"; break; case e.INVALID_OPERATION: t = "INVALID_OPERATION"; break; case e.INVALID_FRAMEBUFFER_OPERATION: t = "INVALID_FRAMEBUFFER_OPERATION"; break; case e.OUT_OF_MEMORY: t = "OUT_OF_MEMORY"; break; case e.CONTEXT_LOST_WEBGL: t = "CONTEXT_LOST_WEBGL"; break; default: t = `Unknown WebGL Error: ${o.toString(16)}`; } throw new Error(t); } } deleteTexture(e) { this.gl.deleteTexture(e); } deleteProgram(e) { this.gl.deleteProgram(e); } getEncoder(e, o, t = 0) { if (this.version === 2) return new nr3(this.gl, o); switch (e) { case "float": return t === 1 || this.isRenderFloat32Supported ? new _e2(this.gl, o) : new _e2(this.gl, o, this.textureHalfFloatExtension.HALF_FLOAT_OES); case "int": throw new Error("not implemented"); case "byte": return new or3(this.gl, o); default: throw new Error(`Invalid dataType: ${e}`); } } clearActiveTextures() { let e = this.gl; for (let o = 0; o < this.maxTextureImageUnits; ++o) e.activeTexture(e.TEXTURE0 + o), e.bindTexture(e.TEXTURE_2D, null); } dispose() { if (this.disposed) return; let e = this.gl; e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteFramebuffer(this.framebuffer), e.bindBuffer(e.ARRAY_BUFFER, null), e.deleteBuffer(this.vertexbuffer), e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, null), e.finish(), this.disposed = true; } createDefaultGeometry() { return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]); } createVertexbuffer() { let e = this.gl, o = e.createBuffer(); if (!o) throw new Error("createBuffer() returned null"); let t = this.createDefaultGeometry(); return e.bindBuffer(e.ARRAY_BUFFER, o), e.bufferData(e.ARRAY_BUFFER, t, e.STATIC_DRAW), this.checkError(), o; } createFramebuffer() { let e = this.gl.createFramebuffer(); if (!e) throw new Error("createFramebuffer returned null"); return e; } queryVitalParameters() { let e = this.gl; if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) throw new Error("both float32 and float16 TextureType are not supported"); this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = e.getParameter(e.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS), this.version; } getExtensions() { this.version === 2 ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float")); } checkFloatTextureAttachableToFrameBuffer() { let e = this.gl, o = e.createTexture(); e.bindTexture(e.TEXTURE_2D, o); let t = this.version === 2 ? e.RGBA32F : e.RGBA; e.texImage2D(e.TEXTURE_2D, 0, t, 1, 1, 0, e.RGBA, e.FLOAT, null); let n = e.createFramebuffer(); e.bindFramebuffer(e.FRAMEBUFFER, n), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, o, 0); let r = e.checkFramebufferStatus(e.FRAMEBUFFER) === e.FRAMEBUFFER_COMPLETE; return e.bindTexture(e.TEXTURE_2D, null), e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteTexture(o), e.deleteFramebuffer(n), r; } checkRenderFloat32() { if (this.version === 2) { if (!this.colorBufferFloatExtension) return false; } else if (!this.textureFloatExtension) return false; return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Download() { if (this.version === 2) { if (!this.colorBufferFloatExtension) return false; } else if (!this.textureFloatExtension || !this.gl.getExtension("WEBGL_color_buffer_float")) return false; return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Blend() { let e = this.gl, o, t, n, r, s; try { o = e.createTexture(), t = e.createFramebuffer(), e.bindTexture(e.TEXTURE_2D, o); let i = this.version === 2 ? e.RGBA32F : e.RGBA; return e.texImage2D(e.TEXTURE_2D, 0, i, 1, 1, 0, e.RGBA, e.FLOAT, null), e.bindFramebuffer(e.FRAMEBUFFER, t), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, o, 0), e.enable(e.BLEND), n = e.createShader(e.VERTEX_SHADER), !n || (e.shaderSource(n, "void main(){}"), e.compileShader(n), r = e.createShader(e.FRAGMENT_SHADER), !r) || (e.shaderSource(r, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), e.compileShader(r), s = e.createProgram(), !s) ? false : (e.attachShader(s, n), e.attachShader(s, r), e.linkProgram(s), e.useProgram(s), e.drawArrays(e.POINTS, 0, 1), e.getError() === e.NO_ERROR); } finally { e.disable(e.BLEND), s && e.deleteProgram(s), n && e.deleteShader(n), r && e.deleteShader(r), t && (e.bindFramebuffer(e.FRAMEBUFFER, null), e.deleteFramebuffer(t)), o && (e.bindTexture(e.TEXTURE_2D, null), e.deleteTexture(o)); } } beginTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let e = this.gl, o = this.disjointTimerQueryWebgl2Extension, t = e.createQuery(); return e.beginQuery(o.TIME_ELAPSED_EXT, t), t; } else throw new Error("WebGL1 profiling currently not supported."); } endTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let e = this.gl, o = this.disjointTimerQueryWebgl2Extension; e.endQuery(o.TIME_ELAPSED_EXT); return; } else throw new Error("WebGL1 profiling currently not supported"); } isTimerResultAvailable(e) { let o = false, t = false; if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { let n = this.gl, r = this.disjointTimerQueryWebgl2Extension; o = n.getQueryParameter(e, n.QUERY_RESULT_AVAILABLE), t = n.getParameter(r.GPU_DISJOINT_EXT); } else throw new Error("WebGL1 profiling currently not supported"); return o && !t; } getTimerResult(e) { let o = 0; if (this.version === 2) { let t = this.gl; o = t.getQueryParameter(e, t.QUERY_RESULT), t.deleteQuery(e); } else throw new Error("WebGL1 profiling currently not supported"); return o / 1e6; } async waitForQueryAndGetTime(e) { return await sn3(() => this.isTimerResultAvailable(e)), this.getTimerResult(e); } async createAndWaitForFence() { let e = this.createFence(this.gl); return this.pollFence(e); } createFence(e) { let o, t = e, n = t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE, 0); return e.flush(), n === null ? o = () => true : o = () => { let r = t.clientWaitSync(n, 0, 0); return r === t.ALREADY_SIGNALED || r === t.CONDITION_SATISFIED; }, { query: n, isFencePassed: o }; } async pollFence(e) { return new Promise((o) => { this.addItemToPoll(() => e.isFencePassed(), () => o()); }); } pollItems() { let e = td3(this.itemsToPoll.map((o) => o.isDoneFn)); for (let o = 0; o <= e; ++o) { let { resolveFn: t } = this.itemsToPoll[o]; t(); } this.itemsToPoll = this.itemsToPoll.slice(e + 1); } async addItemToPoll(e, o) { this.itemsToPoll.push({ isDoneFn: e, resolveFn: o }), !(this.itemsToPoll.length > 1) && await sn3(() => (this.pollItems(), this.itemsToPoll.length === 0)); } }; }); hl3 = x(() => { "use strict"; pt(); pl3(); me2 = {}; }); ml3 = x(() => { "use strict"; Ft3(); pt(); cl3(); hl3(); Or3 = class { get contextId() { return j2.webgl.contextId; } set contextId(e) { j2.webgl.contextId = e; } get matmulMaxBatchSize() { return j2.webgl.matmulMaxBatchSize; } set matmulMaxBatchSize(e) { j2.webgl.matmulMaxBatchSize = e; } get textureCacheMode() { return j2.webgl.textureCacheMode; } set textureCacheMode(e) { j2.webgl.textureCacheMode = e; } get pack() { return j2.webgl.pack; } set pack(e) { j2.webgl.pack = e; } get async() { return j2.webgl.async; } set async(e) { j2.webgl.async = e; } initialize() { try { return this.glContext = Cn2(this.contextId), typeof this.matmulMaxBatchSize != "number" && (this.matmulMaxBatchSize = 16), typeof this.textureCacheMode != "string" && (this.textureCacheMode = "full"), typeof this.pack != "boolean" && (this.pack = false), typeof this.async != "boolean" && (this.async = false), M2.setWithEnv(j2), j2.webgl.context || Object.defineProperty(j2.webgl, "context", { value: this.glContext.gl }), M2.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), true; } catch (e) { return M2.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${e}`), false; } } createSessionHandler(e) { return new Sr3(this, e); } dispose() { this.glContext.dispose(); } }; }); yl3 = x(() => { "use strict"; ml3(); bl3 = /* @__PURE__ */ new Map(), nd3 = { webgl: new Or3() }; }); gl3 = x(() => { "use strict"; pt(); Rn3 = class { constructor(e, o) { this.op = e; this.node = o; } }, Ar3 = class { constructor(e, o, t) { this.graph = e; this.profiler = t; this.initialize(o); } initialize(e) { this.profiler.event("session", "ExecutionPlan.initialize", () => { let o = this.graph.getNodes(); if (o.length !== e.length) throw new Error("The size of nodes and OPs do not match."); this._ops = e.map((t, n) => new Rn3(t, o[n])), this.reset(), this._starter = [], this._ops.forEach((t, n) => { let r = true; for (let s of t.node.inputs) if (!this._values[s] && this.graph.getInputIndices().indexOf(s) === -1) { r = false; break; } r && this._starter.push(n); }); }); } reset() { this._values = this.graph.getValues().map((e) => e.tensor); } async execute(e, o) { return this.profiler.event("session", "ExecutionPlan.execute", async () => { this.reset(); let t = e.createInferenceHandler(), n = this.graph.getInputIndices(); if (o.length !== n.length) throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${o.length} expected: ${n.length}`); o.forEach((f, p) => { let d = n[p]; this._values[d] = f; }); let r = this._starter.slice(0), s = this.graph.getValues(), i = this.graph.getNodes(), u = 0; for (; u < r.length; ) { let f = r[u++], p = this._ops[f], d = p.node.inputs.map((v) => this._values[v]); if (d.indexOf(void 0) !== -1) throw new Error(`unresolved input detected: op: ${p.node}`); let b = d; M2.verbose("ExecPlan", `Running op:${p.node.name} (${b.map((v, _) => `'${p.node.inputs[_]}': ${v.type}[${v.dims.join(",")}]`).join(", ")})`); let g = await this.profiler.event("node", p.node.name, async () => p.op.impl(t, b, p.op.context)); if (g.length !== p.node.outputs.length) throw new Error("the size of output does not match model definition."); g.forEach((v, _) => { let O2 = p.node.outputs[_]; if (this._values[O2]) throw new Error(`output [${O2}] already has value: op:${p.node.name}`); this._values[O2] = v; }); let y = /* @__PURE__ */ new Set(); g.forEach((v, _) => { let O2 = p.node.outputs[_]; for (let S of s[O2].to) { let C = i[S], F2 = true; for (let st2 of C.inputs) if (!this._values[st2]) { F2 = false; break; } F2 && y.add(S); } }), r.push(...y); } let l = []; for (let f = 0; f < this.graph.getOutputIndices().length; f++) { let p = this.graph.getOutputIndices()[f], d = this._values[p]; if (d === void 0) throw new Error(`required output [${p}] does not have value`); p === 0 ? await d.getData() : d.data, l.push(d); } return M2.verbose("ExecPlan", "disposing of inferenceHandler"), t.dispose(), l; }); } }; }); xl3 = x(() => { "use strict"; ge2(); B2 = ne(se()); Yt3(); z2(); xt2 = P.experimental.fbs, Le2 = class a { constructor(e) { if (this._attributes = /* @__PURE__ */ new Map(), e != null) { for (let o of e) o instanceof B2.onnx.AttributeProto ? this._attributes.set(o.name, [a.getValue(o), a.getType(o)]) : o instanceof xt2.Attribute && this._attributes.set(o.name(), [a.getValue(o), a.getType(o)]); if (this._attributes.size < e.length) throw new Error("duplicated attribute names"); } } set(e, o, t) { this._attributes.set(e, [t, o]); } delete(e) { this._attributes.delete(e); } getFloat(e, o) { return this.get(e, "float", o); } getInt(e, o) { return this.get(e, "int", o); } getString(e, o) { return this.get(e, "string", o); } getTensor(e, o) { return this.get(e, "tensor", o); } getFloats(e, o) { return this.get(e, "floats", o); } getInts(e, o) { return this.get(e, "ints", o); } getStrings(e, o) { return this.get(e, "strings", o); } getTensors(e, o) { return this.get(e, "tensors", o); } get(e, o, t) { let n = this._attributes.get(e); if (n === void 0) { if (t !== void 0) return t; throw new Error(`required attribute not found: ${e}`); } if (n[1] !== o) throw new Error(`type mismatch: expected ${o} but got ${n[1]}`); return n[0]; } static getType(e) { let o = e instanceof B2.onnx.AttributeProto ? e.type : e.type(); switch (o) { case B2.onnx.AttributeProto.AttributeType.FLOAT: return "float"; case B2.onnx.AttributeProto.AttributeType.INT: return "int"; case B2.onnx.AttributeProto.AttributeType.STRING: return "string"; case B2.onnx.AttributeProto.AttributeType.TENSOR: return "tensor"; case B2.onnx.AttributeProto.AttributeType.FLOATS: return "floats"; case B2.onnx.AttributeProto.AttributeType.INTS: return "ints"; case B2.onnx.AttributeProto.AttributeType.STRINGS: return "strings"; case B2.onnx.AttributeProto.AttributeType.TENSORS: return "tensors"; default: throw new Error(`attribute type is not supported yet: ${B2.onnx.AttributeProto.AttributeType[o]}`); } } static getValue(e) { let o = e instanceof B2.onnx.AttributeProto ? e.type : e.type(); if (o === B2.onnx.AttributeProto.AttributeType.GRAPH || o === B2.onnx.AttributeProto.AttributeType.GRAPHS) throw new Error("graph attribute is not supported yet"); let t = this.getValueNoCheck(e); if (o === B2.onnx.AttributeProto.AttributeType.INT && ft.isLong(t)) return ft.longToNumber(t); if (o === B2.onnx.AttributeProto.AttributeType.INTS) { let n = t, r = new Array(n.length); for (let s = 0; s < n.length; s++) { let i = n[s]; r[s] = ft.longToNumber(i); } return r; } if (o === B2.onnx.AttributeProto.AttributeType.TENSOR) return e instanceof B2.onnx.AttributeProto ? Y2.fromProto(t) : Y2.fromOrtTensor(t); if (o === B2.onnx.AttributeProto.AttributeType.TENSORS) { if (e instanceof B2.onnx.AttributeProto) return t.map((r) => Y2.fromProto(r)); if (e instanceof xt2.Attribute) return t.map((r) => Y2.fromOrtTensor(r)); } return o === B2.onnx.AttributeProto.AttributeType.STRING && e instanceof B2.onnx.AttributeProto ? Ie3(t) : o === B2.onnx.AttributeProto.AttributeType.STRINGS && e instanceof B2.onnx.AttributeProto ? t.map(Ie3) : t; } static getValueNoCheck(e) { return e instanceof B2.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(e) : this.getValueNoCheckFromOrtFormat(e); } static getValueNoCheckFromOnnxFormat(e) { switch (e.type) { case B2.onnx.AttributeProto.AttributeType.FLOAT: return e.f; case B2.onnx.AttributeProto.AttributeType.INT: return e.i; case B2.onnx.AttributeProto.AttributeType.STRING: return e.s; case B2.onnx.AttributeProto.AttributeType.TENSOR: return e.t; case B2.onnx.AttributeProto.AttributeType.GRAPH: return e.g; case B2.onnx.AttributeProto.AttributeType.FLOATS: return e.floats; case B2.onnx.AttributeProto.AttributeType.INTS: return e.ints; case B2.onnx.AttributeProto.AttributeType.STRINGS: return e.strings; case B2.onnx.AttributeProto.AttributeType.TENSORS: return e.tensors; case B2.onnx.AttributeProto.AttributeType.GRAPHS: return e.graphs; default: throw new Error(`unsupported attribute type: ${B2.onnx.AttributeProto.AttributeType[e.type]}`); } } static getValueNoCheckFromOrtFormat(e) { switch (e.type()) { case xt2.AttributeType.FLOAT: return e.f(); case xt2.AttributeType.INT: return e.i(); case xt2.AttributeType.STRING: return e.s(); case xt2.AttributeType.TENSOR: return e.t(); case xt2.AttributeType.GRAPH: return e.g(); case xt2.AttributeType.FLOATS: return e.floatsArray(); case xt2.AttributeType.INTS: { let o = []; for (let t = 0; t < e.intsLength(); t++) o.push(e.ints(t)); return o; } case xt2.AttributeType.STRINGS: { let o = []; for (let t = 0; t < e.stringsLength(); t++) o.push(e.strings(t)); return o; } case xt2.AttributeType.TENSORS: { let o = []; for (let t = 0; t < e.tensorsLength(); t++) o.push(e.tensors(t)); return o; } default: throw new Error(`unsupported attribute type: ${xt2.AttributeType[e.type()]}`); } } }; }); Tl3 = x(() => { "use strict"; xl3(); ge2(); zn2 = ne(se()); Yt3(); z2(); Pr3 = P.experimental.fbs, Mn3 = { from: (a, e) => new Vn3(a, e) }, Lt2 = class { constructor(e) { this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, e && (this.type = et.tensorValueTypeFromProto(e.type.tensorType)); } get from() { return this._from; } get to() { return this._to; } }, Er2 = class { constructor(e, o) { e instanceof zn2.onnx.NodeProto ? (this.name = e.name, this.opType = e.opType, this.attributes = new Le2(e.attribute)) : e instanceof Pr3.Node && (this.name = o ?? e.name(), this.opType = e.opType(), this.attributes = new Le2(et.tensorAttributesFromORTFormat(e))), this.inputs = [], this.outputs = [], this.executeNode = true; } }, Vn3 = class { constructor(e, o) { if (!e) throw new TypeError("graph is empty"); this.buildGraph(e), this.transformGraph(o), this.checkIsAcyclic(); } getInputIndices() { return this._allInputIndices; } getInputNames() { return this._allInputNames; } getOutputIndices() { return this._allOutputIndices; } getOutputNames() { return this._allOutputNames; } getValues() { return this._allData; } getNodes() { return this._nodes; } buildGraph(e) { if (e instanceof zn2.onnx.GraphProto) this.buildGraphFromOnnxFormat(e); else if (e instanceof Pr3.Graph) this.buildGraphFromOrtFormat(e); else throw new TypeError("Graph type is not supported."); } buildGraphFromOnnxFormat(e) { let o = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; let t = /* @__PURE__ */ new Map(); if (!e.input) throw new Error("missing information in graph: input"); let n = []; for (let r of e.input) { if (o.has(r.name)) throw new Error(`duplicated input name: ${r.name}`); let s = this._allData.push(new Lt2(r)) - 1; o.set(r.name, s), n.push(r.name); } if (!e.initializer) throw new Error("missing information in graph: initializer"); for (let r of e.initializer) { let s = o.get(r.name); if (s === void 0) { let i = new Lt2(); i.type = { shape: { dims: et.tensorDimsFromProto(r.dims) }, tensorType: et.tensorDataTypeFromProto(r.dataType) }, s = this._allData.push(i) - 1, o.set(r.name, s); } this._allData[s]._from = -1, this._allData[s].tensor = Y2.fromProto(r); } for (let r = 0; r < this._allData.length; r++) this._allData[r].tensor || (this._allInputIndices.push(r), this._allInputNames.push(n[r])); if (!e.output) throw new Error("missing information in graph: output"); for (let r of e.output) { if (o.has(r.name)) throw new Error(`duplicated output name: ${r.name}`); let s = this._allData.push(new Lt2(r)) - 1; o.set(r.name, s), this._allOutputIndices.push(s), this._allOutputNames.push(r.name); } if (!e.node) throw new Error("missing information in graph: node"); for (let r of e.node) { if (!r.name) for (let i = 0; ; i++) { let u = `unnamed_${r.opType}_${i}`; if (!t.has(u)) { r.name = u; break; } } if (t.has(r.name)) throw new Error(`duplicated node name: ${r.name}`); let s = this._nodes.push(new Er2(r)) - 1; t.set(r.name, s); } for (let r = 0; r < this._nodes.length; r++) { let s = this._nodes[r], i = e.node[r]; if (!i.output) throw new Error(`missing output for node: ${i.name}`); for (let u of i.output) { let l = o.get(u); if (typeof l > "u" && (l = this._allData.push(new Lt2()) - 1, o.set(u, l)), s.outputs.push(l), this._allData[l]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${l}`); if (this._allData[l]._from = r, i.opType === "Constant") { if (!i.attribute || i.attribute.length !== 1 || !i.attribute[0].t) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (!i.output || i.output.length !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator"); s.outputs.pop(), s.executeNode = false, this._allData[l]._from = -1, this._allData[l].tensor = Y2.fromProto(i.attribute[0].t); } } } for (let r = 0; r < this._nodes.length; r++) { let s = this._nodes[r], i = e.node[r]; if (!i.input) throw new Error(`missing input for node: ${i.name}`); for (let u of i.input) { let l = o.get(u); if (typeof l > "u") { if (u === "" && (i.input.length === 3 || i.input.length === 4) && i.opType === "Resize") continue; throw new Error(`unrecognized input '${u}' for node: ${i.name}`); } s.inputs.push(l), this._allData[l]._to.push(r); } } return true; } buildGraphFromOrtFormat(e) { let o = /* @__PURE__ */ new Map(); this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = []; let t = /* @__PURE__ */ new Map(), n = []; for (let r = 0; r < e.inputsLength(); r++) { let s = e.inputs(r); if (o.has(s)) throw new Error(`duplicated input name: ${s}`); for (let i = 0; i < e.nodeArgsLength(); i++) if (e.nodeArgs(i)?.name() === s) { let u = new Lt2(); if (e.nodeArgs(i)?.type()?.valueType() !== Pr3.TypeInfoValue.tensor_type) throw new Error("Unexpected value type for the nodeArg."); let f = e.nodeArgs(i).type().value(new Pr3.TensorTypeAndShape()), p = et.tensorDataTypeFromProto(f.elemType()), d = f.shape(), b = []; for (let y = 0; y < d.dimLength(); y++) b.push(ft.longToNumber(d.dim(y).value().dimValue())); u.type = { shape: { dims: b }, tensorType: p }; let g = this._allData.push(u) - 1; o.set(s, g), n.push(s); } } for (let r = 0; r < e.initializersLength(); r++) { let s = e.initializers(r), i = o.get(s.name()); if (i === void 0) { let u = new Lt2(), l = et.tensorDimsFromORTFormat(s), f = et.tensorDataTypeFromProto(s.dataType()); u.type = { shape: { dims: l }, tensorType: f }, i = this._allData.push(u) - 1, o.set(s.name(), i); } this._allData[i]._from = -1, this._allData[i].tensor = Y2.fromOrtTensor(s); } for (let r = 0; r < this._allData.length; r++) this._allData[r].tensor || (this._allInputIndices.push(r), this._allInputNames.push(n[r])); for (let r = 0; r < e.outputsLength(); r++) { let s = e.outputs(r); if (o.has(s)) throw new Error(`duplicated output name: ${s}`); let i = this._allData.push(new Lt2()) - 1; o.set(s, i), this._allOutputIndices.push(i), this._allOutputNames.push(s); } if (!e.nodes) throw new Error("missing information in graph: node"); for (let r = 0; r < e.nodesLength(); r++) { let s = e.nodes(r), i = s.name(); if (!i) for (let l = 0; i = `unnamed_${s.opType()}_${l}`, !!t.has(i); l++) ; if (t.has(i)) throw new Error(`duplicated node name: ${i}`); let u = this._nodes.push(new Er2(s, i)) - 1; t.set(i, u); } for (let r = 0; r < this._nodes.length; r++) { let s = this._nodes[r], i = e.nodes(r); if (i == null) throw new Error(`No node exists at index ${r}`); if (i?.outputsLength() === 0) throw new Error(`missing output for node: ${i.name}`); for (let u = 0; u < i?.outputsLength(); u++) { let l = i?.outputs(u), f = o.get(l); if (typeof f > "u" && (f = this._allData.push(new Lt2()) - 1, o.set(l, f)), s.outputs.push(f), this._allData[f]._from !== void 0) throw new Error(`multiple nodes output to one data value: ${f}`); if (this._allData[f]._from = r, i.opType() === "Constant") { if (i.attributesLength() !== 1 || !i.attributes(0).t()) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator"); if (i.outputsLength() !== 1) throw new Error("missing output or incorrect number of outputs for this Constant operator"); s.outputs.pop(), s.executeNode = false, this._allData[f]._from = -1, this._allData[f].tensor = Y2.fromOrtTensor(i.attributes(0).t()); } } } for (let r = 0; r < this._nodes.length; r++) { let s = this._nodes[r], i = e.nodes(r); if (i.inputsLength() === 0) throw new Error(`missing input for node: ${i.name}`); for (let u = 0; u < i.inputsLength(); u++) { let l = i.inputs(u), f = o.get(l); if (typeof f > "u") throw new Error(`unrecognized input '${l}' for node: ${i.name()}`); s.inputs.push(f), this._allData[f]._to.push(r); } } } checkIsAcyclic() { let e = /* @__PURE__ */ new Set(); this._allInputIndices.forEach((n) => { this._allData[n]._to.forEach((s) => { e.add(s); }); }); let o = Array.from(e), t = new Array(this._nodes.length).fill("white"); for (; o.length > 0; ) { let n = o.pop(); t[n] === "gray" ? t[n] = "black" : (o.push(n), t[n] = "gray", this._nodes[n].outputs.forEach((r) => { let s = this._allData[r]; if (typeof s.tensor < "u") throw new Error("node outputs should not be initialized"); if (s._from !== n) throw new Error("from property of the Value object doesn't match index of Node being processed"); s._to.forEach((i) => { if (t[i] === "gray") throw new Error("model graph is cyclic"); t[i] === "white" && o.push(i); }); })); } } transformGraph(e) { this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), e && e.transformGraph(this), this.finalizeGraph(); } finalizeGraph() { let e = 0, o = new Array(this._nodes.length, 0), t = 0; for (let n = 0; n < this._nodes.length; n++) o[n] = t, this._nodes[n].executeNode ? (t !== n && (this._nodes[t] = this._nodes[n]), t++) : this._nodes[n].outputs.forEach((r) => { this._allData[r]._from = -2; }); this._nodes.splice(t, this._nodes.length - t); for (let n = 0; n < this._allData.length; n++) { let r = this._allData[n]; r._from !== void 0 && r._from !== -1 && r._from !== -2 && (r._from = o[r._from]); for (let s = 0; s < r._to.length; s++) if (r._to[s] >= 0) r._to[s] = o[r._to[s]]; else throw new Error("Trying to update a removed node"); } e = 0; for (let n = 0; n < this._allData.length; n++) { if (this._allData[n].from === -2 && this._allOutputIndices.indexOf(n + e) === -1) { e++, this._allData.splice(n, 1), n--; continue; } if (e > 0) { let r = -1; this._allData[n].from !== void 0 && this._allData[n].from !== -1 ? (r = this._nodes[this._allData[n].from].outputs.indexOf(n + e), r !== -1 && (this._nodes[this._allData[n].from].outputs[r] = n)) : (r = this._allInputIndices.indexOf(n + e), r !== -1 && (this._allInputIndices[r] = n)), this._allData[n].to.forEach((s) => { r = this._nodes[s].inputs.indexOf(n + e), r !== -1 && (this._nodes[s].inputs[r] = n); }), this._allData[n].to.length === 0 && (r = this._allOutputIndices.indexOf(n + e), r !== -1 && (this._allOutputIndices[r] = n)); } } } deleteNode(e) { let o = this._nodes[e]; if (o.outputs.length > 1) { for (let i = 1; i < o.outputs.length; i++) if (this._allData[o.outputs[i]].to.length > 0) throw new Error("Node deletion with more than one output connected to other nodes is not supported. "); } o.executeNode = false; let t = o.inputs[0], n = o.outputs[0], r = this._allData[n].to; for (let i = 0; i < o.inputs.length; i++) { let u = this._allData[o.inputs[i]].to.indexOf(e); if (u === -1) throw new Error("The Value object doesn't have the current Node in it's 'to' property "); this._allData[o.inputs[i]].to.splice(u, 1); } this._allData[n]._to = []; let s = this._allOutputIndices.indexOf(n); if (s !== -1 && (this._allOutputIndices[s] = t), r && r.length > 0) for (let i of r) { let u = this._nodes[i].inputs.indexOf(n); if (u === -1) throw new Error("The Node object doesn't have the output Value in it's 'inputs' property "); this._nodes[i].inputs[u] = t, this._allData[t].to.push(i); } } removeAllDropoutNodes() { let e = 0; for (let o of this._nodes) { if (o.opType === "Dropout") { if (o.inputs.length !== 1) throw new Error("Dropout nodes should only contain one input. "); if (o.outputs.length !== 1 && o.outputs.length !== 2) throw new Error("Dropout nodes should contain either 1 or 2 output(s)"); if (o.outputs.length === 2 && this._allData[o.outputs[1]]._to.length !== 0) throw new Error("Dropout nodes's second output should not be referenced by other nodes"); this.deleteNode(e); } e++; } } removeAllIdentityNodes() { let e = 0; for (let o of this._nodes) o.opType === "Identity" && this.deleteNode(e), e++; } isActivation(e) { switch (e.opType) { case "Relu": case "Sigmoid": case "Clip": return true; default: return false; } } fuseConvActivationNodes() { for (let e of this._nodes) if (e.opType === "Conv") { let o = this._allData[e.outputs[0]]._to; if (o.length === 1 && this.isActivation(this._nodes[o[0]])) { let t = this._nodes[o[0]]; if (t.opType === "Clip") if (t.inputs.length === 1) try { e.attributes.set("activation_params", "floats", [t.attributes.getFloat("min"), t.attributes.getFloat("max")]); } catch { e.attributes.set("activation_params", "floats", [Jt3, Zt2]); } else if (t.inputs.length >= 3 && this._allData[t.inputs[1]].tensor !== void 0 && this._allData[t.inputs[2]].tensor !== void 0) e.attributes.set("activation_params", "floats", [this._allData[t.inputs[1]].tensor.floatData[0], this._allData[t.inputs[2]].tensor.floatData[0]]); else continue; e.attributes.set("activation", "string", t.opType), this.deleteNode(o[0]); } } } }; }); wl3 = x(() => { "use strict"; Je(); Tl3(); ge2(); vl3 = ne(se()); z2(); ad3 = P.experimental.fbs, Dr2 = class { constructor() { } load(e, o, t) { let n; if (!t) try { this.loadFromOnnxFormat(e, o); return; } catch (r) { if (t !== void 0) throw r; n = r; } try { this.loadFromOrtFormat(e, o); } catch (r) { throw t !== void 0 ? r : new Error(`Failed to load model as ONNX format: ${n} as ORT format: ${r}`); } } loadFromOnnxFormat(e, o) { let t = vl3.onnx.ModelProto.decode(e); if (ft.longToNumber(t.irVersion) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = t.opsetImport.map((r) => ({ domain: r.domain, version: ft.longToNumber(r.version) })), this._graph = Mn3.from(t.graph, o); } loadFromOrtFormat(e, o) { let t = new m.ByteBuffer(e), n = ad3.InferenceSession.getRootAsInferenceSession(t).model(); if (ft.longToNumber(n.irVersion()) < 3) throw new Error("only support ONNX model with IR_VERSION>=3"); this._opsets = []; for (let s = 0; s < n.opsetImportLength(); s++) { let i = n.opsetImport(s); this._opsets.push({ domain: i?.domain(), version: ft.longToNumber(i.version()) }); } this._graph = Mn3.from(n.graph(), o); } get graph() { return this._graph; } get opsets() { return this._opsets; } }; }); Il3 = x(() => { "use strict"; yl3(); gl3(); pt(); wl3(); Lr2 = class { constructor(e = {}) { this._initialized = false, this.backendHint = e.backendHint, this.profiler = Ke3.create(e.profiler), this.context = { profiler: this.profiler, graphInputTypes: [], graphInputDims: [] }; } get inputNames() { return this._model.graph.getInputNames(); } get outputNames() { return this._model.graph.getOutputNames(); } startProfiling() { this.profiler.start(); } endProfiling() { this.profiler.stop(); } async loadModel(e, o, t) { await this.profiler.event("session", "Session.loadModel", async () => { let n = await Gn3(this.backendHint); if (this.sessionHandler = n.createSessionHandler(this.context), this._model = new Dr2(), typeof e == "string") { let r = e.endsWith(".ort"); { let i = await (await fetch(e)).arrayBuffer(); this.initialize(new Uint8Array(i), r); } } else if (ArrayBuffer.isView(e)) this.initialize(e); else { let r = new Uint8Array(e, o || 0, t || e.byteLength); this.initialize(r); } }); } initialize(e, o) { if (this._initialized) throw new Error("already initialized"); this.profiler.event("session", "Session.initialize", () => { let t = this.sessionHandler.transformGraph ? this.sessionHandler : void 0; this._model.load(e, t, o), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new Ar3(this._model.graph, this._ops, this.profiler); }), this._initialized = true; } async run(e) { if (!this._initialized) throw new Error("session not initialized yet"); return this.profiler.event("session", "Session.run", async () => { let o = this.normalizeAndValidateInputs(e), t = await this._executionPlan.execute(this.sessionHandler, o); return this.createOutput(t); }); } normalizeAndValidateInputs(e) { let o = this._model.graph.getInputNames(); if (Array.isArray(e)) { if (e.length !== o.length) throw new Error(`incorrect input array length: expected ${o.length} but got ${e.length}`); } else { if (e.size !== o.length) throw new Error(`incorrect input map size: expected ${o.length} but got ${e.size}`); let t = new Array(e.size), n = 0; for (let r = 0; r < o.length; ++r) { let s = e.get(o[r]); if (!s) throw new Error(`missing input tensor for: '${name}'`); t[n++] = s; } e = t; } if (!this.context.graphInputTypes || this.context.graphInputTypes.length === 0 || !this.context.graphInputDims || this.context.graphInputDims.length === 0) { let t = this._model.graph.getInputIndices(), n = this._model.graph.getValues(), r = new Array(t.length); for (let s = 0; s < t.length; ++s) { let i = n[t[s]]; r[s] = i.type.shape.dims, this.context.graphInputTypes.push(i.type.tensorType), this.context.graphInputDims.push(e[s].dims); } this.validateInputTensorDims(r, e, true); } else this.validateInputTensorDims(this.context.graphInputDims, e, false); return this.validateInputTensorTypes(this.context.graphInputTypes, e), e; } validateInputTensorTypes(e, o) { for (let t = 0; t < o.length; t++) { let n = e[t], r = o[t].type; if (n !== r) throw new Error(`input tensor[${t}] check failed: expected type '${n}' but got ${r}`); } } validateInputTensorDims(e, o, t) { for (let n = 0; n < o.length; n++) { let r = e[n], s = o[n].dims; if (!this.compareTensorDims(r, s, t)) throw new Error(`input tensor[${n}] check failed: expected shape '[${r.join(",")}]' but got [${s.join(",")}]`); } } compareTensorDims(e, o, t) { if (e.length !== o.length) return false; for (let n = 0; n < e.length; ++n) if (e[n] !== o[n] && (!t || e[n] !== 0)) return false; return true; } createOutput(e) { let o = this._model.graph.getOutputNames(); if (e.length !== o.length) throw new Error("expected number of outputs do not match number of generated outputs"); let t = /* @__PURE__ */ new Map(); for (let n = 0; n < o.length; ++n) t.set(o[n], e[n]); return t; } initializeOps(e) { let o = e.getNodes(); this._ops = new Array(o.length); for (let t = 0; t < o.length; t++) this._ops[t] = this.sessionHandler.resolve(o[t], this._model.opsets, e); } }; }); _l3 = x(() => { "use strict"; Ft3(); Yt3(); $r3 = class { constructor(e) { this.session = e; this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames; } async dispose() { } async run(e, o, t) { let n = /* @__PURE__ */ new Map(); for (let i in e) if (Object.hasOwnProperty.call(e, i)) { let u = e[i]; n.set(i, new Y2(u.dims, u.type, void 0, void 0, u.data)); } let r = await this.session.run(n), s = {}; return r.forEach((i, u) => { s[u] = new ot3(i.type, i.data, i.dims); }), s; } startProfiling() { this.session.startProfiling(); } endProfiling() { this.session.endProfiling(); } }; }); Sl3 = {}; Wn3(Sl3, { onnxjsBackend: () => sd3 }); Ol3 = x(() => { "use strict"; Il3(); _l3(); Un3 = class { async init() { } async createInferenceSessionHandler(e, o) { let t = new Lr2(o); return typeof e == "string" ? await t.loadModel(e) : await t.loadModel(e), new $r3(t); } }, sd3 = new Un3(); }); Ft3(); Ft3(); Ft3(); wo2 = "1.19.2"; zv = Cr3; { let a = (Ol3(), $l3(Sl3)).onnxjsBackend; Fe2("webgl", a, -10); } Object.defineProperty(j2.versions, "web", { value: wo2, enumerable: true }); } }); // node_modules/gliner/dist/index.mjs var __defProp2, __defNormalProp, __publicField, Model, SpanModel, TokenModel, WhitespaceTokenSplitter, Processor2, SpanProcessor, TokenProcessor, isNested, hasOverlapping, hasOverlappingNested, sigmoid, BaseDecoder, SpanDecoder, TokenDecoder, ONNX_WASM_CDN_URL, DEFAULT_WASM_PATHS, ONNXWebWrapper, Gliner; var init_dist2 = __esm({ "node_modules/gliner/dist/index.mjs"() { init_transformers(); init_ort_bundle_min(); init_ort_webgpu_bundle_min(); init_ort_webgl_min(); __defProp2 = Object.defineProperty; __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); Model = class { constructor(config, processor, decoder, onnxWrapper) { this.config = config; this.processor = processor; this.decoder = decoder; this.onnxWrapper = onnxWrapper; } async initialize() { await this.onnxWrapper.init(); } }; SpanModel = class extends Model { prepareInputs(batch) { const batch_size = batch.inputsIds.length; const num_tokens = batch.inputsIds[0].length; const num_spans = batch.spanIdxs[0].length; const createTensor = (data, shape, tensorType = "int64") => { return new this.onnxWrapper.ort.Tensor(tensorType, data.flat(Infinity), shape); }; let input_ids = createTensor(batch.inputsIds, [batch_size, num_tokens]); let attention_mask = createTensor(batch.attentionMasks, [batch_size, num_tokens]); let words_mask = createTensor(batch.wordsMasks, [batch_size, num_tokens]); let text_lengths = createTensor(batch.textLengths, [batch_size, 1]); let span_idx = createTensor(batch.spanIdxs, [batch_size, num_spans, 2]); let span_mask = createTensor(batch.spanMasks, [batch_size, num_spans], "bool"); const feeds = { input_ids, attention_mask, words_mask, text_lengths, span_idx, span_mask }; return feeds; } async inference(texts, entities, flatNer = false, threshold = 0.5, multiLabel = false) { let batch = this.processor.prepareBatch(texts, entities); let feeds = this.prepareInputs(batch); const results = await this.onnxWrapper.run(feeds); const modelOutput = results["logits"].data; const batchSize = batch.batchTokens.length; const inputLength = Math.max(...batch.textLengths); const maxWidth = this.config.max_width; const numEntities = entities.length; const batchIds = Array.from({ length: batchSize }, (_, i) => i); const decodedSpans = this.decoder.decode( batchSize, inputLength, maxWidth, numEntities, texts, batchIds, batch.batchWordsStartIdx, batch.batchWordsEndIdx, batch.idToClass, modelOutput, flatNer, threshold, multiLabel ); return decodedSpans; } async inference_with_chunking(texts, entities, flatNer = false, threshold = 0.5, multiLabel = false, batch_size = 4, max_words = 512) { const { idToClass } = this.processor.createMappings(entities); let batchIds = []; let batchTokens = []; let batchWordsStartIdx = []; let batchWordsEndIdx = []; texts.forEach((text, id4) => { let [tokens, wordsStartIdx, wordsEndIdx] = this.processor.tokenizeText(text); let num_sub_batches = Math.ceil(tokens.length / max_words); for (let i = 0; i < num_sub_batches; i++) { let start = i * max_words; let end = Math.min((i + 1) * max_words, tokens.length); batchIds.push(id4); batchTokens.push(tokens.slice(start, end)); batchWordsStartIdx.push(wordsStartIdx.slice(start, end)); batchWordsEndIdx.push(wordsEndIdx.slice(start, end)); } }); let num_batches = Math.ceil(batchIds.length / batch_size); let finalDecodedSpans = []; for (let id4 = 0; id4 < texts.length; id4++) { finalDecodedSpans.push([]); } for (let batch_id = 0; batch_id < num_batches; batch_id++) { let start = batch_id * batch_size; let end = Math.min((batch_id + 1) * batch_size, batchIds.length); let currBatchTokens = batchTokens.slice(start, end); let currBatchWordsStartIdx = batchWordsStartIdx.slice(start, end); let currBatchWordsEndIdx = batchWordsEndIdx.slice(start, end); let currBatchIds = batchIds.slice(start, end); let [inputTokens, textLengths, promptLengths] = this.processor.prepareTextInputs(currBatchTokens, entities); let [inputsIds, attentionMasks, wordsMasks] = this.processor.encodeInputs(inputTokens, promptLengths); inputsIds = this.processor.padArray(inputsIds); attentionMasks = this.processor.padArray(attentionMasks); wordsMasks = this.processor.padArray(wordsMasks); let { spanIdxs, spanMasks } = this.processor.prepareSpans(currBatchTokens, this.config["max_width"]); spanIdxs = this.processor.padArray(spanIdxs, 3); spanMasks = this.processor.padArray(spanMasks); let batch = { inputsIds, attentionMasks, wordsMasks, textLengths, spanIdxs, spanMasks, idToClass, batchTokens: currBatchTokens, batchWordsStartIdx: currBatchWordsStartIdx, batchWordsEndIdx: currBatchWordsEndIdx }; let feeds = this.prepareInputs(batch); const results = await this.onnxWrapper.run(feeds); const modelOutput = results["logits"].data; const batchSize = batch.batchTokens.length; const inputLength = Math.max(...batch.textLengths); const maxWidth = this.config.max_width; const numEntities = entities.length; const decodedSpans = this.decoder.decode( batchSize, inputLength, maxWidth, numEntities, texts, currBatchIds, batch.batchWordsStartIdx, batch.batchWordsEndIdx, batch.idToClass, modelOutput, flatNer, threshold, multiLabel ); for (let i = 0; i < currBatchIds.length; i++) { const originalTextId = currBatchIds[i]; finalDecodedSpans[originalTextId].push(...decodedSpans[i]); } } return finalDecodedSpans; } }; TokenModel = class extends Model { prepareInputs(batch) { const batch_size = batch.inputsIds.length; const num_tokens = batch.inputsIds[0].length; const createTensor = (data, shape, tensorType = "int64") => { return new this.onnxWrapper.ort.Tensor(tensorType, data.flat(Infinity), shape); }; let input_ids = createTensor(batch.inputsIds, [batch_size, num_tokens]); let attention_mask = createTensor(batch.attentionMasks, [batch_size, num_tokens]); let words_mask = createTensor(batch.wordsMasks, [batch_size, num_tokens]); let text_lengths = createTensor(batch.textLengths, [batch_size, 1]); const feeds = { input_ids, attention_mask, words_mask, text_lengths }; return feeds; } async inference(texts, entities, flatNer = false, threshold = 0.5, multiLabel = false) { let batch = this.processor.prepareBatch(texts, entities); let feeds = this.prepareInputs(batch); const results = await this.onnxWrapper.run(feeds); const modelOutput = results["logits"].data; const batchSize = batch.batchTokens.length; const inputLength = Math.max(...batch.textLengths); const numEntities = entities.length; const batchIds = Array.from({ length: batchSize }, (_, i) => i); const decodedSpans = this.decoder.decode( batchSize, inputLength, numEntities, texts, batchIds, batch.batchWordsStartIdx, batch.batchWordsEndIdx, batch.idToClass, modelOutput, flatNer, threshold, multiLabel ); return decodedSpans; } async inference_with_chunking(texts, entities, flatNer = true, threshold = 0.5, multiLabel = false, batch_size = 4, max_words = 512) { const { idToClass } = this.processor.createMappings(entities); let batchIds = []; let batchTokens = []; let batchWordsStartIdx = []; let batchWordsEndIdx = []; texts.forEach((text, id4) => { let [tokens, wordsStartIdx, wordsEndIdx] = this.processor.tokenizeText(text); let num_sub_batches = Math.ceil(tokens.length / max_words); for (let i = 0; i < num_sub_batches; i++) { let start = i * max_words; let end = Math.min((i + 1) * max_words, tokens.length); batchIds.push(id4); batchTokens.push(tokens.slice(start, end)); batchWordsStartIdx.push(wordsStartIdx.slice(start, end)); batchWordsEndIdx.push(wordsEndIdx.slice(start, end)); } }); let num_batches = Math.ceil(batchIds.length / batch_size); let finalDecodedSpans = []; for (let id4 = 0; id4 < texts.length; id4++) { finalDecodedSpans.push([]); } for (let batch_id = 0; batch_id < num_batches; batch_id++) { let start = batch_id * batch_size; let end = Math.min((batch_id + 1) * batch_size, batchIds.length); let currBatchTokens = batchTokens.slice(start, end); let currBatchWordsStartIdx = batchWordsStartIdx.slice(start, end); let currBatchWordsEndIdx = batchWordsEndIdx.slice(start, end); let currBatchIds = batchIds.slice(start, end); let [inputTokens, textLengths, promptLengths] = this.processor.prepareTextInputs(currBatchTokens, entities); let [inputsIds, attentionMasks, wordsMasks] = this.processor.encodeInputs(inputTokens, promptLengths); inputsIds = this.processor.padArray(inputsIds); attentionMasks = this.processor.padArray(attentionMasks); wordsMasks = this.processor.padArray(wordsMasks); let batch = { inputsIds, attentionMasks, wordsMasks, textLengths, idToClass, batchTokens: currBatchTokens, batchWordsStartIdx: currBatchWordsStartIdx, batchWordsEndIdx: currBatchWordsEndIdx }; let feeds = this.prepareInputs(batch); const results = await this.onnxWrapper.run(feeds); const modelOutput = results["logits"].data; const batchSize = batch.batchTokens.length; const inputLength = Math.max(...batch.textLengths); const numEntities = entities.length; const decodedSpans = this.decoder.decode( batchSize, inputLength, numEntities, texts, currBatchIds, batch.batchWordsStartIdx, batch.batchWordsEndIdx, batch.idToClass, modelOutput, flatNer, threshold, multiLabel ); for (let i = 0; i < currBatchIds.length; i++) { const originalTextId = currBatchIds[i]; finalDecodedSpans[originalTextId].push(...decodedSpans[i]); } } return finalDecodedSpans; } }; WhitespaceTokenSplitter = class { constructor() { __publicField(this, "whitespacePattern"); this.whitespacePattern = /\w+(?:[-_]\w+)*|\S/g; } *call(text) { let match; while ((match = this.whitespacePattern.exec(text)) !== null) { yield [match[0], match.index, this.whitespacePattern.lastIndex]; } } }; Processor2 = class { constructor(config, tokenizer, wordsSplitter) { __publicField(this, "config"); __publicField(this, "tokenizer"); __publicField(this, "wordsSplitter"); this.config = config; this.tokenizer = tokenizer; this.wordsSplitter = wordsSplitter; } tokenizeText(text) { let tokens = []; let wordsStartIdx = []; let wordsEndIdx = []; for (const [token, start, end] of this.wordsSplitter.call(text)) { tokens.push(token); wordsStartIdx.push(start); wordsEndIdx.push(end); } return [tokens, wordsStartIdx, wordsEndIdx]; } batchTokenizeText(texts) { let batchTokens = []; let batchWordsStartIdx = []; let batchWordsEndIdx = []; for (const text of texts) { const [tokens, wordsStartIdx, wordsEndIdx] = this.tokenizeText(text); batchTokens.push(tokens); batchWordsStartIdx.push(wordsStartIdx); batchWordsEndIdx.push(wordsEndIdx); } return [batchTokens, batchWordsStartIdx, batchWordsEndIdx]; } createMappings(classes) { const classToId = {}; const idToClass = {}; classes.forEach((className, index) => { const id4 = index + 1; classToId[className] = id4; idToClass[id4] = className; }); return { classToId, idToClass }; } prepareTextInputs(tokens, entities) { const inputTexts = []; const promptLengths = []; const textLengths = []; tokens.forEach((text) => { textLengths.push(text.length); let inputText = []; for (let ent of entities) { inputText.push("<>"); inputText.push(ent); } inputText.push("<>"); const promptLength = inputText.length; promptLengths.push(promptLength); inputText = inputText.concat(text); inputTexts.push(inputText); }); return [inputTexts, textLengths, promptLengths]; } encodeInputs(texts, promptLengths = null) { let wordsMasks = []; let inputsIds = []; let attentionMasks = []; for (let id4 = 0; id4 < texts.length; id4++) { let promptLength = promptLengths ? promptLengths[id4] : 0; let tokenizedInputs = texts[id4]; let wordsMask = [0]; let inputIds = [1]; let attentionMask = [1]; let c = 1; tokenizedInputs.forEach((word, wordId) => { let wordTokens = this.tokenizer.encode(word).slice(1, -1); wordTokens.forEach((token, tokenId) => { attentionMask.push(1); if (wordId < promptLength) { wordsMask.push(0); } else if (tokenId === 0) { wordsMask.push(c); c++; } else { wordsMask.push(0); } inputIds.push(token); }); }); wordsMask.push(0); inputIds.push(this.tokenizer.sep_token_id); attentionMask.push(1); wordsMasks.push(wordsMask); inputsIds.push(inputIds); attentionMasks.push(attentionMask); } return [inputsIds, attentionMasks, wordsMasks]; } padArray(arr, dimensions = 2) { if (dimensions < 2 || dimensions > 3) { throw new Error("Only 2D and 3D arrays are supported"); } const maxLength = Math.max(...arr.map((subArr) => subArr.length)); const finalDim = dimensions === 3 ? arr[0][0].length : 0; return arr.map((subArr) => { const padCount = maxLength - subArr.length; const padding = Array(padCount).fill(dimensions === 3 ? Array(finalDim).fill(0) : 0); return [...subArr, ...padding]; }); } }; SpanProcessor = class extends Processor2 { constructor(config, tokenizer, wordsSplitter) { super(config, tokenizer, wordsSplitter); } prepareSpans(batchTokens, maxWidth = 12) { let spanIdxs = []; let spanMasks = []; batchTokens.forEach((tokens) => { let textLength = tokens.length; let spanIdx = []; let spanMask = []; for (let i = 0; i < textLength; i++) { for (let j3 = 0; j3 < maxWidth; j3++) { let endIdx = Math.min(i + j3, textLength - 1); spanIdx.push([i, endIdx]); spanMask.push(endIdx < textLength ? true : false); } } spanIdxs.push(spanIdx); spanMasks.push(spanMask); }); return { spanIdxs, spanMasks }; } prepareBatch(texts, entities) { const [batchTokens, batchWordsStartIdx, batchWordsEndIdx] = this.batchTokenizeText(texts); const { idToClass } = this.createMappings(entities); const [inputTokens, textLengths, promptLengths] = this.prepareTextInputs(batchTokens, entities); let [inputsIds, attentionMasks, wordsMasks] = this.encodeInputs(inputTokens, promptLengths); inputsIds = this.padArray(inputsIds); attentionMasks = this.padArray(attentionMasks); wordsMasks = this.padArray(wordsMasks); let { spanIdxs, spanMasks } = this.prepareSpans(batchTokens, this.config["max_width"]); spanIdxs = this.padArray(spanIdxs, 3); spanMasks = this.padArray(spanMasks); return { inputsIds, attentionMasks, wordsMasks, textLengths, spanIdxs, spanMasks, idToClass, batchTokens, batchWordsStartIdx, batchWordsEndIdx }; } }; TokenProcessor = class extends Processor2 { constructor(config, tokenizer, wordsSplitter) { super(config, tokenizer, wordsSplitter); } prepareBatch(texts, entities) { const [batchTokens, batchWordsStartIdx, batchWordsEndIdx] = this.batchTokenizeText(texts); const { idToClass } = this.createMappings(entities); const [inputTokens, textLengths, promptLengths] = this.prepareTextInputs(batchTokens, entities); let [inputsIds, attentionMasks, wordsMasks] = this.encodeInputs(inputTokens, promptLengths); inputsIds = this.padArray(inputsIds); attentionMasks = this.padArray(attentionMasks); wordsMasks = this.padArray(wordsMasks); return { inputsIds, attentionMasks, wordsMasks, textLengths, idToClass, batchTokens, batchWordsStartIdx, batchWordsEndIdx }; } }; isNested = (idx1, idx2) => { return idx1[0] <= idx2[0] && idx1[1] >= idx2[1] || idx2[0] <= idx1[0] && idx2[1] >= idx1[1]; }; hasOverlapping = (idx1, idx2, multiLabel = false) => { if (idx1.slice(0, 2).toString() === idx2.slice(0, 2).toString()) { return !multiLabel; } if (idx1[0] > idx2[1] || idx2[0] > idx1[1]) { return false; } return true; }; hasOverlappingNested = (idx1, idx2, multiLabel = false) => { if (idx1.slice(0, 2).toString() === idx2.slice(0, 2).toString()) { return !multiLabel; } if (idx1[0] > idx2[1] || idx2[0] > idx1[1] || isNested(idx1, idx2)) { return false; } return true; }; sigmoid = (x2) => { return 1 / (1 + Math.exp(-x2)); }; BaseDecoder = class _BaseDecoder { constructor(config) { __publicField(this, "config"); if (new.target === _BaseDecoder) { throw new TypeError("Cannot instantiate an abstract class."); } this.config = config; } greedySearch(spans, flatNer = true, multiLabel = false) { const hasOv = flatNer ? (idx1, idx2) => hasOverlapping(idx1, idx2, multiLabel) : (idx1, idx2) => hasOverlappingNested(idx1, idx2, multiLabel); const newList = []; const spanProb = spans.slice().sort((a, b) => b[b.length - 1] - a[a.length - 1]); for (let i = 0; i < spanProb.length; i++) { const b = spanProb[i]; let flag = false; for (const newSpan of newList) { if (hasOv(b.slice(1, 3), newSpan.slice(1, 3))) { flag = true; break; } } if (!flag) { newList.push(b); } } return newList.sort((a, b) => a[1] - b[1]); } }; SpanDecoder = class extends BaseDecoder { decode(batchSize, inputLength, maxWidth, numEntities, texts, batchIds, batchWordsStartIdx, batchWordsEndIdx, idToClass, modelOutput, flatNer = false, threshold = 0.5, multiLabel = false) { const spans = []; for (let batch = 0; batch < batchSize; batch++) { spans.push([]); } const batchPadding = inputLength * maxWidth * numEntities; const startTokenPadding = maxWidth * numEntities; const endTokenPadding = numEntities * 1; modelOutput.forEach((value, id4) => { let batch = Math.floor(id4 / batchPadding); let startToken = Math.floor(id4 / startTokenPadding) % inputLength; let endToken = startToken + Math.floor(id4 / endTokenPadding) % maxWidth; let entity = id4 % numEntities; let prob = sigmoid(value); if (prob >= threshold && startToken < batchWordsStartIdx[batch].length && endToken < batchWordsEndIdx[batch].length) { let globalBatch = batchIds[batch]; let startIdx = batchWordsStartIdx[batch][startToken]; let endIdx = batchWordsEndIdx[batch][endToken]; let spanText = texts[globalBatch].slice(startIdx, endIdx); spans[batch].push([spanText, startIdx, endIdx, idToClass[entity + 1], prob]); } }); const allSelectedSpans = []; spans.forEach((resI, id4) => { const selectedSpans = this.greedySearch(resI, flatNer, multiLabel); allSelectedSpans.push(selectedSpans); }); return allSelectedSpans; } }; TokenDecoder = class extends BaseDecoder { decode(batchSize, inputLength, numEntities, texts, batchIds, batchWordsStartIdx, batchWordsEndIdx, idToClass, modelOutput, flatNer = false, threshold = 0.5, multiLabel = false) { const positionPadding = batchSize * inputLength * numEntities; const batchPadding = inputLength * numEntities; const tokenPadding = numEntities; let selectedStarts = []; let selectedEnds = []; let insideScore = []; for (let id4 = 0; id4 < batchSize; id4++) { selectedStarts.push([]); selectedEnds.push([]); let batches = []; for (let j3 = 0; j3 < inputLength; j3++) { let sequence = Array(numEntities).fill(0); batches.push(sequence); } insideScore.push(batches); } modelOutput.forEach((value, id4) => { let position = Math.floor(id4 / positionPadding); let batch = Math.floor(id4 / batchPadding) % batchSize; let token = Math.floor(id4 / tokenPadding) % inputLength; let entity = id4 % numEntities; let prob = sigmoid(value); if (prob >= threshold && token < batchWordsEndIdx[batch].length) { if (position == 0) { selectedStarts[batch].push([token, entity]); } else if (position == 1) { selectedEnds[batch].push([token, entity]); } } if (position == 2) { insideScore[batch][token][entity] = prob; } }); const spans = []; for (let batch = 0; batch < batchSize; batch++) { let batchSpans = []; for (let [start, clsSt] of selectedStarts[batch]) { for (let [end, clsEd] of selectedEnds[batch]) { if (end >= start && clsSt === clsEd) { const insideSpanScores = insideScore[batch].slice(start, end + 1).map((tokenScores) => tokenScores[clsSt]); if (insideSpanScores.some((score) => score < threshold)) continue; const spanScore = insideSpanScores.reduce((a, b) => a + b, 0) / insideSpanScores.length; let startIdx = batchWordsStartIdx[batch][start]; let endIdx = batchWordsEndIdx[batch][end]; let spanText = texts[batchIds[batch]].slice(startIdx, endIdx); batchSpans.push([spanText, startIdx, endIdx, idToClass[clsSt + 1], spanScore]); } } } spans.push(batchSpans); } const allSelectedSpans = []; spans.forEach((resI, id4) => { const selectedSpans = this.greedySearch(resI, flatNer, multiLabel); allSelectedSpans.push(selectedSpans); }); return allSelectedSpans; } }; ONNX_WASM_CDN_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/"; DEFAULT_WASM_PATHS = ONNX_WASM_CDN_URL; ONNXWebWrapper = class { constructor(settings) { this.settings = settings; __publicField(this, "ort", bO); __publicField(this, "session", null); const { executionProvider, wasmPaths = DEFAULT_WASM_PATHS } = settings; if (!executionProvider) { this.settings.executionProvider = "webgpu"; } switch (this.settings.executionProvider) { case "cpu": case "wasm": break; case "webgpu": this.ort = K_; break; case "webgl": this.ort = zv; break; default: throw new Error(`ONNXWrapper: Invalid execution provider: '${executionProvider}'`); } this.ort.env.wasm.wasmPaths = wasmPaths; } async init() { if (!this.session) { const { modelPath, executionProvider, fetchBinary, multiThread } = this.settings; if (executionProvider === "cpu" || executionProvider === "wasm") { if (fetchBinary) { const binaryURL = this.ort.env.wasm.wasmPaths + "ort-wasm-simd-threaded.wasm"; const response = await fetch(binaryURL); const binary = await response.arrayBuffer(); this.ort.env.wasm.wasmBinary = binary; } if (multiThread) { const maxPossibleThreads = navigator.hardwareConcurrency ?? 0; const maxThreads = Math.min( this.settings.maxThreads ?? maxPossibleThreads, maxPossibleThreads ); this.ort.env.wasm.numThreads = maxThreads; } } this.session = await this.ort.InferenceSession.create(modelPath, { executionProviders: [executionProvider] }); } } async run(feeds, options = {}) { if (!this.session) { throw new Error("ONNXWrapper: Session not initialized. Please call init() first."); } return await this.session.run(feeds, options); } }; Gliner = class { constructor(config) { this.config = config; __publicField(this, "model", null); env.allowLocalModels = config.transformersSettings?.allowLocalModels ?? false; env.useBrowserCache = config.transformersSettings?.useBrowserCache ?? false; this.config = { ...config, maxWidth: config.maxWidth || 12, modelType: config.modelType || "span-level" }; } async initialize() { const { tokenizerPath, onnxSettings, maxWidth } = this.config; const tokenizer = await AutoTokenizer.from_pretrained(tokenizerPath); const wordSplitter = new WhitespaceTokenSplitter(); const onnxWrapper = new ONNXWebWrapper(onnxSettings); if (this.config.modelType == "span-level") { const processor = new SpanProcessor({ max_width: maxWidth }, tokenizer, wordSplitter); const decoder = new SpanDecoder({ max_width: maxWidth }); this.model = new SpanModel({ max_width: maxWidth }, processor, decoder, onnxWrapper); } else { const processor = new TokenProcessor({ max_width: maxWidth }, tokenizer, wordSplitter); const decoder = new TokenDecoder({ max_width: maxWidth }); this.model = new TokenModel({ max_width: maxWidth }, processor, decoder, onnxWrapper); } await this.model.initialize(); } async inference({ texts, entities, flatNer = true, threshold = 0.5, multiLabel = false }) { if (!this.model) { throw new Error("Model is not initialized. Call initialize() first."); } const result = await this.model.inference(texts, entities, flatNer, threshold, multiLabel); return this.mapRawResultToResponse(result); } async inference_with_chunking({ texts, entities, flatNer = false, threshold = 0.5 }) { if (!this.model) { throw new Error("Model is not initialized. Call initialize() first."); } const result = await this.model.inference_with_chunking(texts, entities, flatNer, threshold); return this.mapRawResultToResponse(result); } mapRawResultToResponse(rawResult) { const response = []; for (const individualResult of rawResult) { const entityResult = individualResult.map( ([spanText, start, end, label, score]) => ({ spanText, start, end, label, score }) ); response.push(entityResult); } return response; } }; } }); // app.js var require_app = __commonJS({ "app.js"() { init_dist2(); var $2 = (id4) => document.getElementById(id4); var input = $2("input"); var classifyBtn = $2("classify"); var clearBtn = $2("clear"); var status = $2("status"); var results = $2("results"); var hits = $2("hits"); var highlightBox = $2("highlight"); var progressTrack = $2("progressTrack"); var progressBar = $2("progressBar"); var ALL_LABELS = [ "person", "organization", "company", "phone number", "mobile phone number", "email", "address", "postal address", "IP address", "SSN", "social security number", "credit card number", "passport number", "IBAN", "bank account number", "driver's license number", "national id number", "tax identification number", "username", "date of birth", "medical condition", "medication", "cvv", "blood type", "license plate number" ]; var DEFAULT_LABELS = [ "person", "organization", "company", "phone number", "email", "address", "IP address", "SSN", "credit card number", "passport number", "IBAN", "username", "date of birth" ]; var EXAMPLES = [ { name: "Person & contact info (EN)", text: "Contact John Smith at john.smith@example.com or call +1-202-555-0147. His SSN is 123-45-6789 and his credit card is 4111-1111-1111-1111." }, { name: "Model card example (FR)", text: "Harilala Rasoanaivo, un homme d'affaires local d'Antananarivo, a enregistr\xE9 une nouvelle soci\xE9t\xE9 nomm\xE9e Rasoanaivo Enterprises au Lot II M 92 Antohomadinika. Son num\xE9ro est le +261 32 22 345 67, et son adresse \xE9lectronique est harilala.rasoanaivo@telma.mg. Il a fourni son num\xE9ro de s\xE9cu 501-02-1234 pour l'enregistrement." }, { name: "No PII (clean)", text: "The weather is nice today and I'm looking forward to our meeting at noon." } ]; var COLORS = [ "#ef4444", "#f97316", "#f59e0b", "#84cc16", "#22c55e", "#14b8a6", "#06b6d4", "#3b82f6", "#6366f1", "#8b5cf6", "#a855f7", "#d946ef", "#ec4899", "#f43f5e" ]; var LABEL_COLOR = /* @__PURE__ */ new Map(); ALL_LABELS.forEach((l, i) => LABEL_COLOR.set(l, COLORS[i % COLORS.length])); var gliner = null; var threshold = $2("threshold"); var thrVal = $2("thrVal"); threshold.addEventListener("input", () => { thrVal.textContent = parseFloat(threshold.value).toFixed(2); }); async function init() { try { status.textContent = "Downloading model weights (665 MB on first load, then cached by browser)\u2026"; progressTrack.style.display = "block"; progressBar.style.width = "5%"; gliner = new Gliner({ tokenizerPath: "rpeel/glitext-pii-edge", onnxSettings: { modelPath: "https://huggingface.co/rpeel/glitext-pii-edge/resolve/main/model.onnx", executionProvider: "wasm", multiThread: false, wasmPaths: "./onnx/", fetchBinary: true }, transformersSettings: { allowLocalModels: false, useBrowserCache: true }, modelType: "span-level", maxWidth: 12 }); await gliner.initialize(); progressTrack.style.display = "none"; classifyBtn.disabled = false; classifyBtn.textContent = "Find PII"; status.textContent = "Model ready. Paste text and click Find PII."; } catch (err) { progressTrack.style.display = "none"; status.textContent = "Failed to load model: " + err.message; classifyBtn.textContent = "Retry"; classifyBtn.onclick = () => location.reload(); } } function buildLabelCheckboxes() { const box = $2("labels"); ALL_LABELS.forEach((l) => { const labelEl = document.createElement("label"); labelEl.className = "lbl-check"; const cb2 = document.createElement("input"); cb2.type = "checkbox"; cb2.value = l; cb2.checked = DEFAULT_LABELS.includes(l); const swatch = document.createElement("span"); swatch.className = "swatch"; swatch.style.background = LABEL_COLOR.get(l); labelEl.append(cb2, swatch, document.createTextNode(l)); box.appendChild(labelEl); }); } function selectedLabels() { return [...document.querySelectorAll("#labels input:checked")].map((c) => c.value); } async function classify() { const text = input.value.trim(); if (!text) { status.textContent = "Enter some text first."; return; } const labels = selectedLabels(); if (!labels.length) { status.textContent = "Select at least one label type."; return; } if (!gliner) { status.textContent = "Model is still loading\u2026"; return; } classifyBtn.disabled = true; classifyBtn.textContent = "Analyzing\u2026"; results.style.display = "block"; hits.innerHTML = ""; highlightBox.innerHTML = ""; try { const out = await gliner.inference({ texts: [text], entities: labels, threshold: parseFloat(threshold.value), flatNer: true, multiLabel: true }); const ents = out && out[0] || []; render(ents, text); } catch (err) { status.textContent = "Inference failed: " + err.message; } finally { classifyBtn.disabled = false; classifyBtn.textContent = "Find PII"; } } function esc(s) { return s.replace(/&/g, "&").replace(//g, ">"); } function render(ents, text) { const labelSet = new Set(ents.map((e) => e.label)); if (!ents.length) { hits.innerHTML = '
No PII found at the current threshold.
'; } ents.forEach((e) => { const row = document.createElement("div"); row.className = "hit"; const textSpan = document.createElement("code"); textSpan.textContent = e.spanText; const lbl = document.createElement("span"); lbl.className = "badge"; lbl.style.background = LABEL_COLOR.get(e.label) || "#64748b"; lbl.textContent = e.label; const sc3 = document.createElement("span"); sc3.className = "score"; sc3.textContent = (e.score * 100).toFixed(1) + "%"; row.append(textSpan, lbl, sc3); hits.appendChild(row); }); const sorted = [...ents].sort((a, b) => a.start - b.start); let html = ""; let pos = 0; for (const e of sorted) { if (e.start < pos) continue; html += esc(text.slice(pos, e.start)); html += `${esc(e.spanText)}`; pos = e.end; } html += esc(text.slice(pos)); highlightBox.innerHTML = html; highlightBox.style.display = "block"; status.textContent = `Found ${ents.length} entity span${ents.length === 1 ? "" : "s"} across ${labelSet.size} label type${labelSet.size === 1 ? "" : "s"}.`; } clearBtn.addEventListener("click", () => { input.value = ""; results.style.display = "none"; highlightBox.style.display = "none"; status.textContent = ""; }); classifyBtn.addEventListener("click", classify); input.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "Enter") classify(); }); var exBox = $2("examples"); EXAMPLES.forEach((ex) => { const b = document.createElement("button"); b.className = "chip"; b.textContent = ex.name; b.addEventListener("click", () => { input.value = ex.text; classify(); }); exBox.appendChild(b); }); buildLabelCheckboxes(); init(); } }); export default require_app(); /*! Bundled license information: onnxruntime-common/dist/ort-common.node.js: (*! * ONNX Runtime Common v1.14.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. *) onnxruntime-web/dist/ort-web.min.js: (*! * ONNX Runtime Web v1.14.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. *) onnxruntime-web/dist/ort.bundle.min.mjs: onnxruntime-web/dist/ort.webgl.min.mjs: (*! * ONNX Runtime Web v1.19.2 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. *) (*! Bundled license information: long/index.js: (** * @license * Copyright 2009 The Closure Library Authors * Copyright 2020 Daniel Wirtz / The long.js Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 *) *) onnxruntime-web/dist/ort.webgpu.bundle.min.mjs: (*! * ONNX Runtime Web v1.19.2 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. *) (** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *) (** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *) (** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *) */