var Xm = { /***/ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm": ( /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm ***! \****************************************************************************/ /***/ (Ie, $, r) => { Ie.exports = r.p + "ort-wasm-simd-threaded.jsep.wasm"; } ), /***/ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb": ( /*!**************************************************************!*\ !*** ./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs ***! \**************************************************************/ /***/ (Ie, $, r) => { Ie.exports = r.p + "ort.bundle.min.mjs"; } ), /***/ "?2ce3": ( /*!**********************************!*\ !*** onnxruntime-node (ignored) ***! \**********************************/ /***/ () => { } ), /***/ "?7a2c": ( /*!********************!*\ !*** fs (ignored) ***! \********************/ /***/ () => { } ), /***/ "?a42a": ( /*!**********************!*\ !*** path (ignored) ***! \**********************/ /***/ () => { } ), /***/ "?2b25": ( /*!***********************!*\ !*** sharp (ignored) ***! \***********************/ /***/ () => { } ), /***/ "?569f": ( /*!********************!*\ !*** fs (ignored) ***! \********************/ /***/ () => { } ), /***/ "?3f59": ( /*!**********************!*\ !*** path (ignored) ***! \**********************/ /***/ () => { } ), /***/ "?154a": ( /*!*********************!*\ !*** url (ignored) ***! \*********************/ /***/ () => { } ), /***/ "./node_modules/@huggingface/jinja/dist/index.js": ( /*!*******************************************************!*\ !*** ./node_modules/@huggingface/jinja/dist/index.js ***! \*******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Environment: () => ( /* binding */ Ze ), /* harmony export */ Interpreter: () => ( /* binding */ at ), /* harmony export */ Template: () => ( /* binding */ ct ), /* harmony export */ parse: () => ( /* binding */ we ), /* harmony export */ tokenize: () => ( /* binding */ b ) /* harmony export */ }); var g = Object.freeze({ Text: "Text", // The text between Jinja statements or expressions NumericLiteral: "NumericLiteral", // e.g., 123 BooleanLiteral: "BooleanLiteral", // true or false NullLiteral: "NullLiteral", // none 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", Macro: "Macro", EndMacro: "EndMacro" }), O = Object.freeze({ set: g.Set, for: g.For, in: g.In, is: g.Is, if: g.If, else: g.Else, endif: g.EndIf, elif: g.ElseIf, endfor: g.EndFor, and: g.And, or: g.Or, not: g.Not, "not in": g.NotIn, macro: g.Macro, endmacro: g.EndMacro, // Literals true: g.BooleanLiteral, false: g.BooleanLiteral, none: g.NullLiteral, // NOTE: According to the Jinja docs: The special constants true, false, and none are indeed lowercase. // Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false), // all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase) // you should use the lowercase versions. True: g.BooleanLiteral, False: g.BooleanLiteral, None: g.NullLiteral }), j = 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(F, ae) { this.value = F, this.type = ae; } }; function ee(F) { return /\w/.test(F); } function N(F) { return /[0-9]/.test(F); } var y = [ // Control sequences ["{%", g.OpenStatement], ["%}", g.CloseStatement], ["{{", g.OpenExpression], ["}}", g.CloseExpression], // Single character tokens ["(", g.OpenParen], [")", g.CloseParen], ["{", g.OpenCurlyBracket], ["}", g.CloseCurlyBracket], ["[", g.OpenSquareBracket], ["]", g.CloseSquareBracket], [",", g.Comma], [".", g.Dot], [":", g.Colon], ["|", g.Pipe], // Comparison operators ["<=", g.ComparisonBinaryOperator], [">=", g.ComparisonBinaryOperator], ["==", g.ComparisonBinaryOperator], ["!=", g.ComparisonBinaryOperator], ["<", g.ComparisonBinaryOperator], [">", g.ComparisonBinaryOperator], // Arithmetic operators ["+", g.AdditiveBinaryOperator], ["-", g.AdditiveBinaryOperator], ["*", g.MultiplicativeBinaryOperator], ["/", g.MultiplicativeBinaryOperator], ["%", g.MultiplicativeBinaryOperator], // Assignment operator ["=", g.Equals] ], T = /* @__PURE__ */ new Map([ ["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 ]); function v(F, ae = {}) { return F.endsWith(` `) && (F = F.slice(0, -1)), F = F.replace(/{#.*?#}/gs, "{##}"), ae.lstrip_blocks && (F = F.replace(/^[ \t]*({[#%])/gm, "$1")), ae.trim_blocks && (F = F.replace(/([#%]})\n/g, "$1")), F.replace(/{##}/g, "").replace(/-%}\s*/g, "%}").replace(/\s*{%-/g, "{%").replace(/-}}\s*/g, "}}").replace(/\s*{{-/g, "{{"); } function b(F, ae = {}) { const H = [], me = v(F, ae); let ke = 0; const ze = (Ge) => { let tt = ""; for (; Ge(me[ke]); ) { if (me[ke] === "\\") { if (++ke, ke >= me.length) throw new SyntaxError("Unexpected end of input"); const et = me[ke++], mt = T.get(et); if (mt === void 0) throw new SyntaxError(`Unexpected escaped character: ${et}`); tt += mt; continue; } if (tt += me[ke++], ke >= me.length) throw new SyntaxError("Unexpected end of input"); } return tt; }; e: for (; ke < me.length; ) { const Ge = H.at(-1)?.type; if (Ge === void 0 || Ge === g.CloseStatement || Ge === g.CloseExpression) { let et = ""; for (; ke < me.length && // Keep going until we hit the next Jinja statement or expression !(me[ke] === "{" && (me[ke + 1] === "%" || me[ke + 1] === "{")); ) et += me[ke++]; if (et.length > 0) { H.push(new j(et, g.Text)); continue; } } ze((et) => /\s/.test(et)); const tt = me[ke]; if (tt === "-" || tt === "+") { const et = H.at(-1)?.type; if (et === g.Text || et === void 0) throw new SyntaxError(`Unexpected character: ${tt}`); switch (et) { case g.Identifier: case g.NumericLiteral: case g.BooleanLiteral: case g.NullLiteral: case g.StringLiteral: case g.CloseParen: case g.CloseSquareBracket: break; default: { ++ke; const mt = ze(N); H.push( new j(`${tt}${mt}`, mt.length > 0 ? g.NumericLiteral : g.UnaryOperator) ); continue; } } } for (const [et, mt] of y) if (me.slice(ke, ke + et.length) === et) { H.push(new j(et, mt)), ke += et.length; continue e; } if (tt === "'" || tt === '"') { ++ke; const et = ze((mt) => mt !== tt); H.push(new j(et, g.StringLiteral)), ++ke; continue; } if (N(tt)) { const et = ze(N); H.push(new j(et, g.NumericLiteral)); continue; } if (ee(tt)) { const et = ze(ee), mt = Object.hasOwn(O, et) ? O[et] : g.Identifier; mt === g.In && H.at(-1)?.type === g.Not ? (H.pop(), H.push(new j("not in", g.NotIn))) : H.push(new j(et, mt)); continue; } throw new SyntaxError(`Unexpected character: ${tt}`); } return H; } var x = class { type = "Statement"; }, L = class extends x { constructor(F) { super(), this.body = F; } type = "Program"; }, K = class extends x { constructor(F, ae, H) { super(), this.test = F, this.body = ae, this.alternate = H; } type = "If"; }, re = class extends x { constructor(F, ae, H, me) { super(), this.loopvar = F, this.iterable = ae, this.body = H, this.defaultBlock = me; } type = "For"; }, ie = class extends x { constructor(F, ae) { super(), this.assignee = F, this.value = ae; } type = "Set"; }, V = class extends x { constructor(F, ae, H) { super(), this.name = F, this.args = ae, this.body = H; } type = "Macro"; }, U = class extends x { type = "Expression"; }, q = class extends U { constructor(F, ae, H) { super(), this.object = F, this.property = ae, this.computed = H; } type = "MemberExpression"; }, A = class extends U { constructor(F, ae) { super(), this.callee = F, this.args = ae; } type = "CallExpression"; }, S = class extends U { /** * @param {string} value The name of the identifier */ constructor(F) { super(), this.value = F; } type = "Identifier"; }, w = class extends U { constructor(F) { super(), this.value = F; } type = "Literal"; }, P = class extends w { type = "NumericLiteral"; }, I = class extends w { type = "StringLiteral"; }, le = class extends w { type = "BooleanLiteral"; }, oe = class extends w { type = "NullLiteral"; }, ye = class extends w { type = "ArrayLiteral"; }, ge = class extends w { type = "TupleLiteral"; }, se = class extends w { type = "ObjectLiteral"; }, be = class extends U { constructor(F, ae, H) { super(), this.operator = F, this.left = ae, this.right = H; } type = "BinaryExpression"; }, pe = class extends U { constructor(F, ae) { super(), this.operand = F, this.filter = ae; } type = "FilterExpression"; }, Ce = class extends U { constructor(F, ae) { super(), this.iterable = F, this.test = ae; } type = "SelectExpression"; }, $e = class extends U { constructor(F, ae, H) { super(), this.operand = F, this.negate = ae, this.test = H; } type = "TestExpression"; }, Pe = class extends U { constructor(F, ae) { super(), this.operator = F, this.argument = ae; } type = "UnaryExpression"; }, Je = class extends U { constructor(F = void 0, ae = void 0, H = void 0) { super(), this.start = F, this.stop = ae, this.step = H; } type = "SliceExpression"; }, Ue = class extends U { constructor(F, ae) { super(), this.key = F, this.value = ae; } type = "KeywordArgumentExpression"; }; function we(F) { const ae = new L([]); let H = 0; function me(nt, vt) { const Ft = F[H++]; if (!Ft || Ft.type !== nt) throw new Error(`Parser Error: ${vt}. ${Ft.type} !== ${nt}.`); return Ft; } function ke() { switch (F[H].type) { case g.Text: return tt(); case g.OpenStatement: return et(); case g.OpenExpression: return mt(); default: throw new SyntaxError(`Unexpected token type: ${F[H].type}`); } } function ze(...nt) { return H + nt.length <= F.length && nt.some((vt, Ft) => vt !== F[H + Ft].type); } function Ge(...nt) { return H + nt.length <= F.length && nt.every((vt, Ft) => vt === F[H + Ft].type); } function tt() { return new I(me(g.Text, "Expected text token").value); } function et() { me(g.OpenStatement, "Expected opening statement token"); let nt; switch (F[H].type) { case g.Set: ++H, nt = Nt(), me(g.CloseStatement, "Expected closing statement token"); break; case g.If: ++H, nt = es(), me(g.OpenStatement, "Expected {% token"), me(g.EndIf, "Expected endif token"), me(g.CloseStatement, "Expected %} token"); break; case g.Macro: ++H, nt = Ts(), me(g.OpenStatement, "Expected {% token"), me(g.EndMacro, "Expected endmacro token"), me(g.CloseStatement, "Expected %} token"); break; case g.For: ++H, nt = Ps(), me(g.OpenStatement, "Expected {% token"), me(g.EndFor, "Expected endfor token"), me(g.CloseStatement, "Expected %} token"); break; default: throw new SyntaxError(`Unknown statement type: ${F[H].type}`); } return nt; } function mt() { me(g.OpenExpression, "Expected opening expression token"); const nt = Is(); return me(g.CloseExpression, "Expected closing expression token"), nt; } function Nt() { const nt = Is(); if (Ge(g.Equals)) { ++H; const vt = Nt(); return new ie(nt, vt); } return nt; } function es() { const nt = Is(); me(g.CloseStatement, "Expected closing statement token"); const vt = [], Ft = []; for (; !(F[H]?.type === g.OpenStatement && (F[H + 1]?.type === g.ElseIf || F[H + 1]?.type === g.Else || F[H + 1]?.type === g.EndIf)); ) vt.push(ke()); if (F[H]?.type === g.OpenStatement && F[H + 1]?.type !== g.EndIf) if (++H, Ge(g.ElseIf)) me(g.ElseIf, "Expected elseif token"), Ft.push(es()); else for (me(g.Else, "Expected else token"), me(g.CloseStatement, "Expected closing statement token"); !(F[H]?.type === g.OpenStatement && F[H + 1]?.type === g.EndIf); ) Ft.push(ke()); return new K(nt, vt, Ft); } function Ts() { const nt = ir(); if (nt.type !== "Identifier") throw new SyntaxError("Expected identifier following macro statement"); const vt = Pr(); me(g.CloseStatement, "Expected closing statement token"); const Ft = []; for (; ze(g.OpenStatement, g.EndMacro); ) Ft.push(ke()); return new V(nt, vt, Ft); } function ms(nt = !1) { const vt = nt ? ir : Is, Ft = [vt()], Zs = Ge(g.Comma); for (; Zs && (++H, Ft.push(vt()), !!Ge(g.Comma)); ) ; return Zs ? new ge(Ft) : Ft[0]; } function Ps() { const nt = ms(!0); if (!(nt instanceof S || nt instanceof ge)) throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${nt.type} instead`); me(g.In, "Expected `in` keyword following loop variable"); const vt = Is(); me(g.CloseStatement, "Expected closing statement token"); const Ft = []; for (; ze(g.OpenStatement, g.EndFor) && ze(g.OpenStatement, g.Else); ) Ft.push(ke()); const Zs = []; if (Ge(g.OpenStatement, g.Else)) for (++H, ++H, me(g.CloseStatement, "Expected closing statement token"); ze(g.OpenStatement, g.EndFor); ) Zs.push(ke()); return new re(nt, vt, Ft, Zs); } function Is() { return tr(); } function tr() { const nt = xr(); if (Ge(g.If)) { ++H; const vt = xr(); if (Ge(g.Else)) { ++H; const Ft = xr(); return new K(vt, [nt], [Ft]); } else return new Ce(nt, vt); } return nt; } function xr() { let nt = Gr(); for (; Ge(g.Or); ) { const vt = F[H]; ++H; const Ft = Gr(); nt = new be(vt, nt, Ft); } return nt; } function Gr() { let nt = Vs(); for (; Ge(g.And); ) { const vt = F[H]; ++H; const Ft = Vs(); nt = new be(vt, nt, Ft); } return nt; } function Vs() { let nt; for (; Ge(g.Not); ) { const vt = F[H]; ++H; const Ft = Vs(); nt = new Pe(vt, Ft); } return nt ?? yr(); } function yr() { let nt = Lt(); for (; Ge(g.ComparisonBinaryOperator) || Ge(g.In) || Ge(g.NotIn); ) { const vt = F[H]; ++H; const Ft = Lt(); nt = new be(vt, nt, Ft); } return nt; } function Lt() { let nt = Er(); for (; Ge(g.AdditiveBinaryOperator); ) { const vt = F[H]; ++H; const Ft = Er(); nt = new be(vt, nt, Ft); } return nt; } function Kr() { const nt = Fr(ir()); return Ge(g.OpenParen) ? Tr(nt) : nt; } function Tr(nt) { let vt = new A(nt, Pr()); return vt = Fr(vt), Ge(g.OpenParen) && (vt = Tr(vt)), vt; } function Pr() { me(g.OpenParen, "Expected opening parenthesis for arguments list"); const nt = Hr(); return me(g.CloseParen, "Expected closing parenthesis for arguments list"), nt; } function Hr() { const nt = []; for (; !Ge(g.CloseParen); ) { let vt = Is(); if (Ge(g.Equals)) { if (++H, !(vt instanceof S)) throw new SyntaxError("Expected identifier for keyword argument"); const Ft = Is(); vt = new Ue(vt, Ft); } nt.push(vt), Ge(g.Comma) && ++H; } return nt; } function lr() { const nt = []; let vt = !1; for (; !Ge(g.CloseSquareBracket); ) Ge(g.Colon) ? (nt.push(void 0), ++H, vt = !0) : (nt.push(Is()), Ge(g.Colon) && (++H, vt = !0)); if (nt.length === 0) throw new SyntaxError("Expected at least one argument for member/slice expression"); if (vt) { if (nt.length > 3) throw new SyntaxError("Expected 0-3 arguments for slice expression"); return new Je(...nt); } return nt[0]; } function Fr(nt) { for (; Ge(g.Dot) || Ge(g.OpenSquareBracket); ) { const vt = F[H]; ++H; let Ft; const Zs = vt.type !== g.Dot; if (Zs) Ft = lr(), me(g.CloseSquareBracket, "Expected closing square bracket"); else if (Ft = ir(), Ft.type !== "Identifier") throw new SyntaxError("Expected identifier following dot operator"); nt = new q(nt, Ft, Zs); } return nt; } function Er() { let nt = Or(); for (; Ge(g.MultiplicativeBinaryOperator); ) { const vt = F[H]; ++H; const Ft = Or(); nt = new be(vt, nt, Ft); } return nt; } function Or() { let nt = Dr(); for (; Ge(g.Is); ) { ++H; const vt = Ge(g.Not); vt && ++H; let Ft = ir(); if (Ft instanceof le ? Ft = new S(Ft.value.toString()) : Ft instanceof oe && (Ft = new S("none")), !(Ft instanceof S)) throw new SyntaxError("Expected identifier for the test"); nt = new $e(nt, vt, Ft); } return nt; } function Dr() { let nt = Kr(); for (; Ge(g.Pipe); ) { ++H; let vt = ir(); if (!(vt instanceof S)) throw new SyntaxError("Expected identifier for the filter"); Ge(g.OpenParen) && (vt = Tr(vt)), nt = new pe(nt, vt); } return nt; } function ir() { const nt = F[H]; switch (nt.type) { case g.NumericLiteral: return ++H, new P(Number(nt.value)); case g.StringLiteral: return ++H, new I(nt.value); case g.BooleanLiteral: return ++H, new le(nt.value.toLowerCase() === "true"); case g.NullLiteral: return ++H, new oe(null); case g.Identifier: return ++H, new S(nt.value); case g.OpenParen: { ++H; const vt = ms(); if (F[H].type !== g.CloseParen) throw new SyntaxError(`Expected closing parenthesis, got ${F[H].type} instead`); return ++H, vt; } case g.OpenSquareBracket: { ++H; const vt = []; for (; !Ge(g.CloseSquareBracket); ) vt.push(Is()), Ge(g.Comma) && ++H; return ++H, new ye(vt); } case g.OpenCurlyBracket: { ++H; const vt = /* @__PURE__ */ new Map(); for (; !Ge(g.CloseCurlyBracket); ) { const Ft = Is(); me(g.Colon, "Expected colon between key and value in object literal"); const Zs = Is(); vt.set(Ft, Zs), Ge(g.Comma) && ++H; } return ++H, new se(vt); } default: throw new SyntaxError(`Unexpected token: ${nt.type}`); } } for (; H < F.length; ) ae.body.push(ke()); return ae; } function X(F, ae, H = 1) { ae === void 0 && (ae = F, F = 0); const me = []; for (let ke = F; ke < ae; ke += H) me.push(ke); return me; } function de(F, ae, H, me = 1) { const ke = Math.sign(me); ke >= 0 ? (ae = (ae ??= 0) < 0 ? Math.max(F.length + ae, 0) : Math.min(ae, F.length), H = (H ??= F.length) < 0 ? Math.max(F.length + H, 0) : Math.min(H, F.length)) : (ae = (ae ??= F.length - 1) < 0 ? Math.max(F.length + ae, -1) : Math.min(ae, F.length - 1), H = (H ??= -1) < -1 ? Math.max(F.length + H, -1) : Math.min(H, F.length - 1)); const ze = []; for (let Ge = ae; ke * Ge < ke * H; Ge += me) ze.push(F[Ge]); return ze; } function Ee(F) { return F.replace(/\b\w/g, (ae) => ae.toUpperCase()); } var Oe = class { type = "RuntimeValue"; value; /** * A collection of built-in functions for this type. */ builtins = /* @__PURE__ */ new Map(); /** * Creates a new RuntimeValue. */ constructor(F = void 0) { this.value = F; } /** * 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 We(!!this.value); } }, Xe = class extends Oe { type = "NumericValue"; }, J = class extends Oe { type = "StringValue"; builtins = /* @__PURE__ */ new Map([ [ "upper", new je(() => new J(this.value.toUpperCase())) ], [ "lower", new je(() => new J(this.value.toLowerCase())) ], [ "strip", new je(() => new J(this.value.trim())) ], [ "title", new je(() => new J(Ee(this.value))) ], ["length", new Xe(this.value.length)], [ "rstrip", new je(() => new J(this.value.trimEnd())) ], [ "lstrip", new je(() => new J(this.value.trimStart())) ], [ "split", // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior // https://docs.python.org/3.13/library/stdtypes.html#str.split new je((F) => { const ae = F[0] ?? new Ve(); if (!(ae instanceof J || ae instanceof Ve)) throw new Error("sep argument must be a string or null"); const H = F[1] ?? new Xe(-1); if (!(H instanceof Xe)) throw new Error("maxsplit argument must be a number"); let me = []; if (ae instanceof Ve) { const ke = this.value.trimStart(); for (const { 0: ze, index: Ge } of ke.matchAll(/\S+/g)) { if (H.value !== -1 && me.length >= H.value && Ge !== void 0) { me.push(ze + ke.slice(Ge + ze.length)); break; } me.push(ze); } } else { if (ae.value === "") throw new Error("empty separator"); me = this.value.split(ae.value), H.value !== -1 && me.length > H.value && me.push(me.splice(H.value).join(ae.value)); } return new ve(me.map((ke) => new J(ke))); }) ] ]); }, We = class extends Oe { type = "BooleanValue"; }, Ne = class extends Oe { 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 We(this.value.size > 0); } builtins = /* @__PURE__ */ new Map([ [ "get", new je(([F, ae]) => { if (!(F instanceof J)) throw new Error(`Object key must be a string: got ${F.type}`); return this.value.get(F.value) ?? ae ?? new Ve(); }) ], [ "items", new je(() => new ve( Array.from(this.value.entries()).map(([F, ae]) => new ve([new J(F), ae])) )) ] ]); }, te = class extends Ne { type = "KeywordArgumentsValue"; }, ve = class extends Oe { type = "ArrayValue"; builtins = /* @__PURE__ */ new Map([["length", new Xe(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 We(this.value.length > 0); } }, He = class extends ve { type = "TupleValue"; }, je = class extends Oe { type = "FunctionValue"; }, Ve = class extends Oe { type = "NullValue"; }, Re = class extends Oe { type = "UndefinedValue"; }, Ze = class { constructor(F) { this.parent = F; } /** * The variables declared in this environment. */ variables = /* @__PURE__ */ new Map([ [ "namespace", new je((F) => { if (F.length === 0) return new Ne(/* @__PURE__ */ new Map()); if (F.length !== 1 || !(F[0] instanceof Ne)) throw new Error("`namespace` expects either zero arguments or a single object argument"); return F[0]; }) ] ]); /** * The tests available in this environment. */ tests = /* @__PURE__ */ new Map([ ["boolean", (F) => F.type === "BooleanValue"], ["callable", (F) => F instanceof je], [ "odd", (F) => { if (F.type !== "NumericValue") throw new Error(`Cannot apply test "odd" to type: ${F.type}`); return F.value % 2 !== 0; } ], [ "even", (F) => { if (F.type !== "NumericValue") throw new Error(`Cannot apply test "even" to type: ${F.type}`); return F.value % 2 === 0; } ], ["false", (F) => F.type === "BooleanValue" && !F.value], ["true", (F) => F.type === "BooleanValue" && F.value], ["none", (F) => F.type === "NullValue"], ["string", (F) => F.type === "StringValue"], ["number", (F) => F.type === "NumericValue"], ["integer", (F) => F.type === "NumericValue" && Number.isInteger(F.value)], ["iterable", (F) => F.type === "ArrayValue" || F.type === "StringValue"], ["mapping", (F) => F.type === "ObjectValue"], [ "lower", (F) => { const ae = F.value; return F.type === "StringValue" && ae === ae.toLowerCase(); } ], [ "upper", (F) => { const ae = F.value; return F.type === "StringValue" && ae === ae.toUpperCase(); } ], ["none", (F) => F.type === "NullValue"], ["defined", (F) => F.type !== "UndefinedValue"], ["undefined", (F) => F.type === "UndefinedValue"], ["equalto", (F, ae) => F.value === ae.value], ["eq", (F, ae) => F.value === ae.value] ]); /** * Set the value of a variable in the current environment. */ set(F, ae) { return this.declareVariable(F, _t(ae)); } declareVariable(F, ae) { if (this.variables.has(F)) throw new SyntaxError(`Variable already declared: ${F}`); return this.variables.set(F, ae), ae; } // 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(F, ae) { return this.variables.set(F, ae), ae; } /** * 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(F) { if (this.variables.has(F)) return this; if (this.parent) return this.parent.resolve(F); throw new Error(`Unknown variable: ${F}`); } lookupVariable(F) { try { return this.resolve(F).variables.get(F) ?? new Re(); } catch { return new Re(); } } }, at = class { global; constructor(F) { this.global = F ?? new Ze(); } /** * Run the program. */ run(F) { return this.evaluate(F, this.global); } /** * Evaluates expressions following the binary operation type. */ evaluateBinaryExpression(F, ae) { const H = this.evaluate(F.left, ae); switch (F.operator.value) { case "and": return H.__bool__().value ? this.evaluate(F.right, ae) : H; case "or": return H.__bool__().value ? H : this.evaluate(F.right, ae); } const me = this.evaluate(F.right, ae); switch (F.operator.value) { case "==": return new We(H.value == me.value); case "!=": return new We(H.value != me.value); } if (H instanceof Re || me instanceof Re) throw new Error("Cannot perform operation on undefined values"); if (H instanceof Ve || me instanceof Ve) throw new Error("Cannot perform operation on null values"); if (H instanceof Xe && me instanceof Xe) switch (F.operator.value) { case "+": return new Xe(H.value + me.value); case "-": return new Xe(H.value - me.value); case "*": return new Xe(H.value * me.value); case "/": return new Xe(H.value / me.value); case "%": return new Xe(H.value % me.value); case "<": return new We(H.value < me.value); case ">": return new We(H.value > me.value); case ">=": return new We(H.value >= me.value); case "<=": return new We(H.value <= me.value); } else if (H instanceof ve && me instanceof ve) switch (F.operator.value) { case "+": return new ve(H.value.concat(me.value)); } else if (me instanceof ve) { const ke = me.value.find((ze) => ze.value === H.value) !== void 0; switch (F.operator.value) { case "in": return new We(ke); case "not in": return new We(!ke); } } if (H instanceof J || me instanceof J) switch (F.operator.value) { case "+": return new J(H.value.toString() + me.value.toString()); } if (H instanceof J && me instanceof J) switch (F.operator.value) { case "in": return new We(me.value.includes(H.value)); case "not in": return new We(!me.value.includes(H.value)); } if (H instanceof J && me instanceof Ne) switch (F.operator.value) { case "in": return new We(me.value.has(H.value)); case "not in": return new We(!me.value.has(H.value)); } throw new SyntaxError(`Unknown operator "${F.operator.value}" between ${H.type} and ${me.type}`); } evaluateArguments(F, ae) { const H = [], me = /* @__PURE__ */ new Map(); for (const ke of F) if (ke.type === "KeywordArgumentExpression") { const ze = ke; me.set(ze.key.value, this.evaluate(ze.value, ae)); } else { if (me.size > 0) throw new Error("Positional arguments must come before keyword arguments"); H.push(this.evaluate(ke, ae)); } return [H, me]; } /** * Evaluates expressions following the filter operation type. */ evaluateFilterExpression(F, ae) { const H = this.evaluate(F.operand, ae); if (F.filter.type === "Identifier") { const me = F.filter; if (me.value === "tojson") return new J(lt(H)); if (H instanceof ve) switch (me.value) { case "list": return H; case "first": return H.value[0]; case "last": return H.value[H.value.length - 1]; case "length": return new Xe(H.value.length); case "reverse": return new ve(H.value.reverse()); case "sort": return new ve( H.value.sort((ke, ze) => { if (ke.type !== ze.type) throw new Error(`Cannot compare different types: ${ke.type} and ${ze.type}`); switch (ke.type) { case "NumericValue": return ke.value - ze.value; case "StringValue": return ke.value.localeCompare(ze.value); default: throw new Error(`Cannot compare type: ${ke.type}`); } }) ); case "join": return new J(H.value.map((ke) => ke.value).join("")); default: throw new Error(`Unknown ArrayValue filter: ${me.value}`); } else if (H instanceof J) switch (me.value) { case "length": return new Xe(H.value.length); case "upper": return new J(H.value.toUpperCase()); case "lower": return new J(H.value.toLowerCase()); case "title": return new J(Ee(H.value)); case "capitalize": return new J(H.value.charAt(0).toUpperCase() + H.value.slice(1)); case "trim": return new J(H.value.trim()); case "indent": return new J( H.value.split(` `).map( (ke, ze) => ( // By default, don't indent the first line or empty lines ze === 0 || ke.length === 0 ? ke : " " + ke ) ).join(` `) ); case "join": case "string": return H; default: throw new Error(`Unknown StringValue filter: ${me.value}`); } else if (H instanceof Xe) switch (me.value) { case "abs": return new Xe(Math.abs(H.value)); default: throw new Error(`Unknown NumericValue filter: ${me.value}`); } else if (H instanceof Ne) switch (me.value) { case "items": return new ve( Array.from(H.value.entries()).map(([ke, ze]) => new ve([new J(ke), ze])) ); case "length": return new Xe(H.value.size); default: throw new Error(`Unknown ObjectValue filter: ${me.value}`); } throw new Error(`Cannot apply filter "${me.value}" to type: ${H.type}`); } else if (F.filter.type === "CallExpression") { const me = F.filter; if (me.callee.type !== "Identifier") throw new Error(`Unknown filter: ${me.callee.type}`); const ke = me.callee.value; if (ke === "tojson") { const [, ze] = this.evaluateArguments(me.args, ae), Ge = ze.get("indent") ?? new Ve(); if (!(Ge instanceof Xe || Ge instanceof Ve)) throw new Error("If set, indent must be a number"); return new J(lt(H, Ge.value)); } else if (ke === "join") { let ze; if (H instanceof J) ze = Array.from(H.value); else if (H instanceof ve) ze = H.value.map((mt) => mt.value); else throw new Error(`Cannot apply filter "${ke}" to type: ${H.type}`); const [Ge, tt] = this.evaluateArguments(me.args, ae), et = Ge.at(0) ?? tt.get("separator") ?? new J(""); if (!(et instanceof J)) throw new Error("separator must be a string"); return new J(ze.join(et.value)); } if (H instanceof ve) { switch (ke) { case "selectattr": case "rejectattr": { const ze = ke === "selectattr"; if (H.value.some((es) => !(es instanceof Ne))) throw new Error(`\`${ke}\` can only be applied to array of objects`); if (me.args.some((es) => es.type !== "StringLiteral")) throw new Error(`arguments of \`${ke}\` must be strings`); const [Ge, tt, et] = me.args.map((es) => this.evaluate(es, ae)); let mt; if (tt) { const es = ae.tests.get(tt.value); if (!es) throw new Error(`Unknown test: ${tt.value}`); mt = es; } else mt = (...es) => es[0].__bool__().value; const Nt = H.value.filter((es) => { const Ts = es.value.get(Ge.value), ms = Ts ? mt(Ts, et) : !1; return ze ? ms : !ms; }); return new ve(Nt); } case "map": { const [, ze] = this.evaluateArguments(me.args, ae); if (ze.has("attribute")) { const Ge = ze.get("attribute"); if (!(Ge instanceof J)) throw new Error("attribute must be a string"); const tt = ze.get("default"), et = H.value.map((mt) => { if (!(mt instanceof Ne)) throw new Error("items in map must be an object"); return mt.value.get(Ge.value) ?? tt ?? new Re(); }); return new ve(et); } else throw new Error("`map` expressions without `attribute` set are not currently supported."); } } throw new Error(`Unknown ArrayValue filter: ${ke}`); } else if (H instanceof J) { switch (ke) { case "indent": { const [ze, Ge] = this.evaluateArguments(me.args, ae), tt = ze.at(0) ?? Ge.get("width") ?? new Xe(4); if (!(tt instanceof Xe)) throw new Error("width must be a number"); const et = ze.at(1) ?? Ge.get("first") ?? new We(!1), mt = ze.at(2) ?? Ge.get("blank") ?? new We(!1), Nt = H.value.split(` `), es = " ".repeat(tt.value), Ts = Nt.map( (ms, Ps) => !et.value && Ps === 0 || !mt.value && ms.length === 0 ? ms : es + ms ); return new J(Ts.join(` `)); } } throw new Error(`Unknown StringValue filter: ${ke}`); } else throw new Error(`Cannot apply filter "${ke}" to type: ${H.type}`); } throw new Error(`Unknown filter: ${F.filter.type}`); } /** * Evaluates expressions following the test operation type. */ evaluateTestExpression(F, ae) { const H = this.evaluate(F.operand, ae), me = ae.tests.get(F.test.value); if (!me) throw new Error(`Unknown test: ${F.test.value}`); const ke = me(H); return new We(F.negate ? !ke : ke); } /** * Evaluates expressions following the unary operation type. */ evaluateUnaryExpression(F, ae) { const H = this.evaluate(F.argument, ae); switch (F.operator.value) { case "not": return new We(!H.value); default: throw new SyntaxError(`Unknown operator: ${F.operator.value}`); } } evalProgram(F, ae) { return this.evaluateBlock(F.body, ae); } evaluateBlock(F, ae) { let H = ""; for (const me of F) { const ke = this.evaluate(me, ae); ke.type !== "NullValue" && ke.type !== "UndefinedValue" && (H += ke.value); } return new J(H); } evaluateIdentifier(F, ae) { return ae.lookupVariable(F.value); } evaluateCallExpression(F, ae) { const [H, me] = this.evaluateArguments(F.args, ae); me.size > 0 && H.push(new te(me)); const ke = this.evaluate(F.callee, ae); if (ke.type !== "FunctionValue") throw new Error(`Cannot call something that is not a function: got ${ke.type}`); return ke.value(H, ae); } evaluateSliceExpression(F, ae, H) { if (!(F instanceof ve || F instanceof J)) throw new Error("Slice object must be an array or string"); const me = this.evaluate(ae.start, H), ke = this.evaluate(ae.stop, H), ze = this.evaluate(ae.step, H); if (!(me instanceof Xe || me instanceof Re)) throw new Error("Slice start must be numeric or undefined"); if (!(ke instanceof Xe || ke instanceof Re)) throw new Error("Slice stop must be numeric or undefined"); if (!(ze instanceof Xe || ze instanceof Re)) throw new Error("Slice step must be numeric or undefined"); return F instanceof ve ? new ve(de(F.value, me.value, ke.value, ze.value)) : new J(de(Array.from(F.value), me.value, ke.value, ze.value).join("")); } evaluateMemberExpression(F, ae) { const H = this.evaluate(F.object, ae); let me; if (F.computed) { if (F.property.type === "SliceExpression") return this.evaluateSliceExpression(H, F.property, ae); me = this.evaluate(F.property, ae); } else me = new J(F.property.value); let ke; if (H instanceof Ne) { if (!(me instanceof J)) throw new Error(`Cannot access property with non-string: got ${me.type}`); ke = H.value.get(me.value) ?? H.builtins.get(me.value); } else if (H instanceof ve || H instanceof J) if (me instanceof Xe) ke = H.value.at(me.value), H instanceof J && (ke = new J(H.value.at(me.value))); else if (me instanceof J) ke = H.builtins.get(me.value); else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`); else { if (!(me instanceof J)) throw new Error(`Cannot access property with non-string: got ${me.type}`); ke = H.builtins.get(me.value); } return ke instanceof Oe ? ke : new Re(); } evaluateSet(F, ae) { const H = this.evaluate(F.value, ae); if (F.assignee.type === "Identifier") { const me = F.assignee.value; ae.setVariable(me, H); } else if (F.assignee.type === "MemberExpression") { const me = F.assignee, ke = this.evaluate(me.object, ae); if (!(ke instanceof Ne)) throw new Error("Cannot assign to member of non-object"); if (me.property.type !== "Identifier") throw new Error("Cannot assign to member with non-identifier property"); ke.value.set(me.property.value, H); } else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(F.assignee)}`); return new Ve(); } evaluateIf(F, ae) { const H = this.evaluate(F.test, ae); return this.evaluateBlock(H.__bool__().value ? F.body : F.alternate, ae); } evaluateFor(F, ae) { const H = new Ze(ae); let me, ke; if (F.iterable.type === "SelectExpression") { const mt = F.iterable; ke = this.evaluate(mt.iterable, H), me = mt.test; } else ke = this.evaluate(F.iterable, H); if (!(ke instanceof ve)) throw new Error(`Expected iterable type in for loop: got ${ke.type}`); const ze = [], Ge = []; for (let mt = 0; mt < ke.value.length; ++mt) { const Nt = new Ze(H), es = ke.value[mt]; let Ts; if (F.loopvar.type === "Identifier") Ts = (ms) => ms.setVariable(F.loopvar.value, es); else if (F.loopvar.type === "TupleLiteral") { const ms = F.loopvar; if (es.type !== "ArrayValue") throw new Error(`Cannot unpack non-iterable type: ${es.type}`); const Ps = es; if (ms.value.length !== Ps.value.length) throw new Error(`Too ${ms.value.length > Ps.value.length ? "few" : "many"} items to unpack`); Ts = (Is) => { for (let tr = 0; tr < ms.value.length; ++tr) { if (ms.value[tr].type !== "Identifier") throw new Error(`Cannot unpack non-identifier type: ${ms.value[tr].type}`); Is.setVariable(ms.value[tr].value, Ps.value[tr]); } }; } else throw new Error(`Invalid loop variable(s): ${F.loopvar.type}`); me && (Ts(Nt), !this.evaluate(me, Nt).__bool__().value) || (ze.push(es), Ge.push(Ts)); } let tt = "", et = !0; for (let mt = 0; mt < ze.length; ++mt) { const Nt = /* @__PURE__ */ new Map([ ["index", new Xe(mt + 1)], ["index0", new Xe(mt)], ["revindex", new Xe(ze.length - mt)], ["revindex0", new Xe(ze.length - mt - 1)], ["first", new We(mt === 0)], ["last", new We(mt === ze.length - 1)], ["length", new Xe(ze.length)], ["previtem", mt > 0 ? ze[mt - 1] : new Re()], ["nextitem", mt < ze.length - 1 ? ze[mt + 1] : new Re()] ]); H.setVariable("loop", new Ne(Nt)), Ge[mt](H); const es = this.evaluateBlock(F.body, H); tt += es.value, et = !1; } if (et) { const mt = this.evaluateBlock(F.defaultBlock, H); tt += mt.value; } return new J(tt); } /** * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information. */ evaluateMacro(F, ae) { return ae.setVariable( F.name.value, new je((H, me) => { const ke = new Ze(me); H = H.slice(); let ze; H.at(-1)?.type === "KeywordArgumentsValue" && (ze = H.pop()); for (let Ge = 0; Ge < F.args.length; ++Ge) { const tt = F.args[Ge], et = H[Ge]; if (tt.type === "Identifier") { const mt = tt; if (!et) throw new Error(`Missing positional argument: ${mt.value}`); ke.setVariable(mt.value, et); } else if (tt.type === "KeywordArgumentExpression") { const mt = tt, Nt = et ?? // Try positional arguments first ze?.value.get(mt.key.value) ?? // Look in user-passed kwargs this.evaluate(mt.value, ke); ke.setVariable(mt.key.value, Nt); } else throw new Error(`Unknown argument type: ${tt.type}`); } return this.evaluateBlock(F.body, ke); }) ), new Ve(); } evaluate(F, ae) { if (F === void 0) return new Re(); switch (F.type) { case "Program": return this.evalProgram(F, ae); case "Set": return this.evaluateSet(F, ae); case "If": return this.evaluateIf(F, ae); case "For": return this.evaluateFor(F, ae); case "Macro": return this.evaluateMacro(F, ae); case "NumericLiteral": return new Xe(Number(F.value)); case "StringLiteral": return new J(F.value); case "BooleanLiteral": return new We(F.value); case "NullLiteral": return new Ve(F.value); case "ArrayLiteral": return new ve(F.value.map((H) => this.evaluate(H, ae))); case "TupleLiteral": return new He(F.value.map((H) => this.evaluate(H, ae))); case "ObjectLiteral": { const H = /* @__PURE__ */ new Map(); for (const [me, ke] of F.value) { const ze = this.evaluate(me, ae); if (!(ze instanceof J)) throw new Error(`Object keys must be strings: got ${ze.type}`); H.set(ze.value, this.evaluate(ke, ae)); } return new Ne(H); } case "Identifier": return this.evaluateIdentifier(F, ae); case "CallExpression": return this.evaluateCallExpression(F, ae); case "MemberExpression": return this.evaluateMemberExpression(F, ae); case "UnaryExpression": return this.evaluateUnaryExpression(F, ae); case "BinaryExpression": return this.evaluateBinaryExpression(F, ae); case "FilterExpression": return this.evaluateFilterExpression(F, ae); case "TestExpression": return this.evaluateTestExpression(F, ae); default: throw new SyntaxError(`Unknown node type: ${F.type}`); } } }; function _t(F) { switch (typeof F) { case "number": return new Xe(F); case "string": return new J(F); case "boolean": return new We(F); case "undefined": return new Re(); case "object": return F === null ? new Ve() : Array.isArray(F) ? new ve(F.map(_t)) : new Ne( new Map(Object.entries(F).map(([ae, H]) => [ae, _t(H)])) ); case "function": return new je((ae, H) => { const me = F(...ae.map((ke) => ke.value)) ?? null; return _t(me); }); default: throw new Error(`Cannot convert to runtime value: ${F}`); } } function lt(F, ae, H) { const me = H ?? 0; switch (F.type) { case "NullValue": case "UndefinedValue": return "null"; case "NumericValue": case "StringValue": case "BooleanValue": return JSON.stringify(F.value); case "ArrayValue": case "ObjectValue": { const ke = ae ? " ".repeat(ae) : "", ze = ` ` + ke.repeat(me), Ge = ze + ke; if (F.type === "ArrayValue") { const tt = F.value.map((et) => lt(et, ae, me + 1)); return ae ? `[${Ge}${tt.join(`,${Ge}`)}${ze}]` : `[${tt.join(", ")}]`; } else { const tt = Array.from(F.value.entries()).map(([et, mt]) => { const Nt = `"${et}": ${lt(mt, ae, me + 1)}`; return ae ? `${Ge}${Nt}` : Nt; }); return ae ? `{${tt.join(",")}${ze}}` : `{${tt.join(", ")}}`; } } default: throw new Error(`Cannot convert to JSON: ${F.type}`); } } var ct = class { parsed; /** * @param {string} template The template string */ constructor(F) { const ae = b(F, { lstrip_blocks: !0, trim_blocks: !0 }); this.parsed = we(ae); } render(F) { const ae = new Ze(); if (ae.set("false", !1), ae.set("true", !0), ae.set("raise_exception", (ke) => { throw new Error(ke); }), ae.set("range", X), F) for (const [ke, ze] of Object.entries(F)) ae.set(ke, ze); return new at(ae).run(this.parsed).value; } }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js": ( /*!******************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ registerBackend: () => ( /* binding */ j ), /* harmony export */ resolveBackendAndExecutionProviders: () => ( /* binding */ N ) /* harmony export */ }); const g = /* @__PURE__ */ new Map(), O = [], j = (y, T, v) => { if (T && typeof T.init == "function" && typeof T.createInferenceSessionHandler == "function") { const b = g.get(y); if (b === void 0) g.set(y, { backend: T, priority: v }); else { if (b.priority > v) return; if (b.priority === v && b.backend !== T) throw new Error(`cannot register backend "${y}" using priority ${v}`); } if (v >= 0) { const x = O.indexOf(y); x !== -1 && O.splice(x, 1); for (let L = 0; L < O.length; L++) if (g.get(O[L]).priority <= v) { O.splice(L, 0, y); return; } O.push(y); } return; } throw new TypeError("not a valid backend"); }, ee = async (y) => { const T = g.get(y); if (!T) return "backend not found."; if (T.initialized) return T.backend; if (T.aborted) return T.error; { const v = !!T.initPromise; try { return v || (T.initPromise = T.backend.init(y)), await T.initPromise, T.initialized = !0, T.backend; } catch (b) { return v || (T.error = `${b}`, T.aborted = !0), T.error; } finally { delete T.initPromise; } } }, N = async (y) => { const T = y.executionProviders || [], v = T.map((ie) => typeof ie == "string" ? ie : ie.name), b = v.length === 0 ? O : v; let x; const L = [], K = /* @__PURE__ */ new Set(); for (const ie of b) { const V = await ee(ie); typeof V == "string" ? L.push({ name: ie, err: V }) : (x || (x = V), x === V && K.add(ie)); } if (!x) throw new Error(`no available backend found. ERR: ${L.map((ie) => `[${ie.name}] ${ie.err}`).join(", ")}`); for (const { name: ie, err: V } of L) v.includes(ie) && console.warn(`removing requested execution provider "${ie}" from session options because it is not available: ${V}`); const re = T.filter((ie) => K.has(typeof ie == "string" ? ie : ie.name)); return [ x, new Proxy(y, { get: (ie, V) => V === "executionProviders" ? re : Reflect.get(ie, V) }) ]; }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/backend.js": ( /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend.js ***! \*************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ registerBackend: () => ( /* reexport safe */ g.registerBackend ) /* harmony export */ }); var g = r( /*! ./backend-impl.js */ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js" ); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/env-impl.js": ( /*!**************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env-impl.js ***! \**************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ env: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ./version.js */ "./node_modules/onnxruntime-common/dist/esm/version.js" ); let O = "warning"; const j = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: g.version }, set logLevel(ee) { if (ee !== void 0) { if (typeof ee != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(ee) === -1) throw new Error(`Unsupported logging level: ${ee}`); O = ee; } }, get logLevel() { return O; } }; Object.defineProperty(j, "logLevel", { enumerable: !0 }); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/env.js": ( /*!*********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/env.js ***! \*********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ env: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ./env-impl.js */ "./node_modules/onnxruntime-common/dist/esm/env-impl.js" ); const O = g.env; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/index.js": ( /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/index.js ***! \***********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ InferenceSession: () => ( /* reexport safe */ j.InferenceSession ), /* harmony export */ TRACE: () => ( /* reexport safe */ N.TRACE ), /* harmony export */ TRACE_FUNC_BEGIN: () => ( /* reexport safe */ N.TRACE_FUNC_BEGIN ), /* harmony export */ TRACE_FUNC_END: () => ( /* reexport safe */ N.TRACE_FUNC_END ), /* harmony export */ Tensor: () => ( /* reexport safe */ ee.Tensor ), /* harmony export */ TrainingSession: () => ( /* reexport safe */ y.TrainingSession ), /* harmony export */ env: () => ( /* reexport safe */ O.env ), /* harmony export */ registerBackend: () => ( /* reexport safe */ g.registerBackend ) /* harmony export */ }); var g = r( /*! ./backend.js */ "./node_modules/onnxruntime-common/dist/esm/backend.js" ), O = r( /*! ./env.js */ "./node_modules/onnxruntime-common/dist/esm/env.js" ), j = r( /*! ./inference-session.js */ "./node_modules/onnxruntime-common/dist/esm/inference-session.js" ), ee = r( /*! ./tensor.js */ "./node_modules/onnxruntime-common/dist/esm/tensor.js" ); r( /*! ./tensor-conversion.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js" ), r( /*! ./tensor-factory.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-factory.js" ); var N = r( /*! ./trace.js */ "./node_modules/onnxruntime-common/dist/esm/trace.js" ); r( /*! ./onnx-model.js */ "./node_modules/onnxruntime-common/dist/esm/onnx-model.js" ), r( /*! ./onnx-value.js */ "./node_modules/onnxruntime-common/dist/esm/onnx-value.js" ); var y = r( /*! ./training-session.js */ "./node_modules/onnxruntime-common/dist/esm/training-session.js" ); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js": ( /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js ***! \****************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ InferenceSession: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ./backend-impl.js */ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js" ), O = r( /*! ./tensor.js */ "./node_modules/onnxruntime-common/dist/esm/tensor.js" ), j = r( /*! ./trace.js */ "./node_modules/onnxruntime-common/dist/esm/trace.js" ); class ee { constructor(y) { this.handler = y; } async run(y, T, v) { (0, j.TRACE_FUNC_BEGIN)(); const b = {}; let x = {}; if (typeof y != "object" || y === null || y instanceof O.Tensor || Array.isArray(y)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let L = !0; if (typeof T == "object") { if (T === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (T instanceof O.Tensor) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(T)) { if (T.length === 0) throw new TypeError("'fetches' cannot be an empty array."); L = !1; for (const ie of T) { if (typeof ie != "string") throw new TypeError("'fetches' must be a string array or an object."); if (this.outputNames.indexOf(ie) === -1) throw new RangeError(`'fetches' contains invalid output name: ${ie}.`); b[ie] = null; } if (typeof v == "object" && v !== null) x = v; else if (typeof v < "u") throw new TypeError("'options' must be an object."); } else { let ie = !1; const V = Object.getOwnPropertyNames(T); for (const U of this.outputNames) if (V.indexOf(U) !== -1) { const q = T[U]; (q === null || q instanceof O.Tensor) && (ie = !0, L = !1, b[U] = q); } if (ie) { if (typeof v == "object" && v !== null) x = v; else if (typeof v < "u") throw new TypeError("'options' must be an object."); } else x = T; } } else if (typeof T < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (const ie of this.inputNames) if (typeof y[ie] > "u") throw new Error(`input '${ie}' is missing in 'feeds'.`); if (L) for (const ie of this.outputNames) b[ie] = null; const K = await this.handler.run(y, b, x), re = {}; for (const ie in K) if (Object.hasOwnProperty.call(K, ie)) { const V = K[ie]; V instanceof O.Tensor ? re[ie] = V : re[ie] = new O.Tensor(V.type, V.data, V.dims); } return (0, j.TRACE_FUNC_END)(), re; } async release() { return this.handler.dispose(); } static async create(y, T, v, b) { (0, j.TRACE_FUNC_BEGIN)(); let x, L = {}; if (typeof y == "string") { if (x = y, typeof T == "object" && T !== null) L = T; else if (typeof T < "u") throw new TypeError("'options' must be an object."); } else if (y instanceof Uint8Array) { if (x = y, typeof T == "object" && T !== null) L = T; else if (typeof T < "u") throw new TypeError("'options' must be an object."); } else if (y instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && y instanceof SharedArrayBuffer) { const V = y; let U = 0, q = y.byteLength; if (typeof T == "object" && T !== null) L = T; else if (typeof T == "number") { if (U = T, !Number.isSafeInteger(U)) throw new RangeError("'byteOffset' must be an integer."); if (U < 0 || U >= V.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${V.byteLength}).`); if (q = y.byteLength - U, typeof v == "number") { if (q = v, !Number.isSafeInteger(q)) throw new RangeError("'byteLength' must be an integer."); if (q <= 0 || U + q > V.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${V.byteLength - U}].`); if (typeof b == "object" && b !== null) L = b; else if (typeof b < "u") throw new TypeError("'options' must be an object."); } else if (typeof v < "u") throw new TypeError("'byteLength' must be a number."); } else if (typeof T < "u") throw new TypeError("'options' must be an object."); x = new Uint8Array(V, U, q); } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); const [K, re] = await (0, g.resolveBackendAndExecutionProviders)(L), ie = await K.createInferenceSessionHandler(x, re); return (0, j.TRACE_FUNC_END)(), new ee(ie); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } } } ), /***/ "./node_modules/onnxruntime-common/dist/esm/inference-session.js": ( /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/inference-session.js ***! \***********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ InferenceSession: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ./inference-session-impl.js */ "./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js" ); const O = g.InferenceSession; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/onnx-model.js": ( /*!****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/onnx-model.js ***! \****************************************************************/ /***/ (Ie, $, r) => { r.r($); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/onnx-value.js": ( /*!****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/onnx-value.js ***! \****************************************************************/ /***/ (Ie, $, r) => { r.r($); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js": ( /*!****************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js ***! \****************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ tensorToDataURL: () => ( /* binding */ g ), /* harmony export */ tensorToImageData: () => ( /* binding */ O ) /* harmony export */ }); const g = (j, ee) => { const N = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); N.width = j.dims[3], N.height = j.dims[2]; const y = N.getContext("2d"); if (y != null) { let T, v; ee?.tensorLayout !== void 0 && ee.tensorLayout === "NHWC" ? (T = j.dims[2], v = j.dims[3]) : (T = j.dims[3], v = j.dims[2]); const b = ee?.format !== void 0 ? ee.format : "RGB", x = ee?.norm; let L, K; x === void 0 || x.mean === void 0 ? L = [255, 255, 255, 255] : typeof x.mean == "number" ? L = [x.mean, x.mean, x.mean, x.mean] : (L = [x.mean[0], x.mean[1], x.mean[2], 0], x.mean[3] !== void 0 && (L[3] = x.mean[3])), x === void 0 || x.bias === void 0 ? K = [0, 0, 0, 0] : typeof x.bias == "number" ? K = [x.bias, x.bias, x.bias, x.bias] : (K = [x.bias[0], x.bias[1], x.bias[2], 0], x.bias[3] !== void 0 && (K[3] = x.bias[3])); const re = v * T; let ie = 0, V = re, U = re * 2, q = -1; b === "RGBA" ? (ie = 0, V = re, U = re * 2, q = re * 3) : b === "RGB" ? (ie = 0, V = re, U = re * 2) : b === "RBG" && (ie = 0, U = re, V = re * 2); for (let A = 0; A < v; A++) for (let S = 0; S < T; S++) { const w = (j.data[ie++] - K[0]) * L[0], P = (j.data[V++] - K[1]) * L[1], I = (j.data[U++] - K[2]) * L[2], le = q === -1 ? 255 : (j.data[q++] - K[3]) * L[3]; y.fillStyle = "rgba(" + w + "," + P + "," + I + "," + le + ")", y.fillRect(S, A, 1, 1); } if ("toDataURL" in N) return N.toDataURL(); throw new Error("toDataURL is not supported"); } else throw new Error("Can not access image data"); }, O = (j, ee) => { const N = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"); let y; if (N != null) { let T, v, b; ee?.tensorLayout !== void 0 && ee.tensorLayout === "NHWC" ? (T = j.dims[2], v = j.dims[1], b = j.dims[3]) : (T = j.dims[3], v = j.dims[2], b = j.dims[1]); const x = ee !== void 0 && ee.format !== void 0 ? ee.format : "RGB", L = ee?.norm; let K, re; L === void 0 || L.mean === void 0 ? K = [255, 255, 255, 255] : typeof L.mean == "number" ? K = [L.mean, L.mean, L.mean, L.mean] : (K = [L.mean[0], L.mean[1], L.mean[2], 255], L.mean[3] !== void 0 && (K[3] = L.mean[3])), L === void 0 || L.bias === void 0 ? re = [0, 0, 0, 0] : typeof L.bias == "number" ? re = [L.bias, L.bias, L.bias, L.bias] : (re = [L.bias[0], L.bias[1], L.bias[2], 0], L.bias[3] !== void 0 && (re[3] = L.bias[3])); const ie = v * T; if (ee !== void 0 && (ee.format !== void 0 && b === 4 && ee.format !== "RGBA" || b === 3 && ee.format !== "RGB" && ee.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); const V = 4; let U = 0, q = 1, A = 2, S = 3, w = 0, P = ie, I = ie * 2, le = -1; x === "RGBA" ? (w = 0, P = ie, I = ie * 2, le = ie * 3) : x === "RGB" ? (w = 0, P = ie, I = ie * 2) : x === "RBG" && (w = 0, I = ie, P = ie * 2), y = N.createImageData(T, v); for (let oe = 0; oe < v * T; U += V, q += V, A += V, S += V, oe++) y.data[U] = (j.data[w++] - re[0]) * K[0], y.data[q] = (j.data[P++] - re[1]) * K[1], y.data[A] = (j.data[I++] - re[2]) * K[2], y.data[S] = le === -1 ? 255 : (j.data[le++] - re[3]) * K[3]; } else throw new Error("Can not access image data"); return y; }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js": ( /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js ***! \***********************************************************************/ /***/ (Ie, $, r) => { r.r($); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js": ( /*!*************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js ***! \*************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ bufferToTensor: () => ( /* binding */ O ), /* harmony export */ tensorFromGpuBuffer: () => ( /* binding */ N ), /* harmony export */ tensorFromImage: () => ( /* binding */ j ), /* harmony export */ tensorFromMLTensor: () => ( /* binding */ y ), /* harmony export */ tensorFromPinnedBuffer: () => ( /* binding */ T ), /* harmony export */ tensorFromTexture: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js" ); const O = (v, b) => { if (v === void 0) throw new Error("Image buffer must be defined"); if (b.height === void 0 || b.width === void 0) throw new Error("Image height and width must be defined"); if (b.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet"); const { height: x, width: L } = b, K = b.norm ?? { mean: 255, bias: 0 }; let re, ie; typeof K.mean == "number" ? re = [K.mean, K.mean, K.mean, K.mean] : re = [K.mean[0], K.mean[1], K.mean[2], K.mean[3] ?? 255], typeof K.bias == "number" ? ie = [K.bias, K.bias, K.bias, K.bias] : ie = [K.bias[0], K.bias[1], K.bias[2], K.bias[3] ?? 0]; const V = b.format !== void 0 ? b.format : "RGBA", U = b.tensorFormat !== void 0 && b.tensorFormat !== void 0 ? b.tensorFormat : "RGB", q = x * L, A = U === "RGBA" ? new Float32Array(q * 4) : new Float32Array(q * 3); let S = 4, w = 0, P = 1, I = 2, le = 3, oe = 0, ye = q, ge = q * 2, se = -1; V === "RGB" && (S = 3, w = 0, P = 1, I = 2, le = -1), U === "RGBA" ? se = q * 3 : U === "RBG" ? (oe = 0, ge = q, ye = q * 2) : U === "BGR" && (ge = 0, ye = q, oe = q * 2); for (let pe = 0; pe < q; pe++, w += S, I += S, P += S, le += S) A[oe++] = (v[w] + ie[0]) / re[0], A[ye++] = (v[P] + ie[1]) / re[1], A[ge++] = (v[I] + ie[2]) / re[2], se !== -1 && le !== -1 && (A[se++] = (v[le] + ie[3]) / re[3]); return U === "RGBA" ? new g.Tensor("float32", A, [1, 4, x, L]) : new g.Tensor("float32", A, [1, 3, x, L]); }, j = async (v, b) => { const x = typeof HTMLImageElement < "u" && v instanceof HTMLImageElement, L = typeof ImageData < "u" && v instanceof ImageData, K = typeof ImageBitmap < "u" && v instanceof ImageBitmap, re = typeof v == "string"; let ie, V = b ?? {}; const 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"); }, q = (A) => typeof HTMLCanvasElement < "u" && A instanceof HTMLCanvasElement || A instanceof OffscreenCanvas ? A.getContext("2d") : null; if (x) { const A = U(); A.width = v.width, A.height = v.height; const S = q(A); if (S != null) { let w = v.height, P = v.width; if (b !== void 0 && b.resizedHeight !== void 0 && b.resizedWidth !== void 0 && (w = b.resizedHeight, P = b.resizedWidth), b !== void 0) { if (V = b, b.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); V.tensorFormat = "RGBA", V.height = w, V.width = P; } else V.tensorFormat = "RGBA", V.height = w, V.width = P; S.drawImage(v, 0, 0), ie = S.getImageData(0, 0, P, w).data; } else throw new Error("Can not access image data"); } else if (L) { let A, S; if (b !== void 0 && b.resizedWidth !== void 0 && b.resizedHeight !== void 0 ? (A = b.resizedHeight, S = b.resizedWidth) : (A = v.height, S = v.width), b !== void 0 && (V = b), V.format = "RGBA", V.height = A, V.width = S, b !== void 0) { const w = U(); w.width = S, w.height = A; const P = q(w); if (P != null) P.putImageData(v, 0, 0), ie = P.getImageData(0, 0, S, A).data; else throw new Error("Can not access image data"); } else ie = v.data; } else if (K) { if (b === void 0) throw new Error("Please provide image config with format for Imagebitmap"); const A = U(); A.width = v.width, A.height = v.height; const S = q(A); if (S != null) { const w = v.height, P = v.width; return S.drawImage(v, 0, 0, P, w), ie = S.getImageData(0, 0, P, w).data, V.height = w, V.width = P, O(ie, V); } else throw new Error("Can not access image data"); } else { if (re) return new Promise((A, S) => { const w = U(), P = q(w); if (!v || !P) return S(); const I = new Image(); I.crossOrigin = "Anonymous", I.src = v, I.onload = () => { w.width = I.width, w.height = I.height, P.drawImage(I, 0, 0, w.width, w.height); const le = P.getImageData(0, 0, w.width, w.height); V.height = w.height, V.width = w.width, A(O(le.data, V)); }; }); throw new Error("Input data provided is not supported - aborted tensor creation"); } if (ie !== void 0) return O(ie, V); throw new Error("Input data provided is not supported - aborted tensor creation"); }, ee = (v, b) => { const { width: x, height: L, download: K, dispose: re } = b, ie = [1, L, x, 4]; return new g.Tensor({ location: "texture", type: "float32", texture: v, dims: ie, download: K, dispose: re }); }, N = (v, b) => { const { dataType: x, dims: L, download: K, dispose: re } = b; return new g.Tensor({ location: "gpu-buffer", type: x ?? "float32", gpuBuffer: v, dims: L, download: K, dispose: re }); }, y = (v, b) => { const { dataType: x, dims: L, download: K, dispose: re } = b; return new g.Tensor({ location: "ml-tensor", type: x ?? "float32", mlTensor: v, dims: L, download: K, dispose: re }); }, T = (v, b, x) => new g.Tensor({ location: "cpu-pinned", type: v, data: b, dims: x ?? [b.length] }); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-factory.js": ( /*!********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory.js ***! \********************************************************************/ /***/ (Ie, $, r) => { r.r($); } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js": ( /*!******************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js ***! \******************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP: () => ( /* binding */ O ), /* harmony export */ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP: () => ( /* binding */ g ), /* harmony export */ checkTypedArray: () => ( /* binding */ ee ) /* harmony export */ }); const g = /* @__PURE__ */ new Map([ ["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array], ["int4", Uint8Array], ["uint4", Uint8Array] ]), O = /* @__PURE__ */ new Map([ [Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"] ]); let j = !1; const ee = () => { if (!j) { j = !0; const N = typeof BigInt64Array < "u" && BigInt64Array.from, y = typeof BigUint64Array < "u" && BigUint64Array.from, T = typeof Float16Array < "u" && Float16Array.from; N && (g.set("int64", BigInt64Array), O.set(BigInt64Array, "int64")), y && (g.set("uint64", BigUint64Array), O.set(BigUint64Array, "uint64")), T ? (g.set("float16", Float16Array), O.set(Float16Array, "float16")) : g.set("float16", Uint16Array); } }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js": ( /*!*****************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl.js ***! \*****************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Tensor: () => ( /* binding */ N ) /* harmony export */ }); var g = r( /*! ./tensor-conversion-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js" ), O = r( /*! ./tensor-factory-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js" ), j = r( /*! ./tensor-impl-type-mapping.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js" ), ee = r( /*! ./tensor-utils-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js" ); class N { /** * implementation. */ constructor(T, v, b) { (0, j.checkTypedArray)(); let x, L; if (typeof T == "object" && "location" in T) switch (this.dataLocation = T.location, x = T.type, L = T.dims, T.location) { case "cpu-pinned": { const re = j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(x); if (!re) throw new TypeError(`unsupported type "${x}" to create tensor from pinned buffer`); if (!(T.data instanceof re)) throw new TypeError(`buffer should be of type ${re.name}`); this.cpuData = T.data; break; } case "texture": { if (x !== "float32") throw new TypeError(`unsupported type "${x}" to create tensor from texture`); this.gpuTextureData = T.texture, this.downloader = T.download, this.disposer = T.dispose; break; } case "gpu-buffer": { if (x !== "float32" && x !== "float16" && x !== "int32" && x !== "int64" && x !== "uint32" && x !== "uint8" && x !== "bool" && x !== "uint4" && x !== "int4") throw new TypeError(`unsupported type "${x}" to create tensor from gpu buffer`); this.gpuBufferData = T.gpuBuffer, this.downloader = T.download, this.disposer = T.dispose; break; } case "ml-tensor": { if (x !== "float32" && x !== "float16" && x !== "int32" && x !== "int64" && x !== "uint32" && x !== "uint64" && x !== "int8" && x !== "uint8" && x !== "bool") throw new TypeError(`unsupported type "${x}" to create tensor from MLTensor`); this.mlTensorData = T.mlTensor, this.downloader = T.download, this.disposer = T.dispose; break; } default: throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); } else { let re, ie; if (typeof T == "string") if (x = T, ie = b, T === "string") { if (!Array.isArray(v)) throw new TypeError("A string tensor's data must be a string array."); re = v; } else { const V = j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(T); if (V === void 0) throw new TypeError(`Unsupported tensor type: ${T}.`); if (Array.isArray(v)) { if (T === "float16" && V === Uint16Array || T === "uint4" || T === "int4") throw new TypeError(`Creating a ${T} tensor from number array is not supported. Please use ${V.name} as data.`); T === "uint64" || T === "int64" ? re = V.from(v, BigInt) : re = V.from(v); } else if (v instanceof V) re = v; else if (v instanceof Uint8ClampedArray) if (T === "uint8") re = Uint8Array.from(v); else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8"); else throw new TypeError(`A ${x} tensor's data must be type of ${V}`); } else if (ie = v, Array.isArray(T)) { if (T.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); const V = typeof T[0]; if (V === "string") x = "string", re = T; else if (V === "boolean") x = "bool", re = Uint8Array.from(T); else throw new TypeError(`Invalid element type of data array: ${V}.`); } else if (T instanceof Uint8ClampedArray) x = "uint8", re = Uint8Array.from(T); else { const V = j.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(T.constructor); if (V === void 0) throw new TypeError(`Unsupported type for tensor data: ${T.constructor}.`); x = V, re = T; } if (ie === void 0) ie = [re.length]; else if (!Array.isArray(ie)) throw new TypeError("A tensor's dims must be a number array"); L = ie, this.cpuData = re, this.dataLocation = "cpu"; } const K = (0, ee.calculateSize)(L); if (this.cpuData && K !== this.cpuData.length && !((x === "uint4" || x === "int4") && Math.ceil(K / 2) === this.cpuData.length)) throw new Error(`Tensor's size(${K}) does not match data length(${this.cpuData.length}).`); this.type = x, this.dims = L, this.size = K; } // #endregion // #region factory static async fromImage(T, v) { return (0, O.tensorFromImage)(T, v); } static fromTexture(T, v) { return (0, O.tensorFromTexture)(T, v); } static fromGpuBuffer(T, v) { return (0, O.tensorFromGpuBuffer)(T, v); } static fromMLTensor(T, v) { return (0, O.tensorFromMLTensor)(T, v); } static fromPinnedBuffer(T, v, b) { return (0, O.tensorFromPinnedBuffer)(T, v, b); } // #endregion // #region conversions toDataURL(T) { return (0, g.tensorToDataURL)(this, T); } toImageData(T) { return (0, g.tensorToImageData)(this, T); } // #endregion // #region properties 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; } get mlTensor() { if (this.ensureValid(), !this.mlTensorData) throw new Error("The data is not stored as a WebNN MLTensor."); return this.mlTensorData; } // #endregion // #region methods async getData(T) { switch (this.ensureValid(), this.dataLocation) { case "cpu": case "cpu-pinned": return this.data; case "texture": case "gpu-buffer": case "ml-tensor": { 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 = !0; const v = await this.downloader(); return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = v, T && this.disposer && (this.disposer(), this.disposer = void 0), v; } finally { this.isDownloading = !1; } } 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.mlTensorData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none"; } // #endregion // #region tensor utilities 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 (0, ee.tensorReshape)(this, T); } } } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js": ( /*!***********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js ***! \***********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ calculateSize: () => ( /* binding */ O ), /* harmony export */ tensorReshape: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js" ); const O = (ee) => { let N = 1; for (let y = 0; y < ee.length; y++) { const T = ee[y]; if (typeof T != "number" || !Number.isSafeInteger(T)) throw new TypeError(`dims[${y}] must be an integer, got: ${T}`); if (T < 0) throw new RangeError(`dims[${y}] must be a non-negative integer, got: ${T}`); N *= T; } return N; }, j = (ee, N) => { switch (ee.location) { case "cpu": return new g.Tensor(ee.type, ee.data, N); case "cpu-pinned": return new g.Tensor({ location: "cpu-pinned", data: ee.data, type: ee.type, dims: N }); case "texture": return new g.Tensor({ location: "texture", texture: ee.texture, type: ee.type, dims: N }); case "gpu-buffer": return new g.Tensor({ location: "gpu-buffer", gpuBuffer: ee.gpuBuffer, type: ee.type, dims: N }); case "ml-tensor": return new g.Tensor({ location: "ml-tensor", mlTensor: ee.mlTensor, type: ee.type, dims: N }); default: throw new Error(`tensorReshape: tensor location ${ee.location} is not supported`); } }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/tensor.js": ( /*!************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/tensor.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Tensor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js" ); const O = g.Tensor; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/trace.js": ( /*!***********************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/trace.js ***! \***********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ TRACE: () => ( /* binding */ O ), /* harmony export */ TRACE_FUNC_BEGIN: () => ( /* binding */ ee ), /* harmony export */ TRACE_FUNC_END: () => ( /* binding */ N ) /* harmony export */ }); var g = r( /*! ./env-impl.js */ "./node_modules/onnxruntime-common/dist/esm/env-impl.js" ); const O = (y, T) => { (typeof g.env.trace > "u" ? !g.env.wasm.trace : !g.env.trace) || console.timeStamp(`${y}::ORT::${T}`); }, j = (y, T) => { const v = new Error().stack?.split(/\r\n|\r|\n/g) || []; let b = !1; for (let x = 0; x < v.length; x++) { if (b && !v[x].includes("TRACE_FUNC")) { let L = `FUNC_${y}::${v[x].trim().split(" ")[1]}`; T && (L += `::${T}`), O("CPU", L); return; } v[x].includes("TRACE_FUNC") && (b = !0); } }, ee = (y) => { (typeof g.env.trace > "u" ? !g.env.wasm.trace : !g.env.trace) || j("BEGIN", y); }, N = (y) => { (typeof g.env.trace > "u" ? !g.env.wasm.trace : !g.env.trace) || j("END", y); }; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/training-session-impl.js": ( /*!***************************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session-impl.js ***! \***************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ TrainingSession: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ./backend-impl.js */ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js" ), O = r( /*! ./tensor.js */ "./node_modules/onnxruntime-common/dist/esm/tensor.js" ); const j = "Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files."; class ee { constructor(y, T, v) { this.handler = y, this.hasOptimizerModel = T, this.hasEvalModel = v; } 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(y, T) { const v = y.evalModel || "", b = y.optimizerModel || "", x = T || {}, [L, K] = await (0, g.resolveBackendAndExecutionProviders)(x); if (L.createTrainingSessionHandler) { const re = await L.createTrainingSessionHandler(y.checkpointState, y.trainModel, v, b, K); return new ee(re, !!y.optimizerModel, !!y.evalModel); } else throw new Error(j); } /** * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from * the given parameters to SessionHandler.FetchesType and RunOptions. * * @param inputNames the feeds object is checked that they contain all input names in the provided list of input * names. * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output * names. * @param feeds the required input * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object * @param arg2 optional RunOptions object. * @returns */ typeNarrowingForRunStep(y, T, v, b, x) { const L = {}; let K = {}; if (typeof v != "object" || v === null || v instanceof O.Tensor || Array.isArray(v)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let re = !0; if (typeof b == "object") { if (b === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (b instanceof O.Tensor) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(b)) { if (b.length === 0) throw new TypeError("'fetches' cannot be an empty array."); re = !1; for (const ie of b) { if (typeof ie != "string") throw new TypeError("'fetches' must be a string array or an object."); if (T.indexOf(ie) === -1) throw new RangeError(`'fetches' contains invalid output name: ${ie}.`); L[ie] = null; } if (typeof x == "object" && x !== null) K = x; else if (typeof x < "u") throw new TypeError("'options' must be an object."); } else { let ie = !1; const V = Object.getOwnPropertyNames(b); for (const U of T) if (V.indexOf(U) !== -1) { const q = b[U]; (q === null || q instanceof O.Tensor) && (ie = !0, re = !1, L[U] = q); } if (ie) { if (typeof x == "object" && x !== null) K = x; else if (typeof x < "u") throw new TypeError("'options' must be an object."); } else K = b; } } else if (typeof b < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (const ie of y) if (typeof v[ie] > "u") throw new Error(`input '${ie}' is missing in 'feeds'.`); if (re) for (const ie of T) L[ie] = null; return [L, K]; } /** * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler * and changes it into a map of Tensors. * * @param results * @returns */ convertHandlerReturnTypeToMapOfTensors(y) { const T = {}; for (const v in y) if (Object.hasOwnProperty.call(y, v)) { const b = y[v]; b instanceof O.Tensor ? T[v] = b : T[v] = new O.Tensor(b.type, b.data, b.dims); } return T; } async lazyResetGrad() { await this.handler.lazyResetGrad(); } async runTrainStep(y, T, v) { const [b, x] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, y, T, v), L = await this.handler.runTrainStep(y, b, x); return this.convertHandlerReturnTypeToMapOfTensors(L); } async runOptimizerStep(y) { if (this.hasOptimizerModel) await this.handler.runOptimizerStep(y || {}); else throw new Error("This TrainingSession has no OptimizerModel loaded."); } async runEvalStep(y, T, v) { if (this.hasEvalModel) { const [b, x] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, y, T, v), L = await this.handler.runEvalStep(y, b, x); return this.convertHandlerReturnTypeToMapOfTensors(L); } else throw new Error("This TrainingSession has no EvalModel loaded."); } async getParametersSize(y = !0) { return this.handler.getParametersSize(y); } async loadParametersBuffer(y, T = !0) { const v = await this.getParametersSize(T); if (y.length !== 4 * v) 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(y, T); } async getContiguousParameters(y = !0) { return this.handler.getContiguousParameters(y); } async release() { return this.handler.dispose(); } } } ), /***/ "./node_modules/onnxruntime-common/dist/esm/training-session.js": ( /*!**********************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/training-session.js ***! \**********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ TrainingSession: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ./training-session-impl.js */ "./node_modules/onnxruntime-common/dist/esm/training-session-impl.js" ); const O = g.TrainingSession; } ), /***/ "./node_modules/onnxruntime-common/dist/esm/version.js": ( /*!*************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/version.js ***! \*************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ version: () => ( /* binding */ g ) /* harmony export */ }); const g = "1.20.1"; } ), /***/ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96": ( /*!**************************************************************!*\ !*** ./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs ***! \**************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ InferenceSession: () => ( /* binding */ lt ), /* harmony export */ TRACE: () => ( /* binding */ He ), /* harmony export */ TRACE_FUNC_BEGIN: () => ( /* binding */ Ve ), /* harmony export */ TRACE_FUNC_END: () => ( /* binding */ Re ), /* harmony export */ Tensor: () => ( /* binding */ te ), /* harmony export */ default: () => ( /* binding */ s_ ), /* harmony export */ env: () => ( /* binding */ I ), /* harmony export */ registerBackend: () => ( /* binding */ K ) /* harmony export */ }); /*! * ONNX Runtime Web v1.21.0-dev.20250206-d981b153d3 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ var g = Object.defineProperty, O = Object.getOwnPropertyDescriptor, j = Object.getOwnPropertyNames, ee = Object.prototype.hasOwnProperty, N = ((e) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(e, { get: (t, s) => (typeof require < "u" ? require : t)[s] }) : e)(function(e) { if (typeof require < "u") return require.apply(this, arguments); throw Error('Dynamic require of "' + e + '" is not supported'); }), y = (e, t) => () => (e && (t = e(e = 0)), t), T = (e, t) => { for (var s in t) g(e, s, { get: t[s], enumerable: !0 }); }, v = (e, t, s, n) => { if (t && typeof t == "object" || typeof t == "function") for (let o of j(t)) !ee.call(e, o) && o !== s && g(e, o, { get: () => t[o], enumerable: !(n = O(t, o)) || n.enumerable }); return e; }, b = (e) => v(g({}, "__esModule", { value: !0 }), e), x, L, K, re, ie, V = y(() => { x = /* @__PURE__ */ new Map(), L = [], K = (e, t, s) => { if (t && typeof t.init == "function" && typeof t.createInferenceSessionHandler == "function") { let n = x.get(e); if (n === void 0) x.set(e, { backend: t, priority: s }); else { if (n.priority > s) return; if (n.priority === s && n.backend !== t) throw new Error(`cannot register backend "${e}" using priority ${s}`); } if (s >= 0) { let o = L.indexOf(e); o !== -1 && L.splice(o, 1); for (let i = 0; i < L.length; i++) if (x.get(L[i]).priority <= s) { L.splice(i, 0, e); return; } L.push(e); } return; } throw new TypeError("not a valid backend"); }, re = async (e) => { let t = x.get(e); if (!t) return "backend not found."; if (t.initialized) return t.backend; if (t.aborted) return t.error; { let s = !!t.initPromise; try { return s || (t.initPromise = t.backend.init(e)), await t.initPromise, t.initialized = !0, t.backend; } catch (n) { return s || (t.error = `${n}`, t.aborted = !0), t.error; } finally { delete t.initPromise; } } }, ie = async (e) => { let t = e.executionProviders || [], s = t.map((p) => typeof p == "string" ? p : p.name), n = s.length === 0 ? L : s, o, i = [], a = /* @__PURE__ */ new Set(); for (let p of n) { let h = await re(p); typeof h == "string" ? i.push({ name: p, err: h }) : (o || (o = h), o === h && a.add(p)); } if (!o) throw new Error(`no available backend found. ERR: ${i.map((p) => `[${p.name}] ${p.err}`).join(", ")}`); for (let { name: p, err: h } of i) s.includes(p) && console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`); let c = t.filter((p) => a.has(typeof p == "string" ? p : p.name)); return [o, new Proxy(e, { get: (p, h) => h === "executionProviders" ? c : Reflect.get(p, h) })]; }; }), U = y(() => { V(); }), q, A = y(() => { q = "1.21.0-dev.20250206-d981b153d3"; }), S, w, P = y(() => { A(), S = "warning", w = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: q }, 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}`); S = e; } }, get logLevel() { return S; } }, Object.defineProperty(w, "logLevel", { enumerable: !0 }); }), I, le = y(() => { P(), I = w; }), oe, ye, ge = y(() => { oe = (e, t) => { let s = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); s.width = e.dims[3], s.height = e.dims[2]; let n = s.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", c = t?.norm, p, h; c === void 0 || c.mean === void 0 ? p = [255, 255, 255, 255] : typeof c.mean == "number" ? p = [c.mean, c.mean, c.mean, c.mean] : (p = [c.mean[0], c.mean[1], c.mean[2], 0], c.mean[3] !== void 0 && (p[3] = c.mean[3])), c === void 0 || c.bias === void 0 ? h = [0, 0, 0, 0] : typeof c.bias == "number" ? h = [c.bias, c.bias, c.bias, c.bias] : (h = [c.bias[0], c.bias[1], c.bias[2], 0], c.bias[3] !== void 0 && (h[3] = c.bias[3])); let C = i * o, u = 0, k = C, B = C * 2, R = -1; a === "RGBA" ? (u = 0, k = C, B = C * 2, R = C * 3) : a === "RGB" ? (u = 0, k = C, B = C * 2) : a === "RBG" && (u = 0, B = C, k = C * 2); for (let z = 0; z < i; z++) for (let ne = 0; ne < o; ne++) { let Z = (e.data[u++] - h[0]) * p[0], W = (e.data[k++] - h[1]) * p[1], ue = (e.data[B++] - h[2]) * p[2], he = R === -1 ? 255 : (e.data[R++] - h[3]) * p[3]; n.fillStyle = "rgba(" + Z + "," + W + "," + ue + "," + he + ")", n.fillRect(ne, z, 1, 1); } if ("toDataURL" in s) return s.toDataURL(); throw new Error("toDataURL is not supported"); } else throw new Error("Can not access image data"); }, ye = (e, t) => { let s = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), n; if (s != 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 c = t !== void 0 && t.format !== void 0 ? t.format : "RGB", p = t?.norm, h, C; p === void 0 || p.mean === void 0 ? h = [255, 255, 255, 255] : typeof p.mean == "number" ? h = [p.mean, p.mean, p.mean, p.mean] : (h = [p.mean[0], p.mean[1], p.mean[2], 255], p.mean[3] !== void 0 && (h[3] = p.mean[3])), p === void 0 || p.bias === void 0 ? C = [0, 0, 0, 0] : typeof p.bias == "number" ? C = [p.bias, p.bias, p.bias, p.bias] : (C = [p.bias[0], p.bias[1], p.bias[2], 0], p.bias[3] !== void 0 && (C[3] = p.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 k = 4, B = 0, R = 1, z = 2, ne = 3, Z = 0, W = u, ue = u * 2, he = -1; c === "RGBA" ? (Z = 0, W = u, ue = u * 2, he = u * 3) : c === "RGB" ? (Z = 0, W = u, ue = u * 2) : c === "RBG" && (Z = 0, ue = u, W = u * 2), n = s.createImageData(o, i); for (let Me = 0; Me < i * o; B += k, R += k, z += k, ne += k, Me++) n.data[B] = (e.data[Z++] - C[0]) * h[0], n.data[R] = (e.data[W++] - C[1]) * h[1], n.data[z] = (e.data[ue++] - C[2]) * h[2], n.data[ne] = he === -1 ? 255 : (e.data[he++] - C[3]) * h[3]; } else throw new Error("Can not access image data"); return n; }; }), se, be, pe, Ce, $e, Pe, Je = y(() => { Ne(), se = (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: s, 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 c = t.format !== void 0 ? t.format : "RGBA", p = t.tensorFormat !== void 0 && t.tensorFormat !== void 0 ? t.tensorFormat : "RGB", h = s * n, C = p === "RGBA" ? new Float32Array(h * 4) : new Float32Array(h * 3), u = 4, k = 0, B = 1, R = 2, z = 3, ne = 0, Z = h, W = h * 2, ue = -1; c === "RGB" && (u = 3, k = 0, B = 1, R = 2, z = -1), p === "RGBA" ? ue = h * 3 : p === "RBG" ? (ne = 0, W = h, Z = h * 2) : p === "BGR" && (W = 0, Z = h, ne = h * 2); for (let he = 0; he < h; he++, k += u, R += u, B += u, z += u) C[ne++] = (e[k] + a[0]) / i[0], C[Z++] = (e[B] + a[1]) / i[1], C[W++] = (e[R] + a[2]) / i[2], ue !== -1 && z !== -1 && (C[ue++] = (e[z] + a[3]) / i[3]); return p === "RGBA" ? new We("float32", C, [1, 4, s, n]) : new We("float32", C, [1, 3, s, n]); }, be = async (e, t) => { let s = 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, c = t ?? {}, p = () => { if (typeof document < "u") return document.createElement("canvas"); if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); throw new Error("Canvas is not supported"); }, h = (C) => typeof HTMLCanvasElement < "u" && C instanceof HTMLCanvasElement || C instanceof OffscreenCanvas ? C.getContext("2d") : null; if (s) { let C = p(); C.width = e.width, C.height = e.height; let u = h(C); if (u != null) { let k = e.height, B = e.width; if (t !== void 0 && t.resizedHeight !== void 0 && t.resizedWidth !== void 0 && (k = t.resizedHeight, B = t.resizedWidth), t !== void 0) { if (c = t, t.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); c.tensorFormat = "RGBA", c.height = k, c.width = B; } else c.tensorFormat = "RGBA", c.height = k, c.width = B; u.drawImage(e, 0, 0), a = u.getImageData(0, 0, B, k).data; } else throw new Error("Can not access image data"); } else if (n) { let C, u; if (t !== void 0 && t.resizedWidth !== void 0 && t.resizedHeight !== void 0 ? (C = t.resizedHeight, u = t.resizedWidth) : (C = e.height, u = e.width), t !== void 0 && (c = t), c.format = "RGBA", c.height = C, c.width = u, t !== void 0) { let k = p(); k.width = u, k.height = C; let B = h(k); if (B != null) B.putImageData(e, 0, 0), a = B.getImageData(0, 0, u, C).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 C = p(); C.width = e.width, C.height = e.height; let u = h(C); if (u != null) { let k = e.height, B = e.width; return u.drawImage(e, 0, 0, B, k), a = u.getImageData(0, 0, B, k).data, c.height = k, c.width = B, se(a, c); } else throw new Error("Can not access image data"); } else { if (i) return new Promise((C, u) => { let k = p(), B = h(k); if (!e || !B) return u(); let R = new Image(); R.crossOrigin = "Anonymous", R.src = e, R.onload = () => { k.width = R.width, k.height = R.height, B.drawImage(R, 0, 0, k.width, k.height); let z = B.getImageData(0, 0, k.width, k.height); c.height = k.height, c.width = k.width, C(se(z.data, c)); }; }); throw new Error("Input data provided is not supported - aborted tensor creation"); } if (a !== void 0) return se(a, c); throw new Error("Input data provided is not supported - aborted tensor creation"); }, pe = (e, t) => { let { width: s, height: n, download: o, dispose: i } = t, a = [1, n, s, 4]; return new We({ location: "texture", type: "float32", texture: e, dims: a, download: o, dispose: i }); }, Ce = (e, t) => { let { dataType: s, dims: n, download: o, dispose: i } = t; return new We({ location: "gpu-buffer", type: s ?? "float32", gpuBuffer: e, dims: n, download: o, dispose: i }); }, $e = (e, t) => { let { dataType: s, dims: n, download: o, dispose: i } = t; return new We({ location: "ml-tensor", type: s ?? "float32", mlTensor: e, dims: n, download: o, dispose: i }); }, Pe = (e, t, s) => new We({ location: "cpu-pinned", type: e, data: t, dims: s ?? [t.length] }); }), Ue, we, X, de, Ee = y(() => { Ue = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array], ["int4", Uint8Array], ["uint4", Uint8Array]]), we = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), X = !1, de = () => { if (!X) { X = !0; let e = typeof BigInt64Array < "u" && BigInt64Array.from, t = typeof BigUint64Array < "u" && BigUint64Array.from, s = typeof Float16Array < "u" && Float16Array.from; e && (Ue.set("int64", BigInt64Array), we.set(BigInt64Array, "int64")), t && (Ue.set("uint64", BigUint64Array), we.set(BigUint64Array, "uint64")), s ? (Ue.set("float16", Float16Array), we.set(Float16Array, "float16")) : Ue.set("float16", Uint16Array); } }; }), Oe, Xe, J = y(() => { Ne(), Oe = (e) => { let t = 1; for (let s = 0; s < e.length; s++) { let n = e[s]; if (typeof n != "number" || !Number.isSafeInteger(n)) throw new TypeError(`dims[${s}] must be an integer, got: ${n}`); if (n < 0) throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${n}`); t *= n; } return t; }, Xe = (e, t) => { switch (e.location) { case "cpu": return new We(e.type, e.data, t); case "cpu-pinned": return new We({ location: "cpu-pinned", data: e.data, type: e.type, dims: t }); case "texture": return new We({ location: "texture", texture: e.texture, type: e.type, dims: t }); case "gpu-buffer": return new We({ location: "gpu-buffer", gpuBuffer: e.gpuBuffer, type: e.type, dims: t }); case "ml-tensor": return new We({ location: "ml-tensor", mlTensor: e.mlTensor, type: e.type, dims: t }); default: throw new Error(`tensorReshape: tensor location ${e.location} is not supported`); } }; }), We, Ne = y(() => { ge(), Je(), Ee(), J(), We = class { constructor(e, t, s) { de(); let n, o; if (typeof e == "object" && "location" in e) switch (this.dataLocation = e.location, n = e.type, o = e.dims, e.location) { case "cpu-pinned": { let a = Ue.get(n); if (!a) throw new TypeError(`unsupported type "${n}" 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 (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" && n !== "uint4" && n !== "int4") 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; } case "ml-tensor": { if (n !== "float32" && n !== "float16" && n !== "int32" && n !== "int64" && n !== "uint32" && n !== "uint64" && n !== "int8" && n !== "uint8" && n !== "bool" && n !== "uint4" && n !== "int4") throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`); this.mlTensorData = e.mlTensor, this.downloader = e.download, this.disposer = e.dispose; break; } default: throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); } else { let a, c; if (typeof e == "string") if (n = e, c = s, e === "string") { if (!Array.isArray(t)) throw new TypeError("A string tensor's data must be a string array."); a = t; } else { let p = Ue.get(e); if (p === void 0) throw new TypeError(`Unsupported tensor type: ${e}.`); if (Array.isArray(t)) { if (e === "float16" && p === Uint16Array || e === "uint4" || e === "int4") throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`); e === "uint64" || e === "int64" ? a = p.from(t, BigInt) : a = p.from(t); } else if (t instanceof p) a = t; else if (t instanceof Uint8ClampedArray) if (e === "uint8") a = Uint8Array.from(t); else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8"); else throw new TypeError(`A ${n} tensor's data must be type of ${p}`); } else if (c = t, Array.isArray(e)) { if (e.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); let p = typeof e[0]; if (p === "string") n = "string", a = e; else if (p === "boolean") n = "bool", a = Uint8Array.from(e); else throw new TypeError(`Invalid element type of data array: ${p}.`); } else if (e instanceof Uint8ClampedArray) n = "uint8", a = Uint8Array.from(e); else { let p = we.get(e.constructor); if (p === void 0) throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`); n = p, a = e; } if (c === void 0) c = [a.length]; else if (!Array.isArray(c)) throw new TypeError("A tensor's dims must be a number array"); o = c, this.cpuData = a, this.dataLocation = "cpu"; } let i = Oe(o); if (this.cpuData && i !== this.cpuData.length && !((n === "uint4" || n === "int4") && Math.ceil(i / 2) === this.cpuData.length)) throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`); this.type = n, this.dims = o, this.size = i; } static async fromImage(e, t) { return be(e, t); } static fromTexture(e, t) { return pe(e, t); } static fromGpuBuffer(e, t) { return Ce(e, t); } static fromMLTensor(e, t) { return $e(e, t); } static fromPinnedBuffer(e, t, s) { return Pe(e, t, s); } toDataURL(e) { return oe(this, e); } toImageData(e) { return ye(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; } get mlTensor() { if (this.ensureValid(), !this.mlTensorData) throw new Error("The data is not stored as a WebNN MLTensor."); return this.mlTensorData; } async getData(e) { switch (this.ensureValid(), this.dataLocation) { case "cpu": case "cpu-pinned": return this.data; case "texture": case "gpu-buffer": case "ml-tensor": { 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 = !0; let t = await this.downloader(); return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = t, e && this.disposer && (this.disposer(), this.disposer = void 0), t; } finally { this.isDownloading = !1; } } 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.mlTensorData = 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 Xe(this, e); } }; }), te, ve = y(() => { Ne(), te = We; }), He, je, Ve, Re, Ze = y(() => { P(), He = (e, t) => { (typeof w.trace > "u" ? !w.wasm.trace : !w.trace) || console.timeStamp(`${e}::ORT::${t}`); }, je = (e, t) => { let s = new Error().stack?.split(/\r\n|\r|\n/g) || [], n = !1; for (let o = 0; o < s.length; o++) { if (n && !s[o].includes("TRACE_FUNC")) { let i = `FUNC_${e}::${s[o].trim().split(" ")[1]}`; t && (i += `::${t}`), He("CPU", i); return; } s[o].includes("TRACE_FUNC") && (n = !0); } }, Ve = (e) => { (typeof w.trace > "u" ? !w.wasm.trace : !w.trace) || je("BEGIN", e); }, Re = (e) => { (typeof w.trace > "u" ? !w.wasm.trace : !w.trace) || je("END", e); }; }), at, _t = y(() => { V(), ve(), Ze(), at = class Ym { constructor(t) { this.handler = t; } async run(t, s, n) { Ve(); let o = {}, i = {}; if (typeof t != "object" || t === null || t instanceof te || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); let a = !0; if (typeof s == "object") { if (s === null) throw new TypeError("Unexpected argument[1]: cannot be null."); if (s instanceof te) throw new TypeError("'fetches' cannot be a Tensor"); if (Array.isArray(s)) { if (s.length === 0) throw new TypeError("'fetches' cannot be an empty array."); a = !1; for (let h of s) { if (typeof h != "string") throw new TypeError("'fetches' must be a string array or an object."); if (this.outputNames.indexOf(h) === -1) throw new RangeError(`'fetches' contains invalid output name: ${h}.`); o[h] = null; } if (typeof n == "object" && n !== null) i = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else { let h = !1, C = Object.getOwnPropertyNames(s); for (let u of this.outputNames) if (C.indexOf(u) !== -1) { let k = s[u]; (k === null || k instanceof te) && (h = !0, a = !1, o[u] = k); } if (h) { if (typeof n == "object" && n !== null) i = n; else if (typeof n < "u") throw new TypeError("'options' must be an object."); } else i = s; } } else if (typeof s < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); for (let h of this.inputNames) if (typeof t[h] > "u") throw new Error(`input '${h}' is missing in 'feeds'.`); if (a) for (let h of this.outputNames) o[h] = null; let c = await this.handler.run(t, o, i), p = {}; for (let h in c) if (Object.hasOwnProperty.call(c, h)) { let C = c[h]; C instanceof te ? p[h] = C : p[h] = new te(C.type, C.data, C.dims); } return Re(), p; } async release() { return this.handler.dispose(); } static async create(t, s, n, o) { Ve(); let i, a = {}; if (typeof t == "string") { if (i = t, typeof s == "object" && s !== null) a = s; else if (typeof s < "u") throw new TypeError("'options' must be an object."); } else if (t instanceof Uint8Array) { if (i = t, typeof s == "object" && s !== null) a = s; else if (typeof s < "u") throw new TypeError("'options' must be an object."); } else if (t instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && t instanceof SharedArrayBuffer) { let C = t, u = 0, k = t.byteLength; if (typeof s == "object" && s !== null) a = s; else if (typeof s == "number") { if (u = s, !Number.isSafeInteger(u)) throw new RangeError("'byteOffset' must be an integer."); if (u < 0 || u >= C.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${C.byteLength}).`); if (k = t.byteLength - u, typeof n == "number") { if (k = n, !Number.isSafeInteger(k)) throw new RangeError("'byteLength' must be an integer."); if (k <= 0 || u + k > C.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${C.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 s < "u") throw new TypeError("'options' must be an object."); i = new Uint8Array(C, u, k); } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); let [c, p] = await ie(a), h = await c.createInferenceSessionHandler(i, p); return Re(), new Ym(h); } startProfiling() { this.handler.startProfiling(); } endProfiling() { this.handler.endProfiling(); } get inputNames() { return this.handler.inputNames; } get outputNames() { return this.handler.outputNames; } }; }), lt, ct = y(() => { _t(), lt = at; }), F = y(() => { }), ae = y(() => { }), H = y(() => { }), me = y(() => { }), ke = {}; T(ke, { InferenceSession: () => lt, TRACE: () => He, TRACE_FUNC_BEGIN: () => Ve, TRACE_FUNC_END: () => Re, Tensor: () => te, env: () => I, registerBackend: () => K }); var ze = y(() => { U(), le(), ct(), ve(), F(), ae(), Ze(), H(), me(); }), Ge = y(() => { }), tt = {}; T(tt, { default: () => Nt }); var et, mt, Nt, es = y(() => { fh(), Mr(), Dr(), et = "ort-wasm-proxy-worker", mt = globalThis.self?.name === et, mt && (self.onmessage = (e) => { let { type: t, in: s } = e.data; try { switch (t) { case "init-wasm": cn(s.wasm).then(() => { Kn(s).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 } = s; So(o, n).then(() => { postMessage({ type: t }); }, (i) => { postMessage({ type: t, err: i }); }); break; } case "copy-from": { let { buffer: n } = s, o = bn(n); postMessage({ type: t, out: o }); break; } case "create": { let { model: n, options: o } = s; Jd(n, o).then((i) => { postMessage({ type: t, out: i }); }, (i) => { postMessage({ type: t, err: i }); }); break; } case "release": Zd(s), postMessage({ type: t }); break; case "run": { let { sessionId: n, inputIndices: o, inputs: i, outputIndices: a, options: c } = s; Wr(n, o, i, a, new Array(a.length).fill(null), c).then((p) => { p.some((h) => h[3] !== "cpu") ? postMessage({ type: t, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: t, out: p }, Vp([...i, ...p])); }, (p) => { postMessage({ type: t, err: p }); }); break; } case "end-profiling": cr(s), postMessage({ type: t }); break; default: } } catch (n) { postMessage({ type: t, err: n }); } }), Nt = mt ? null : (e) => new Worker(e ?? Vs, { type: "module", name: et }); }), Ts = {}; T(Ts, { default: () => Is }); var ms, Ps, Is, tr = y(() => { Ps = (ms = import.meta.url, async function(e = {}) { function t() { return zt.buffer != Yt.buffer && ys(), Yt; } function s() { return zt.buffer != Yt.buffer && ys(), os; } function n() { return zt.buffer != Yt.buffer && ys(), Vt; } function o() { return zt.buffer != Yt.buffer && ys(), As; } function i() { return zt.buffer != Yt.buffer && ys(), ut; } function a() { return zt.buffer != Yt.buffer && ys(), xt; } function c() { return zt.buffer != Yt.buffer && ys(), hs; } function p() { return zt.buffer != Yt.buffer && ys(), vn; } var h, C, u = Object.assign({}, e), k = new Promise((l, m) => { h = l, C = m; }), B = typeof window == "object", R = typeof importScripts == "function", z = R && self.name == "em-pthread"; u.mountExternalData = (l, m) => { l.startsWith("./") && (l = l.substring(2)), (u.Fb || (u.Fb = /* @__PURE__ */ new Map())).set(l, m); }, u.unmountExternalData = () => { delete u.Fb; }; var ne = globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, shared: !0 }).buffer.constructor; let Z = () => { let l = (E, D, G) => (...fe) => { let Qe = un, st = D?.(); fe = E(...fe); let bt = D?.(); return st !== bt && (E = bt, G(st), D = G = null), un != Qe ? new Promise((Ct, Rt) => { lh = { resolve: Ct, reject: Rt }; }) : fe; }, m = (E) => async (...D) => { try { if (u.Gb) throw Error("Session already started"); let G = u.Gb = { hc: D[0], errors: [] }, fe = await E(...D); if (u.Gb !== G) throw Error("Session mismatch"); u.Hb?.flush(); let Qe = G.errors; if (0 < Qe.length) { let st = await Promise.all(Qe); if (st = st.filter((bt) => bt), 0 < st.length) throw Error(st.join(` `)); } return fe; } finally { u.Gb = null; } }; u._OrtCreateSession = l(u._OrtCreateSession, () => u._OrtCreateSession, (E) => u._OrtCreateSession = E), u._OrtRun = m(l(u._OrtRun, () => u._OrtRun, (E) => u._OrtRun = E)), u._OrtRunWithBinding = m(l(u._OrtRunWithBinding, () => u._OrtRunWithBinding, (E) => u._OrtRunWithBinding = E)), u._OrtBindInput = l(u._OrtBindInput, () => u._OrtBindInput, (E) => u._OrtBindInput = E), Z = void 0; }; u.jsepInit = (l, m) => { if (Z?.(), l === "webgpu") { [u.Hb, u.Vb, u.Zb, u.Ob, u.Yb, u.kb, u.$b, u.cc, u.Wb, u.Xb, u.ac] = m; let E = u.Hb; u.jsepRegisterBuffer = (D, G, fe, Qe) => E.registerBuffer(D, G, fe, Qe), u.jsepGetBuffer = (D) => E.getBuffer(D), u.jsepCreateDownloader = (D, G, fe) => E.createDownloader(D, G, fe), u.jsepOnCreateSession = (D) => { E.onCreateSession(D); }, u.jsepOnReleaseSession = (D) => { E.onReleaseSession(D); }, u.jsepOnRunStart = (D) => E.onRunStart(D), u.dc = (D, G) => { E.upload(D, G); }; } else if (l === "webnn") { [u.Hb, u.bc, u.Pb, u.jsepEnsureTensor, u.ec, u.jsepDownloadTensor] = m, u.jsepReleaseTensorId = u.Pb; let E = u.Hb; u.jsepOnRunStart = (D) => E.onRunStart(D), u.jsepRegisterMLContext = (D, G) => { E.registerMLContext(D, G); }, u.jsepOnReleaseSession = (D) => { E.onReleaseSession(D); }, u.jsepCreateMLTensorDownloader = (D, G) => E.createMLTensorDownloader(D, G), u.jsepRegisterMLTensor = (D, G, fe) => E.registerMLTensor(D, G, fe), u.jsepCreateMLContext = (D) => E.createMLContext(D), u.jsepRegisterMLConstant = (D, G, fe, Qe, st) => E.registerMLConstant(D, G, fe, Qe, st, u.Fb); } }; var W, ue, he = Object.assign({}, u), Me = (l, m) => { throw m; }, Le = ""; (B || R) && (R ? Le = self.location.href : typeof document < "u" && document.currentScript && (Le = document.currentScript.src), ms && (Le = ms), Le = Le.startsWith("blob:") ? "" : Le.substr(0, Le.replace(/[?#].*/, "").lastIndexOf("/") + 1), R && (ue = (l) => { var m = new XMLHttpRequest(); return m.open("GET", l, !1), m.responseType = "arraybuffer", m.send(null), new Uint8Array(m.response); }), W = (l, m, E) => { var D = new XMLHttpRequest(); D.open("GET", l, !0), D.responseType = "arraybuffer", D.onload = () => { D.status == 200 || D.status == 0 && D.response ? m(D.response) : E(); }, D.onerror = E, D.send(null); }); var Ae, it = console.log.bind(console), dt = console.error.bind(console), kt = it, Et = dt; if (Object.assign(u, he), he = null, z) { let l = function(m) { try { var E = m.data, D = E.cmd; if (D === "load") { let G = []; self.onmessage = (fe) => G.push(fe), self.startWorker = () => { postMessage({ cmd: "loaded" }); for (let fe of G) l(fe); self.onmessage = l; }; for (let fe of E.handlers) u[fe] && !u[fe].proxy || (u[fe] = (...Qe) => { postMessage({ Nb: "callHandler", pc: fe, args: Qe }); }, fe == "print" && (kt = u[fe]), fe == "printErr" && (Et = u[fe])); zt = E.wasmMemory, ys(), Ut(E.wasmModule); } else if (D === "run") { ph(E.pthread_ptr, 0, 0, 1, 0, 0), ih(E.pthread_ptr), o_(), Nh(), pt || (zm(), pt = !0); try { i_(E.start_routine, E.arg); } catch (G) { if (G != "unwind") throw G; } } else D === "cancel" ? Ca() && Ip(-1) : E.target !== "setimmediate" && (D === "checkMailbox" ? pt && vp() : D && (Et(`worker: received unknown command ${D}`), Et(E))); } catch (G) { throw Bm(), G; } }; var Ut, pt = !1; Et = function(...m) { m = m.join(" "), console.error(m); }, self.alert = function(...m) { postMessage({ Nb: "alert", text: m.join(" "), rc: Ca() }); }, u.instantiateWasm = (m, E) => new Promise((D) => { Ut = (G) => { G = new WebAssembly.Instance(G, Dh()), E(G), D(); }; }), self.onunhandledrejection = (m) => { throw m.reason || m; }, self.onmessage = l; } u.wasmBinary && (Ae = u.wasmBinary); var zt, ns, Tt, Yt, os, Vt, As, ut, xt, hs, cs, Js, vn, Ds = !1; function ys() { var l = zt.buffer; u.HEAP8 = Yt = new Int8Array(l), u.HEAP16 = Vt = new Int16Array(l), u.HEAPU8 = os = new Uint8Array(l), u.HEAPU16 = As = new Uint16Array(l), u.HEAP32 = ut = new Int32Array(l), u.HEAPU32 = xt = new Uint32Array(l), u.HEAPF32 = hs = new Float32Array(l), u.HEAPF64 = vn = new Float64Array(l), u.HEAP64 = cs = new BigInt64Array(l), u.HEAPU64 = Js = new BigUint64Array(l); } if (!z) { if (!((zt = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: !0 })).buffer instanceof ne)) throw Et("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"); ys(); } var qn = [], rc = [], Hp = [], nc = 0, oc = null; function $h() { if (--nc == 0 && oc) { var l = oc; oc = null, l(); } } function Qn(l) { throw Et(l = "Aborted(" + l + ")"), Ds = !0, Tt = 1, l = new WebAssembly.RuntimeError(l + ". Build with -sASSERTIONS for more info."), C(l), l; } var qp, Ah = (l) => l.startsWith("data:application/octet-stream;base64,"), Ih = (l) => l.startsWith("file://"); function Fh(l) { if (l == qp && Ae) return new Uint8Array(Ae); if (ue) return ue(l); throw "both async and sync fetching of the wasm failed"; } function Oh(l, m, E) { return function(D) { if (!Ae && (B || R)) { if (typeof fetch == "function" && !Ih(D)) return fetch(D, { credentials: "same-origin" }).then((G) => { if (!G.ok) throw `failed to load wasm binary file at '${D}'`; return G.arrayBuffer(); }).catch(() => Fh(D)); if (W) return new Promise((G, fe) => { W(D, (Qe) => G(new Uint8Array(Qe)), fe); }); } return Promise.resolve().then(() => Fh(D)); }(l).then((D) => WebAssembly.instantiate(D, m)).then(E, (D) => { Et(`failed to asynchronously prepare wasm: ${D}`), Qn(D); }); } function Dh() { return { a: { O: n_, Aa: r_, b: l_, aa: Wh, B: Hh, qa: qh, Y: Xh, _: Yh, ra: Jh, oa: Zh, ha: em, na: tm, L: sm, Z: rm, W: nm, pa: om, X: im, va: u_, F: d_, Q: c_, P: h_, E: __, u: f_, q: g_, G: w_, A: P_, R: E_, ua: C_, ka: k_, U: S_, ba: $_, H: A_, ja: ih, ta: I_, t: F_, Ba: O_, x: z_, o: B_, m: N_, c: nh, n: j_, k: W_, w: G_, p: K_, f: H_, s: q_, l: Q_, e: X_, j: Y_, i: J_, g: Z_, d: ef, ea: tf, fa: sf, ga: rf, ca: Mm, da: bm, T: nf, h: of, D: af, I: lf, M: uf, y: df, sa: cf, V: pf, v: xm, z: hf, N: mf, S: _f, za: ff, ya: gf, la: Em, ma: Cm, $: Zp, C: km, K: Sm, ia: $m, J: Am, a: zt, xa: Jp, wa: Om, r: Mf } }; } var Qp = { 916868: (l, m, E, D, G) => { if (u === void 0 || !u.Fb) return 1; if ((l = Gs(Number(l >>> 0))).startsWith("./") && (l = l.substring(2)), !(l = u.Fb.get(l))) return 2; if (m = Number(m >>> 0), E = Number(E >>> 0), D = Number(D >>> 0), m + E > l.byteLength) return 3; try { let fe = l.subarray(m, m + E); switch (G) { case 0: s().set(fe, D >>> 0); break; case 1: u.dc(D, fe); break; default: return 4; } return 0; } catch { return 4; } }, 917583: (l, m, E) => { u.ec(l, s().subarray(m >>> 0, m + E >>> 0)); }, 917646: () => u.bc(), 917687: (l) => { u.Pb(l); }, 917723: () => { u.Wb(); }, 917754: () => { u.Xb(); }, 917783: () => { u.ac(); }, 917808: (l) => u.Vb(l), 917841: (l) => u.Zb(l), 917873: (l, m, E) => { u.Ob(Number(l), Number(m), Number(E), !0); }, 917936: (l, m, E) => { u.Ob(Number(l), Number(m), Number(E)); }, 917993: () => typeof wasmOffsetConverter < "u", 918050: (l) => { u.kb("Abs", l, void 0); }, 918101: (l) => { u.kb("Neg", l, void 0); }, 918152: (l) => { u.kb("Floor", l, void 0); }, 918205: (l) => { u.kb("Ceil", l, void 0); }, 918257: (l) => { u.kb("Reciprocal", l, void 0); }, 918315: (l) => { u.kb("Sqrt", l, void 0); }, 918367: (l) => { u.kb("Exp", l, void 0); }, 918418: (l) => { u.kb("Erf", l, void 0); }, 918469: (l) => { u.kb("Sigmoid", l, void 0); }, 918524: (l, m, E) => { u.kb("HardSigmoid", l, { alpha: m, beta: E }); }, 918603: (l) => { u.kb("Log", l, void 0); }, 918654: (l) => { u.kb("Sin", l, void 0); }, 918705: (l) => { u.kb("Cos", l, void 0); }, 918756: (l) => { u.kb("Tan", l, void 0); }, 918807: (l) => { u.kb("Asin", l, void 0); }, 918859: (l) => { u.kb("Acos", l, void 0); }, 918911: (l) => { u.kb("Atan", l, void 0); }, 918963: (l) => { u.kb("Sinh", l, void 0); }, 919015: (l) => { u.kb("Cosh", l, void 0); }, 919067: (l) => { u.kb("Asinh", l, void 0); }, 919120: (l) => { u.kb("Acosh", l, void 0); }, 919173: (l) => { u.kb("Atanh", l, void 0); }, 919226: (l) => { u.kb("Tanh", l, void 0); }, 919278: (l) => { u.kb("Not", l, void 0); }, 919329: (l, m, E) => { u.kb("Clip", l, { min: m, max: E }); }, 919398: (l) => { u.kb("Clip", l, void 0); }, 919450: (l, m) => { u.kb("Elu", l, { alpha: m }); }, 919508: (l) => { u.kb("Gelu", l, void 0); }, 919560: (l) => { u.kb("Relu", l, void 0); }, 919612: (l, m) => { u.kb("LeakyRelu", l, { alpha: m }); }, 919676: (l, m) => { u.kb("ThresholdedRelu", l, { alpha: m }); }, 919746: (l, m) => { u.kb("Cast", l, { to: m }); }, 919804: (l) => { u.kb("Add", l, void 0); }, 919855: (l) => { u.kb("Sub", l, void 0); }, 919906: (l) => { u.kb("Mul", l, void 0); }, 919957: (l) => { u.kb("Div", l, void 0); }, 920008: (l) => { u.kb("Pow", l, void 0); }, 920059: (l) => { u.kb("Equal", l, void 0); }, 920112: (l) => { u.kb("Greater", l, void 0); }, 920167: (l) => { u.kb("GreaterOrEqual", l, void 0); }, 920229: (l) => { u.kb("Less", l, void 0); }, 920281: (l) => { u.kb("LessOrEqual", l, void 0); }, 920340: (l, m, E, D, G) => { u.kb("ReduceMean", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 920515: (l, m, E, D, G) => { u.kb("ReduceMax", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 920689: (l, m, E, D, G) => { u.kb("ReduceMin", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 920863: (l, m, E, D, G) => { u.kb("ReduceProd", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921038: (l, m, E, D, G) => { u.kb("ReduceSum", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921212: (l, m, E, D, G) => { u.kb("ReduceL1", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921385: (l, m, E, D, G) => { u.kb("ReduceL2", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921558: (l, m, E, D, G) => { u.kb("ReduceLogSum", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921735: (l, m, E, D, G) => { u.kb("ReduceSumSquare", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 921915: (l, m, E, D, G) => { u.kb("ReduceLogSumExp", l, { keepDims: !!m, noopWithEmptyAxes: !!E, axes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 922095: (l) => { u.kb("Where", l, void 0); }, 922148: (l, m, E) => { u.kb("Transpose", l, { perm: m ? Array.from(i().subarray(Number(m) >>> 0, Number(E) >>> 0)) : [] }); }, 922272: (l, m, E, D) => { u.kb("DepthToSpace", l, { blocksize: m, mode: Gs(E), format: D ? "NHWC" : "NCHW" }); }, 922405: (l, m, E, D) => { u.kb("DepthToSpace", l, { blocksize: m, mode: Gs(E), format: D ? "NHWC" : "NCHW" }); }, 922538: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke, is) => { u.kb("ConvTranspose", l, { format: bt ? "NHWC" : "NCHW", autoPad: m, dilations: [E], group: D, kernelShape: [G], pads: [fe, Qe], strides: [st], wIsConst: () => !!t()[Ct >>> 0], outputPadding: Rt ? Array.from(i().subarray(Number(Rt) >>> 0, Number(us) >>> 0)) : [], outputShape: gs ? Array.from(i().subarray(Number(gs) >>> 0, Number(Ke) >>> 0)) : [], activation: Gs(is) }); }, 922971: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("ConvTranspose", l, { format: st ? "NHWC" : "NCHW", autoPad: m, dilations: Array.from(i().subarray(Number(E) >>> 0, 2 + (Number(E) >>> 0) >>> 0)), group: D, kernelShape: Array.from(i().subarray(Number(G) >>> 0, 2 + (Number(G) >>> 0) >>> 0)), pads: Array.from(i().subarray(Number(fe) >>> 0, 4 + (Number(fe) >>> 0) >>> 0)), strides: Array.from(i().subarray(Number(Qe) >>> 0, 2 + (Number(Qe) >>> 0) >>> 0)), wIsConst: () => !!t()[bt >>> 0], outputPadding: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], outputShape: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [], activation: Gs(Ke) }); }, 923632: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke, is) => { u.kb("ConvTranspose", l, { format: bt ? "NHWC" : "NCHW", autoPad: m, dilations: [E], group: D, kernelShape: [G], pads: [fe, Qe], strides: [st], wIsConst: () => !!t()[Ct >>> 0], outputPadding: Rt ? Array.from(i().subarray(Number(Rt) >>> 0, Number(us) >>> 0)) : [], outputShape: gs ? Array.from(i().subarray(Number(gs) >>> 0, Number(Ke) >>> 0)) : [], activation: Gs(is) }); }, 924065: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("ConvTranspose", l, { format: st ? "NHWC" : "NCHW", autoPad: m, dilations: Array.from(i().subarray(Number(E) >>> 0, 2 + (Number(E) >>> 0) >>> 0)), group: D, kernelShape: Array.from(i().subarray(Number(G) >>> 0, 2 + (Number(G) >>> 0) >>> 0)), pads: Array.from(i().subarray(Number(fe) >>> 0, 4 + (Number(fe) >>> 0) >>> 0)), strides: Array.from(i().subarray(Number(Qe) >>> 0, 2 + (Number(Qe) >>> 0) >>> 0)), wIsConst: () => !!t()[bt >>> 0], outputPadding: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], outputShape: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [], activation: Gs(Ke) }); }, 924726: (l, m) => { u.kb("GlobalAveragePool", l, { format: m ? "NHWC" : "NCHW" }); }, 924817: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("AveragePool", l, { format: Ke ? "NHWC" : "NCHW", auto_pad: m, ceil_mode: E, count_include_pad: D, storage_order: G, dilations: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [], kernel_shape: st ? Array.from(i().subarray(Number(st) >>> 0, Number(bt) >>> 0)) : [], pads: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], strides: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [] }); }, 925296: (l, m) => { u.kb("GlobalAveragePool", l, { format: m ? "NHWC" : "NCHW" }); }, 925387: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("AveragePool", l, { format: Ke ? "NHWC" : "NCHW", auto_pad: m, ceil_mode: E, count_include_pad: D, storage_order: G, dilations: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [], kernel_shape: st ? Array.from(i().subarray(Number(st) >>> 0, Number(bt) >>> 0)) : [], pads: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], strides: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [] }); }, 925866: (l, m) => { u.kb("GlobalMaxPool", l, { format: m ? "NHWC" : "NCHW" }); }, 925953: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("MaxPool", l, { format: Ke ? "NHWC" : "NCHW", auto_pad: m, ceil_mode: E, count_include_pad: D, storage_order: G, dilations: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [], kernel_shape: st ? Array.from(i().subarray(Number(st) >>> 0, Number(bt) >>> 0)) : [], pads: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], strides: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [] }); }, 926428: (l, m) => { u.kb("GlobalMaxPool", l, { format: m ? "NHWC" : "NCHW" }); }, 926515: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke) => { u.kb("MaxPool", l, { format: Ke ? "NHWC" : "NCHW", auto_pad: m, ceil_mode: E, count_include_pad: D, storage_order: G, dilations: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [], kernel_shape: st ? Array.from(i().subarray(Number(st) >>> 0, Number(bt) >>> 0)) : [], pads: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], strides: us ? Array.from(i().subarray(Number(us) >>> 0, Number(gs) >>> 0)) : [] }); }, 926990: (l, m, E, D, G) => { u.kb("Gemm", l, { alpha: m, beta: E, transA: D, transB: G }); }, 927094: (l) => { u.kb("MatMul", l, void 0); }, 927148: (l, m, E, D) => { u.kb("ArgMax", l, { keepDims: !!m, selectLastIndex: !!E, axis: D }); }, 927256: (l, m, E, D) => { u.kb("ArgMin", l, { keepDims: !!m, selectLastIndex: !!E, axis: D }); }, 927364: (l, m) => { u.kb("Softmax", l, { axis: m }); }, 927427: (l, m) => { u.kb("Concat", l, { axis: m }); }, 927487: (l, m, E, D, G) => { u.kb("Split", l, { axis: m, numOutputs: E, splitSizes: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 927643: (l) => { u.kb("Expand", l, void 0); }, 927697: (l, m) => { u.kb("Gather", l, { axis: Number(m) }); }, 927768: (l, m) => { u.kb("GatherElements", l, { axis: Number(m) }); }, 927847: (l, m) => { u.kb("GatherND", l, { batch_dims: Number(m) }); }, 927926: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt) => { u.kb("Resize", l, { antialias: m, axes: E ? Array.from(i().subarray(Number(E) >>> 0, Number(D) >>> 0)) : [], coordinateTransformMode: Gs(G), cubicCoeffA: fe, excludeOutside: Qe, extrapolationValue: st, keepAspectRatioPolicy: Gs(bt), mode: Gs(Ct), nearestMode: Gs(Rt) }); }, 928288: (l, m, E, D, G, fe, Qe) => { u.kb("Slice", l, { starts: m ? Array.from(i().subarray(Number(m) >>> 0, Number(E) >>> 0)) : [], ends: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [], axes: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [] }); }, 928552: (l) => { u.kb("Tile", l, void 0); }, 928604: (l, m, E) => { u.kb("InstanceNormalization", l, { epsilon: m, format: E ? "NHWC" : "NCHW" }); }, 928718: (l, m, E) => { u.kb("InstanceNormalization", l, { epsilon: m, format: E ? "NHWC" : "NCHW" }); }, 928832: (l) => { u.kb("Range", l, void 0); }, 928885: (l, m) => { u.kb("Einsum", l, { equation: Gs(m) }); }, 928966: (l, m, E, D, G) => { u.kb("Pad", l, { mode: m, value: E, pads: D ? Array.from(i().subarray(Number(D) >>> 0, Number(G) >>> 0)) : [] }); }, 929109: (l, m, E, D, G, fe) => { u.kb("BatchNormalization", l, { epsilon: m, momentum: E, spatial: !!G, trainingMode: !!D, format: fe ? "NHWC" : "NCHW" }); }, 929278: (l, m, E, D, G, fe) => { u.kb("BatchNormalization", l, { epsilon: m, momentum: E, spatial: !!G, trainingMode: !!D, format: fe ? "NHWC" : "NCHW" }); }, 929447: (l, m, E) => { u.kb("CumSum", l, { exclusive: Number(m), reverse: Number(E) }); }, 929544: (l, m, E) => { u.kb("DequantizeLinear", l, { axis: m, blockSize: E }); }, 929634: (l, m, E, D, G) => { u.kb("GridSample", l, { align_corners: m, mode: Gs(E), padding_mode: Gs(D), format: G ? "NHWC" : "NCHW" }); }, 929804: (l, m, E, D, G) => { u.kb("GridSample", l, { align_corners: m, mode: Gs(E), padding_mode: Gs(D), format: G ? "NHWC" : "NCHW" }); }, 929974: (l, m, E, D, G, fe, Qe, st, bt) => { u.kb("Attention", l, { numHeads: m, isUnidirectional: E, maskFilterValue: D, scale: G, doRotary: fe, qkvHiddenSizes: Qe ? Array.from(i().subarray(Number(st) >>> 0, Number(st) + Qe >>> 0)) : [], pastPresentShareBuffer: !!bt }); }, 930246: (l) => { u.kb("BiasAdd", l, void 0); }, 930301: (l) => { u.kb("BiasSplitGelu", l, void 0); }, 930362: (l) => { u.kb("FastGelu", l, void 0); }, 930418: (l, m, E, D, G, fe, Qe, st, bt, Ct, Rt, us, gs, Ke, is, js) => { u.kb("Conv", l, { format: us ? "NHWC" : "NCHW", auto_pad: m, dilations: E ? Array.from(i().subarray(Number(E) >>> 0, Number(D) >>> 0)) : [], group: G, kernel_shape: fe ? Array.from(i().subarray(Number(fe) >>> 0, Number(Qe) >>> 0)) : [], pads: st ? Array.from(i().subarray(Number(st) >>> 0, Number(bt) >>> 0)) : [], strides: Ct ? Array.from(i().subarray(Number(Ct) >>> 0, Number(Rt) >>> 0)) : [], w_is_const: () => !!t()[Number(gs) >>> 0], activation: Gs(Ke), activation_params: is ? Array.from(c().subarray(Number(is) >>> 0, Number(js) >>> 0)) : [] }); }, 931002: (l) => { u.kb("Gelu", l, void 0); }, 931054: (l, m, E, D, G, fe, Qe, st, bt) => { u.kb("GroupQueryAttention", l, { numHeads: m, kvNumHeads: E, scale: D, softcap: G, doRotary: fe, rotaryInterleaved: Qe, smoothSoftmax: st, localWindowSize: bt }); }, 931271: (l, m, E, D) => { u.kb("LayerNormalization", l, { axis: m, epsilon: E, simplified: !!D }); }, 931382: (l, m, E, D) => { u.kb("LayerNormalization", l, { axis: m, epsilon: E, simplified: !!D }); }, 931493: (l, m, E, D, G, fe) => { u.kb("MatMulNBits", l, { k: m, n: E, accuracyLevel: D, bits: G, blockSize: fe }); }, 931620: (l, m, E, D, G, fe) => { u.kb("MultiHeadAttention", l, { numHeads: m, isUnidirectional: E, maskFilterValue: D, scale: G, doRotary: fe }); }, 931779: (l, m) => { u.kb("QuickGelu", l, { alpha: m }); }, 931843: (l, m, E, D, G) => { u.kb("RotaryEmbedding", l, { interleaved: !!m, numHeads: E, rotaryEmbeddingDim: D, scale: G }); }, 931982: (l, m, E) => { u.kb("SkipLayerNormalization", l, { epsilon: m, simplified: !!E }); }, 932084: (l, m, E) => { u.kb("SkipLayerNormalization", l, { epsilon: m, simplified: !!E }); }, 932186: (l, m, E, D) => { u.kb("GatherBlockQuantized", l, { gatherAxis: m, quantizeAxis: E, blockSize: D }); }, 932307: (l) => { u.$b(l); }, 932341: (l, m) => u.cc(Number(l), Number(m), u.Gb.hc, u.Gb.errors) }; function r_(l, m, E) { return _m(async () => { await u.Yb(Number(l), Number(m), Number(E)); }); } function n_() { return typeof wasmOffsetConverter < "u"; } function Xp(l) { this.name = "ExitStatus", this.message = `Program terminated with exit(${l})`, this.status = l; } var Yp = (l) => { l.terminate(), l.onmessage = () => { }; }, Lh = (l) => { Xn.length == 0 && (Vh(), jh(Xn[0])); var m = Xn.pop(); if (!m) return 6; Fo.push(m), an[l.Bb] = m, m.Bb = l.Bb; var E = { cmd: "run", start_routine: l.ic, arg: l.Rb, pthread_ptr: l.Bb }; return m.postMessage(E, l.nc), 0; }, Io = 0, Ls = (l, m, ...E) => { for (var D = 2 * E.length, G = _h(), fe = mh(8 * D), Qe = fe >>> 3, st = 0; st < E.length; st++) { var bt = E[st]; typeof bt == "bigint" ? (cs[Qe + 2 * st] = 1n, cs[Qe + 2 * st + 1] = bt) : (cs[Qe + 2 * st] = 0n, p()[Qe + 2 * st + 1 >>> 0] = bt); } return l = Rm(l, 0, D, fe, m), Fp(G), l; }; function Jp(l) { if (z) return Ls(0, 1, l); if (Tt = l, !(0 < Io)) { for (var m of Fo) Yp(m); for (m of Xn) Yp(m); Xn = [], Fo = [], an = [], Ds = !0; } Me(0, new Xp(l)); } function zh(l) { if (z) return Ls(1, 0, l); Zp(l); } var Zp = (l) => { if (Tt = l, z) throw zh(l), "unwind"; Jp(l); }, Xn = [], Fo = [], Bh = [], an = {}, Rh = (l) => { var m = l.Bb; delete an[m], Xn.push(l), Fo.splice(Fo.indexOf(l), 1), l.Bb = 0, hh(m); }; function Nh() { Bh.forEach((l) => l()); } var jh = (l) => new Promise((m) => { l.onmessage = (G) => { var fe = (G = G.data).cmd; if (G.targetThread && G.targetThread != Ca()) { var Qe = an[G.targetThread]; Qe ? Qe.postMessage(G, G.transferList) : Et(`Internal error! Worker sent a message "${fe}" to target pthread ${G.targetThread}, but that thread no longer exists!`); } else fe === "checkMailbox" ? vp() : fe === "spawnThread" ? Lh(G) : fe === "cleanupThread" ? Rh(an[G.thread]) : fe === "killThread" ? (G = G.thread, fe = an[G], delete an[G], Yp(fe), hh(G), Fo.splice(Fo.indexOf(fe), 1), fe.Bb = 0) : fe === "cancelThread" ? an[G.thread].postMessage({ cmd: "cancel" }) : fe === "loaded" ? (l.loaded = !0, m(l)) : fe === "alert" ? alert(`Thread ${G.threadId}: ${G.text}`) : G.target === "setimmediate" ? l.postMessage(G) : fe === "callHandler" ? u[G.handler](...G.args) : fe && Et(`worker sent an unknown command ${fe}`); }, l.onerror = (G) => { throw Et(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`), G; }; var E, D = []; for (E of []) u.hasOwnProperty(E) && D.push(E); l.postMessage({ cmd: "load", handlers: D, wasmMemory: zt, wasmModule: ns }); }); function Vh() { var l = new Worker(import.meta.url.startsWith("file:") ? new URL( /* asset import */ r( /*! ort.bundle.min.mjs */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb" ), r.b ) : new URL(import.meta.url), { type: "module", workerData: "em-pthread", name: "em-pthread" }); Xn.push(l); } var bp = (l) => { for (; 0 < l.length; ) l.shift()(u); }, o_ = () => { var l = Ca(), m = a()[l + 52 >>> 2 >>> 0]; l = a()[l + 56 >>> 2 >>> 0], jm(m, m - l), Fp(m); }, i_ = (l, m) => { Io = 0, l = Vm(l, m), 0 < Io ? Tt = l : Ip(l); }; class a_ { constructor(m) { this.Kb = m - 24; } } function l_(l, m, E) { var D = new a_(l >>>= 0); throw m >>>= 0, E >>>= 0, a()[D.Kb + 16 >>> 2 >>> 0] = 0, a()[D.Kb + 4 >>> 2 >>> 0] = m, a()[D.Kb + 8 >>> 2 >>> 0] = E, l; } function Uh(l, m, E, D) { return z ? Ls(2, 1, l, m, E, D) : Wh(l, m, E, D); } function Wh(l, m, E, D) { if (l >>>= 0, m >>>= 0, E >>>= 0, D >>>= 0, ne === void 0) return Et("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; var G = []; return z && G.length === 0 ? Uh(l, m, E, D) : (l = { ic: E, Bb: l, Rb: D, nc: G }, z ? (l.Nb = "spawnThread", postMessage(l, G), 0) : Lh(l)); } var Gh = typeof TextDecoder < "u" ? new TextDecoder("utf8") : void 0, Kh = (l, m, E) => { var D = (m >>>= 0) + E; for (E = m; l[E] && !(E >= D); ) ++E; if (16 < E - m && l.buffer && Gh) return Gh.decode(l.buffer instanceof ne ? l.slice(m, E) : l.subarray(m, E)); for (D = ""; m < E; ) { var G = l[m++]; if (128 & G) { var fe = 63 & l[m++]; if ((224 & G) == 192) D += String.fromCharCode((31 & G) << 6 | fe); else { var Qe = 63 & l[m++]; 65536 > (G = (240 & G) == 224 ? (15 & G) << 12 | fe << 6 | Qe : (7 & G) << 18 | fe << 12 | Qe << 6 | 63 & l[m++]) ? D += String.fromCharCode(G) : (G -= 65536, D += String.fromCharCode(55296 | G >> 10, 56320 | 1023 & G)); } } else D += String.fromCharCode(G); } return D; }, Gs = (l, m) => (l >>>= 0) ? Kh(s(), l, m) : ""; function Hh(l, m, E) { return z ? Ls(3, 1, l, m, E) : 0; } function qh(l, m) { if (z) return Ls(4, 1, l, m); } var eh = (l) => { for (var m = 0, E = 0; E < l.length; ++E) { var D = l.charCodeAt(E); 127 >= D ? m++ : 2047 >= D ? m += 2 : 55296 <= D && 57343 >= D ? (m += 4, ++E) : m += 3; } return m; }, Qh = (l, m, E, D) => { if (!(0 < D)) return 0; var G = E >>>= 0; D = E + D - 1; for (var fe = 0; fe < l.length; ++fe) { var Qe = l.charCodeAt(fe); if (55296 <= Qe && 57343 >= Qe && (Qe = 65536 + ((1023 & Qe) << 10) | 1023 & l.charCodeAt(++fe)), 127 >= Qe) { if (E >= D) break; m[E++ >>> 0] = Qe; } else { if (2047 >= Qe) { if (E + 1 >= D) break; m[E++ >>> 0] = 192 | Qe >> 6; } else { if (65535 >= Qe) { if (E + 2 >= D) break; m[E++ >>> 0] = 224 | Qe >> 12; } else { if (E + 3 >= D) break; m[E++ >>> 0] = 240 | Qe >> 18, m[E++ >>> 0] = 128 | Qe >> 12 & 63; } m[E++ >>> 0] = 128 | Qe >> 6 & 63; } m[E++ >>> 0] = 128 | 63 & Qe; } } return m[E >>> 0] = 0, E - G; }, Pa = (l, m, E) => Qh(l, s(), m, E); function Xh(l, m) { if (z) return Ls(5, 1, l, m); } function Yh(l, m, E) { if (z) return Ls(6, 1, l, m, E); } function Jh(l, m, E) { return z ? Ls(7, 1, l, m, E) : 0; } function Zh(l, m) { if (z) return Ls(8, 1, l, m); } function em(l, m, E) { if (z) return Ls(9, 1, l, m, E); } function tm(l, m, E, D) { if (z) return Ls(10, 1, l, m, E, D); } function sm(l, m, E, D) { if (z) return Ls(11, 1, l, m, E, D); } function rm(l, m, E, D) { if (z) return Ls(12, 1, l, m, E, D); } function nm(l) { if (z) return Ls(13, 1, l); } function om(l, m) { if (z) return Ls(14, 1, l, m); } function im(l, m, E) { if (z) return Ls(15, 1, l, m, E); } var am, Yn, u_ = () => { Qn(""); }, ln = (l) => { for (var m = ""; s()[l >>> 0]; ) m += am[s()[l++ >>> 0]]; return m; }, th = {}, sh = {}; function xn(l, m, E = {}) { if (!("argPackAdvance" in m)) throw new TypeError("registerType registeredInstance requires argPackAdvance"); return function(D, G, fe = {}) { var Qe = G.name; if (!D) throw new Yn(`type "${Qe}" must have a positive integer typeid pointer`); if (sh.hasOwnProperty(D)) { if (fe.Tb) return; throw new Yn(`Cannot register type '${Qe}' twice`); } sh[D] = G, th.hasOwnProperty(D) && (G = th[D], delete th[D], G.forEach((st) => st())); }(l, m, E); } var lm = (l, m, E) => { switch (m) { case 1: return E ? (D) => t()[D >>> 0] : (D) => s()[D >>> 0]; case 2: return E ? (D) => n()[D >>> 1 >>> 0] : (D) => o()[D >>> 1 >>> 0]; case 4: return E ? (D) => i()[D >>> 2 >>> 0] : (D) => a()[D >>> 2 >>> 0]; case 8: return E ? (D) => cs[D >>> 3] : (D) => Js[D >>> 3]; default: throw new TypeError(`invalid integer width (${m}): ${l}`); } }; function d_(l, m, E) { E >>>= 0, xn(l >>>= 0, { name: m = ln(m >>> 0), fromWireType: (D) => D, toWireType: function(D, G) { if (typeof G != "bigint" && typeof G != "number") throw G = G === null ? "null" : (D = typeof G) == "object" || D === "array" || D === "function" ? G.toString() : "" + G, new TypeError(`Cannot convert "${G}" to ${this.name}`); return typeof G == "number" && (G = BigInt(G)), G; }, argPackAdvance: Jn, readValueFromPointer: lm(m, E, m.indexOf("u") == -1), Eb: null }); } var Jn = 8; function c_(l, m, E, D) { xn(l >>>= 0, { name: m = ln(m >>> 0), fromWireType: function(G) { return !!G; }, toWireType: function(G, fe) { return fe ? E : D; }, argPackAdvance: Jn, readValueFromPointer: function(G) { return this.fromWireType(s()[G >>> 0]); }, Eb: null }); } var rh = [], Tn = []; function nh(l) { 9 < (l >>>= 0) && --Tn[l + 1] == 0 && (Tn[l] = void 0, rh.push(l)); } var vr = (l) => { if (!l) throw new Yn("Cannot use deleted val. handle = " + l); return Tn[l]; }, Ir = (l) => { switch (l) { case void 0: return 2; case null: return 4; case !0: return 6; case !1: return 8; default: let m = rh.pop() || Tn.length; return Tn[m] = l, Tn[m + 1] = 1, m; } }; function oh(l) { return this.fromWireType(a()[l >>> 2 >>> 0]); } var p_ = { name: "emscripten::val", fromWireType: (l) => { var m = vr(l); return nh(l), m; }, toWireType: (l, m) => Ir(m), argPackAdvance: Jn, readValueFromPointer: oh, Eb: null }; function h_(l) { return xn(l >>> 0, p_); } var m_ = (l, m) => { switch (m) { case 4: return function(E) { return this.fromWireType(c()[E >>> 2 >>> 0]); }; case 8: return function(E) { return this.fromWireType(p()[E >>> 3 >>> 0]); }; default: throw new TypeError(`invalid float width (${m}): ${l}`); } }; function __(l, m, E) { E >>>= 0, xn(l >>>= 0, { name: m = ln(m >>> 0), fromWireType: (D) => D, toWireType: (D, G) => G, argPackAdvance: Jn, readValueFromPointer: m_(m, E), Eb: null }); } function f_(l, m, E, D, G) { if (l >>>= 0, E >>>= 0, m = ln(m >>> 0), G === -1 && (G = 4294967295), G = (st) => st, D === 0) { var fe = 32 - 8 * E; G = (st) => st << fe >>> fe; } var Qe = m.includes("unsigned") ? function(st, bt) { return bt >>> 0; } : function(st, bt) { return bt; }; xn(l, { name: m, fromWireType: G, toWireType: Qe, argPackAdvance: Jn, readValueFromPointer: lm(m, E, D !== 0), Eb: null }); } function g_(l, m, E) { function D(fe) { var Qe = a()[fe >>> 2 >>> 0]; return fe = a()[fe + 4 >>> 2 >>> 0], new G(t().buffer, fe, Qe); } var G = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array][m]; xn(l >>>= 0, { name: E = ln(E >>> 0), fromWireType: D, argPackAdvance: Jn, readValueFromPointer: D }, { Tb: !0 }); } function w_(l, m) { l >>>= 0; var E = (m = ln(m >>> 0)) === "std::string"; xn(l, { name: m, fromWireType: function(D) { var G = a()[D >>> 2 >>> 0], fe = D + 4; if (E) for (var Qe = fe, st = 0; st <= G; ++st) { var bt = fe + st; if (st == G || s()[bt >>> 0] == 0) { if (Qe = Gs(Qe, bt - Qe), Ct === void 0) var Ct = Qe; else Ct += "\0", Ct += Qe; Qe = bt + 1; } } else { for (Ct = Array(G), st = 0; st < G; ++st) Ct[st] = String.fromCharCode(s()[fe + st >>> 0]); Ct = Ct.join(""); } return dn(D), Ct; }, toWireType: function(D, G) { G instanceof ArrayBuffer && (G = new Uint8Array(G)); var fe = typeof G == "string"; if (!(fe || G instanceof Uint8Array || G instanceof Uint8ClampedArray || G instanceof Int8Array)) throw new Yn("Cannot pass non-string to std::string"); var Qe = E && fe ? eh(G) : G.length, st = Ap(4 + Qe + 1), bt = st + 4; if (a()[st >>> 2 >>> 0] = Qe, E && fe) Pa(G, bt, Qe + 1); else if (fe) for (fe = 0; fe < Qe; ++fe) { var Ct = G.charCodeAt(fe); if (255 < Ct) throw dn(bt), new Yn("String has UTF-16 code units that do not fit in 8 bits"); s()[bt + fe >>> 0] = Ct; } else for (fe = 0; fe < Qe; ++fe) s()[bt + fe >>> 0] = G[fe]; return D !== null && D.push(dn, st), st; }, argPackAdvance: Jn, readValueFromPointer: oh, Eb(D) { dn(D); } }); } var um = typeof TextDecoder < "u" ? new TextDecoder("utf-16le") : void 0, y_ = (l, m) => { for (var E = l >> 1, D = E + m / 2; !(E >= D) && o()[E >>> 0]; ) ++E; if (32 < (E <<= 1) - l && um) return um.decode(s().slice(l, E)); for (E = "", D = 0; !(D >= m / 2); ++D) { var G = n()[l + 2 * D >>> 1 >>> 0]; if (G == 0) break; E += String.fromCharCode(G); } return E; }, M_ = (l, m, E) => { if (E ??= 2147483647, 2 > E) return 0; var D = m; E = (E -= 2) < 2 * l.length ? E / 2 : l.length; for (var G = 0; G < E; ++G) { var fe = l.charCodeAt(G); n()[m >>> 1 >>> 0] = fe, m += 2; } return n()[m >>> 1 >>> 0] = 0, m - D; }, b_ = (l) => 2 * l.length, v_ = (l, m) => { for (var E = 0, D = ""; !(E >= m / 4); ) { var G = i()[l + 4 * E >>> 2 >>> 0]; if (G == 0) break; ++E, 65536 <= G ? (G -= 65536, D += String.fromCharCode(55296 | G >> 10, 56320 | 1023 & G)) : D += String.fromCharCode(G); } return D; }, x_ = (l, m, E) => { if (m >>>= 0, E ??= 2147483647, 4 > E) return 0; var D = m; E = D + E - 4; for (var G = 0; G < l.length; ++G) { var fe = l.charCodeAt(G); if (55296 <= fe && 57343 >= fe && (fe = 65536 + ((1023 & fe) << 10) | 1023 & l.charCodeAt(++G)), i()[m >>> 2 >>> 0] = fe, (m += 4) + 4 > E) break; } return i()[m >>> 2 >>> 0] = 0, m - D; }, T_ = (l) => { for (var m = 0, E = 0; E < l.length; ++E) { var D = l.charCodeAt(E); 55296 <= D && 57343 >= D && ++E, m += 4; } return m; }; function P_(l, m, E) { if (l >>>= 0, m >>>= 0, E = ln(E >>>= 0), m === 2) var D = y_, G = M_, fe = b_, Qe = (st) => o()[st >>> 1 >>> 0]; else m === 4 && (D = v_, G = x_, fe = T_, Qe = (st) => a()[st >>> 2 >>> 0]); xn(l, { name: E, fromWireType: (st) => { for (var bt, Ct = a()[st >>> 2 >>> 0], Rt = st + 4, us = 0; us <= Ct; ++us) { var gs = st + 4 + us * m; us != Ct && Qe(gs) != 0 || (Rt = D(Rt, gs - Rt), bt === void 0 ? bt = Rt : (bt += "\0", bt += Rt), Rt = gs + m); } return dn(st), bt; }, toWireType: (st, bt) => { if (typeof bt != "string") throw new Yn(`Cannot pass non-string to C++ string type ${E}`); var Ct = fe(bt), Rt = Ap(4 + Ct + m); return a()[Rt >>> 2 >>> 0] = Ct / m, G(bt, Rt + 4, Ct + m), st !== null && st.push(dn, Rt), Rt; }, argPackAdvance: Jn, readValueFromPointer: oh, Eb(st) { dn(st); } }); } function E_(l, m) { xn(l >>>= 0, { Ub: !0, name: m = ln(m >>> 0), argPackAdvance: 0, fromWireType: () => { }, toWireType: () => { } }); } var C_ = () => 1; function k_(l) { ph(l >>> 0, !R, 1, !B, 131072, !1), Nh(); } var dm = (l) => { if (!Ds) try { if (l(), !(0 < Io)) try { z ? Ip(Tt) : Zp(Tt); } catch (m) { m instanceof Xp || m == "unwind" || Me(0, m); } } catch (m) { m instanceof Xp || m == "unwind" || Me(0, m); } }; function ih(l) { l >>>= 0, typeof Atomics.oc == "function" && (Atomics.oc(i(), l >>> 2, l).value.then(vp), l += 128, Atomics.store(i(), l >>> 2, 1)); } var vp = () => { var l = Ca(); l && (ih(l), dm(Nm)); }; function S_(l, m) { (l >>>= 0) == m >>> 0 ? setTimeout(vp) : z ? postMessage({ targetThread: l, cmd: "checkMailbox" }) : (l = an[l]) && l.postMessage({ cmd: "checkMailbox" }); } var ah = []; function $_(l, m, E, D, G) { for (m >>>= 0, D /= 2, ah.length = D, E = G >>> 0 >>> 3, G = 0; G < D; G++) ah[G] = cs[E + 2 * G] ? cs[E + 2 * G + 1] : p()[E + 2 * G + 1 >>> 0]; return (m ? Qp[m] : bf[l])(...ah); } function A_(l) { l >>>= 0, z ? postMessage({ cmd: "cleanupThread", thread: l }) : Rh(an[l]); } function I_(l) { } var xp = (l, m) => { var E = sh[l]; if (E === void 0) throw l = Lm(l), E = ln(l), dn(l), new Yn(`${m} has unknown type ${E}`); return E; }, cm = (l, m, E) => { var D = []; return l = l.toWireType(D, E), D.length && (a()[m >>> 2 >>> 0] = Ir(D)), l; }; function F_(l, m, E) { return m >>>= 0, E >>>= 0, l = vr(l >>> 0), m = xp(m, "emval::as"), cm(m, E, l); } function O_(l, m) { return m >>>= 0, l = vr(l >>> 0), (m = xp(m, "emval::as")).toWireType(null, l); } var Tp = (l) => { try { l(); } catch (m) { Qn(m); } }, Zn = 0, un = null, pm = 0, Pp = [], hm = {}, mm = {}, D_ = 0, lh = null, L_ = []; function _m(l) { return function(m) { if (!Ds) { if (Zn === 0) { var E = !1, D = !1; m((G = 0) => { if (!Ds && (pm = G, E = !0, D)) { Zn = 2, Tp(() => Gm(un)), typeof Browser < "u" && Browser.Lb.Sb && Browser.Lb.resume(), G = !1; try { var fe = function() { var bt = i()[un + 8 >>> 2 >>> 0]; return bt = Bt[mm[bt]], --Io, bt(); }(); } catch (bt) { fe = bt, G = !0; } var Qe = !1; if (!un) { var st = lh; st && (lh = null, (G ? st.reject : st.resolve)(fe), Qe = !0); } if (G && !Qe) throw fe; } }), D = !0, E || (Zn = 1, un = function() { var G = Ap(65548), fe = G + 12; a()[G >>> 2 >>> 0] = fe, a()[G + 4 >>> 2 >>> 0] = fe + 65536, fe = Pp[0]; var Qe = hm[fe]; return Qe === void 0 && (Qe = D_++, hm[fe] = Qe, mm[Qe] = fe), fe = Qe, i()[G + 8 >>> 2 >>> 0] = fe, G; }(), typeof Browser < "u" && Browser.Lb.Sb && Browser.Lb.pause(), Tp(() => Um(un))); } else Zn === 2 ? (Zn = 0, Tp(Km), dn(un), un = null, L_.forEach(dm)) : Qn(`invalid state: ${Zn}`); return pm; } }((m) => { l().then(m); }); } function z_(l) { return l >>>= 0, _m(() => (l = vr(l)).then(Ir)); } var Ep = []; function B_(l, m, E, D) { return E >>>= 0, D >>>= 0, (l = Ep[l >>> 0])(null, m = vr(m >>> 0), E, D); } var R_ = {}, Cp = (l) => { var m = R_[l]; return m === void 0 ? ln(l) : m; }; function N_(l, m, E, D, G) { return E >>>= 0, D >>>= 0, G >>>= 0, (l = Ep[l >>> 0])(m = vr(m >>> 0), m[E = Cp(E)], D, G); } var fm = () => typeof globalThis == "object" ? globalThis : Function("return this")(); function j_(l) { return (l >>>= 0) == 0 ? Ir(fm()) : (l = Cp(l), Ir(fm()[l])); } var V_ = (l) => { var m = Ep.length; return Ep.push(l), m; }, U_ = (l, m) => { for (var E = Array(l), D = 0; D < l; ++D) E[D] = xp(a()[m + 4 * D >>> 2 >>> 0], "parameter " + D); return E; }, gm = (l, m) => Object.defineProperty(m, "name", { value: l }); function W_(l, m, E) { var D = (m = U_(l, m >>> 0)).shift(); l--; var G = `return function (obj, func, destructorsRef, args) { `, fe = 0, Qe = []; E === 0 && Qe.push("obj"); for (var st = ["retType"], bt = [D], Ct = 0; Ct < l; ++Ct) Qe.push("arg" + Ct), st.push("argType" + Ct), bt.push(m[Ct]), G += ` var arg${Ct} = argType${Ct}.readValueFromPointer(args${fe ? "+" + fe : ""}); `, fe += m[Ct].argPackAdvance; return G += ` var rv = ${E === 1 ? "new func" : "func.call"}(${Qe.join(", ")}); `, D.Ub || (st.push("emval_returnValue"), bt.push(cm), G += ` return emval_returnValue(retType, destructorsRef, rv); `), st.push(G + `}; `), l = function(Rt) { var us = Function; if (!(us instanceof Function)) throw new TypeError(`new_ called with constructor type ${typeof us} which is not a function`); var gs = gm(us.name || "unknownFunctionName", function() { }); return gs.prototype = us.prototype, gs = new gs(), (Rt = us.apply(gs, Rt)) instanceof Object ? Rt : gs; }(st)(...bt), E = `methodCaller<(${m.map((Rt) => Rt.name).join(", ")}) => ${D.name}>`, V_(gm(E, l)); } function G_(l) { return l = Cp(l >>> 0), Ir(u[l]); } function K_(l, m) { return m >>>= 0, l = vr(l >>> 0), m = vr(m), Ir(l[m]); } function H_(l) { 9 < (l >>>= 0) && (Tn[l + 1] += 1); } function q_() { return Ir([]); } function Q_(l) { l = vr(l >>> 0); for (var m = Array(l.length), E = 0; E < l.length; E++) m[E] = l[E]; return Ir(m); } function X_(l) { return Ir(Cp(l >>> 0)); } function Y_() { return Ir({}); } function J_(l) { for (var m = vr(l >>>= 0); m.length; ) { var E = m.pop(); m.pop()(E); } nh(l); } function Z_(l, m, E) { m >>>= 0, E >>>= 0, l = vr(l >>> 0), m = vr(m), E = vr(E), l[m] = E; } function ef(l, m) { return m >>>= 0, l = (l = xp(l >>> 0, "_emval_take_value")).readValueFromPointer(m), Ir(l); } function tf(l, m) { l = -9007199254740992 > l || 9007199254740992 < l ? NaN : Number(l), m >>>= 0, l = new Date(1e3 * l), i()[m >>> 2 >>> 0] = l.getUTCSeconds(), i()[m + 4 >>> 2 >>> 0] = l.getUTCMinutes(), i()[m + 8 >>> 2 >>> 0] = l.getUTCHours(), i()[m + 12 >>> 2 >>> 0] = l.getUTCDate(), i()[m + 16 >>> 2 >>> 0] = l.getUTCMonth(), i()[m + 20 >>> 2 >>> 0] = l.getUTCFullYear() - 1900, i()[m + 24 >>> 2 >>> 0] = l.getUTCDay(), l = (l.getTime() - Date.UTC(l.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i()[m + 28 >>> 2 >>> 0] = l; } var Ea = (l) => l % 4 == 0 && (l % 100 != 0 || l % 400 == 0), wm = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], ym = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; function sf(l, m) { l = -9007199254740992 > l || 9007199254740992 < l ? NaN : Number(l), m >>>= 0, l = new Date(1e3 * l), i()[m >>> 2 >>> 0] = l.getSeconds(), i()[m + 4 >>> 2 >>> 0] = l.getMinutes(), i()[m + 8 >>> 2 >>> 0] = l.getHours(), i()[m + 12 >>> 2 >>> 0] = l.getDate(), i()[m + 16 >>> 2 >>> 0] = l.getMonth(), i()[m + 20 >>> 2 >>> 0] = l.getFullYear() - 1900, i()[m + 24 >>> 2 >>> 0] = l.getDay(); var E = (Ea(l.getFullYear()) ? wm : ym)[l.getMonth()] + l.getDate() - 1 | 0; i()[m + 28 >>> 2 >>> 0] = E, i()[m + 36 >>> 2 >>> 0] = -60 * l.getTimezoneOffset(), E = new Date(l.getFullYear(), 6, 1).getTimezoneOffset(); var D = new Date(l.getFullYear(), 0, 1).getTimezoneOffset(); l = 0 | (E != D && l.getTimezoneOffset() == Math.min(D, E)), i()[m + 32 >>> 2 >>> 0] = l; } function rf(l) { l >>>= 0; var m = new Date(i()[l + 20 >>> 2 >>> 0] + 1900, i()[l + 16 >>> 2 >>> 0], i()[l + 12 >>> 2 >>> 0], i()[l + 8 >>> 2 >>> 0], i()[l + 4 >>> 2 >>> 0], i()[l >>> 2 >>> 0], 0), E = i()[l + 32 >>> 2 >>> 0], D = m.getTimezoneOffset(), G = new Date(m.getFullYear(), 6, 1).getTimezoneOffset(), fe = new Date(m.getFullYear(), 0, 1).getTimezoneOffset(), Qe = Math.min(fe, G); return 0 > E ? i()[l + 32 >>> 2 >>> 0] = +(G != fe && Qe == D) : 0 < E != (Qe == D) && (G = Math.max(fe, G), m.setTime(m.getTime() + 6e4 * ((0 < E ? Qe : G) - D))), i()[l + 24 >>> 2 >>> 0] = m.getDay(), E = (Ea(m.getFullYear()) ? wm : ym)[m.getMonth()] + m.getDate() - 1 | 0, i()[l + 28 >>> 2 >>> 0] = E, i()[l >>> 2 >>> 0] = m.getSeconds(), i()[l + 4 >>> 2 >>> 0] = m.getMinutes(), i()[l + 8 >>> 2 >>> 0] = m.getHours(), i()[l + 12 >>> 2 >>> 0] = m.getDate(), i()[l + 16 >>> 2 >>> 0] = m.getMonth(), i()[l + 20 >>> 2 >>> 0] = m.getYear(), l = m.getTime(), BigInt(isNaN(l) ? -1 : l / 1e3); } function Mm(l, m, E, D, G, fe, Qe) { return z ? Ls(16, 1, l, m, E, D, G, fe, Qe) : -52; } function bm(l, m, E, D, G, fe) { if (z) return Ls(17, 1, l, m, E, D, G, fe); } function nf(l, m, E, D) { l >>>= 0, m >>>= 0, E >>>= 0, D >>>= 0; var G = (/* @__PURE__ */ new Date()).getFullYear(), fe = new Date(G, 0, 1), Qe = new Date(G, 6, 1); G = fe.getTimezoneOffset(); var st = Qe.getTimezoneOffset(), bt = Math.max(G, st); a()[l >>> 2 >>> 0] = 60 * bt, i()[m >>> 2 >>> 0] = +(G != st), fe = (l = (Ct) => Ct.toLocaleTimeString(void 0, { hour12: !1, timeZoneName: "short" }).split(" ")[1])(fe), Qe = l(Qe), st < G ? (Pa(fe, E, 17), Pa(Qe, D, 17)) : (Pa(fe, D, 17), Pa(Qe, E, 17)); } var uh = [], vm = (l, m) => { uh.length = 0; for (var E; E = s()[l++ >>> 0]; ) { var D = E != 105; m += (D &= E != 112) && m % 8 ? 4 : 0, uh.push(E == 112 ? a()[m >>> 2 >>> 0] : E == 106 ? cs[m >>> 3] : E == 105 ? i()[m >>> 2 >>> 0] : p()[m >>> 3 >>> 0]), m += D ? 8 : 4; } return uh; }; function of(l, m, E) { return l >>>= 0, m = vm(m >>> 0, E >>> 0), Qp[l](...m); } function af(l, m, E) { return l >>>= 0, m = vm(m >>> 0, E >>> 0), Qp[l](...m); } var lf = () => { }, uf = () => Date.now(); function df(l, m) { return Et(Gs(l >>> 0, m >>> 0)); } var xm, cf = () => { throw Io += 1, "unwind"; }; function pf() { return 4294901760; } xm = () => performance.timeOrigin + performance.now(); var hf = () => navigator.hardwareConcurrency; function mf() { return Qn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"), 0; } function _f(l) { l >>>= 0; var m = s().length; if (l <= m || 4294901760 < l) return !1; for (var E = 1; 4 >= E; E *= 2) { var D = m * (1 + 0.2 / E); D = Math.min(D, l + 100663296); var G = Math; D = Math.max(l, D); e: { G = (G.min.call(G, 4294901760, D + (65536 - D % 65536) % 65536) - zt.buffer.byteLength + 65535) / 65536; try { zt.grow(G), ys(); var fe = 1; break e; } catch { } fe = void 0; } if (fe) return !0; } return !1; } var kp = () => (Qn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"), 0), ic = {}, Tm = (l) => { l.forEach((m) => { kp(); }); }; function ff() { var l = Error().stack.toString().split(` `); return l[0] == "Error" && l.shift(), Tm(l), ic.Qb = kp(), ic.fc = l, ic.Qb; } function gf(l, m, E) { if (l >>>= 0, m >>>= 0, ic.Qb == l) var D = ic.fc; else (D = Error().stack.toString().split(` `))[0] == "Error" && D.shift(), Tm(D); for (var G = 3; D[G] && kp() != l; ) ++G; for (l = 0; l < E && D[l + G]; ++l) i()[m + 4 * l >>> 2 >>> 0] = kp(); return l; } var dh, ch = {}, Pm = () => { if (!dh) { var l, m = { 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", _: "./this.program" }; for (l in ch) ch[l] === void 0 ? delete m[l] : m[l] = ch[l]; var E = []; for (l in m) E.push(`${l}=${m[l]}`); dh = E; } return dh; }; function Em(l, m) { if (z) return Ls(18, 1, l, m); l >>>= 0, m >>>= 0; var E = 0; return Pm().forEach((D, G) => { var fe = m + E; for (G = a()[l + 4 * G >>> 2 >>> 0] = fe, fe = 0; fe < D.length; ++fe) t()[G++ >>> 0] = D.charCodeAt(fe); t()[G >>> 0] = 0, E += D.length + 1; }), 0; } function Cm(l, m) { if (z) return Ls(19, 1, l, m); l >>>= 0, m >>>= 0; var E = Pm(); a()[l >>> 2 >>> 0] = E.length; var D = 0; return E.forEach((G) => D += G.length + 1), a()[m >>> 2 >>> 0] = D, 0; } function km(l) { return z ? Ls(20, 1, l) : 52; } function Sm(l, m, E, D) { return z ? Ls(21, 1, l, m, E, D) : 52; } function $m(l, m, E, D) { return z ? Ls(22, 1, l, m, E, D) : 70; } var wf = [null, [], []]; function Am(l, m, E, D) { if (z) return Ls(23, 1, l, m, E, D); m >>>= 0, E >>>= 0, D >>>= 0; for (var G = 0, fe = 0; fe < E; fe++) { var Qe = a()[m >>> 2 >>> 0], st = a()[m + 4 >>> 2 >>> 0]; m += 8; for (var bt = 0; bt < st; bt++) { var Ct = s()[Qe + bt >>> 0], Rt = wf[l]; Ct === 0 || Ct === 10 ? ((l === 1 ? kt : Et)(Kh(Rt, 0)), Rt.length = 0) : Rt.push(Ct); } G += st; } return a()[D >>> 2 >>> 0] = G, 0; } var Im = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Fm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], yf = (l, m) => { t().set(l, m >>> 0); }; function Om(l, m, E, D) { function G(Ke, is, js) { for (Ke = typeof Ke == "number" ? Ke.toString() : Ke || ""; Ke.length < is; ) Ke = js[0] + Ke; return Ke; } function fe(Ke, is) { return G(Ke, is, "0"); } function Qe(Ke, is) { function js(qm) { return 0 > qm ? -1 : 0 < qm ? 1 : 0; } var Oo; return (Oo = js(Ke.getFullYear() - is.getFullYear())) === 0 && (Oo = js(Ke.getMonth() - is.getMonth())) === 0 && (Oo = js(Ke.getDate() - is.getDate())), Oo; } function st(Ke) { switch (Ke.getDay()) { case 0: return new Date(Ke.getFullYear() - 1, 11, 29); case 1: return Ke; case 2: return new Date(Ke.getFullYear(), 0, 3); case 3: return new Date(Ke.getFullYear(), 0, 2); case 4: return new Date(Ke.getFullYear(), 0, 1); case 5: return new Date(Ke.getFullYear() - 1, 11, 31); case 6: return new Date(Ke.getFullYear() - 1, 11, 30); } } function bt(Ke) { var is = Ke.Cb; for (Ke = new Date(new Date(Ke.Db + 1900, 0, 1).getTime()); 0 < is; ) { var js = Ke.getMonth(), Oo = (Ea(Ke.getFullYear()) ? Im : Fm)[js]; if (!(is > Oo - Ke.getDate())) { Ke.setDate(Ke.getDate() + is); break; } is -= Oo - Ke.getDate() + 1, Ke.setDate(1), 11 > js ? Ke.setMonth(js + 1) : (Ke.setMonth(0), Ke.setFullYear(Ke.getFullYear() + 1)); } return js = new Date(Ke.getFullYear() + 1, 0, 4), is = st(new Date(Ke.getFullYear(), 0, 4)), js = st(js), 0 >= Qe(is, Ke) ? 0 >= Qe(js, Ke) ? Ke.getFullYear() + 1 : Ke.getFullYear() : Ke.getFullYear() - 1; } l >>>= 0, m >>>= 0, E >>>= 0, D >>>= 0; var Ct = a()[D + 40 >>> 2 >>> 0]; for (var Rt in D = { lc: i()[D >>> 2 >>> 0], kc: i()[D + 4 >>> 2 >>> 0], Ib: i()[D + 8 >>> 2 >>> 0], Mb: i()[D + 12 >>> 2 >>> 0], Jb: i()[D + 16 >>> 2 >>> 0], Db: i()[D + 20 >>> 2 >>> 0], vb: i()[D + 24 >>> 2 >>> 0], Cb: i()[D + 28 >>> 2 >>> 0], sc: i()[D + 32 >>> 2 >>> 0], jc: i()[D + 36 >>> 2 >>> 0], mc: Ct ? Gs(Ct) : "" }, E = Gs(E), Ct = { "%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" }) E = E.replace(new RegExp(Rt, "g"), Ct[Rt]); var us = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), gs = "January February March April May June July August September October November December".split(" "); for (Rt in Ct = { "%a": (Ke) => us[Ke.vb].substring(0, 3), "%A": (Ke) => us[Ke.vb], "%b": (Ke) => gs[Ke.Jb].substring(0, 3), "%B": (Ke) => gs[Ke.Jb], "%C": (Ke) => fe((Ke.Db + 1900) / 100 | 0, 2), "%d": (Ke) => fe(Ke.Mb, 2), "%e": (Ke) => G(Ke.Mb, 2, " "), "%g": (Ke) => bt(Ke).toString().substring(2), "%G": bt, "%H": (Ke) => fe(Ke.Ib, 2), "%I": (Ke) => ((Ke = Ke.Ib) == 0 ? Ke = 12 : 12 < Ke && (Ke -= 12), fe(Ke, 2)), "%j": (Ke) => { for (var is = 0, js = 0; js <= Ke.Jb - 1; is += (Ea(Ke.Db + 1900) ? Im : Fm)[js++]) ; return fe(Ke.Mb + is, 3); }, "%m": (Ke) => fe(Ke.Jb + 1, 2), "%M": (Ke) => fe(Ke.kc, 2), "%n": () => ` `, "%p": (Ke) => 0 <= Ke.Ib && 12 > Ke.Ib ? "AM" : "PM", "%S": (Ke) => fe(Ke.lc, 2), "%t": () => " ", "%u": (Ke) => Ke.vb || 7, "%U": (Ke) => fe(Math.floor((Ke.Cb + 7 - Ke.vb) / 7), 2), "%V": (Ke) => { var is = Math.floor((Ke.Cb + 7 - (Ke.vb + 6) % 7) / 7); if (2 >= (Ke.vb + 371 - Ke.Cb - 2) % 7 && is++, is) is == 53 && ((js = (Ke.vb + 371 - Ke.Cb) % 7) == 4 || js == 3 && Ea(Ke.Db) || (is = 1)); else { is = 52; var js = (Ke.vb + 7 - Ke.Cb - 1) % 7; (js == 4 || js == 5 && Ea(Ke.Db % 400 - 1)) && is++; } return fe(is, 2); }, "%w": (Ke) => Ke.vb, "%W": (Ke) => fe(Math.floor((Ke.Cb + 7 - (Ke.vb + 6) % 7) / 7), 2), "%y": (Ke) => (Ke.Db + 1900).toString().substring(2), "%Y": (Ke) => Ke.Db + 1900, "%z": (Ke) => { var is = 0 <= (Ke = Ke.jc); return Ke = Math.abs(Ke) / 60, (is ? "+" : "-") + ("0000" + (Ke / 60 * 100 + Ke % 60)).slice(-4); }, "%Z": (Ke) => Ke.mc, "%%": () => "%" }, E = E.replace(/%%/g, "\0\0"), Ct) E.includes(Rt) && (E = E.replace(new RegExp(Rt, "g"), Ct[Rt](D))); return Rt = function(Ke) { var is = Array(eh(Ke) + 1); return Qh(Ke, is, 0, is.length), is; }(E = E.replace(/\0\0/g, "%")), Rt.length > m ? 0 : (yf(Rt, l), Rt.length - 1); } function Mf(l, m, E, D) { return Om(l >>> 0, m >>> 0, E >>> 0, D >>> 0); } z || function() { for (var l = u.numThreads - 1; l--; ) Vh(); qn.unshift(() => { nc++, function(m) { z ? m() : Promise.all(Xn.map(jh)).then(m); }(() => $h()); }); }(); for (var Dm = Array(256), Sp = 0; 256 > Sp; ++Sp) Dm[Sp] = String.fromCharCode(Sp); am = Dm, Yn = u.BindingError = class extends Error { constructor(l) { super(l), this.name = "BindingError"; } }, u.InternalError = class extends Error { constructor(l) { super(l), this.name = "InternalError"; } }, Tn.push(0, 1, void 0, 1, null, 1, !0, 1, !1, 1), u.count_emval_handles = () => Tn.length / 2 - 5 - rh.length; var bf = [Jp, zh, Uh, Hh, qh, Xh, Yh, Jh, Zh, em, tm, sm, rm, nm, om, im, Mm, bm, Em, Cm, km, Sm, $m, Am], Bt = function() { function l(E, D) { return Bt = E.exports, Bt = function() { var G = Bt, fe = {}; for (let [Qe, st] of Object.entries(G)) fe[Qe] = typeof st == "function" ? (...bt) => { Pp.push(Qe); try { return st(...bt); } finally { Ds || (Pp.pop(), un && Zn === 1 && Pp.length === 0 && (Zn = 0, Io += 1, Tp(Wm), typeof Fibers < "u" && Fibers.tc())); } } : st; return fe; }(), Bt = function() { var G = Bt, fe = (st) => (bt) => st(bt) >>> 0, Qe = (st) => () => st() >>> 0; return (G = Object.assign({}, G)).Da = fe(G.Da), G.gb = Qe(G.gb), G.ib = fe(G.ib), G.emscripten_main_runtime_thread_id = Qe(G.emscripten_main_runtime_thread_id), G.tb = fe(G.tb), G.ub = Qe(G.ub), G; }(), Bh.push(Bt.jb), rc.unshift(Bt.Ca), ns = D, $h(), Bt; } var m = Dh(); if (nc++, u.instantiateWasm) try { return u.instantiateWasm(m, l); } catch (E) { Et(`Module.instantiateWasm callback failed with error: ${E}`), C(E); } return qp ||= u.locateFile ? Ah("ort-wasm-simd-threaded.jsep.wasm") ? "ort-wasm-simd-threaded.jsep.wasm" : u.locateFile ? u.locateFile("ort-wasm-simd-threaded.jsep.wasm", Le) : Le + "ort-wasm-simd-threaded.jsep.wasm" : new URL( /* asset import */ r( /*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm" ), r.b ).href, function(E, D) { var G = qp; return Ae || typeof WebAssembly.instantiateStreaming != "function" || Ah(G) || Ih(G) || typeof fetch != "function" ? Oh(G, E, D) : fetch(G, { credentials: "same-origin" }).then((fe) => WebAssembly.instantiateStreaming(fe, E).then(D, function(Qe) { return Et(`wasm streaming compile failed: ${Qe}`), Et("falling back to ArrayBuffer instantiation"), Oh(G, E, D); })); }(m, function(E) { l(E.instance, E.module); }).catch(C), {}; }(), Lm = (l) => (Lm = Bt.Da)(l), zm = () => (zm = Bt.Ea)(); u._OrtInit = (l, m) => (u._OrtInit = Bt.Fa)(l, m), u._OrtGetLastError = (l, m) => (u._OrtGetLastError = Bt.Ga)(l, m), u._OrtCreateSessionOptions = (l, m, E, D, G, fe, Qe, st, bt, Ct) => (u._OrtCreateSessionOptions = Bt.Ha)(l, m, E, D, G, fe, Qe, st, bt, Ct), u._OrtAppendExecutionProvider = (l, m) => (u._OrtAppendExecutionProvider = Bt.Ia)(l, m), u._OrtAddFreeDimensionOverride = (l, m, E) => (u._OrtAddFreeDimensionOverride = Bt.Ja)(l, m, E), u._OrtAddSessionConfigEntry = (l, m, E) => (u._OrtAddSessionConfigEntry = Bt.Ka)(l, m, E), u._OrtReleaseSessionOptions = (l) => (u._OrtReleaseSessionOptions = Bt.La)(l), u._OrtCreateSession = (l, m, E) => (u._OrtCreateSession = Bt.Ma)(l, m, E), u._OrtReleaseSession = (l) => (u._OrtReleaseSession = Bt.Na)(l), u._OrtGetInputOutputCount = (l, m, E) => (u._OrtGetInputOutputCount = Bt.Oa)(l, m, E), u._OrtGetInputName = (l, m) => (u._OrtGetInputName = Bt.Pa)(l, m), u._OrtGetOutputName = (l, m) => (u._OrtGetOutputName = Bt.Qa)(l, m), u._OrtFree = (l) => (u._OrtFree = Bt.Ra)(l), u._OrtCreateTensor = (l, m, E, D, G, fe) => (u._OrtCreateTensor = Bt.Sa)(l, m, E, D, G, fe), u._OrtGetTensorData = (l, m, E, D, G) => (u._OrtGetTensorData = Bt.Ta)(l, m, E, D, G), u._OrtReleaseTensor = (l) => (u._OrtReleaseTensor = Bt.Ua)(l), u._OrtCreateRunOptions = (l, m, E, D) => (u._OrtCreateRunOptions = Bt.Va)(l, m, E, D), u._OrtAddRunConfigEntry = (l, m, E) => (u._OrtAddRunConfigEntry = Bt.Wa)(l, m, E), u._OrtReleaseRunOptions = (l) => (u._OrtReleaseRunOptions = Bt.Xa)(l), u._OrtCreateBinding = (l) => (u._OrtCreateBinding = Bt.Ya)(l), u._OrtBindInput = (l, m, E) => (u._OrtBindInput = Bt.Za)(l, m, E), u._OrtBindOutput = (l, m, E, D) => (u._OrtBindOutput = Bt._a)(l, m, E, D), u._OrtClearBoundOutputs = (l) => (u._OrtClearBoundOutputs = Bt.$a)(l), u._OrtReleaseBinding = (l) => (u._OrtReleaseBinding = Bt.ab)(l), u._OrtRunWithBinding = (l, m, E, D, G) => (u._OrtRunWithBinding = Bt.bb)(l, m, E, D, G), u._OrtRun = (l, m, E, D, G, fe, Qe, st) => (u._OrtRun = Bt.cb)(l, m, E, D, G, fe, Qe, st), u._OrtEndProfiling = (l) => (u._OrtEndProfiling = Bt.db)(l), u._JsepOutput = (l, m, E) => (u._JsepOutput = Bt.eb)(l, m, E), u._JsepGetNodeName = (l) => (u._JsepGetNodeName = Bt.fb)(l); var $p, Ca = () => (Ca = Bt.gb)(), dn = u._free = (l) => (dn = u._free = Bt.hb)(l), Ap = u._malloc = (l) => (Ap = u._malloc = Bt.ib)(l), ph = (l, m, E, D, G, fe) => (ph = Bt.lb)(l, m, E, D, G, fe), Bm = () => (Bm = Bt.mb)(), Rm = (l, m, E, D, G) => (Rm = Bt.nb)(l, m, E, D, G), hh = (l) => (hh = Bt.ob)(l), Ip = (l) => (Ip = Bt.pb)(l), Nm = () => (Nm = Bt.qb)(), jm = (l, m) => (jm = Bt.rb)(l, m), Fp = (l) => (Fp = Bt.sb)(l), mh = (l) => (mh = Bt.tb)(l), _h = () => (_h = Bt.ub)(), Vm = u.dynCall_ii = (l, m) => (Vm = u.dynCall_ii = Bt.wb)(l, m), Um = (l) => (Um = Bt.xb)(l), Wm = () => (Wm = Bt.yb)(), Gm = (l) => (Gm = Bt.zb)(l), Km = () => (Km = Bt.Ab)(); function Hm() { 0 < nc || (z ? (h(u), z || bp(rc), startWorker(u)) : (bp(qn), 0 < nc || $p || ($p = !0, u.calledRun = !0, Ds || (z || bp(rc), h(u), z || bp(Hp))))); } return u.___start_em_js = 932469, u.___stop_em_js = 932715, u.stackSave = () => _h(), u.stackRestore = (l) => Fp(l), u.stackAlloc = (l) => mh(l), u.setValue = function(l, m, E = "i8") { switch (E.endsWith("*") && (E = "*"), E) { case "i1": case "i8": t()[l >>> 0] = m; break; case "i16": n()[l >>> 1 >>> 0] = m; break; case "i32": i()[l >>> 2 >>> 0] = m; break; case "i64": cs[l >>> 3] = BigInt(m); break; case "float": c()[l >>> 2 >>> 0] = m; break; case "double": p()[l >>> 3 >>> 0] = m; break; case "*": a()[l >>> 2 >>> 0] = m; break; default: Qn(`invalid type for setValue: ${E}`); } }, u.getValue = function(l, m = "i8") { switch (m.endsWith("*") && (m = "*"), m) { case "i1": case "i8": return t()[l >>> 0]; case "i16": return n()[l >>> 1 >>> 0]; case "i32": return i()[l >>> 2 >>> 0]; case "i64": return cs[l >>> 3]; case "float": return c()[l >>> 2 >>> 0]; case "double": return p()[l >>> 3 >>> 0]; case "*": return a()[l >>> 2 >>> 0]; default: Qn(`invalid type for getValue: ${m}`); } }, u.UTF8ToString = Gs, u.stringToUTF8 = Pa, u.lengthBytesUTF8 = eh, oc = function l() { $p || Hm(), $p || (oc = l); }, Hm(), u.PTR_SIZE = 4, k; }), Is = Ps, globalThis.self?.name === "em-pthread" && Ps(); }), xr, Gr, Vs, yr, Lt, Kr, Tr, Pr, Hr, lr, Fr, Er, Or, Dr = y(() => { Ge(), xr = typeof location > "u" ? void 0 : location.origin, Gr = () => import.meta.url?.startsWith("file:") ? new URL(new URL( /* asset import */ r( /*! ort.bundle.min.mjs */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb" ), r.b ).href, xr).href : import.meta.url, Vs = Gr(), yr = () => { if (Vs && !Vs.startsWith("blob:")) return Vs.substring(0, Vs.lastIndexOf("/") + 1); }, Lt = (e, t) => { try { let s = t ?? Vs; return (s ? new URL(e, s) : new URL(e)).origin === xr; } catch { return !1; } }, Kr = (e, t) => { let s = t ?? Vs; try { return (s ? new URL(e, s) : new URL(e)).href; } catch { return; } }, Tr = (e, t) => `${t ?? "./"}${e}`, Pr = async (e) => { let t = await (await fetch(e, { credentials: "same-origin" })).blob(); return URL.createObjectURL(t); }, Hr = async (e) => (await import( /*webpackIgnore:true*/ e )).default, lr = (es(), b(tt)).default, Fr = async () => { if (!Vs) throw new Error("Failed to load proxy worker: cannot determine the script source URL."); if (Lt(Vs)) return [void 0, lr()]; let e = await Pr(Vs); return [e, lr(e)]; }, Er = (tr(), b(Ts)).default, Or = async (e, t, s) => { if (!e && !t && Er && Vs && Lt(Vs)) return [void 0, Er]; { let n = "ort-wasm-simd-threaded.jsep.mjs", o = e ?? Kr(n, t), i = s && o && !Lt(o, t), a = i ? await Pr(o) : o ?? Tr(n, t); return [i ? a : void 0, await Hr(a)]; } }; }), ir, nt, vt, Ft, Zs, Pn, cn, ws, Mr = y(() => { Dr(), nt = !1, vt = !1, Ft = !1, Zs = () => { if (typeof SharedArrayBuffer > "u") return !1; 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 !1; } }, Pn = () => { 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 !1; } }, cn = async (e) => { if (nt) return Promise.resolve(); if (vt) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); if (Ft) throw new Error("previous call to 'initializeWebAssembly()' failed."); vt = !0; let t = e.initTimeout, s = e.numThreads; if (!Pn()) throw new Error("WebAssembly SIMD is not supported in the current environment."); let n = Zs(); s > 1 && !n && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + s + ", 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 = s = 1); let o = e.wasmPaths, i = typeof o == "string" ? o : void 0, a = o?.mjs, c = a?.href ?? a, p = o?.wasm, h = p?.href ?? p, C = e.wasmBinary, [u, k] = await Or(c, i, s > 1), B = !1, R = []; if (t > 0 && R.push(new Promise((z) => { setTimeout(() => { B = !0, z(); }, t); })), R.push(new Promise((z, ne) => { let Z = { numThreads: s }; if (C) Z.wasmBinary = C; else if (h || i) Z.locateFile = (W) => h ?? i + W; else if (c && c.indexOf("blob:") !== 0) Z.locateFile = (W) => new URL(W, c).href; else if (u) { let W = yr(); W && (Z.locateFile = (ue) => W + ue); } k(Z).then((W) => { vt = !1, nt = !0, ir = W, z(), u && URL.revokeObjectURL(u); }, (W) => { vt = !1, Ft = !0, ne(W); }); })), await Promise.race(R), B) throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`); }, ws = () => { if (nt && ir) return ir; throw new Error("WebAssembly is not initialized yet."); }; }), zs, qr, ss, pn = y(() => { Mr(), zs = (e, t) => { let s = ws(), n = s.lengthBytesUTF8(e) + 1, o = s._malloc(n); return s.stringToUTF8(e, o, n), t.push(o), o; }, qr = (e, t, s, n) => { if (typeof e == "object" && e !== null) { if (s.has(e)) throw new Error("Circular reference in options"); s.add(e); } Object.entries(e).forEach(([o, i]) => { let a = t ? t + o : o; if (typeof i == "object") qr(i, a + ".", s, 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}`); }); }, ss = (e) => { let t = ws(), s = t.stackSave(); try { let n = t.PTR_SIZE, o = t.stackAlloc(2 * n); t._OrtGetLastError(o, o + n); let i = Number(t.getValue(o, n === 4 ? "i32" : "i64")), a = t.getValue(o + n, "*"), c = a ? t.UTF8ToString(a) : ""; throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${c}`); } finally { t.stackRestore(s); } }; }), Lr, eo = y(() => { Mr(), pn(), Lr = (e) => { let t = ws(), s = 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 = !1); let i = 0; return e?.tag !== void 0 && (i = zs(e.tag, n)), s = t._OrtCreateRunOptions(o.logSeverityLevel, o.logVerbosityLevel, !!o.terminate, i), s === 0 && ss("Can't create run options."), e?.extra !== void 0 && qr(e.extra, "", /* @__PURE__ */ new WeakSet(), (a, c) => { let p = zs(a, n), h = zs(c, n); t._OrtAddRunConfigEntry(s, p, h) !== 0 && ss(`Can't set a run config entry: ${a} - ${c}.`); }), [s, n]; } catch (i) { throw s !== 0 && t._OrtReleaseRunOptions(s), n.forEach((a) => t._free(a)), i; } }; }), En, Cn, kn, zr, Sn, to = y(() => { Mr(), pn(), En = (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}`); } }, Cn = (e) => { switch (e) { case "sequential": return 0; case "parallel": return 1; default: throw new Error(`unsupported execution mode: ${e}`); } }, kn = (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((s) => (typeof s == "string" ? s : s.name) === "webgpu") && (e.enableMemPattern = !1); }, zr = (e, t, s) => { for (let n of t) { let o = typeof n == "string" ? n : n.name; switch (o) { case "webnn": if (o = "WEBNN", typeof n != "string") { let a = n?.deviceType; if (a) { let c = zs("deviceType", s), p = zs(a, s); ws()._OrtAddSessionConfigEntry(e, c, p) !== 0 && ss(`Can't set a session config entry: 'deviceType' - ${a}.`); } } 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 c = zs("preferredLayout", s), p = zs(a.preferredLayout, s); ws()._OrtAddSessionConfigEntry(e, c, p) !== 0 && ss(`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 = zs(o, s); ws()._OrtAppendExecutionProvider(e, i) !== 0 && ss(`Can't append execution provider: ${o}.`); } }, Sn = (e) => { let t = ws(), s = 0, n = [], o = e || {}; kn(o); try { let i = En(o.graphOptimizationLevel ?? "all"), a = Cn(o.executionMode ?? "sequential"), c = typeof o.logId == "string" ? zs(o.logId, n) : 0, p = o.logSeverityLevel ?? 2; if (!Number.isInteger(p) || p < 0 || p > 4) throw new Error(`log serverity level is not valid: ${p}`); let h = o.logVerbosityLevel ?? 0; if (!Number.isInteger(h) || h < 0 || h > 4) throw new Error(`log verbosity level is not valid: ${h}`); let C = typeof o.optimizedModelFilePath == "string" ? zs(o.optimizedModelFilePath, n) : 0; if (s = t._OrtCreateSessionOptions(i, !!o.enableCpuMemArena, !!o.enableMemPattern, a, !!o.enableProfiling, 0, c, p, h, C), s === 0 && ss("Can't create session options."), o.executionProviders && zr(s, 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 = zs("enableGraphCapture", n), k = zs(o.enableGraphCapture.toString(), n); t._OrtAddSessionConfigEntry(s, u, k) !== 0 && ss(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`); } if (o.freeDimensionOverrides) for (let [u, k] of Object.entries(o.freeDimensionOverrides)) { if (typeof u != "string") throw new Error(`free dimension override name must be a string: ${u}`); if (typeof k != "number" || !Number.isInteger(k) || k < 0) throw new Error(`free dimension override value must be a non-negative integer: ${k}`); let B = zs(u, n); t._OrtAddFreeDimensionOverride(s, B, k) !== 0 && ss(`Can't set a free dimension override: ${u} - ${k}.`); } return o.extra !== void 0 && qr(o.extra, "", /* @__PURE__ */ new WeakSet(), (u, k) => { let B = zs(u, n), R = zs(k, n); t._OrtAddSessionConfigEntry(s, B, R) !== 0 && ss(`Can't set a session config entry: ${u} - ${k}.`); }), [s, n]; } catch (i) { throw s !== 0 && t._OrtReleaseSessionOptions(s) !== 0 && ss("Can't release session options."), n.forEach((a) => t._free(a)), i; } }; }), Br, pr, ar, hn, Qr, mn, _n, fn, Ot = y(() => { Br = (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; case "int4": return 22; case "uint4": return 21; default: throw new Error(`unsupported data type: ${e}`); } }, pr = (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"; case 22: return "int4"; case 21: return "uint4"; default: throw new Error(`unsupported data type: ${e}`); } }, ar = (e, t) => { let s = [-1, 4, 1, 1, 2, 2, 4, 8, -1, 1, 2, 8, 4, 8, -1, -1, -1, -1, -1, -1, -1, 0.5, 0.5][e], n = typeof t == "number" ? t : t.reduce((o, i) => o * i, 1); return s > 0 ? Math.ceil(n * s) : void 0; }, hn = (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}`); } }, Qr = (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}`); } }, mn = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", _n = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint64" || e === "int8" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", fn = (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; case "ml-tensor": return 5; default: throw new Error(`unsupported data location: ${e}`); } }; }), gn, $n = y(() => { Ge(), gn = async (e) => { if (typeof e == "string") { let t = await fetch(e); if (!t.ok) throw new Error(`failed to load external data file: ${e}`); let s = t.headers.get("Content-Length"), n = s ? parseInt(s, 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 (c) { if (c instanceof RangeError) { let p = Math.ceil(n / 65536); i = new WebAssembly.Memory({ initial: p, maximum: p }).buffer; } else throw c; } let a = 0; for (; ; ) { let { done: c, value: p } = await o.read(); if (c) break; let h = p.byteLength; new Uint8Array(i, a, h).set(p), a += h; } return new Uint8Array(i, 0, n); } } else return e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : e instanceof Uint8Array ? e : new Uint8Array(e); }; }), An, In, Rr, Fn, wn, On, as, Te = y(() => { Ot(), An = ["V", "I", "W", "E", "F"], In = (e, t) => { console.log(`[${An[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`); }, wn = (e, t) => { Rr = e, Fn = t; }, On = (e, t) => { let s = Qr(e), n = Qr(Rr); s >= n && In(s, typeof t == "function" ? t() : t); }, as = (...e) => { Fn && On(...e); }; }), M, Y = y(() => { Ot(), M = (e, t) => new (hn(t))(e); }), ce = y(() => { }), _e, Fe, Ye, gt, wt, yt, ht, ts, Xt, bs = y(() => { Te(), ce(), _e = /* @__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]]), Fe = [], Ye = (e) => Math.ceil(Number(e) / 16) * 16, gt = (e) => { for (let t = 0; t < Fe.length; t++) { let s = Fe[t]; if (e <= s) return s; } return Math.ceil(e / 16) * 16; }, wt = 1, yt = () => wt++, ht = async (e, t, s, n) => { let o = Ye(s), 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 c = i.getMappedRange(); if (n) { let p = n(); return p.set(new Uint8Array(c, 0, s)), p; } else return new Uint8Array(c.slice(0, s)); } finally { i.destroy(); } }, ts = class { constructor(e) { this.backend = e, this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.buffersPending = [], this.capturedPendingBuffers = /* @__PURE__ */ new Map(); for (let [t] of _e) Fe.push(t), this.freeBuffers.set(t, []), this.freeUniformBuffers.set(t, []); this.sessionCount = 0; } upload(e, t) { let s = t.buffer, n = t.byteOffset, o = t.byteLength, i = Ye(o), a = this.storageCache.get(e); if (!a) throw new Error("gpu data for uploading does not exist"); if (Number(a.originalSize) !== o) throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${o}`); let c = this.backend.device.createBuffer({ mappedAtCreation: !0, size: i, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC }), p = c.getMappedRange(); new Uint8Array(p).set(new Uint8Array(s, n, o)), c.unmap(); let h = this.backend.device.createCommandEncoder(); h.copyBufferToBuffer(c, 0, a.gpuData.buffer, 0, i), this.backend.device.queue.submit([h.finish()]), c.destroy(), as("verbose", () => `[WebGPU] GpuDataManager.upload(id=${e})`); } memcpy(e, t) { let s = this.storageCache.get(e); if (!s) throw new Error("source gpu data for memcpy does not exist"); let n = this.storageCache.get(t); if (!n) throw new Error("destination gpu data for memcpy does not exist"); if (s.originalSize !== n.originalSize) throw new Error("inconsistent source and destination gpu data size"); let o = Ye(s.originalSize), i = this.backend.getCommandEncoder(); this.backend.endComputePass(), i.copyBufferToBuffer(s.gpuData.buffer, 0, n.gpuData.buffer, 0, o); } registerExternalBuffer(e, t, s) { let n; if (s) { if (n = s[0], e === s[1]) return as("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`), n; 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!`); } else n = yt(); return this.storageCache.set(n, { gpuData: { id: n, type: 0, buffer: e }, originalSize: t }), as("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`), n; } unregisterExternalBuffer(e) { e !== void 0 && (this.storageCache.delete(e), as("verbose", () => `[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`)); } create(e, t = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) { let s = gt(e), n, o = (t & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE, i = (t & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM; if (o || i) { let c = (o ? this.freeBuffers : this.freeUniformBuffers).get(s); c ? c.length > 0 ? n = c.pop() : n = this.backend.device.createBuffer({ size: s, usage: t }) : n = this.backend.device.createBuffer({ size: s, usage: t }); } else n = this.backend.device.createBuffer({ size: s, usage: t }); let a = { id: yt(), type: 0, buffer: n }; return this.storageCache.set(a.id, { gpuData: a, originalSize: Number(e) }), as("verbose", () => `[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`), a; } get(e) { return this.storageCache.get(e)?.gpuData; } release(e) { let t = typeof e == "bigint" ? Number(e) : e, s = this.storageCache.get(t); if (!s) { if (this.storageCache.size === 0) return 0; throw new Error("releasing data does not exist"); } return as("verbose", () => `[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`), this.storageCache.delete(t), this.buffersPending.push(s.gpuData.buffer), s.originalSize; } async download(e, t) { let s = this.storageCache.get(Number(e)); if (!s) throw new Error("data does not exist"); await ht(this.backend, s.gpuData.buffer, s.originalSize, t); } refreshPendingBuffers() { if (this.buffersPending.length !== 0) if (this.backend.sessionStatus === "default") { for (let e of this.buffersPending) { let t = _e.get(e.size); if ((e.usage & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE) { let s = this.freeBuffers.get(e.size) || []; t === void 0 || s.length >= t ? e.destroy() : s.push(e); } else if ((e.usage & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM) { let s = this.freeUniformBuffers.get(e.size) || []; t === void 0 || s.length >= t ? e.destroy() : s.push(e); } else e.destroy(); } this.buffersPending = []; } else { let e = this.capturedPendingBuffers.get(this.backend.currentSessionId); e || (e = [], this.capturedPendingBuffers.set(this.backend.currentSessionId, e)); for (let t of this.buffersPending) e.push(t); this.buffersPending = []; } } dispose() { this.freeBuffers.forEach((e) => { e.forEach((t) => { t.destroy(); }); }), this.freeUniformBuffers.forEach((e) => { e.forEach((t) => { t.destroy(); }); }), this.storageCache.forEach((e) => { e.gpuData.buffer.destroy(); }), this.capturedPendingBuffers.forEach((e) => { e.forEach((t) => { t.destroy(); }); }), this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.capturedPendingBuffers = /* @__PURE__ */ new Map(); } onCreateSession() { this.sessionCount += 1; } onReleaseSession(e) { let t = this.capturedPendingBuffers.get(e); t && (t.forEach((s) => { s.destroy(); }), this.capturedPendingBuffers.delete(e)), this.sessionCount -= 1, this.sessionCount === 0 && (as("warning", () => "[WebGPU] Clearing webgpu buffer cache"), this.storageCache.forEach((s) => { s.gpuData.buffer.destroy(); }), this.storageCache = /* @__PURE__ */ new Map()); } }, Xt = (...e) => new ts(...e); }), Ks, jt, rs = y(() => { Ks = 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; } }, jt = (e) => new Ks(e); }), Hs, er, De, Xs, Cr, Es, qs, At = y(() => { Hs = class { static calcMatMulShape(e, t) { return e[1] !== t[0] ? void 0 : [e[0], t[1]]; } }, er = class { static calcShape(e, t, s = !1) { let n = e.length, o = t.length; if (n === 0) return t; if (o === 0) return e; let i = Math.max(e.length, t.length), a = new Array(i); if (s) { if (n < 2 || o < 2) return; let c = Hs.calcMatMulShape([e[n - 2], e[n - 1]], [t[o - 2], t[o - 1]]); if (c === void 0) return; [a[i - 2], a[i - 1]] = c; } for (let c = s ? 3 : 1; c <= i; c++) { let p = n - c < 0 ? 1 : e[n - c], h = o - c < 0 ? 1 : t[o - c]; if (p !== h && p > 1 && h > 1) return; let C = Math.max(p, h); if (p && h) a[i - c] = Math.max(p, h); else { if (C > 1) return; a[i - c] = 0; } } return a; } static isValidBroadcast(e, t) { let s = e.length, n = t.length; if (s > n) return !1; for (let o = 1; o <= s; o++) if (e[s - o] !== 1 && e[s - o] !== t[n - o]) return !1; return !0; } }, De = class Dp { static size(t) { return Dp.getSizeFromDimensionRange(t, 0, t.length); } static convertShape(t, s = 4) { let n = t.length; if (n === 0) return []; let o = new Array(n), i = n - 1; for (; i >= 0; ) { if (t[i] % s === 0) { o[i] = t[i] / s; break; } if (s % t[i] !== 0) throw new Error("cannot convert shape"); o[i] = 1, s /= t[i], i--; } for (i--; i >= 0; i--) o[i] = t[i]; return o; } static sizeFromDimension(t, s) { if (s < 0 || s > t.length) throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`); return Dp.getSizeFromDimensionRange(t, s, t.length); } static sizeToDimension(t, s) { if (s < 0 || s > t.length) throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`); return Dp.getSizeFromDimensionRange(t, 0, s); } static getSizeFromDimensionRange(t, s, n) { let o = 1; for (let i = s; 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 *= Number(t[i]); } return o; } static computeStrides(t) { let s = t.length; if (s === 0) return []; if (s === 1) return [1]; let n = new Array(s); n[s - 1] = 1, n[s - 2] = t[s - 1]; for (let o = s - 3; o >= 0; --o) n[o] = n[o + 1] * t[o + 1]; return n; } static normalizeAxis(t, s) { if (t < -s && t >= s) throw new Error("unsupported axis for this operation."); return t < 0 ? t + s : t; } static normalizeAxes(t, s) { return t.map((n) => this.normalizeAxis(n, s ?? t.length)); } static sortBasedOnPerm(t, s) { return s ? s.map((n) => t[n]) : t.slice().reverse(); } static padShape(t, s) { let n = t.length; return t.map((o, i) => o + s[i] + s[i + n]); } static areEqual(t, s) { return t.length !== s.length ? !1 : t.every((n, o) => n === s[o]); } }, Xs = class ac { static adjustPoolAttributes(t, s, n, o, i, a) { if (!t && n.length !== s.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); if (t) for (let c = 0; c < s.length - 2; c++) c >= n.length ? n.push(s[c + 2]) : n[c] = s[c + 2]; for (let c = 0; c < n.length; c++) if (c < o.length) { if (o[c] < 0) throw new Error("strides should be greater than or equal to 1"); } else o.push(1); for (let c = 0; c < n.length; c++) if (c < i.length) { if (i[c] < 0) throw new Error("dilations should be greater than or equal to 1"); } else i.push(1); for (let c = 0; c < n.length * 2; c++) if (c < a.length) { if (a[c] < 0) throw new Error("pad should be greater than or equal to 1"); } else a.push(0); for (let c = 0; c < n.length; c++) { if (n[c] <= 0) throw new Error("kernel shapes need to be greater than 0"); if (a[c] >= n[c] || a[c + n.length] >= n[c]) throw new Error("pads should be smaller than kernel"); } } static adjustPadsBasedOnAutoPad(t, s, n, o, i, a, c) { if (c) { if (i.length !== 2 * (t.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); if (s.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 p = 0; p < t.length - 2; p++) ac.adjustPadAndReturnShape(t[p + (a ? 1 : 2)], s[p], n[p], o[p], i, p, p + t.length - 2, c); } } static computePoolOutputShape(t, s, n, o, i, a, c) { if (s.length <= 0) throw new Error("input shape must be of size greater than 0"); let p = [s[0], s[1]]; return ac.computeShapeHelper(t, s, p, n, o, i, a, c), p; } static computeConvOutputShape(t, s, n, o, i, a, c) { if (t.length <= 0 || s.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); let p = [t[0], s[0]]; return ac.computeShapeHelper(!1, t, p, n, o, i, a, c), p; } static computeShapeHelper(t, s, n, o, i, a, c, p) { if (t) for (let h = 0; h < s.length - 2; h++) n.push(1); else for (let h = 0; h < s.length - 2; h++) n.push(ac.adjustPadAndReturnShape(s[h + 2], o[h], i[h], a[h], c, h, h + s.length - 2, p)); } static adjustPadAndReturnShape(t, s, n, o, i, a, c, p) { let h = n * (o - 1) + 1; if (p && p !== "NOTSET") switch (p) { case "VALID": return i[a] = 0, i[c] = 0, Math.floor((t - h) / s + 1); case "SAME_LOWER": case "SAME_UPPER": if (n !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); { let C = ((t + s - 1) / s - 1) * s + o - t; return i[a] = Math.floor(p === "SAME_LOWER" ? (C + 1) / 2 : C / 2), i[c] = C - i[a], Math.floor((t + C - o) / s + 1); } default: throw new Error("Unsupported AutoPad type"); } else return Math.floor((t + i[a] + i[c] - h) / s + 1); } }, Cr = class { static getShapeOfGemmResult(e, t, s, n, o) { if (e.length !== 2 || s.length !== 2) throw new Error("shape need to be of size 2"); let i, a, c; t ? (i = e[1], a = e[0]) : (i = e[0], a = e[1]); let p = -1; if (n ? (c = s[0], p = 1) : (c = s[1], p = 0), s[p] !== a) throw new Error("dimension mismatch"); if (i <= 0 || c <= 0 || a <= 0) throw new Error("invalid shape specified"); if (o && !er.isValidBroadcast(o, [i, c])) throw new Error("gemm: invalid bias shape for broadcast"); return [i, c, a]; } }, Es = -34028234663852886e22, qs = 34028234663852886e22; }), nr, hr, ds, Cs, Mt, Wt, Fs, ks, Us, Pt, Xr, qe, St, ka, Do, Sa, $a, Kt = y(() => { Ot(), At(), nr = 64, hr = (e, t) => { if (t === 3) throw new Error("vec3 has same alignment as vec4, use vec4 instead"); switch (Number(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"]; case 22: return "i32"; case 21: return "u32"; default: throw new Error(`Unknown data type: ${e}`); } }, ds = (e, t = 1) => { let s = hr(e, t); return typeof s == "string" ? s : s[0]; }, Cs = (e, t = 1) => { let s = hr(e, t); return typeof s == "string" ? s : s[1]; }, Mt = (...e) => { let t = []; return e.forEach((s) => { s.length !== 0 && t.push({ type: 12, data: s }, { type: 12, data: De.computeStrides(s) }); }), t; }, Wt = (e) => e % 4 === 0 ? 4 : e % 2 === 0 ? 2 : 1, Fs = (e = "f32", t, s = "0") => !t || t === 1 ? `${e}(${s})` : `vec${t}<${e}>(${s})`, ks = (e, t, s) => e === "f32" ? s : t === 1 ? `f32(${s})` : `vec${t}(${s})`, Us = (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, Pt = (e, t, s, n) => e.startsWith("uniforms.") && s > 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}]` : s > 1 ? `${e}[${t}]` : e, Xr = (e, t, s, n, o) => { let i = typeof s == "number", a = i ? s : s.length, c = [...new Array(a).keys()], p = a < 2 ? "u32" : a <= 4 ? `vec${a}` : `array`, h = hr(t, o), C = typeof h == "string" ? h : h[1], u = typeof h == "string" ? h : h[0], k = { indices: p, value: C, storage: u, tensor: t }, B = (ut) => typeof ut == "string" ? ut : `${ut}u`, R = { offsetToIndices: !1, indicesToOffset: !1, broadcastedIndicesToOffset: !1, set: !1, setByIndices: !1, get: !1, getByIndices: !1 }, z = i ? "uniforms." : "", ne = `${z}${e}_shape`, Z = `${z}${e}_strides`, W = ""; for (let ut = 0; ut < a - 1; ut++) W += ` let dim${ut} = current / ${Pt(Z, ut, a)}; let rest${ut} = current % ${Pt(Z, ut, a)}; indices[${ut}] = dim${ut}; current = rest${ut}; `; W += `indices[${a - 1}] = current;`; let ue = a < 2 ? "" : ` fn o2i_${e}(offset: u32) -> ${k.indices} { var indices: ${k.indices}; var current = offset; ${W} return indices; }`, he = (ut) => (R.offsetToIndices = !0, a < 2 ? ut : `o2i_${e}(${ut})`), Me = []; if (a >= 2) for (let ut = a - 1; ut >= 0; ut--) Me.push(`${Pt(Z, ut, a)} * (indices[${ut}])`); let Le = a < 2 ? "" : ` fn i2o_${e}(indices: ${k.indices}) -> u32 { return ${Me.join("+")}; }`, Ae = (ut) => (R.indicesToOffset = !0, a < 2 ? ut : `i2o_${e}(${ut})`), it = (...ut) => a === 0 ? "0u" : `${k.indices}(${ut.map(B).join(",")})`, dt = (ut, xt) => a < 2 ? `${ut}` : `${Pt(ut, xt, a)}`, kt = (ut, xt, hs) => a < 2 ? `${ut}=${hs};` : `${Pt(ut, xt, a)}=${hs};`, Et = {}, Ut = (ut, xt) => { R.broadcastedIndicesToOffset = !0; let hs = `${xt.name}broadcastedIndicesTo${e}Offset`; if (hs in Et) return `${hs}(${ut})`; let cs = []; for (let Js = a - 1; Js >= 0; Js--) { let vn = xt.indicesGet("outputIndices", Js + xt.rank - a); cs.push(`${dt(Z, Js)} * (${vn} % ${dt(ne, Js)})`); } return Et[hs] = `fn ${hs}(outputIndices: ${xt.type.indices}) -> u32 { return ${cs.length > 0 ? cs.join("+") : "0u"}; }`, `${hs}(${ut})`; }, pt = (ut, xt) => (() => { if (k.storage === k.value) return `${e}[${ut}]=${xt};`; if (k.storage === "vec2" && k.value === "i32") return `${e}[${ut}]=vec2(u32(${xt}), select(0u, 0xFFFFFFFFu, ${xt} < 0));`; if (k.storage === "vec2" && k.value === "u32") return `${e}[${ut}]=vec2(u32(${xt}), 0u);`; if (k.storage === "u32" && k.value === "vec4") return `${e}[${ut}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${xt}));`; throw new Error(`not supported combination of storage type ${k.storage} and value type ${k.value} yet`); })(), zt = (ut) => (() => { if (k.storage === k.value) return `${e}[${ut}]`; if (k.storage === "vec2" && k.value === "i32") return `i32(${e}[${ut}].x)`; if (k.storage === "vec2" && k.value === "u32") return `u32(${e}[${ut}].x)`; if (k.storage === "u32" && k.value === "vec4") return `vec4(bool(${e}[${ut}] & 0xFFu), bool(${e}[${ut}] & 0xFF00u), bool(${e}[${ut}] & 0xFF0000u), bool(${e}[${ut}] & 0xFF000000u))`; throw new Error(`not supported combination of storage type ${k.storage} and value type ${k.value} yet`); })(), ns = a < 2 ? "" : ` fn get_${e}ByIndices(indices: ${k.indices}) -> ${C} { return ${zt(`i2o_${e}(indices)`)}; }`, Tt = a < 2 ? "" : (() => { let ut = c.map((hs) => `d${hs}: u32`).join(", "), xt = c.map((hs) => `d${hs}`).join(", "); return ` fn get_${e}(${ut}) -> ${C} { return get_${e}ByIndices(${it(xt)}); }`; })(), Yt = (...ut) => { if (ut.length !== a) throw new Error(`indices length must be ${a}`); let xt = ut.map(B).join(","); return a === 0 ? zt("0u") : a === 1 ? zt(xt[0]) : (R.get = !0, R.getByIndices = !0, R.indicesToOffset = !0, `get_${e}(${xt})`); }, os = (ut) => a < 2 ? zt(ut) : (R.getByIndices = !0, R.indicesToOffset = !0, `get_${e}ByIndices(${ut})`), Vt = a < 2 ? "" : ` fn set_${e}ByIndices(indices: ${k.indices}, value: ${C}) { ${pt(`i2o_${e}(indices)`, "value")} }`, As = a < 2 ? "" : (() => { let ut = c.map((hs) => `d${hs}: u32`).join(", "), xt = c.map((hs) => `d${hs}`).join(", "); return ` fn set_${e}(${ut}, value: ${C}) { set_${e}ByIndices(${it(xt)}, value); }`; })(); return { impl: () => { let ut = [], xt = !1; return R.offsetToIndices && (ut.push(ue), xt = !0), R.indicesToOffset && (ut.push(Le), xt = !0), R.broadcastedIndicesToOffset && (Object.values(Et).forEach((hs) => ut.push(hs)), xt = !0), R.set && (ut.push(As), xt = !0), R.setByIndices && (ut.push(Vt), xt = !0), R.get && (ut.push(Tt), xt = !0), R.getByIndices && (ut.push(ns), xt = !0), !i && xt && ut.unshift(`const ${ne} = ${k.indices}(${s.join(",")});`, `const ${Z} = ${k.indices}(${De.computeStrides(s).join(",")});`), ut.join(` `); }, type: k, offsetToIndices: he, indicesToOffset: Ae, broadcastedIndicesToOffset: Ut, indices: it, indicesGet: dt, indicesSet: kt, set: (...ut) => { if (ut.length !== a + 1) throw new Error(`indices length must be ${a}`); let xt = ut[a]; if (typeof xt != "string") throw new Error("value must be string"); let hs = ut.slice(0, a).map(B).join(","); return a === 0 ? pt("0u", xt) : a === 1 ? pt(hs[0], xt) : (R.set = !0, R.setByIndices = !0, R.indicesToOffset = !0, `set_${e}(${hs}, ${xt})`); }, setByOffset: pt, setByIndices: (ut, xt) => a < 2 ? pt(ut, xt) : (R.setByIndices = !0, R.indicesToOffset = !0, `set_${e}ByIndices(${ut}, ${xt});`), get: Yt, getByOffset: zt, getByIndices: os, usage: n, name: e, strides: Z, shape: ne, rank: a }; }, qe = (e, t, s, n = 1) => Xr(e, t, s, "input", n), St = (e, t, s, n = 1) => Xr(e, t, s, "output", n), ka = (e, t, s) => Xr(e, t, s, "atomicOutput", 1), Do = (e, t, s, n = 1) => Xr(e, t, s, "internal", n), Sa = class { constructor(e, t) { this.normalizedDispatchGroup = e, this.limits = t, this.internalVariables = [], this.variables = [], this.uniforms = [], this.variableIndex = 0; } guardAgainstOutOfBoundsWorkgroupSizes(e) { return `if (global_idx >= ${typeof e == "number" ? `${e}u` : e}) { return; }`; } mainStart(e = nr) { let t = typeof e == "number" ? e : e[0], s = typeof e == "number" ? 1 : e[1], n = typeof e == "number" ? 1 : e[2]; if (t > this.limits.maxComputeWorkgroupSizeX || s > this.limits.maxComputeWorkgroupSizeY || n > this.limits.maxComputeWorkgroupSizeZ) throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`); if (t * s * n > this.limits.maxComputeInvocationsPerWorkgroup) throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`); let o = this.normalizedDispatchGroup[1] === 1 && this.normalizedDispatchGroup[2] === 1, i = o ? `@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @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`, a = o ? `let global_idx = global_id.x; let workgroup_index = workgroup_id.x;` : `let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x; let global_idx = workgroup_index * ${t * s * n}u + local_idx;`; return `@compute @workgroup_size(${t}, ${s}, ${n}) fn main(${i}) { ${a} `; } appendVariableUniforms(e) { e.rank !== 0 && (e.shape.startsWith("uniforms.") && this.uniforms.push({ name: e.shape.replace("uniforms.", ""), type: "u32", length: e.rank }), e.strides.startsWith("uniforms.") && this.uniforms.push({ name: e.strides.replace("uniforms.", ""), type: "u32", length: e.rank })); } declareVariable(e, t) { if (e.usage === "internal") throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead."); this.variables.push(e), this.appendVariableUniforms(e); let s = e.usage === "input" ? "read" : "read_write", n = e.usage === "atomicOutput" ? "atomic" : e.type.storage; return `@group(0) @binding(${t}) var ${e.name}: array<${n}>;`; } declareVariables(...e) { return e.map((t) => this.declareVariable(t, this.variableIndex++)).join(` `); } registerInternalVariable(e) { if (e.usage !== "internal") throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead."); this.internalVariables.push(e), this.appendVariableUniforms(e); } registerInternalVariables(...e) { return e.forEach((t) => this.registerInternalVariable(t)), this; } registerUniform(e, t, s = 1) { return this.uniforms.push({ name: e, type: t, length: s }), this; } registerUniforms(e) { return this.uniforms = this.uniforms.concat(e), this; } uniformDeclaration() { if (this.uniforms.length === 0) return ""; let e = []; for (let { name: t, type: s, length: n } of this.uniforms) if (n && n > 4) s === "f16" ? e.push(`@align(16) ${t}:array, ${Math.ceil(n / 8)}>`) : e.push(`${t}:array, ${Math.ceil(n / 4)}>`); else { let o = n == null || n === 1 ? s : `vec${n}<${s}>`; e.push(`${t}:${o}`); } return ` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`; } get additionalImplementations() { return this.uniformDeclaration() + this.variables.map((e) => e.impl()).join(` `) + this.internalVariables.map((e) => e.impl()).join(` `); } get variablesInfo() { if (this.uniforms.length === 0) return; let e = (t) => [12, 10, 1, 6][["u32", "f16", "f32", "i32"].indexOf(t)]; return this.uniforms.map((t) => [e(t.type), t.length ?? 1]); } }, $a = (e, t) => new Sa(e, t); }), Aa, Lo, zo, Ia, Fa, Bo, ur, Oa, Ro, Nr = y(() => { Ot(), At(), rs(), Kt(), Aa = (e, t) => { if (!e || e.length !== 1) throw new Error("Transpose requires 1 input."); if (t.length !== 0 && t.length !== e[0].dims.length) throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`); }, Lo = (e, t) => t.length !== 0 ? t : [...new Array(e).keys()].reverse(), zo = (e, t) => De.sortBasedOnPerm(e, Lo(e.length, t)), Ia = (e, t, s, n) => { let o = `fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`; for (let i = 0; i < t; ++i) o += `a[${e[i]}]=i[${i}];`; return o += "return a;}"; }, Fa = (e, t) => { let s = [], n = []; for (let o = 0; o < e.length; ++o) e[o] !== 1 && s.push(e[o]), e[t[o]] !== 1 && n.push(t[o]); return { newShape: s, newPerm: n }; }, Bo = (e, t) => { let s = 0; for (let n = 0; n < e.length; ++n) if (t[e[n]] !== 1) { if (e[n] < s) return !1; s = e[n]; } return !0; }, ur = (e, t) => { let s = e.dataType, n = e.dims.length, o = Lo(n, t), i = zo(e.dims, o), a = e.dims, c = i, p = n < 2 || Bo(o, e.dims), h; if (p) return h = (R) => { let z = qe("input", s, a, 4), ne = St("output", s, c, 4); return ` ${R.registerUniform("output_size", "u32").declareVariables(z, ne)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`; }, { name: "TransposeCopy", shaderCache: { inputDependencies: ["type"] }, getRunData: () => { let R = De.size(i); return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(R / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(R / 4) }] }; }, getShaderSource: h }; let { newShape: C, newPerm: u } = Fa(e.dims, o), k = De.areEqual(u, [2, 3, 1]), B = De.areEqual(u, [3, 1, 2]); if (C.length === 2 || k || B) { a = k ? [C[0], C[1] * C[2]] : B ? [C[0] * C[1], C[2]] : C, c = [a[1], a[0]]; let R = 16; return h = (z) => { let ne = qe("a", s, a.length), Z = St("output", s, c.length); return ` ${z.registerUniform("output_size", "u32").declareVariables(ne, Z)} var tile : array, ${R}>; ${z.mainStart([R, R, 1])} let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${R}u + local_id.x; let input_row = workgroup_id_x * ${R}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${ne.getByIndices(`${ne.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${R}u + local_id.x; let output_row = workgroup_id_y * ${R}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${Z.setByIndices(`${Z.type.indices}(output_row, output_col)`, "tile[local_id.x][local_id.y]")} } }`; }, { name: "TransposeShared", shaderCache: { inputDependencies: ["type"] }, getRunData: () => { let z = De.size(i); return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(c[1] / R), y: Math.ceil(c[0] / R) }, programUniforms: [{ type: 12, data: z }, ...Mt(a, c)] }; }, getShaderSource: h }; } return h = (R) => { let z = qe("a", s, a.length), ne = St("output", s, c.length); return ` ${R.registerUniform("output_size", "u32").declareVariables(z, ne)} ${Ia(o, n, z, ne)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${ne.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${ne.setByOffset("global_idx", z.getByIndices("aIndices"))} }`; }, { name: "Transpose", shaderCache: { hint: `${t}`, inputDependencies: ["rank"] }, getRunData: () => { let R = De.size(i); return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(R / 64) }, programUniforms: [{ type: 12, data: R }, ...Mt(a, c)] }; }, getShaderSource: h }; }, Oa = (e, t) => { Aa(e.inputs, t.perm), e.compute(ur(e.inputs[0], t.perm)); }, Ro = (e) => jt({ perm: e.perm }); }), so, Da, La, za, Ba, Ra, Na, ja, No, Va, dr, Yr, Ua, lc, Wa, uc, Ga, jo, Ka, Ha, qa, dc = y(() => { Ot(), At(), Kt(), oo(), Nr(), so = { 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" }, Da = { 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" }, La = { max: "_A[offset]", min: "_A[offset]", mean: "0", sum: "0", prod: "1", sumSquare: "0", logSumExp: "0", l1: "0", l2: "0", logSum: "0" }, za = { max: "bestValue", min: "bestValue", sum: "bestValue", prod: "bestValue", sumSquare: "bestValue", logSumExp: "log(bestValue)", l1: "bestValue", l2: "sqrt(bestValue)", logSum: "log(bestValue)" }, Ba = (e, t) => { let s = []; for (let n = t - e; n < t; ++n) s.push(n); return s; }, Ra = (e, t) => { let s = [], n = e.length; for (let i = 0; i < n; i++) t.indexOf(i) === -1 && s.push(e[i]); let o = t.map((i) => e[i]); return [s, o]; }, Na = (e, t) => { let s = e.length + t.length, n = [], o = 0; for (let i = 0; i < s; i++) t.indexOf(i) === -1 ? n.push(e[o++]) : n.push(1); return n; }, ja = (e, t) => { for (let s = 0; s < e.length; ++s) if (e[e.length - s - 1] !== t - 1 - s) return !1; return !0; }, No = (e, t) => { let s = []; if (!ja(e, t)) { for (let n = 0; n < t; ++n) e.indexOf(n) === -1 && s.push(n); e.forEach((n) => s.push(n)); } return s; }, Va = (e, t, s, n, o, i, a) => { let c = s[0].dims, p = De.size(i), h = De.size(a), C = qe("_A", s[0].dataType, c), u = St("output", o, i), k = 64; p === 1 && (k = 256); let B = ` var aBestValues : array; `, R = (z) => ` ${z.registerUniform("reduceSize", "u32").declareVariables(C, u)} ${B} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${z.mainStart(k)} let outputIndex = global_idx / ${k}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${La[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${k}) { let candidate = f32(${C.getByOffset("offset + k")}); bestValue = ${so[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${k}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 = ${Da[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}(${za[n]})`}`)}; } }`; return { name: e, shaderCache: { hint: `${t};${k}`, inputDependencies: ["type"] }, getShaderSource: R, getRunData: () => ({ outputs: [{ dims: i, dataType: o }], dispatchGroup: { x: p }, programUniforms: [{ type: 12, data: h }] }) }; }, dr = (e, t, s, n) => { let o = e.inputs.length === 1 ? s : Vo(e.inputs, s), i = o.axes; i.length === 0 && !o.noopWithEmptyAxes && (i = e.inputs[0].dims.map((B, R) => R)); let a = De.normalizeAxes(i, e.inputs[0].dims.length), c = a, p = e.inputs[0], h = No(c, e.inputs[0].dims.length); h.length > 0 && (p = e.compute(ur(e.inputs[0], h), { inputs: [0], outputs: [-1] })[0], c = Ba(c.length, p.dims.length)); let [C, u] = Ra(p.dims, c), k = C; o.keepDims && (k = Na(C, a)), e.compute(Va(t, o.cacheKey, [p], n, e.inputs[0].dataType, k, u), { inputs: [p] }); }, Yr = (e, t) => { dr(e, "ReduceMeanShared", t, "mean"); }, Ua = (e, t) => { dr(e, "ReduceL1Shared", t, "l1"); }, lc = (e, t) => { dr(e, "ReduceL2Shared", t, "l2"); }, Wa = (e, t) => { dr(e, "ReduceLogSumExpShared", t, "logSumExp"); }, uc = (e, t) => { dr(e, "ReduceMaxShared", t, "max"); }, Ga = (e, t) => { dr(e, "ReduceMinShared", t, "min"); }, jo = (e, t) => { dr(e, "ReduceProdShared", t, "prod"); }, Ka = (e, t) => { dr(e, "ReduceSumShared", t, "sum"); }, Ha = (e, t) => { dr(e, "ReduceSumSquareShared", t, "sumSquare"); }, qa = (e, t) => { dr(e, "ReduceLogSumShared", t, "logSum"); }; }), mr, ro, no, Vo, _r, Uo, Qa, Xa, Wo, Ya, Ja, Go, Za, el, Ko, fr, tl, Ho, sl, rl, qo, nl, ol, Qo, il, al, oo = y(() => { Ot(), At(), rs(), Kt(), dc(), mr = (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."); }, ro = (e) => ["", "", `var value = ${e.getByIndices("input_indices")};`, ""], no = (e, t, s, n, o, i, a = !1, c = !1) => { let p = [], h = s[0].dims, C = h.length, u = De.normalizeAxes(o, C), k = !c && u.length === 0; h.forEach((z, ne) => { k || u.indexOf(ne) >= 0 ? a && p.push(1) : p.push(z); }); let B = p.length, R = De.size(p); return { name: e, shaderCache: t, getShaderSource: (z) => { let ne = [], Z = qe("_A", s[0].dataType, C), W = St("output", i, B), ue = n(Z, W, u), he = ue[2]; for (let Me = 0, Le = 0; Me < C; Me++) k || u.indexOf(Me) >= 0 ? (a && Le++, he = `for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { ${ue[2].includes("last_index") ? `let last_index = j${Me};` : ""} ${Z.indicesSet("input_indices", Me, `j${Me}`)} ${he} }`) : (ne.push(`${Z.indicesSet("input_indices", Me, W.indicesGet("output_indices", Le))};`), Le++); return ` ${z.registerUniform("output_size", "u32").declareVariables(Z, W)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${Z.type.indices}; let output_indices = ${W.offsetToIndices("global_idx")}; ${ne.join(` `)} ${ue[0]} // init ops for reduce max/min ${ue[1]} ${he} ${ue[3]} ${ue.length === 4 ? W.setByOffset("global_idx", "value") : ue.slice(4).join(` `)} }`; }, getRunData: () => ({ outputs: [{ dims: p, dataType: i }], dispatchGroup: { x: Math.ceil(R / 64) }, programUniforms: [{ type: 12, data: R }, ...Mt(h, p)] }) }; }, Vo = (e, t) => { let s = []; return e[1].dims[0] > 0 && e[1].getBigInt64Array().forEach((n) => s.push(Number(n))), jt({ axes: s, keepDims: t.keepDims, noopWithEmptyAxes: t.noopWithEmptyAxes }); }, _r = (e, t, s, n) => { let o = e.inputs, i = o.length === 1 ? s : Vo(o, s); e.compute(no(t, { hint: i.cacheKey, inputDependencies: ["rank"] }, [o[0]], i.noopWithEmptyAxes && i.axes.length === 0 ? ro : n, i.axes, o[0].dataType, i.keepDims, i.noopWithEmptyAxes), { inputs: [0] }); }, Uo = (e, t) => { mr(e.inputs), _r(e, "ReduceLogSum", t, (s, n) => [`var value = ${n.type.storage}(0);`, "", `value += ${s.getByIndices("input_indices")};`, "value = log(value);"]); }, Qa = (e, t) => { mr(e.inputs), _r(e, "ReduceL1", t, (s, n) => [`var value = ${n.type.storage}(0);`, "", `value += abs(${s.getByIndices("input_indices")});`, ""]); }, Xa = (e, t) => { mr(e.inputs), _r(e, "ReduceL2", t, (s, n) => [`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`, "", `t = ${s.getByIndices("input_indices")}; value += (t * t);`, "value = sqrt(value);"]); }, Wo = (e, t) => { mr(e.inputs), _r(e, "ReduceLogSumExp", t, (s, n) => [`var value = ${n.type.storage}(0);`, "", `value += exp(${s.getByIndices("input_indices")});`, "value = log(value);"]); }, Ya = (e, t) => { mr(e.inputs), _r(e, "ReduceMax", t, (s, n, o) => { let i = []; for (let a = 0; a < s.rank; a++) (o.indexOf(a) >= 0 || o.length === 0) && i.push(s.indicesSet("input_indices", a, 0)); return [`${i.join(` `)}`, `var value = ${s.getByIndices("input_indices")};`, `value = max(value, ${s.getByIndices("input_indices")});`, ""]; }); }, Ja = (e, t) => { mr(e.inputs), _r(e, "ReduceMean", t, (s, n, o) => { let i = 1; for (let a = 0; a < s.rank; a++) (o.indexOf(a) >= 0 || o.length === 0) && (i *= e.inputs[0].dims[a]); return ["var sum = f32(0);", "", `sum += f32(${s.getByIndices("input_indices")});`, `let value = ${n.type.value}(sum / ${i});`]; }); }, Go = (e, t) => { mr(e.inputs), _r(e, "ReduceMin", t, (s, n, o) => { let i = []; for (let a = 0; a < s.rank; a++) (o.indexOf(a) >= 0 || o.length === 0) && i.push(`input_indices[${a}] = 0;`); return [`${i.join(` `)}`, `var value = ${s.getByIndices("input_indices")};`, `value = min(value, ${s.getByIndices("input_indices")});`, ""]; }); }, Za = (e, t) => { mr(e.inputs), _r(e, "ReduceProd", t, (s, n) => [`var value = ${n.type.storage}(1);`, "", `value *= ${s.getByIndices("input_indices")};`, ""]); }, el = (e, t) => { mr(e.inputs), _r(e, "ReduceSum", t, (s, n) => [`var value = ${n.type.storage}(0);`, "", `value += ${s.getByIndices("input_indices")};`, ""]); }, Ko = (e, t) => { mr(e.inputs), _r(e, "ReduceSumSquare", t, (s, n) => [`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`, "", `t = ${s.getByIndices("input_indices")}; value += t * t;`, ""]); }, fr = (e, t, s) => { if (t.length === 0) return s; 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; }, tl = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Ja(e, t) : Yr(e, t); }, Ho = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Qa(e, t) : Ua(e, t); }, sl = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Xa(e, t) : lc(e, t); }, rl = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Wo(e, t) : Wa(e, t); }, qo = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Ya(e, t) : uc(e, t); }, nl = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Go(e, t) : Ga(e, t); }, ol = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Za(e, t) : jo(e, t); }, Qo = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? el(e, t) : Ka(e, t); }, il = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Ko(e, t) : Ha(e, t); }, al = (e, t) => { fr(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Uo(e, t) : qa(e, t); }; }), Xo, ll, Yo, Jo, cc = y(() => { Ot(), rs(), oo(), Xo = (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."); }, ll = (e, t) => { Xo(e.inputs); let s = (n, o, i) => { let a = []; for (let c = 0; c < n.rank; c++) (i.indexOf(c) >= 0 || i.length === 0) && a.push(`input_indices[${c}] = 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(no("ArgMin", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], s, [t.axis], 7, t.keepDims), { inputs: [0] }); }, Yo = (e, t) => { Xo(e.inputs); let s = (n, o, i) => { let a = []; for (let c = 0; c < n.rank; c++) (i.indexOf(c) >= 0 || i.length === 0) && a.push(`input_indices[${c}] = 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(no("argMax", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], s, [t.axis], 7, t.keepDims), { inputs: [0] }); }, Jo = (e) => jt(e); }), Zo, io, ul, ei, dl, Dn, ti, cl, si = y(() => { Ot(), At(), ce(), Kt(), Zo = (e, t) => { let s = e[0], n = e[1], o = e[2], i = e[3], a = e[4], c = e[5]; if (a && c) throw new Error("Attention cannot have both past and attention_bias"); if (s.dims.length !== 3) throw new Error('Input "input" must have 3 dimensions'); let p = s.dims[0], h = s.dims[1], C = s.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] !== C) 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, k = u, B = k; if (t.qkvHiddenSizes.length > 0) { if (t.qkvHiddenSizes.length !== 3) throw new Error("qkv_hidden_sizes attribute should have 3 elements"); for (let ue of t.qkvHiddenSizes) if (ue % t.numHeads !== 0) throw new Error("qkv_hidden_sizes should be divisible by num_heads"); u = t.qkvHiddenSizes[0], k = t.qkvHiddenSizes[1], B = t.qkvHiddenSizes[2]; } let R = h; if (u !== k) throw new Error("qkv_hidden_sizes first element should be same as the second"); if (o.dims[0] !== u + k + B) throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes'); let z = 0; if (a) { if (k !== B) 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] !== p) 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] !== k / t.numHeads) throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads'); t.pastPresentShareBuffer || (z = a.dims[3]); } let ne = R + z, Z = -1, W = 0; if (i) throw new Error("Mask not supported"); if (a) throw new Error("past is not supported"); if (c) { if (c.dims.length !== 4) throw new Error('Input "attention_bias" must have 4 dimensions'); if (c.dims[0] !== p || c.dims[1] !== t.numHeads || c.dims[2] !== h || c.dims[3] !== ne) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)'); } return { batchSize: p, sequenceLength: h, pastSequenceLength: z, kvSequenceLength: R, totalSequenceLength: ne, maxSequenceLength: Z, inputHiddenSize: C, hiddenSize: u, vHiddenSize: B, headSize: Math.floor(u / t.numHeads), vHeadSize: Math.floor(B / t.numHeads), numHeads: t.numHeads, isUnidirectional: !1, pastPresentShareBuffer: !1, maskFilterValue: t.maskFilterValue, maskType: W, scale: t.scale, broadcastResPosBias: !1, passPastInKv: !1, qkvFormat: 1 }; }, io = (e, t, s) => t && e ? ` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; var past_sequence_length: u32 = 0; if (is_first_prompt == false) { past_sequence_length = total_sequence_length - sequence_length; } ` : ` ${s ? "let past_sequence_length = uniforms.past_sequence_length" : ""}; let present_sequence_length = total_sequence_length; `, ul = (e, t, s, n, o, i, a, c) => { let p = Wt(a ? 1 : i), h = 64, C = i / p; C < h && (h = 32); let u = Math.ceil(i / p / h), k = [{ type: 12, data: t }, { type: 12, data: s }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: C }, { type: 12, data: u }], B = ds(e.dataType, p), R = Cs(1, p), z = ["type"]; a && z.push("type"), c && z.push("type"); let ne = (Z) => { let W = St("x", e.dataType, e.dims, p), ue = [W], he = a ? qe("seq_lens", a.dataType, a.dims) : void 0; he && ue.push(he); let Me = c ? qe("total_sequence_length_input", c.dataType, c.dims) : void 0; Me && ue.push(Me); let Le = Cs(e.dataType), Ae = [{ name: "batch_size", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "sequence_length", type: "u32" }, { name: "total_sequence_length", type: "u32" }, { name: "elements_per_thread", type: "u32" }]; return ` var thread_max: array; var thread_sum: array; ${Z.registerUniforms(Ae).declareVariables(...ue)} ${Z.mainStart([h, 1, 1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${io(he, Me, !1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${a ? "u32(past_sequence_length + workgroup_id.y + 1)" : "total_sequence_length"}; var thread_max_vector = ${R}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(() => { switch (p) { 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: ${p}`); } })()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${h}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${R}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${R}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(() => { switch (p) { 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: ${p}`); } })()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${h}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${W.type.value}(${Le}(1.0) / ${Le}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${R}(x[offset + i]); x[offset + i] = ${W.type.value}(exp(f32input - max_value) / sum); } } ${a ? ` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${W.type.value}(${Le}(0)); }` : ""}; }`; }; return { name: "AttentionProbsSoftmax", shaderCache: { hint: `${h};${B};${p}`, inputDependencies: z }, getShaderSource: ne, getRunData: () => ({ outputs: [], dispatchGroup: { x: Math.ceil(i / h), y: o, z: t * s }, programUniforms: k }) }; }, ei = (e, t, s, n, o, i, a, c, p) => { let h = a + i.kvSequenceLength, C = [i.batchSize, i.numHeads, i.sequenceLength, h], u = e > 1 && n, k = i.kvNumHeads ? i.kvNumHeads : i.numHeads, B = u ? [i.batchSize, k, h, i.headSize] : void 0, R = i.nReps ? i.nReps : 1, z = i.scale === 0 ? 1 / Math.sqrt(i.headSize) : i.scale, ne = Wt(i.headSize), Z = i.headSize / ne, W = 12, ue = { x: Math.ceil(h / W), y: Math.ceil(i.sequenceLength / W), z: i.batchSize * i.numHeads }, he = [{ type: 12, data: i.sequenceLength }, { type: 12, data: Z }, { type: 12, data: h }, { type: 12, data: i.numHeads }, { type: 12, data: i.headSize }, { type: 1, data: z }, { type: 12, data: a }, { type: 12, data: i.kvSequenceLength }, { type: 12, data: R }], Me = u && n && De.size(n.dims) > 0, Le = ["type", "type"]; Me && Le.push("type"), o && Le.push("type"), c && Le.push("type"), p && Le.push("type"); let Ae = [{ dims: C, dataType: t.dataType, gpuDataType: 0 }]; u && Ae.push({ dims: B, dataType: t.dataType, gpuDataType: 0 }); let it = (dt) => { let kt = qe("q", t.dataType, t.dims, ne), Et = qe("key", s.dataType, s.dims, ne), Ut = [kt, Et]; if (Me) { let Vt = qe("past_key", n.dataType, n.dims, ne); Ut.push(Vt); } o && Ut.push(qe("attention_bias", o.dataType, o.dims)); let pt = c ? qe("seq_lens", c.dataType, c.dims) : void 0; pt && Ut.push(pt); let zt = p ? qe("total_sequence_length_input", p.dataType, p.dims) : void 0; zt && Ut.push(zt); let ns = St("output", t.dataType, C), Tt = [ns]; u && Tt.push(St("present_key", t.dataType, B, ne)); let Yt = Cs(1, ne), os = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "alpha", type: "f32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }]; return ` const TILE_SIZE = ${W}u; var tileQ: array<${kt.type.storage}, ${W * W}>; var tileK: array<${kt.type.storage}, ${W * W}>; ${dt.registerUniforms(os).declareVariables(...Ut, ...Tt)} ${dt.mainStart([W, W, 1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${R === 1 ? "headIdx" : "headIdx / uniforms.n_reps"}; let kv_num_heads = ${R === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${io(pt, zt, !0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${Me && u ? "let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;" : ""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${u ? "let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;" : ""} var value = ${Yt}(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; ${Me && u ? ` if (n + local_id.y < past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; }` : ` if (n + local_id.y < uniforms.kv_sequence_length) { tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; }`} ${u ? `if (n + local_id.y < present_sequence_length) { 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 += ${Yt}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(() => { switch (ne) { 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: ${ne}`); } })()}; output[outputIdx] = ${ns.type.value} (sum * uniforms.alpha) + ${o ? "attention_bias[outputIdx]" : "0.0"}; } }`; }; return { name: "AttentionProbs", shaderCache: { hint: `${ne};${o !== void 0};${n !== void 0};${e}`, inputDependencies: Le }, getRunData: () => ({ outputs: Ae, dispatchGroup: ue, programUniforms: he }), getShaderSource: it }; }, dl = (e, t, s, n, o, i, a = void 0, c = void 0) => { let p = i + o.kvSequenceLength, h = o.nReps ? o.nReps : 1, C = o.vHiddenSize * h, u = e > 1 && n, k = o.kvNumHeads ? o.kvNumHeads : o.numHeads, B = u ? [o.batchSize, k, p, o.headSize] : void 0, R = [o.batchSize, o.sequenceLength, C], z = 12, ne = { x: Math.ceil(o.vHeadSize / z), y: Math.ceil(o.sequenceLength / z), z: o.batchSize * o.numHeads }, Z = [{ type: 12, data: o.sequenceLength }, { type: 12, data: p }, { type: 12, data: o.vHeadSize }, { type: 12, data: o.numHeads }, { type: 12, data: o.headSize }, { type: 12, data: C }, { type: 12, data: i }, { type: 12, data: o.kvSequenceLength }, { type: 12, data: h }], W = u && n && De.size(n.dims) > 0, ue = ["type", "type"]; W && ue.push("type"), a && ue.push("type"), c && ue.push("type"); let he = [{ dims: R, dataType: t.dataType, gpuDataType: 0 }]; u && he.push({ dims: B, dataType: t.dataType, gpuDataType: 0 }); let Me = (Le) => { let Ae = qe("probs", t.dataType, t.dims), it = qe("v", s.dataType, s.dims), dt = [Ae, it]; W && dt.push(qe("past_value", n.dataType, n.dims)); let kt = a ? qe("seq_lens", a.dataType, a.dims) : void 0; a && dt.push(kt); let Et = c ? qe("total_sequence_length_input", c.dataType, c.dims) : void 0; c && dt.push(Et); let Ut = [St("output", t.dataType, R)]; u && Ut.push(St("present_value", t.dataType, B)); let pt = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "v_hidden_size", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }]; return ` const TILE_SIZE = ${z}u; var tileQ: array<${Ae.type.value}, ${z * z}>; var tileV: array<${Ae.type.value}, ${z * z}>; ${Le.registerUniforms(pt).declareVariables(...dt, ...Ut)} ${Le.mainStart([z, z, 1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${h === 1 ? "headIdx" : "headIdx / uniforms.n_reps"}; let kv_num_heads = ${h === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${io(kt, Et, !0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${W && u ? "let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;" : ""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${u ? "let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;" : ""} var value = ${Ae.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; ${W && u ? ` if (w + local_id.y < past_sequence_length) { tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; } ` : ` if (w + local_id.y < uniforms.kv_sequence_length) { tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; }`} ${u ? ` if (w + local_id.y < present_sequence_length) { present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; }` : ""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + headIdx * uniforms.N + n; output[outputIdx] = value; } }`; }; return { name: "AttentionScore", shaderCache: { hint: `${n !== void 0};${e}`, inputDependencies: ue }, getRunData: () => ({ outputs: he, dispatchGroup: ne, programUniforms: Z }), getShaderSource: Me }; }, Dn = (e, t, s, n, o, i, a, c, p, h, C = void 0, u = void 0) => { let k = Math.min(e.outputCount, 1 + (a ? 1 : 0) + (c ? 1 : 0)), B = k > 1 ? h.pastSequenceLength : 0, R = B + h.kvSequenceLength, z = p && De.size(p.dims) > 0 ? p : void 0, ne = [t, s]; k > 1 && a && De.size(a.dims) > 0 && ne.push(a), z && ne.push(z), C && ne.push(C), u && ne.push(u); let Z = e.compute(ei(k, t, s, a, z, h, B, C, u), { inputs: ne, outputs: k > 1 ? [-1, 1] : [-1] })[0]; e.compute(ul(Z, h.batchSize, h.numHeads, B, h.sequenceLength, R, C, u), { inputs: C && u ? [Z, C, u] : [Z], outputs: [] }); let W = [Z, n]; k > 1 && c && De.size(c.dims) > 0 && W.push(c), C && W.push(C), u && W.push(u), e.compute(dl(k, Z, n, c, h, B, C, u), { inputs: W, outputs: k > 1 ? [0, 2] : [0] }); }, ti = (e, t) => { let s = [t.batchSize, t.numHeads, t.sequenceLength, t.headSize], n = t.sequenceLength, o = t.inputHiddenSize, i = t.headSize, a = 12, c = { x: Math.ceil(t.headSize / a), y: Math.ceil(t.sequenceLength / a), z: t.batchSize * t.numHeads }, p = [e.inputs[0], e.inputs[1], e.inputs[2]], h = [{ 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 }], C = (u) => { let k = St("output_q", p[0].dataType, s), B = St("output_k", p[0].dataType, s), R = St("output_v", p[0].dataType, s), z = qe("input", p[0].dataType, p[0].dims), ne = qe("weight", p[1].dataType, p[1].dims), Z = qe("bias", p[2].dataType, p[2].dims), W = z.type.storage, ue = [{ 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<${W}, ${a * a}>; var tileWeightQ: array<${W}, ${a * a}>; var tileWeightK: array<${W}, ${a * a}>; var tileWeightV: array<${W}, ${a * a}>; ${u.registerUniforms(ue).declareVariables(z, ne, Z, k, B, R)} ${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 = ${W}(0); var valueK = ${W}(0); var valueV = ${W}(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: s, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: s, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: s, dataType: e.inputs[0].dataType, gpuDataType: 0 }], dispatchGroup: c, programUniforms: h }), getShaderSource: C }, { inputs: p, outputs: [-1, -1, -1] }); }, cl = (e, t) => { let s = Zo(e.inputs, t), [n, o, i] = ti(e, s); return Dn(e, n, o, i, e.inputs[4], void 0, void 0, void 0, e.inputs[5], s); }; }), ri, pl, hl, ni, pc = y(() => { ze(), Ot(), At(), rs(), Kt(), ri = (e, t) => { if (!e || e.length !== 5) throw new Error("BatchNormalization requires 5 inputs"); let s = (n, o, i) => { let a = o.length; if (a !== n.length) throw new Error(`${i}: num dimensions != ${a}`); o.forEach((c, p) => { if (c !== n[p]) throw new Error(`${i}: dim[${p}] 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); s(e[1].dims, n, "Invalid input scale"), s(e[2].dims, n, "Invalid input B"), s(e[3].dims, n, "Invalid input mean"), s(e[4].dims, n, "Invalid input var"); } else s(e[1].dims, [1], "Invalid input scale"), s(e[2].dims, [1], "Invalid input B"), s(e[3].dims, [1], "Invalid input mean"), s(e[4].dims, [1], "Invalid input var"); }, pl = (e, t) => { let { epsilon: s, spatial: n, format: o } = t, i = e[0].dims, a = n ? Wt(i[i.length - 1]) : 1, c = o === "NHWC" && i.length > 1 ? a : 1, p = De.size(i) / a, h = n, C = h ? i.length : i, u = qe("x", e[0].dataType, e[0].dims, a), k = qe("scale", e[1].dataType, e[1].dims, c), B = qe("bias", e[2].dataType, e[2].dims, c), R = qe("inputMean", e[3].dataType, e[3].dims, c), z = qe("inputVar", e[4].dataType, e[4].dims, c), ne = St("y", e[0].dataType, C, a), Z = () => { let ue = ""; if (n) ue = `let cOffset = ${i.length === 1 ? "0u" : o === "NHWC" ? `outputIndices[${i.length - 1}] / ${a}` : "outputIndices[1]"};`; else if (o === "NCHW") ue = ` ${ne.indicesSet("outputIndices", "0", "0")} let cOffset = ${ne.indicesToOffset("outputIndices")};`; else { ue = `var cIndices = ${k.type.indices}(0); cIndices[0] = outputIndices[${i.length - 1}];`; for (let he = 1; he < k.rank; he++) ue += `cIndices[${he}] = outputIndices[${he}];`; ue += `let cOffset = ${k.indicesToOffset("cIndices")};`; } return ue; }, W = (ue) => ` const epsilon = ${s}; ${ue.registerUniform("outputSize", "u32").declareVariables(u, k, B, R, z, ne)} ${ue.mainStart()} ${ue.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${ne.offsetToIndices(`global_idx * ${a}`)}; ${Z()} let scale = ${k.getByOffset("cOffset")}; let bias = ${B.getByOffset("cOffset")}; let inputMean = ${R.getByOffset("cOffset")}; let inputVar = ${z.getByOffset("cOffset")}; let x = ${u.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${ne.setByOffset("global_idx", "value")} }`; return { name: "BatchNormalization", shaderCache: { hint: `${t.epsilon}_${t.format}_${n}_${a}`, inputDependencies: h ? ["rank", "type", "type", "type", "type"] : void 0 }, getShaderSource: W, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: h ? [{ type: 12, data: p }, ...Mt(i)] : [{ type: 12, data: p }] }) }; }, hl = (e) => jt(e), ni = (e, t) => { let { inputs: s, outputCount: n } = e, o = hl({ ...t, outputCount: n }); if (I.webgpu.validateInputContent && ri(s, o), t.trainingMode) throw new Error("BatchNormalization trainingMode is not supported yet."); e.compute(pl(s, o)); }; }), ml, oi, _l, hc = y(() => { At(), Kt(), ml = (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"); }, oi = (e) => { let t = e[0].dims, s = e[0].dims[2], n = De.size(t) / 4, o = e[0].dataType, i = qe("input", o, t, 4), a = qe("bias", o, [s], 4), c = qe("residual", o, t, 4), p = St("output", o, t, 4); return { name: "BiasAdd", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(n / 64) } }), getShaderSource: (h) => ` const channels = ${s}u / 4; ${h.declareVariables(i, a, c, p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} let value = ${i.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")}; ${p.setByOffset("global_idx", "value")} }` }; }, _l = (e) => { ml(e.inputs), e.compute(oi(e.inputs)); }; }), ii, ls, fl, ai, gl, wl, li, yl, Ml, ui, bl, vl, di, xl, Tl, ci, Ln, Pl, ao, El, pi, Cl, kl, hi, Sl, $l, mi, Al, Il, _i, Fl, Ol, fi, Dl, Ll, lo, zl, gi, uo, Bl, Rl, Nl, jl, wi, Vl, yi = y(() => { Ot(), At(), rs(), Kt(), ii = (e, t, s, n, o, i, a) => { let c = Math.ceil(t / 4), p = ""; typeof o == "string" ? p = `${o}(a)` : p = o("a"); let h = qe("inputData", s, [c], 4), C = St("outputData", n, [c], 4), u = [{ name: "vec_size", type: "u32" }]; return a && u.push(...a), ` ${e.registerUniforms(u).declareVariables(h, C)} ${i ?? ""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${C.setByOffset("global_idx", p)} }`; }, ls = (e, t, s, n, o, i = e.dataType, a, c) => { let p = [{ type: 12, data: Math.ceil(De.size(e.dims) / 4) }]; return a && p.push(...a), { name: t, shaderCache: { hint: o, inputDependencies: ["type"] }, getShaderSource: (h) => ii(h, De.size(e.dims), e.dataType, i, s, n, c), getRunData: (h) => ({ outputs: [{ dims: e.dims, dataType: i }], dispatchGroup: { x: Math.ceil(De.size(h[0].dims) / 64 / 4) }, programUniforms: p }) }; }, fl = (e) => { e.compute(ls(e.inputs[0], "Abs", "abs")); }, ai = (e) => { e.compute(ls(e.inputs[0], "Acos", "acos")); }, gl = (e) => { e.compute(ls(e.inputs[0], "Acosh", "acosh")); }, wl = (e) => { e.compute(ls(e.inputs[0], "Asin", "asin")); }, li = (e) => { e.compute(ls(e.inputs[0], "Asinh", "asinh")); }, yl = (e) => { e.compute(ls(e.inputs[0], "Atan", "atan")); }, Ml = (e) => { e.compute(ls(e.inputs[0], "Atanh", "atanh")); }, ui = (e) => jt(e), bl = (e, t) => { let s; switch (t.to) { case 10: s = "vec4"; break; case 1: s = "vec4"; break; case 12: s = "vec4"; break; case 6: s = "vec4"; break; case 9: s = "vec4"; break; default: throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`); } e.compute(ls(e.inputs[0], "Cast", s, void 0, t.cacheKey, t.to)); }, vl = (e) => { let t, s, n = e.length >= 2 && e[1].data !== 0, o = e.length >= 3 && e[2].data !== 0; switch (e[0].dataType) { case 1: t = n ? e[1].getFloat32Array()[0] : -34028234663852886e22, s = o ? e[2].getFloat32Array()[0] : 34028234663852886e22; break; case 10: t = n ? e[1].getUint16Array()[0] : 64511, s = o ? e[2].getUint16Array()[0] : 31743; break; default: throw new Error("Unsupport data type"); } return jt({ min: t, max: s }); }, di = (e, t) => { let s = t || vl(e.inputs), n = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "Clip", (o) => `clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`, void 0, s.cacheKey, void 0, [{ type: e.inputs[0].dataType, data: s.min }, { type: e.inputs[0].dataType, data: s.max }], [{ name: "min", type: n }, { name: "max", type: n }]), { inputs: [0] }); }, xl = (e) => { e.compute(ls(e.inputs[0], "Ceil", "ceil")); }, Tl = (e) => { e.compute(ls(e.inputs[0], "Cos", "cos")); }, ci = (e) => { e.compute(ls(e.inputs[0], "Cosh", "cosh")); }, Ln = (e) => jt(e), Pl = (e, t) => { let s = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "Elu", (n) => `elu_vf32(${n})`, ` const elu_alpha_ = ${s}(${t.alpha}); fn elu_f32(a: ${s}) -> ${s} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`, t.cacheKey)); }, ao = (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)); }`, El = (e) => { let t = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "Erf", (s) => `erf_vf32(${s})`, ao(t))); }, pi = (e) => { e.compute(ls(e.inputs[0], "Exp", "exp")); }, Cl = (e) => { e.compute(ls(e.inputs[0], "Floor", "floor")); }, kl = (e) => { let t = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "Gelu", (s) => `0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`, ao(t))); }, hi = (e, t) => { let s = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "LeakyRelu", (n) => `select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`, `const leaky_relu_alpha_ = ${s}(${t.alpha});`, t.cacheKey)); }, Sl = (e) => { e.compute(ls(e.inputs[0], "Not", (t) => `!${t}`)); }, $l = (e) => { e.compute(ls(e.inputs[0], "Neg", (t) => `-${t}`)); }, mi = (e) => { e.compute(ls(e.inputs[0], "Reciprocal", (t) => `1.0/${t}`)); }, Al = (e) => { let t = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "Relu", (s) => `select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`)); }, Il = (e) => { e.compute(ls(e.inputs[0], "Sigmoid", (t) => `(1.0 / (1.0 + exp(-${t})))`)); }, _i = (e) => jt(e), Fl = (e, t) => { let s = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "HardSigmoid", (n) => `max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`, void 0, t.cacheKey)); }, Ol = (e) => { e.compute(ls(e.inputs[0], "Sin", "sin")); }, fi = (e) => { e.compute(ls(e.inputs[0], "Sinh", "sinh")); }, Dl = (e) => { e.compute(ls(e.inputs[0], "Sqrt", "sqrt")); }, Ll = (e) => { e.compute(ls(e.inputs[0], "Tan", "tan")); }, lo = (e) => `sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`, zl = (e) => { e.compute(ls(e.inputs[0], "Tanh", lo)); }, gi = (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 ${lo("v")}; } `, uo = (e) => `(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`, Bl = (e) => { let t = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "FastGelu", uo, gi(t), void 0, e.inputs[0].dataType)); }, Rl = (e, t) => { let s = Cs(e.inputs[0].dataType); return e.compute(ls(e.inputs[0], "ThresholdedRelu", (n) => `select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`, `const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`, t.cacheKey)), 0; }, Nl = (e) => { e.compute(ls(e.inputs[0], "Log", "log")); }, jl = (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; } `, wi = (e) => `quick_gelu_impl(${e})`, Vl = (e, t) => { let s = Cs(e.inputs[0].dataType); e.compute(ls(e.inputs[0], "QuickGelu", wi, jl(s, t.alpha), t.cacheKey, e.inputs[0].dataType)); }; }), Ul, Wl, Mi, mc = y(() => { At(), Kt(), yi(), Ul = (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"); }, Wl = (e) => { let t = e[0].dims.slice(); t[2] = t[2] / 2; let s = qe("input", e[0].dataType, e[0].dims, 4), n = qe("bias", e[0].dataType, [e[0].dims[2]], 4), o = St("output", e[0].dataType, t, 4), i = De.size(t) / 4, a = ds(e[0].dataType); return { name: "BiasSplitGelu", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) } }), getShaderSource: (c) => ` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2] / 4 / 2}u; ${c.declareVariables(s, n, o)} ${ao(a)} ${c.mainStart()} ${c.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")} }` }; }, Mi = (e) => { Ul(e.inputs), e.compute(Wl(e.inputs)); }; }), Gl, Kl, gr, bi, Hl, ql, Ql, Xl, vi, Yl, Jl, xi, Zl, _c = y(() => { Ot(), At(), Kt(), Gl = (e, t, s, n, o, i, a, c, p, h, C, u) => { let k, B; typeof c == "string" ? k = B = (W, ue) => `${c}((${W}),(${ue}))` : typeof c == "function" ? k = B = c : (k = c.scalar, B = c.vector); let R = St("outputData", C, n.length, 4), z = qe("aData", p, t.length, 4), ne = qe("bData", h, s.length, 4), Z; if (o) if (i) { let W = De.size(t) === 1, ue = De.size(s) === 1, he = t.length > 0 && t[t.length - 1] % 4 === 0, Me = s.length > 0 && s[s.length - 1] % 4 === 0; W || ue ? Z = R.setByOffset("global_idx", B(W ? `${z.type.value}(${z.getByOffset("0")}.x)` : z.getByOffset("global_idx"), ue ? `${ne.type.value}(${ne.getByOffset("0")}.x)` : ne.getByOffset("global_idx"))) : Z = ` let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; let offsetA = ${z.broadcastedIndicesToOffset("outputIndices", R)}; let offsetB = ${ne.broadcastedIndicesToOffset("outputIndices", R)}; ${R.setByOffset("global_idx", B(a || he ? z.getByOffset("offsetA / 4u") : `${z.type.value}(${z.getByOffset("offsetA / 4u")}[offsetA % 4u])`, a || Me ? ne.getByOffset("offsetB / 4u") : `${ne.type.value}(${ne.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `; } else Z = R.setByOffset("global_idx", B(z.getByOffset("global_idx"), ne.getByOffset("global_idx"))); else { if (!i) throw new Error("no necessary to use scalar implementation for element-wise binary op implementation."); let W = (ue, he, Me = "") => { let Le = `aData[indexA${he}][componentA${he}]`, Ae = `bData[indexB${he}][componentB${he}]`; return ` let outputIndices${he} = ${R.offsetToIndices(`global_idx * 4u + ${he}u`)}; let offsetA${he} = ${z.broadcastedIndicesToOffset(`outputIndices${he}`, R)}; let offsetB${he} = ${ne.broadcastedIndicesToOffset(`outputIndices${he}`, R)}; let indexA${he} = offsetA${he} / 4u; let indexB${he} = offsetB${he} / 4u; let componentA${he} = offsetA${he} % 4u; let componentB${he} = offsetB${he} % 4u; ${ue}[${he}] = ${Me}(${k(Le, Ae)}); `; }; C === 9 ? Z = ` var data = vec4(0); ${W("data", 0, "u32")} ${W("data", 1, "u32")} ${W("data", 2, "u32")} ${W("data", 3, "u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : Z = ` ${W("outputData[global_idx]", 0)} ${W("outputData[global_idx]", 1)} ${W("outputData[global_idx]", 2)} ${W("outputData[global_idx]", 3)} `; } return ` ${e.registerUniform("vec_size", "u32").declareVariables(z, ne, R)} ${u ?? ""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${Z} }`; }, Kl = (e, t, s, n, o, i, a = s.dataType) => { let c = s.dims.map((z) => Number(z) ?? 1), p = n.dims.map((z) => Number(z) ?? 1), h = !De.areEqual(c, p), C = c, u = De.size(c), k = !1, B = !1, R = [h]; if (h) { let z = er.calcShape(c, p, !1); if (!z) throw new Error("Can't perform binary op on the given tensors"); C = z.slice(), u = De.size(C); let ne = De.size(c) === 1, Z = De.size(p) === 1, W = c.length > 0 && c[c.length - 1] % 4 === 0, ue = p.length > 0 && p[p.length - 1] % 4 === 0; R.push(ne), R.push(Z), R.push(W), R.push(ue); let he = 1; for (let Me = 1; Me < C.length; Me++) { let Le = c[c.length - Me], Ae = p[p.length - Me]; if (Le === Ae) he *= Le; else break; } he % 4 === 0 ? (B = !0, k = !0) : (ne || Z || W || ue) && (k = !0); } else k = !0; return R.push(k), { name: e, shaderCache: { hint: t + R.map((z) => z.toString()).join("_"), inputDependencies: ["rank", "rank"] }, getShaderSource: (z) => Gl(z, c, p, C, k, h, B, o, s.dataType, n.dataType, a, i), getRunData: () => ({ outputs: [{ dims: C, dataType: a }], dispatchGroup: { x: Math.ceil(u / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(De.size(C) / 4) }, ...Mt(c, p, C)] }) }; }, gr = (e, t, s, n, o, i) => { e.compute(Kl(t, o ?? "", e.inputs[0], e.inputs[1], s, n, i)); }, bi = (e) => { gr(e, "Add", (t, s) => `${t}+${s}`); }, Hl = (e) => { gr(e, "Div", (t, s) => `${t}/${s}`); }, ql = (e) => { gr(e, "Equal", { scalar: (t, s) => `u32(${t}==${s})`, vector: (t, s) => `vec4(${t}==${s})` }, void 0, void 0, 9); }, Ql = (e) => { gr(e, "Mul", (t, s) => `${t}*${s}`); }, Xl = (e) => { let t = qe("input", e.inputs[0].dataType, e.inputs[0].dims).type.value; gr(e, "Pow", { scalar: (s, n) => `pow_custom(${s},${n})`, vector: (s, n) => `pow_vector_custom(${s},${n})` }, ` 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)); } `); }, vi = (e) => { gr(e, "Sub", (t, s) => `${t}-${s}`); }, Yl = (e) => { gr(e, "Greater", { scalar: (t, s) => `u32(${t}>${s})`, vector: (t, s) => `vec4(${t}>${s})` }, void 0, void 0, 9); }, Jl = (e) => { gr(e, "Less", { scalar: (t, s) => `u32(${t}<${s})`, vector: (t, s) => `vec4(${t}<${s})` }, void 0, void 0, 9); }, xi = (e) => { gr(e, "GreaterOrEqual", { scalar: (t, s) => `u32(${t}>=${s})`, vector: (t, s) => `vec4(${t}>=${s})` }, void 0, void 0, 9); }, Zl = (e) => { gr(e, "LessOrEqual", { scalar: (t, s) => `u32(${t}<=${s})`, vector: (t, s) => `vec4(${t}<=${s})` }, void 0, void 0, 9); }; }), Ti, eu, tu, Pi, su, ru, nu = y(() => { Ot(), At(), rs(), Kt(), Ti = (e, t) => { if (!e || e.length < 1) throw new Error("too few inputs"); let s = 0, n = e[s], o = n.dataType, i = n.dims.length; e.forEach((a, c) => { if (c !== s) { 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((p, h) => { if (h !== t && p !== n.dims[h]) throw new Error("non concat dimensions must match"); }); } }); }, eu = (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; }`, tu = (e, t) => { let s = e.length, n = []; for (let o = 0; o < s; ++o) { let i = t.setByOffset("global_idx", e[o].getByIndices("indices")); s === 1 ? n.push(i) : o === 0 ? n.push(`if (inputIndex == ${o}u) { ${i} }`) : o === s - 1 ? n.push(`else { ${i} }`) : n.push(`else if (inputIndex == ${o}) { ${i} }`); } return n.join(` `); }, Pi = (e, t, s, n) => { let o = De.size(s), i = new Array(e.length), a = new Array(e.length), c = 0, p = [], h = [], C = [{ type: 12, data: o }]; for (let z = 0; z < e.length; ++z) c += e[z].dims[t], i[z] = c, h.push(e[z].dims.length), a[z] = qe(`input${z}`, n, h[z]), p.push("rank"), C.push({ type: 12, data: i[z] }); for (let z = 0; z < e.length; ++z) C.push(...Mt(e[z].dims)); C.push(...Mt(s)); let u = St("output", n, s.length), k = u.indicesGet("indices", t), B = Array.from(Array(i.length).keys()).map((z) => `uniforms.sizeInConcatAxis${z}`).join(","), R = (z) => ` ${(() => { z.registerUniform("outputSize", "u32"); for (let ne = 0; ne < e.length; ne++) z.registerUniform(`sizeInConcatAxis${ne}`, "u32"); return z.declareVariables(...a, u); })()} ${eu(i.length, B)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var indices = ${u.offsetToIndices("global_idx")}; let inputIndex = calculateInputIndex(${k}); if (inputIndex != 0u) { let sizeInConcatAxis = array(${B}); ${k} -= sizeInConcatAxis[inputIndex - 1u]; } ${tu(a, u)} }`; return { name: "Concat", shaderCache: { hint: `${t}`, inputDependencies: p }, getRunData: () => ({ outputs: [{ dims: s, dataType: n }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: C }), getShaderSource: R }; }, su = (e, t) => { let s = e.inputs, n = s[0].dims, o = De.normalizeAxis(t.axis, n.length); Ti(s, o); let i = n.slice(); i[o] = s.reduce((c, p) => c + (p.dims.length > o ? p.dims[o] : 0), 0); let a = s.filter((c) => De.size(c.dims) > 0); e.compute(Pi(a, o, i, s[0].dataType), { inputs: a }); }, ru = (e) => jt({ axis: e.axis }); }), Jr, Zr, kr, Ei, en = y(() => { Ot(), At(), Jr = (e, t, s = "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}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`; case "HardSigmoid": return `value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`; case "LeakyRelu": return `value = select(${s}(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}`); } }, Zr = (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 }); }, kr = (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" }); }, Ei = (e) => { let t = e?.activation || ""; if (t === "HardSigmoid") { let [s, n] = e?.activation_params || [0.2, 0.5]; return { activation: t, alpha: s, beta: n }; } else if (t === "Clip") { let [s, n] = e?.activation_params || [Es, qs]; return { activation: t, clipMax: n, clipMin: s }; } else if (t === "LeakyRelu") { let [s] = e?.activation_params || [0.01]; return { activation: t, alpha: s }; } return { activation: t }; }; }), Ws, Ci, ki = y(() => { Ws = (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.`); } }, Ci = (e) => ` ${e ? "value = value + getBiasByOutputCoords(coords);" : ""} `; }), Si, fc = y(() => { Si = (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)); } `; }), zn, $i, co = y(() => { Ot(), At(), Kt(), en(), zn = (e, t, s, n, o) => { let i = n - s; return ` ${Array.from({ length: s }).map((a, c) => ` if (${Pt(t.shape, c, t.rank)} != 1) { ${t.indicesSet(e, c, Pt(o, c + i, n))} } else { ${t.indicesSet(e, c, 0)} }`).join("")} `; }, $i = (e, t, s, n, o = !1, i) => { let a = e[0].dims, c = e[1].dims, p = a[a.length - 2], h = c[c.length - 1], C = a[a.length - 1], u = Wt(h), k = Wt(C), B = Wt(p), R = De.size(s) / u / B, z = e.length > 2, ne = n ? n.slice(0, -2) : s.slice(0, -2), Z = [De.size(ne), p, h], W = [{ type: 12, data: R }, { type: 12, data: p }, { type: 12, data: h }, { type: 12, data: C }]; Zr(t, W), W.push(...Mt(ne, a, c)), z && W.push(...Mt(e[2].dims)), W.push(...Mt(Z)); let ue = (he) => { let Me = Do("batch_dims", e[0].dataType, ne.length), Le = qe("a", e[0].dataType, a.length, k), Ae = qe("b", e[1].dataType, c.length, u), it = St("output", e[0].dataType, Z.length, u), dt = ds(it.type.tensor), kt = Jr(t, it.type.value, dt), Et = [Le, Ae], Ut = ""; if (z) { let ns = o ? u : 1; Et.push(qe("bias", e[2].dataType, e[2].dims.length, ns)), Ut = `${o ? `value += bias[col / ${ns}];` : `value += ${it.type.value}(bias[row + i]);`}`; } let pt = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }]; kr(t, pt); let zt = () => { let ns = `var a_data: ${Le.type.value};`; for (let Tt = 0; Tt < k; Tt++) ns += ` let b_data${Tt} = b[(b_offset + (k + ${Tt}) * uniforms.N + col) / ${u}];`; for (let Tt = 0; Tt < B; Tt++) { ns += `a_data = a[(a_offset + (row + ${Tt}) * uniforms.K + k) / ${k}];`; for (let Yt = 0; Yt < k; Yt++) ns += ` values[${Tt}] = fma(${Ae.type.value}(a_data${k === 1 ? "" : `[${Yt}]`}), b_data${Yt}, values[${Tt}]); `; } return ns; }; return ` ${he.registerUniforms(pt).registerInternalVariables(Me).declareVariables(...Et, it)} ${he.mainStart()} ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let col = (global_idx % (uniforms.N / ${u})) * ${u}; var index1 = global_idx / (uniforms.N / ${u}); let stride1 = uniforms.M / ${B}; let row = (index1 % stride1) * ${B}; let batch = index1 / stride1; ${s.length === 2 ? "" : `let batch_indices = ${Me.offsetToIndices("batch")};`} var a_indices: ${Le.type.indices}; ${zn("a_indices", Le, Le.rank - 2, Me.rank, "batch_indices")} ${Le.indicesSet("a_indices", Le.rank - 2, 0)} ${Le.indicesSet("a_indices", Le.rank - 1, 0)} let a_offset = ${Le.indicesToOffset("a_indices")}; var b_indices: ${Ae.type.indices}; ${zn("b_indices", Ae, Ae.rank - 2, Me.rank, "batch_indices")} ${Ae.indicesSet("b_indices", Ae.rank - 2, 0)} ${Ae.indicesSet("b_indices", Ae.rank - 1, 0)} let b_offset = ${Ae.indicesToOffset("b_indices")}; var values: array<${it.type.value}, ${B}>; for (var k: u32 = 0u; k < uniforms.K; k = k + ${k}) { ${zt()} } for (var i = 0u; i < ${B}u; i++) { var value = values[i]; ${Ut} ${kt} let cur_indices = ${it.type.indices}(batch, row + i, col); let offset = ${it.indicesToOffset("cur_indices")}; ${it.setByOffset(`offset / ${u}`, "value")}; } } `; }; return { name: "MatMulNaive", shaderCache: { hint: `${t.activation};${u};${k};${B};${o}`, inputDependencies: z ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: i ? i(s) : s, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(R / 64) }, programUniforms: W }), getShaderSource: ue }; }; }), ou, iu, Ai, po, au, Ii, Fi, ho, Oi = y(() => { Ot(), At(), Kt(), en(), co(), ki(), ou = (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" : ""}); `, iu = (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];"} }`, Ai = (e, t, s = "f32", n, o = !1, i = 32, a = !1, c = 32) => { let p = t[1] * e[1], h = t[0] * e[0], C = o ? p : i, u = o ? i : p, k = C / t[0], B = i / t[1]; if (!((o && k === 4 && e[1] === 4 || !o && (k === 3 || k === 4)) && C % t[0] === 0 && i % t[1] === 0 && e[0] === 4)) throw new Error(`If transposeA ${o} is true, innerElementSize ${k} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${k} must be 3 or 4. tileAWidth ${C} 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, ${C / k}>, ${u}>; var mm_Bsub: array, ${h / e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${k}; 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) * ${p}; let num_tiles = ${a ? `${Math.ceil(c / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a ? `i32(globalId.z) * ${c}` : "0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${B}; 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; ${ou(o, n)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${B}; 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]; ${k === 3 ? "" : "let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${iu(o, k)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`; }, po = (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" : ""}); `, au = (e) => e ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];", Ii = (e, t, s = "f32", n, o = !1, i = 32, a = !1, c = 32, p = !1) => { let h = e[1] * t[1], C = e[0] * t[0], u = o ? h : i, k = o ? i : h; if (!(k % t[1] === 0 && u % t[0] === 0 && i % t[1] === 0)) throw new Error(`tileAHight ${k} 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 B = k / t[1], R = u / t[0], z = i / t[1], ne = p ? ` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${C}; // 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 < ${k}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { ${po(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 < ${C}; 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<${s}, 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) * ${h}; let tileRowA = i32(localId.y) * ${B}; let tileColA = i32(localId.x) * ${R}; let tileRowB = i32(localId.y) * ${z}; // 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 < ${B}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${po(o, n)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${z}; 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<${s}, 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) { ${au(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, ${k}>; 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(c / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a ? `i32(globalId.z) * ${c}` : "0"}; var acc : array, rowPerThread>; ${ne} } `; }, Fi = (e, t, s, n, o = !1) => { let [i, a, c, p] = n, h = ds(n[0].type.tensor); return ` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ws(e, h)} { var value = ${Ws(e, h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${a.type.indices}; ${zn("aIndices", a, a.rank - 2, i.rank, "batchIndices")} ${a.indicesSet("aIndices", a.rank - 2, "u32(row)")} ${a.indicesSet("aIndices", a.rank - 1, "u32(colIn)")} value = ${a.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ws(e, h)} { var value = ${Ws(e, h)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${c.type.indices}; ${zn("bIndices", c, c.rank - 2, i.rank, "batchIndices")} ${c.indicesSet("bIndices", c.rank - 2, "u32(row)")} ${c.indicesSet("bIndices", c.rank - 1, "u32(colIn)")} value = ${c.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ws(e, h)}) { 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 + ${o ? "bias[colIn]" : `${Ws(e, h)}(bias[row])`};` : ""} ${s} ${p.setByIndices("vec3(coords)", "value")} } } `; }, ho = (e, t, s, n, o = !1, i) => { let a = e[0].dims, c = e[1].dims, p = a.slice(0, -2), h = c.slice(0, -2), C = n ? n.slice(0, -2) : s.slice(0, -2), u = De.size(C), k = a[a.length - 2], B = a[a.length - 1], R = c[c.length - 1], z = B % 4 === 0 && R % 4 === 0, ne = k <= 8 ? [4, 1, 1] : [4, 4, 1], Z = [8, 8, 1], W = [Math.ceil(R / Z[0] / ne[0]), Math.ceil(k / Z[1] / ne[1]), Math.ceil(u / Z[2] / ne[2])], ue = z ? 4 : 1, he = [...p, k, B / ue], Me = he.length, Le = [...h, B, R / ue], Ae = Le.length, it = [u, k, R / ue], dt = [{ type: 6, data: k }, { type: 6, data: R }, { type: 6, data: B }]; Zr(t, dt), dt.push(...Mt(C, he, Le)); let kt = ["rank", "rank"], Et = e.length > 2; Et && (dt.push(...Mt(e[2].dims)), kt.push("rank")), dt.push(...Mt(it)); let Ut = (pt) => { let zt = C.length, ns = Do("batchDims", e[0].dataType, zt, 1), Tt = ds(e[0].dataType), Yt = qe("a", e[0].dataType, Me, ue), os = qe("b", e[1].dataType, Ae, ue), Vt = St("result", e[0].dataType, it.length, ue), As = [Yt, os]; if (Et) { let Js = o ? ue : 1; As.push(qe("bias", e[2].dataType, e[2].dims.length, Js)); } let ut = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }]; kr(t, ut); let xt = ds(Vt.type.tensor), hs = Jr(t, Vt.type.value, xt), cs = Fi(ue, Et, hs, [ns, Yt, os, Vt], o); return ` ${pt.registerUniforms(ut).registerInternalVariables(ns).declareVariables(...As, Vt)} ${cs} ${z ? Ai(ne, Z, Tt, ns) : Ii(ne, Z, Tt, ns)} `; }; return { name: "MatMul", shaderCache: { hint: `${ne};${t.activation};${z};${o}`, inputDependencies: kt }, getRunData: () => ({ outputs: [{ dims: i ? i(s) : s, dataType: e[0].dataType }], dispatchGroup: { x: W[0], y: W[1], z: W[2] }, programUniforms: dt }), getShaderSource: Ut }; }; }), Di, lu, gc = y(() => { Ot(), Te(), Kt(), en(), ki(), fc(), Oi(), Di = (e, t, s, n, o = !1, i, a = 4, c = 4, p = 4, h = "f32") => { let C = (dt) => { switch (dt) { case 1: return "resData = x[xIndex];"; case 3: return `resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`; case 4: return "resData = x[xIndex / 4];"; default: throw new Error(`innerElementSize ${dt} is not supported.`); } }, u = (dt) => { switch (dt) { 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 ${dt} is not supported.`); } }, k = e ? ` let coord = vec4(batch, xRow, xCol, xCh); ` : ` let coord = vec4(batch, xCh, xRow, xCol); `, B = e ? ` let coords = vec4( batch, row / outWidth, row % outWidth, col); ` : ` let coords = vec4( batch, row, col / outWidth, col % outWidth); `, R = e ? "i32(uniforms.x_shape[1])" : "i32(uniforms.x_shape[2])", z = e ? "i32(uniforms.x_shape[2])" : "i32(uniforms.x_shape[3])", ne = e ? "row" : "col", Z = e ? "col" : "row", W = ` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; let outRow = ${ne} / outWidth; let outCol = ${ne} % outWidth; let WRow = ${Z} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${Z} / 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 = ${Z} % inChannels; var resData = ${Ws(a, h)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${z}) { ${k} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${C(a)} } return resData;`, ue = e ? t && n ? ` let col = colIn * ${a}; ${W}` : ` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${W} } return ${Ws(a, h)}(0.0);` : n && s ? ` let col = colIn * ${a}; ${W}` : ` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${W} } return ${Ws(a, h)}(0.0);`, he = e ? n && s ? u(c) : ` let col = colIn * ${c}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${u(c)} } return ${Ws(c, h)}(0.0);` : ` let col = colIn * ${c}; if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { ${u(c)} } return ${Ws(c, h)}(0.0);`, Me = Ws(p, h), Le = Ws(e ? a : c, h), Ae = Ws(e ? c : a, h), it = Jr(i, Me, h); return ` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Le} { ${e ? ue : he} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ae} { ${e ? he : ue} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { let col = colIn * ${p}; 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])"}; ${B} ${Ci(o)} ${it} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`; }, lu = (e, t, s, n, o, i, a, c, p) => { let h = t.format === "NHWC", C = h ? e[0].dims[3] : e[0].dims[1], u = s[0], k = h ? s[2] : s[3], B = h ? s[1] : s[2], R = h ? s[3] : s[1], z = h && (C % 4 === 0 || C % 3 === 0) && R % 4 === 0, ne = h ? R : k * B, Z = h ? k * B : R, W = [8, 8, 1], ue = n <= 8 ? [4, 1, 1] : [4, 4, 1], he = [Math.ceil(ne / W[0] / ue[0]), Math.ceil(Z / W[1] / ue[1]), Math.ceil(u / W[2] / ue[2])]; as("verbose", () => `[conv2d_mm_webgpu] dispatch = ${he}`); let Me = z ? h && C % 4 !== 0 ? 3 : 4 : 1, Le = W[1] * ue[1], Ae = W[0] * ue[0], it = Math.max(W[0] * Me, W[1]), dt = n % Le === 0, kt = o % Ae === 0, Et = i % it === 0, Ut = z ? [Me, 4, 4] : [1, 1, 1], pt = [{ 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 }]; Zr(t, pt), pt.push(...Mt(e[0].dims, e[1].dims)); let zt = ["rank", "rank"]; a && (pt.push(...Mt(e[2].dims)), zt.push("rank")), pt.push(...Mt(s)); let ns = (Tt) => { let Yt = [{ 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 }]; kr(t, Yt); let os = z ? 4 : 1, Vt = ds(e[0].dataType), As = ` fn setOutputAtIndex(flatIndex : i32, value : ${z ? `vec4<${Vt}>` : Vt}) { result[flatIndex] = ${z ? `vec4<${Vt}>` : Vt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${z ? `vec4<${Vt}>` : Vt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${z ? "/ 4" : ""}, value); }`, ut = qe("x", e[0].dataType, e[0].dims.length, Me === 3 ? 1 : Me), xt = qe("w", e[1].dataType, e[1].dims.length, os), hs = [ut, xt], cs = St("result", e[0].dataType, s.length, os); if (a) { let Js = qe("bias", e[2].dataType, e[2].dims.length, os); hs.push(Js), As += ` fn getBiasByOutputCoords(coords : vec4) -> ${z ? `vec4<${Vt}>` : Vt} { return bias[coords.${h ? "w" : "y"}${z ? "/ 4" : ""}]; }`; } return ` ${Si("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 }; ${Tt.registerUniforms(Yt).declareVariables(...hs, cs)} ${As} ${Di(h, dt, kt, Et, a, t, Ut[0], Ut[1], Ut[2], Vt)} ${z ? Ai(ue, W, Vt, void 0, !h, it) : Ii(ue, W, Vt, void 0, !h, it, !1, void 0, c)}`; }; return { name: "Conv2DMatMul", shaderCache: { hint: `${t.cacheKey};${Me};${z};${dt};${kt};${Et};${Le};${Ae};${it}`, inputDependencies: zt }, getRunData: () => ({ outputs: [{ dims: p ? p(s) : s, dataType: e[0].dataType }], dispatchGroup: { x: he[0], y: he[1], z: he[2] }, programUniforms: pt }), getShaderSource: ns }; }; }), Li, zi, Bn, Bi, Ri, uu, Ni, du, wc = y(() => { Ot(), Te(), At(), Kt(), en(), ki(), Li = (e) => { let t = 1; for (let s = 0; s < e.length; s++) t *= e[s]; return t; }, zi = (e) => typeof e == "number" ? [e, e, e] : e, Bn = (e, t) => t <= 1 ? e : e + (e - 1) * (t - 1), Bi = (e, t, s, n = 1) => { let o = Bn(t, n); return Math.floor((e[0] * (s - 1) - s + o) / 2); }, Ri = (e, t, s, n, o) => { o == null && (o = Bi(e, t[0], n[0])); let i = [0, 0, 0, s]; 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; }, uu = (e, t, s, n, o, i, a, c, p, h) => { let C, u, k, B; if (e === "VALID" && (e = 0), typeof e == "number") { C = { top: e, bottom: e, left: e, right: e, front: e, back: e }; let R = Ri([t, s, n, 1], [c, p, h], 1, [o, i, a], e); u = R[0], k = R[1], B = R[2]; } else if (Array.isArray(e)) { if (!e.every((z, ne, Z) => z === Z[0])) throw Error(`Unsupported padding parameter: ${e}`); C = { top: e[0], bottom: e[1], left: e[2], right: e[3], front: e[4], back: e[5] }; let R = Ri([t, s, n, 1], [c, p, h], 1, [o, i, a], e[0]); u = R[0], k = R[1], B = R[2]; } else if (e === "SAME_UPPER") { u = Math.ceil(t / o), k = Math.ceil(s / i), B = Math.ceil(n / a); let R = (u - 1) * o + c - t, z = (k - 1) * i + p - s, ne = (B - 1) * a + h - n, Z = Math.floor(R / 2), W = R - Z, ue = Math.floor(z / 2), he = z - ue, Me = Math.floor(ne / 2), Le = ne - Me; C = { top: ue, bottom: he, left: Me, right: Le, front: Z, back: W }; } else throw Error(`Unknown padding parameter: ${e}`); return { padInfo: C, outDepth: u, outHeight: k, outWidth: B }; }, Ni = (e, t, s, n, o, i = !1, a = "channelsLast") => { let c, p, h, C, u; if (a === "channelsLast") [c, p, h, C, u] = e; else if (a === "channelsFirst") [c, u, p, h, C] = e; else throw new Error(`Unknown dataFormat ${a}`); let [k, , B, R, z] = t, [ne, Z, W] = zi(s), [ue, he, Me] = zi(n), Le = Bn(B, ue), Ae = Bn(R, he), it = Bn(z, Me), { padInfo: dt, outDepth: kt, outHeight: Et, outWidth: Ut } = uu(o, p, h, C, ne, Z, W, Le, Ae, it), pt = i ? k * u : k, zt = [0, 0, 0, 0, 0]; return a === "channelsFirst" ? zt = [c, pt, kt, Et, Ut] : a === "channelsLast" && (zt = [c, kt, Et, Ut, pt]), { batchSize: c, dataFormat: a, inDepth: p, inHeight: h, inWidth: C, inChannels: u, outDepth: kt, outHeight: Et, outWidth: Ut, outChannels: pt, padInfo: dt, strideDepth: ne, strideHeight: Z, strideWidth: W, filterDepth: B, filterHeight: R, filterWidth: z, effectiveFilterDepth: Le, effectiveFilterHeight: Ae, effectiveFilterWidth: it, dilationDepth: ue, dilationHeight: he, dilationWidth: Me, inShape: e, outShape: zt, filterShape: t }; }, du = (e, t, s, n, o, i) => { let a = i === "channelsLast"; a ? e[0].dims[3] : e[0].dims[1]; let c = [64, 1, 1], p = { x: s.map((ne, Z) => Z) }, h = [Math.ceil(Li(p.x.map((ne) => s[ne])) / c[0]), 1, 1]; as("verbose", () => `[conv3d_naive_webgpu] dispatch = ${h}`); let C = 1, u = De.size(s), k = [{ type: 12, data: u }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: t.strides }, { type: 12, data: t.dilations }]; Zr(t, k), k.push(...Mt(e[0].dims, e[1].dims)); let B = ["rank", "rank"], R = e.length === 3; R && (k.push(...Mt(e[2].dims)), B.push("rank")), k.push(...Mt(s)); let z = (ne) => { let Z = [{ 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 }]; kr(t, Z); let W = 1, ue = ds(e[0].dataType), he = qe("x", e[0].dataType, e[0].dims.length, C), Me = qe("W", e[1].dataType, e[1].dims.length, W), Le = [he, Me], Ae = St("result", e[0].dataType, s.length, W), it = ""; if (R) { let Et = qe("bias", e[2].dataType, e[2].dims.length, W); Le.push(Et), it += ` fn getBiasByOutputCoords(coords : array) -> ${ue} { return bias[${a ? Pt("coords", 4, 5) : Pt("coords", 1, 5)}]; }`; } let dt = Ws(C, ue), kt = Jr(t, dt, ue); return ` ${it} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${he.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Me.getByIndices("aIndices")}; } ${ne.registerUniforms(Z).declareVariables(...Le, Ae)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Ae.offsetToIndices("global_idx")}; let batch = ${Pt("coords", 0, he.rank)}; let d2 = ${a ? Pt("coords", he.rank - 1, he.rank) : Pt("coords", 1, he.rank)}; let xFRCCorner = vec3(${a ? Pt("coords", 1, he.rank) : Pt("coords", 2, he.rank)}, ${a ? Pt("coords", 2, he.rank) : Pt("coords", 3, he.rank)}, ${a ? Pt("coords", 3, he.rank) : Pt("coords", 4, he.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${a ? Pt("uniforms.x_shape", 1, he.rank) : Pt("uniforms.x_shape", 2, he.rank)}; let xShapeZ = ${a ? Pt("uniforms.x_shape", 2, he.rank) : Pt("uniforms.x_shape", 3, he.rank)}; let xShapeW = ${a ? Pt("uniforms.x_shape", 3, he.rank) : Pt("uniforms.x_shape", 4, he.rank)}; let xShapeU = ${a ? Pt("uniforms.x_shape", 4, he.rank) : Pt("uniforms.x_shape", 1, he.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); } } } } ${R ? "value = value + getBiasByOutputCoords(coords)" : ""}; ${kt} result[global_idx] = f32(value); }`; }; return { name: "Conv3DNaive", shaderCache: { hint: `${t.cacheKey};${a};${C};${R}`, inputDependencies: B }, getRunData: () => ({ outputs: [{ dims: s, dataType: e[0].dataType }], dispatchGroup: { x: h[0], y: h[1], z: h[2] }, programUniforms: k }), getShaderSource: z }; }; }), cu, pu, ji = y(() => { Ot(), At(), Kt(), en(), cu = (e, t, s, n) => { let o = e.length > 2, i = o ? "value += b[output_channel];" : "", a = e[0].dims, c = e[1].dims, p = t.format === "NHWC", h = p ? s[3] : s[1], C = h / t.group, u = p && C >= 4 ? Wt(h) : 1, k = De.size(s) / u, B = [{ type: 12, data: k }, { 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: C }]; Zr(t, B), B.push(...Mt(a, [c[0], c[1], c[2], c[3] / u])); let R = o ? ["rank", "rank", "rank"] : ["rank", "rank"]; B.push(...Mt([s[0], s[1], s[2], s[3] / u])); let z = (ne) => { let Z = St("output", e[0].dataType, s.length, u), W = ds(Z.type.tensor), ue = Jr(t, Z.type.value, W), he = qe("x", e[0].dataType, a.length), Me = qe("w", e[1].dataType, c.length, u), Le = [he, Me]; o && Le.push(qe("b", e[2].dataType, e[2].dims, u)); let Ae = [{ 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" }]; kr(t, Ae); let it = p ? ` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${he.get("batch", "xHeight", "xWidth", "input_channel")}; let wVal = ${Me.get("wHeight", "wWidth", "wInChannel", "output_channel")}; value += xVal * wVal; } } } ` : ` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + 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[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[3]) { continue; } let xVal = ${he.get("batch", "input_channel", "xHeight", "xWidth")}; let wVal = ${Me.get("output_channel", "wInChannel", "wHeight", "wWidth")}; value += xVal * wVal; } } } `; return ` ${ne.registerUniforms(Ae).declareVariables(...Le, Z)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${Z.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${p ? 3 : 1}]; let xRCCorner: vec2 = vec2(outputIndices[${p ? 1 : 2}], outputIndices[${p ? 2 : 3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p ? 2 : 1}]; var value: ${Z.type.value} = ${Z.type.value}(0); ${it} ${i} ${ue} ${Z.setByOffset("global_idx", "value")} }`; }; return { name: "GroupedConv", shaderCache: { hint: `${t.cacheKey}_${u}`, inputDependencies: R }, getRunData: () => ({ outputs: [{ dims: n ? n(s) : s, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k / 64) }, programUniforms: B }), getShaderSource: z }; }, pu = (e, t, s, n) => { let o = e.length > 2, i = Wt(s[3]), a = Wt(s[2]), c = De.size(s) / i / a, p = [e[0].dims[0], e[0].dims[1], e[0].dims[2], e[0].dims[3] / i], h = [e[1].dims[0], e[1].dims[1], e[1].dims[2], e[1].dims[3] / i], C = [s[0], s[1], s[2], s[3] / i], u = [{ type: 12, data: c }, { type: 6, data: [t.strides[0], t.strides[1]] }, { type: 6, data: [t.pads[0], t.pads[1]] }]; Zr(t, u), u.push(...Mt(p, h, C)); let k = (a - 1) * t.strides[1] + h[1], B = (R) => { let z = St("output", e[0].dataType, C.length, i), ne = ds(z.type.tensor), Z = Jr(t, z.type.value, ne), W = qe("x", e[0].dataType, p.length, i), ue = qe("w", e[1].dataType, h.length, i), he = [W, ue]; o && he.push(qe("b", e[2].dataType, e[2].dims, i)); let Me = o ? "value += b[output_channel];" : "", Le = [{ name: "output_size", type: "u32" }, { name: "strides", type: "i32", length: 2 }, { name: "pads", type: "i32", length: 2 }]; return kr(t, Le), ` ${R.registerUniforms(Le).declareVariables(...he, z)} ${R.mainStart()} ${R.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] / ${a}u; let col = (index1 % width1) * ${a}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<${W.type.value}, ${k}>; var values: array<${z.type.value}, ${a}>; 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 < ${h[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 < ${k}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${W.get("batch", "u32(x_height)", "u32(x_width)", "input_channel")}; } else { x_vals[i] = ${W.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${ue.get("w_height", "w_width", "0", "output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${a}u; i++) { var value = values[i]; ${Me} ${Z} ${z.set("batch", "row", "col + i", "output_channel", "value")}; } }`; }; return { name: "GroupedConv-Vectorize", shaderCache: { hint: `${t.cacheKey};${i};${a};${k};${h[0]};${h[1]}`, inputDependencies: o ? ["rank", "rank", "type"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: n ? n(s) : s, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: u }), getShaderSource: B }; }; }), hu, mo, mu, _o, Vi, fo, _u, fu, go, yc = y(() => { At(), gc(), wc(), Oi(), ji(), en(), co(), Nr(), hu = (e, t, s, n, o, i) => { let a = e[0], c = e.slice(i ? 1 : 2, i ? 3 : 4), p = c.length, h = t[0], C = t.slice(2).map((k, B) => k + (k - 1) * (s[B] - 1)), u = c.map((k, B) => k + n[B] + n[B + p]).map((k, B) => Math.floor((k - C[B] + o[B]) / o[B])); return u.splice(0, 0, a), u.splice(i ? 3 : 1, 0, h), u; }, mo = [2, 3, 1, 0], mu = (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 s = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[1] * t.group; if (s !== 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"); }, _o = (e, t) => { let s = e.kernelShape.slice(); s.length < t[1].dims.length - 2 && s.push(...Array(t[1].dims.length - 2 - s.length).fill(0)); for (let i = 2; i < t[1].dims.length; ++i) s[i - 2] === 0 && (s[i - 2] = t[1].dims[i]); let n = e.pads.slice(); Xs.adjustPadsBasedOnAutoPad(t[0].dims, e.strides, e.dilations, s, n, e.format === "NHWC", e.autoPad); let o = Object.assign({}, e); return Object.assign(o, { kernelShape: s, pads: n }), o; }, Vi = (e) => { let t = Ei(e), s = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], o = e.dilations, i = e.group, a = e.kernel_shape, c = e.pads, p = e.strides, h = e.w_is_const(); return { autoPad: n, format: s, dilations: o, group: i, kernelShape: a, pads: c, strides: p, wIsConst: h, ...t, cacheKey: `${e.format};${t.activation};` }; }, fo = (e, t, s, n) => { let o = s.format === "NHWC", i = hu(t[0].dims, t[1].dims, s.dilations, s.pads, s.strides, o); if (s.group !== 1) { let Le = [t[0]]; if (o) { let Ae = e.kernelCustomData.wT ?? e.compute(ur(t[1], mo), { inputs: [1], outputs: [s.wIsConst ? -2 : -1] })[0]; s.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = Ae), Le.push(Ae); } else Le.push(t[1]); t.length === 3 && Le.push(t[2]), !e.adapterInfo.isArchitecture("ampere") && o && t[1].dims[0] === s.group && t[1].dims[1] === 1 && s.dilations[0] === 1 && s.dilations[1] === 1 ? e.compute(pu(Le, s, i, n), { inputs: Le }) : e.compute(cu(Le, s, i, n), { inputs: Le }); return; } let a = t.length === 3, c = t[0].dims[o ? 1 : 2], p = t[0].dims[o ? 2 : 3], h = t[0].dims[o ? 3 : 1], C = t[1].dims[2], u = t[1].dims[3], k = i[o ? 1 : 2], B = i[o ? 2 : 3], R = i[o ? 3 : 1], z = o && C === c && u === p && s.pads[0] === 0 && s.pads[1] === 0; if (z || C === 1 && u === 1 && s.dilations[0] === 1 && s.dilations[1] === 1 && s.strides[0] === 1 && s.strides[1] === 1 && s.pads[0] === 0 && s.pads[1] === 0) { let Le = i[0], Ae, it, dt, kt = []; if (o) { let pt = e.kernelCustomData.wT ?? e.compute(ur(t[1], mo), { inputs: [1], outputs: [s.wIsConst ? -2 : -1] })[0]; if (s.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = pt), z) { let zt = c * p * h; Ae = t[0].reshape([1, Le, zt]), it = pt.reshape([1, zt, R]), dt = [1, Le, R]; } else Ae = t[0].reshape([Le, c * p, h]), it = pt.reshape([1, h, R]), dt = [Le, k * B, R]; kt.push(Ae), kt.push(it); } else Ae = t[0].reshape([Le, h, c * p]), it = t[1].reshape([1, R, h]), dt = [Le, R, k * B], kt.push(it), kt.push(Ae); a && kt.push(t[2]); let Et = dt[2], Ut = kt[0].dims[kt[0].dims.length - 1]; Et < 8 && Ut < 8 ? e.compute($i(kt, s, i, dt, o, n), { inputs: kt }) : e.compute(ho(kt, s, i, dt, o, n), { inputs: kt }); return; } let ne = !0, Z = e.kernelCustomData.wT ?? e.compute(ur(t[1], mo), { inputs: [1], outputs: [s.wIsConst ? -2 : -1] })[0]; s.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = Z); let W = [t[0], Z]; a && W.push(t[2]); let ue = o ? k * B : R, he = o ? R : k * B, Me = C * u * h; e.compute(lu(W, s, i, ue, he, Me, a, ne, n), { inputs: W }); }, _u = (e, t) => { let s = t.format === "NHWC", n = [e.inputs[0].reshape(s ? [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), c = [1].concat(t.kernelShape), p = _o({ ...t, pads: o, strides: i, dilations: a, kernelShape: c }, n); fo(e, n, p, (h) => s ? [h[0], h[2], h[3]] : [h[0], h[1], h[3]]); }, fu = (e, t, s) => { let n = s.format === "NHWC" ? "channelsLast" : "channelsFirst", o = _o(s, t), i = s.autoPad === "NOTSET" ? s.pads : s.autoPad, a = Ni(t[0].dims, t[1].dims, s.strides, s.dilations, i, !1, n); e.compute(du(t, o, a.outShape, [a.filterDepth, a.filterHeight, a.filterWidth], [a.padInfo.front, a.padInfo.top, a.padInfo.left], n)); }, go = (e, t) => { if (mu(e.inputs, t), e.inputs[0].dims.length === 3) _u(e, t); else if (e.inputs[0].dims.length === 5) fu(e, e.inputs, t); else { let s = _o(t, e.inputs); fo(e, e.inputs, s); } }; }), gu, Mc = y(() => { Ot(), Te(), At(), Kt(), gu = (e, t, s) => { let n = e.length > 2, o = t.outputShape, i = t.format === "NHWC", a = t.group, c = e[1].dims, p = c[2] / a, h = c[3], C = i ? Wt(p) : 1, u = i ? Wt(h) : 1, k = i ? h === 1 ? C : u : 1, B = De.size(o) / u, R = [Math.ceil(B / 64), 1, 1]; as("verbose", () => `[conv2d_backprop_webgpu] dispatch = ${R}`); let z = ["rank", "rank"], ne = [t.strides[0], t.strides[1]], Z = [t.kernelShape[i ? 1 : 2], t.kernelShape[i ? 2 : 3]], W = [t.dilations[0], t.dilations[1]], ue = [Z[0] + (t.dilations[0] <= 1 ? 0 : (t.kernelShape[i ? 1 : 2] - 1) * (t.dilations[0] - 1)), Z[1] + (t.dilations[1] <= 1 ? 0 : (t.kernelShape[i ? 2 : 3] - 1) * (t.dilations[1] - 1))], he = [ue[0] - 1 - Math.floor((t.pads[0] + t.pads[2]) / 2), ue[1] - 1 - Math.floor((t.pads[1] + t.pads[3]) / 2)], Me = [{ type: 12, data: B }, { type: 12, data: ne }, { type: 12, data: Z }, { type: 12, data: W }, { type: 12, data: ue }, { type: 6, data: he }, { type: 12, data: p }, { type: 12, data: h }, ...Mt(e[0].dims, e[1].dims)]; n && (Me.push(...Mt(e[2].dims)), z.push("rank")), Me.push(...Mt(o)); let Le = (Ae) => { let it = [{ name: "output_size", type: "u32" }, { name: "strides", type: "u32", length: ne.length }, { name: "filter_dims", type: "u32", length: Z.length }, { name: "dilations", type: "u32", length: Z.length }, { name: "effective_filter_dims", type: "u32", length: ue.length }, { name: "pads", type: "i32", length: he.length }, { name: "input_channels_per_group", type: "u32" }, { name: "output_channels_per_group", type: "u32" }], dt = ds(e[0].dataType), kt = i ? 1 : 2, Et = i ? 2 : 3, Ut = i ? 3 : 1, pt = qe("W", e[1].dataType, e[1].dims.length, k), zt = qe("Dy", e[0].dataType, e[0].dims.length, C), ns = [zt, pt]; n && ns.push(qe("bias", e[2].dataType, [o[Ut]].length, u)); let Tt = St("result", e[0].dataType, o.length, u), Yt = () => { let Vt = ""; if (C === 1) Vt += ` let w_offset = ${pt.indicesToOffset(`${pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${pt.getByOffset(`w_offset / ${k}`)}; dotProd = dotProd + xValue * wValue;`; else if (h === 1) Vt += ` let wValue = ${pt.getByOffset(`${pt.indicesToOffset(`${pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${k}`)}; dotProd = dotProd + dot(xValue, wValue);`; else for (let As = 0; As < C; As++) Vt += ` let wValue${As} = ${pt.getByOffset(`${pt.indicesToOffset(`${pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${As}, wOutChannel)`)} / ${k}`)}; dotProd = dotProd + xValue[${As}] * wValue${As};`; return Vt; }, os = ` let outputIndices = ${Tt.offsetToIndices(`global_idx * ${u}`)}; let batch = ${Tt.indicesGet("outputIndices", 0)}; let d1 = ${Tt.indicesGet("outputIndices", Ut)}; let r = ${Tt.indicesGet("outputIndices", kt)}; let c = ${Tt.indicesGet("outputIndices", Et)}; 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 = ${Tt.type.value}(0.0); var wR: u32 = 0; if (uniforms.dilations.x == 1) { // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); } for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${dt}(dyRCorner) + ${dt}(wR)) / ${dt}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${dt}(uniforms.Dy_shape[${kt}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); var wC: u32 = 0; if (uniforms.dilations.y == 1) { // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); } for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${dt}(dyCCorner) + ${dt}(wC)) / ${dt}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${dt}(uniforms.Dy_shape[${Et}]) || 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 + ${C}) { let xValue = ${i ? zt.getByOffset(`${zt.indicesToOffset(`${zt.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${C}`) : zt.get("batch", "inputChannel", "idyR", "idyC")}; ${Yt()} inputChannel = inputChannel + ${C}; } wC = wC + uniforms.strides.y - 1; } wR = wR + uniforms.strides[0] - 1; } let value = dotProd${n ? ` + bias[d1 / ${u}]` : ""}; ${Tt.setByOffset("global_idx", "value")}; `; return ` ${Ae.registerUniforms(it).declareVariables(...ns, Tt)} ${Ae.mainStart()} ${Ae.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${os}}`; }; return { name: "ConvTranspose2D", shaderCache: { hint: `${t.cacheKey};${C}${k}${u}${h === 1}`, inputDependencies: z }, getRunData: () => ({ dispatchGroup: { x: R[0], y: R[1], z: R[2] }, outputs: [{ dims: s ? s(o) : o, dataType: e[0].dataType }], programUniforms: Me }), getShaderSource: Le }; }; }), wu, Ui, yu, Wi, Gi, Mu, Ki, Hi, bu, bc = y(() => { Mc(), en(), Nr(), wu = (e, t, s, n, o, i) => (e - 1) * t + s + (n - 1) * o + 1 - i, Ui = (e, t, s, n, o) => { let i = Math.floor(e / 2); t === "SAME_UPPER" ? (s[n] = i, s[o] = e - i) : t === "SAME_LOWER" && (s[n] = e - i, s[o] = i); }, yu = (e, t, s, n, o, i, a, c, p, h) => { let C = e.length - 2, u = h.length === 0; p.length < C && p.push(...Array(C - p.length).fill(0)); let k = e[0], B = t[c ? 3 : 1] * o; for (let R = 0, z = e.length - C - (c ? 1 : 0); R < C; ++R, ++z) { let ne = e[z], Z = u ? ne * a[R] : h[R], W = wu(ne, a[R], i[R], t[z], s[R], Z); Ui(W, n, i, R, R + C), u && h.push(a[R] * (ne - 1) + p[R] + (t[z] - 1) * s[R] + 1 - i[R] - i[R + C]); } h.splice(0, 0, k), h.splice(c ? 3 : 1, 0, B); }, Wi = (e, t) => { let s = e.kernelShape.slice(); if (e.kernelShape.length === 0 || e.kernelShape.reduce((u, k) => u * k, 1) === 0) { s.length = 0; for (let u = 2; u < t[1].dims.length; ++u) s.push(t[1].dims[u]); } let n = e.format === "NHWC"; s.splice(0, 0, t[1].dims[0]), s.splice(n ? 3 : 1, 0, t[1].dims[1]); let o = e.pads.slice(), i = e.outputShape.slice(), a = e.outputPadding.slice(), c = t[0].dims, p = e.dilations.slice(); if (p.reduce((u, k) => u + k, 0) === 0) { let u = t[0].dims.length - 2; p = new Array(u).fill(1); } let h = e.strides.slice(); if (h.reduce((u, k) => u + k, 0) === 0) { let u = t[0].dims.length - 2; h = new Array(u).fill(1); } yu(c, s, p, e.autoPad, e.group, o, h, n, a, i); let C = Object.assign({}, e); return Object.assign(C, { kernelShape: s, pads: o, outputPadding: a, outputShape: i, dilations: p, strides: h }), C; }, Gi = (e) => { let t = Ei(e), s = 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, c = e.pads, p = e.strides, h = e.wIsConst(), C = e.outputPadding, u = e.outputShape; return { autoPad: n, format: s, dilations: o, group: i, kernelShape: a, outputPadding: C, outputShape: u, pads: c, strides: p, wIsConst: h, ...t, cacheKey: `${e.format};${t.activation};` }; }, Mu = (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 s = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[0]; if (s !== 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((a, c) => a + c, 0) > 0 && t.dilations.length !== i) throw new Error(`dilations should be ${i}D`); if (t.strides.reduce((a, c) => a + c, 0) > 0 && t.strides.length !== i) throw new Error(`strides should be ${i}D`); if (t.pads.reduce((a, c) => a + c, 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((a, c) => a + c, 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"); }, Ki = (e, t, s, n) => { let o = e.kernelCustomData.wT ?? e.compute(ur(t[1], [2, 3, 0, 1]), { inputs: [1], outputs: [s.wIsConst ? -2 : -1] })[0]; s.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = o); let i = [t[0], o]; t.length === 3 && i.push(t[2]), e.compute(gu(i, s, n), { inputs: i }); }, Hi = (e, t) => { let s = t.format === "NHWC", n = [e.inputs[0].reshape(s ? [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 c = t.pads; c.length === 0 && (c = [0, 0]), c = [0, c[0], 0, c[1]], a = [1].concat(a), i = [1].concat(i), o = [1].concat(o); let p = t.outputPadding; p = [0].concat(p); let h = Wi({ ...t, pads: c, strides: a, dilations: i, kernelShape: o, outputPadding: p }, n); Ki(e, n, h, (C) => s ? [C[0], C[2], C[3]] : [C[0], C[1], C[3]]); }, bu = (e, t) => { if (Mu(e.inputs, t), e.inputs[0].dims.length === 3) Hi(e, t); else { let s = Wi(t, e.inputs); Ki(e, e.inputs, s); } }; }), qi, vu, xu, vc = y(() => { Ot(), At(), rs(), Kt(), qi = (e, t, s, n) => { let o = De.size(t), i = t.length, a = qe("input", e, i), c = St("output", e, i), p = s.dataType === 6 ? s.getInt32Array()[0] : Number(s.getBigInt64Array()[0]), h = De.normalizeAxis(p, i), C = (u) => { let k = ` i32(${a.indicesGet("inputIndices", "uniforms.axis")}) `, B = Pt("uniforms.input_shape", "uniforms.axis", i), R = n.reverse ? k + (n.exclusive ? " + 1" : "") : "0", z = n.reverse ? B : k + (n.exclusive ? "" : " + 1"); return ` ${u.registerUniform("outputSize", "u32").registerUniform("axis", "u32").declareVariables(a, c)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${c.offsetToIndices("global_idx")}; var sum = ${c.type.value}(0); let first : i32 = ${R}; let last : i32 = ${z}; for (var i : i32 = first; i < last; i++) { ${a.indicesSet("inputIndices", "uniforms.axis", "u32(i)")}; sum = sum + ${a.getByIndices("inputIndices")}; } ${c.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: h }, ...Mt(t, t)] }), getShaderSource: C }; }, vu = (e, t) => { let s = e.inputs[0].dims, n = e.inputs[0].dataType, o = e.inputs[1]; e.compute(qi(n, s, o, t), { inputs: [0] }); }, xu = (e) => { let t = e.exclusive === 1, s = e.reverse === 1; return jt({ exclusive: t, reverse: s }); }; }), Tu, Qi, Pu, Eu, Cu, xc = y(() => { Ot(), At(), rs(), Kt(), Tu = (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."); }, Qi = (e, t, s, n) => { let o = []; o.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { var a: ${s.type.indices};`); for (let i = 0; i < t; ++i) o.push(s.indicesSet("a", e[i], `i[${i}]`)); return o.push("return a;}"), o.join(` `); }, Pu = (e, t) => { let s, n, o, i, a, c, p = t.format === "NHWC", h = t.blocksize, C = t.mode === "DCR"; p ? ([s, n, o, i] = e.dims, a = C ? [s, n, o, h, h, i / h ** 2] : [s, n, o, i / h ** 2, h, h], c = C ? [0, 1, 3, 2, 4, 5] : [0, 1, 4, 2, 5, 3]) : ([s, n, o, i] = [e.dims[0], e.dims[2], e.dims[3], e.dims[1]], a = C ? [s, h, h, i / h ** 2, n, o] : [s, i / h ** 2, h, h, n, o], c = C ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3]); let u = e.reshape(a), k = u.dims.length, B = e.dataType, R = qe("a", B, k), z = St("output", B, k), ne = (Z) => ` ${Z.registerUniform("output_size", "u32").declareVariables(R, z)} ${Qi(c, k, R, z)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${z.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${z.setByOffset("global_idx", R.getByIndices("aIndices"))} }`; return { name: "DepthToSpace", shaderCache: { hint: `${e.dims};${t.blocksize};${t.mode}`, inputDependencies: ["rank"] }, getRunData: (Z) => { let W = p ? [s, n * h, o * h, i / h ** 2] : [s, i / h ** 2, n * h, o * h], ue = De.size(W), he = u.dims, Me = De.sortBasedOnPerm(he, c); return { outputs: [{ dims: W, dataType: Z[0].dataType }], dispatchGroup: { x: Math.ceil(ue / 64) }, programUniforms: [{ type: 12, data: ue }, ...Mt(he, Me)] }; }, getShaderSource: ne }; }, Eu = (e, t) => { Tu(e.inputs), e.compute(Pu(e.inputs[0], t)); }, Cu = (e) => jt({ blocksize: e.blocksize, mode: e.mode, format: e.format }); }), wo, Rn, yo, ku, Su, Xi, $u, Yi, jr, Au, Iu, Tc = y(() => { Ot(), At(), rs(), Kt(), wo = "[a-zA-Z]|\\.\\.\\.", Rn = "(" + wo + ")+", yo = "^" + Rn + "$", ku = "(" + Rn + ",)*" + Rn, Su = "^" + ku + "$", Xi = class { constructor(e = -1) { this.symbolToIndices = /* @__PURE__ */ new Map(), this.inputIndex = e; } addSymbol(e, t) { let s = this.symbolToIndices.get(e); s === void 0 ? s = [t] : s.push(t), this.symbolToIndices.set(e, s); } }, $u = class { constructor(e, t) { this.equation = t, this.hasEllipsis = !1, this.symbolToInfo = /* @__PURE__ */ new Map(), this.lhs = new Array(), this.outputDims = []; let [s, n] = t.includes("->") ? t.split("->", 2) : [t, ""]; if (!s.match(RegExp(Su))) throw new Error("Invalid LHS term"); if (s.split(",").forEach((o, i) => { let a = e[i].dims.slice(); if (!o.match(RegExp(yo))) throw new Error("Invalid LHS term"); let c = this.processTerm(o, !0, a, i); this.lhs.push(c); }), n === "") n += [...this.symbolToInfo.entries()].filter(([o, i]) => i.count === 1 || o === "...").map(([o]) => o).join(""); else if (!n.match(RegExp(Rn))) throw new Error("Invalid RHS"); n.match(RegExp(wo, "g"))?.forEach((o) => { if (o === "...") this.outputDims = this.outputDims.concat(this.ellipsisDims); else { let i = this.symbolToInfo.get(o); if (i === void 0) throw new Error("Invalid RHS symbol"); this.outputDims.push(i.dimValue); } }), this.rhs = this.processTerm(n, !1, this.outputDims); } addSymbol(e, t, s) { let n = this.symbolToInfo.get(e); if (n !== void 0) { if (n.dimValue !== t && n.count !== 1) throw new Error("Dimension mismatch"); n.count++, n.inputIndices.push(s); } else n = { count: 1, dimValue: t, inputIndices: [s] }; this.symbolToInfo.set(e, n); } processTerm(e, t, s, n = -1) { let o = s.length, i = !1, a = [], c = 0; if (!e.match(RegExp(yo)) && !t && e !== "") throw new Error("Invalid LHS term"); let p = e.match(RegExp(wo, "g")), h = new Xi(n); return p?.forEach((C, u) => { if (C === "...") { if (i) throw new Error("Only one ellipsis is allowed per input term"); i = !0; let k = o - p.length + 1; if (k < 0) throw new Error("Ellipsis out of bounds"); if (a = s.slice(c, c + k), this.hasEllipsis) { if (this.ellipsisDims.length !== a.length || this.ellipsisDims.toString() !== a.toString()) throw new Error("Ellipsis dimensions mismatch"); } else if (t) this.hasEllipsis = !0, this.ellipsisDims = a; else throw new Error("Ellipsis must be specified in the LHS"); for (let B = 0; B < a.length; B++) { let R = String.fromCharCode(48 + B); h.addSymbol(R, u + B), this.addSymbol(R, s[c++], n); } } else h.addSymbol(C, u + (this.hasEllipsis ? this.ellipsisDims.length - 1 : 0)), this.addSymbol(C, s[c++], n); }), h; } }, Yi = (e) => e + "_max", jr = (e, t, s, n) => { let o = e.map((h) => h.length).map((h, C) => qe(`input${C}`, t, h)), i = De.size(n), a = St("output", t, n.length), c = [...s.symbolToInfo.keys()].filter((h) => !s.rhs.symbolToIndices.has(h)), p = (h) => { let C = [], u = "var prod = 1.0;", k = "var sum = 0.0;", B = "sum += prod;", R = [], z = [], ne = [], Z = [], W = s.symbolToInfo.size === s.rhs.symbolToIndices.size; s.symbolToInfo.forEach((he, Me) => { if (s.rhs.symbolToIndices.has(Me)) { let Le = s.rhs.symbolToIndices.get(Me)?.[0]; Le !== void 0 && s.lhs.forEach((Ae, it) => { if (he.inputIndices.includes(it)) { let dt = Ae.symbolToIndices.get(Me); if (dt === void 0) throw new Error("Invalid symbol error"); dt.forEach((kt) => { C.push(`${o[it].indicesSet(`input${it}Indices`, kt, a.indicesGet("outputIndices", Le))}`); }); } }); } else s.lhs.forEach((Le, Ae) => { if (he.inputIndices.includes(Ae)) { let it = Le.symbolToIndices.get(Me); if (it === void 0) throw new Error("Invalid symbol error"); it.forEach((dt) => { R.push(`${o[Ae].indicesSet(`input${Ae}Indices`, dt, `${Me}`)}`); }), Z.push(`prod *= ${o[Ae].getByIndices(`input${Ae}Indices`)};`); } }), z.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${Yi(Me)}; ${Me}++) {`), ne.push("}"); }); let ue = W ? [...C, `let sum = ${o.map((he, Me) => he.getByIndices(`input${Me}Indices`)).join(" * ")};`] : [...C, k, ...z, ...R, u, ...Z, B, ...ne]; return ` ${h.registerUniforms(c.map((he) => ({ name: `${Yi(he)}`, type: "u32" }))).registerUniform("outputSize", "u32").declareVariables(...o, a)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${a.offsetToIndices("global_idx")}; ${o.map((he, Me) => `var input${Me}Indices: ${o[Me].type.indices};`).join(` `)} ${ue.join(` `)}; ${a.setByOffset("global_idx", "sum")}; }`; }; return { name: "Einsum", shaderCache: { hint: s.equation, inputDependencies: e.map(() => "rank") }, getRunData: () => { let h = c.filter((u) => s.symbolToInfo.has(u)).map((u) => ({ type: 12, data: s.symbolToInfo.get(u)?.dimValue || 0 })); h.push({ type: 12, data: i }); let C = e.map((u, k) => [...Mt(u)]).reduce((u, k) => u.concat(k), h); return C.push(...Mt(n)), { outputs: [{ dims: n, dataType: t }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: C }; }, getShaderSource: p }; }, Au = (e, t) => { let s = new $u(e.inputs, t.equation), n = s.outputDims, o = e.inputs.map((i, a) => i.dims); e.compute(jr(o, e.inputs[0].dataType, s, n)); }, Iu = (e) => { let t = e.equation.replace(/\s+/g, ""); return jt({ equation: t }); }; }), Fu, Mo, Ou, Du, Lu, Pc = y(() => { Ot(), At(), Kt(), Fu = (e) => { if (!e || e.length !== 2) throw new Error("Expand requires 2 input."); let t = e[0].dims, s = Array.from(e[1].getBigInt64Array(), Number), n = s.length < t.length ? 0 : s.length - t.length, o = t.length < s.length ? 0 : t.length - s.length; for (; n < s.length && o < t.length; ++n, ++o) if (s[n] !== t[o] && s[n] !== 1 && t[o] !== 1) throw new Error("Expand requires shape to be broadcastable to input"); }, Mo = (e, t) => { let s = e.length - t.length, n = []; for (let o = 0; o < s; ++o) n.push(e[o]); for (let o = 0; o < t.length; ++o) n.push(t[o] === 1 ? e[o + s] : t[o]); return n; }, Ou = (e, t) => e.length > t.length ? Mo(e, t) : Mo(t, e), Du = (e) => { let t = e[0].dims, s = Array.from(e[1].getBigInt64Array(), Number), n = Ou(t, s), o = e[0].dataType, i = o === 9 || De.size(t) === 1, a = o === 9 || t.length > 0 && t[t.length - 1] % 4 === 0 ? 4 : 1, c = i || n.length > 0 && n[n.length - 1] % 4 === 0 ? 4 : 1, p = Math.ceil(De.size(n) / c), h = (u) => { let k = qe("input", o, t.length, a), B = St("output", o, n.length, c), R; if (o === 9) { let z = (ne, Z, W = "") => ` let outputIndices${Z} = ${B.offsetToIndices(`outputOffset + ${Z}u`)}; let offset${Z} = ${k.broadcastedIndicesToOffset(`outputIndices${Z}`, B)}; let index${Z} = offset${Z} / 4u; let component${Z} = offset${Z} % 4u; ${ne}[${Z}] = ${W}(${k.getByOffset(`index${Z}`)}[component${Z}]); `; R = ` let outputOffset = global_idx * ${c}; var data = vec4(0); ${z("data", 0, "u32")} ${z("data", 1, "u32")} ${z("data", 2, "u32")} ${z("data", 3, "u32")} ${B.setByOffset("global_idx", "data")} }`; } else R = ` let outputIndices = ${B.offsetToIndices(`global_idx * ${c}`)}; let inputOffset = ${k.broadcastedIndicesToOffset("outputIndices", B)}; let data = ${B.type.value}(${k.getByOffset(`inputOffset / ${a}`)}); ${B.setByOffset("global_idx", "data")} }`; return ` ${u.registerUniform("vec_size", "u32").declareVariables(k, B)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${R}`; }, C = [{ type: 12, data: p }, ...Mt(t, n)]; return { name: "Expand", shaderCache: { hint: `${n.length};${a}${c}`, inputDependencies: ["rank"] }, getShaderSource: h, getRunData: () => ({ outputs: [{ dims: n, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: C }) }; }, Lu = (e) => { Fu(e.inputs), e.compute(Du(e.inputs), { inputs: [0] }); }; }), bo, zu, Ec = y(() => { Ot(), At(), Kt(), yi(), bo = (e) => { let t = e[0].dataType, s = De.size(e[0].dims), n = De.size(e[1].dims), o = n % 4 === 0, i = (a) => { let c = qe("x", t, [1], 4), p = qe("bias", t, [1], 4), h = St("y", t, [1], 4), C = [{ name: "output_vec_size", type: "u32" }, { name: "bias_size", type: "u32" }], u = (B) => ` let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`, k = o ? ` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};` : `${u(0)}${u(1)}${u(2)}${u(3)} let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`; return `${a.registerUniforms(C).declareVariables(c, p, h)} ${gi(Cs(t))} ${a.mainStart(nr)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${c.getByOffset("global_idx")}; ${k} let x_in = x + bias; ${h.setByOffset("global_idx", uo("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(s / 4) }, { type: 12, data: n }], dispatchGroup: { x: Math.ceil(s / nr / 4) } }) }; }, zu = (e) => { e.inputs.length < 2 || De.size(e.inputs[1].dims) === 0 ? Bl(e) : e.compute(bo(e.inputs)); }; }), Bu, Nn, Ru, Nu, Cc = y(() => { Ot(), At(), rs(), Kt(), Bu = (e) => { if (!e || e.length !== 2) throw new Error("Gather requires 2 inputs."); }, Nn = (e, t) => { let s = e[0].dims, n = e[1].dims, o = s.length, i = De.normalizeAxis(t.axis, o), a = s.slice(0); a.splice(i, 1, ...n); let c = s[i], p = e[0].dataType === 9 ? 4 : 1, h = Math.ceil(De.size(a) / p), C = [{ type: 12, data: h }, { type: 6, data: c }, { type: 12, data: i }, ...Mt(e[0].dims, e[1].dims, a)], u = (k) => { let B = qe("data", e[0].dataType, e[0].dims.length, p), R = qe("inputIndices", e[1].dataType, e[1].dims.length), z = St("output", e[0].dataType, a.length, p), ne = (W) => { let ue = n.length, he = `var indicesIndices${W} = ${R.type.indices}(0);`; for (let Me = 0; Me < ue; Me++) he += `${ue > 1 ? `indicesIndices${W}[${Me}]` : `indicesIndices${W}`} = ${a.length > 1 ? `outputIndices${W}[uniforms.axis + ${Me}]` : `outputIndices${W}`};`; he += ` var idx${W} = ${R.getByIndices(`indicesIndices${W}`)}; if (idx${W} < 0) { idx${W} = idx${W} + uniforms.axisDimLimit; } var dataIndices${W} : ${B.type.indices}; `; for (let Me = 0, Le = 0; Me < o; Me++) Me === i ? (he += `${o > 1 ? `dataIndices${W}[${Me}]` : `dataIndices${W}`} = u32(idx${W});`, Le += ue) : (he += `${o > 1 ? `dataIndices${W}[${Me}]` : `dataIndices${W}`} = ${a.length > 1 ? `outputIndices${W}[${Le}]` : `outputIndices${W}`};`, Le++); return he; }, Z; if (e[0].dataType === 9) { let W = (ue, he, Me = "") => ` let outputIndices${he} = ${z.offsetToIndices(`outputOffset + ${he}u`)}; ${ne(he)}; let offset${he} = ${B.indicesToOffset(`dataIndices${he}`)}; let index${he} = offset${he} / 4u; let component${he} = offset${he} % 4u; ${ue}[${he}] = ${Me}(${B.getByOffset(`index${he}`)}[component${he}]); `; Z = ` let outputOffset = global_idx * ${p}; var value = vec4(0); ${W("value", 0, "u32")} ${W("value", 1, "u32")} ${W("value", 2, "u32")} ${W("value", 3, "u32")} ${z.setByOffset("global_idx", "value")} `; } else Z = ` let outputIndices = ${z.offsetToIndices("global_idx")}; ${ne("")}; let value = ${B.getByIndices("dataIndices")}; ${z.setByOffset("global_idx", "value")}; `; return ` ${k.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(B, R, z)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${Z} }`; }; return { name: "Gather", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: a, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(h / 64) }, programUniforms: C }), getShaderSource: u }; }, Ru = (e) => jt({ axis: e.axis }), Nu = (e, t) => { let s = e.inputs; Bu(s), e.compute(Nn(e.inputs, t)); }; }), ju, vo, Vu, kc = y(() => { Ot(), At(), Kt(), ju = (e, t, s, n, o, i, a, c, p) => { let h = [{ type: 12, data: i }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: s }, { type: 12, data: a }, { type: 12, data: c }, { type: 12, data: p }], C = [i]; h.push(...Mt(t.dims, C)); let u = (k) => { let B = qe("indices_data", t.dataType, t.dims.length), R = St("input_slice_offsets_data", 12, 1, 1), z = [B, R], ne = [{ name: "output_size", type: "u32" }, { name: "batch_dims", type: "u32" }, { name: "input_dims", type: "u32", length: o.length }, { name: "sizes_from_slice_dims_data", type: "u32", length: s.length }, { name: "num_slices_per_batch", type: "u32" }, { name: "input_batch_stride", type: "u32" }, { name: "num_slice_dims", type: "u32" }]; return ` ${k.registerUniforms(ne).declareVariables(...z)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${o.length === 1 ? "index += i32(uniforms.input_dims);" : "index += i32(uniforms.input_dims[input_dim_idx]);"} } ${s.length === 1 ? "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);" : "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); }`; }; return e.compute({ name: "computeSliceOffsets", shaderCache: { hint: `${o.length}_${s.length}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: C, dataType: e.inputs[1].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: h }), getShaderSource: u }, { inputs: [t], outputs: [-1] })[0]; }, vo = (e, t) => { let s = e.inputs, n = s[0].dims, o = s[0].dataType, i = s[1].dims, a = i[i.length - 1], c = De.sizeToDimension(i, i.length - 1), p = De.sizeFromDimension(n, t.batchDims + a), h = De.sizeToDimension(n, t.batchDims), C = De.sizeFromDimension(n, t.batchDims), u = c / h, k = new Array(a), B = p; for (let he = 0; he < a; ++he) k[a - 1 - he] = B, B *= n[t.batchDims + a - 1 - he]; let R = ju(e, s[1], k, t.batchDims, n, c, u, C, a), z = t.batchDims + a; if (z > n.length) throw new Error("last dimension of indices must not be larger than rank of input tensor"); let ne = i.slice(0, -1).concat(n.slice(z)), Z = De.size(ne), W = [{ type: 12, data: Z }, { type: 12, data: p }, ...Mt(s[0].dims, R.dims, ne)], ue = (he) => { let Me = qe("data", s[0].dataType, s[0].dims.length), Le = qe("slice_offsets", 12, R.dims.length), Ae = St("output", s[0].dataType, ne.length); return ` ${he.registerUniform("output_size", "u32").registerUniform("slice_size", "u32").declareVariables(Me, Le, Ae)} ${he.mainStart()} ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`; }; e.compute({ name: "GatherND", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: ne, dataType: o }], dispatchGroup: { x: Math.ceil(Z / 64) }, programUniforms: W }), getShaderSource: ue }, { inputs: [s[0], R] }); }, Vu = (e) => ({ batchDims: e.batch_dims, cacheKey: "" }); }), Uu, Sc, Wu, Gu, $c = y(() => { Ot(), At(), rs(), Kt(), Uu = (e, t) => { if (e.length < 3 || e.length > 4) throw new Error("GatherBlockQuantized requires 3 or 4 inputs."); let s = De.normalizeAxis(t.quantizeAxis, e[0].dims.length), n = t.blockSize, o = e[0], i = e[2], a = e.length === 4 ? e[3] : void 0; if (i.dims.length !== o.dims.length || !o.dims.map((c, p) => p === s ? Math.ceil(c / n) === i.dims[p] : c === i.dims[p]).reduce((c, p) => c && p, !0)) throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis."); if (a) { if (a.dataType !== o.dataType) throw new Error("Zero point must have the same data type as the input tensor."); if (a.dims.length !== i.dims.length || !a.dims.map((c, p) => c === i.dims[p]).reduce((c, p) => c && p, !0)) throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis."); } }, Sc = (e, t) => { let s = e[0].dims, n = e[1].dims, o = s.length, i = De.normalizeAxis(t.gatherAxis, o), a = De.normalizeAxis(t.quantizeAxis, o), c = s.slice(0); c.splice(i, 1, ...n); let p = De.size(c), h = e[2].dataType, C = e[0].dataType === 22, u = [{ type: 12, data: p }, { type: 12, data: a }, { type: 12, data: i }, { type: 12, data: t.blockSize }, ...Mt(...e.map((B, R) => B.dims), c)], k = (B) => { let R = qe("data", e[0].dataType, e[0].dims.length), z = qe("inputIndices", e[1].dataType, e[1].dims.length), ne = qe("scales", e[2].dataType, e[2].dims.length), Z = e.length > 3 ? qe("zeroPoint", e[3].dataType, e[3].dims.length) : void 0, W = St("output", h, c.length), ue = [R, z, ne]; Z && ue.push(Z); let he = [{ name: "output_size", type: "u32" }, { name: "quantize_axis", type: "u32" }, { name: "gather_axis", type: "u32" }, { name: "block_size", type: "u32" }]; return ` ${B.registerUniforms(he).declareVariables(...ue, W)} ${B.mainStart()} let output_indices = ${W.offsetToIndices("global_idx")}; var indices_indices = ${z.type.indices}(0); ${n.length > 1 ? ` for (var i: u32 = 0; i < ${n.length}; i++) { let index = ${W.indicesGet("output_indices", "uniforms.gather_axis + i")}; ${z.indicesSet("indices_indices", "i", "index")}; }` : `indices_indices = ${W.indicesGet("output_indices", "uniforms.gather_axis")};`}; var data_indices = ${R.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${W.indicesGet("output_indices", "i")}; ${R.indicesSet("data_indices", "i", "index")}; } var index_from_indices = ${z.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${s[i]}; } ${R.indicesSet("data_indices", "uniforms.gather_axis", "u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) { let index = ${W.indicesGet("output_indices", `i + ${n.length} - 1`)}; ${R.indicesSet("data_indices", "i", "index")}; } let data_offset = ${R.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${C ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${ne.indicesGet("data_indices", "uniforms.quantize_axis")} / uniforms.block_size; ${ne.indicesSet("scale_indices", "uniforms.quantize_axis", "quantize_axis_index")}; var scale = ${ne.getByIndices("scale_indices")}; ${Z ? ` let zero_point_indices = scale_indices; let zero_point_offset = ${Z.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${Z.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${C ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];` : "var zero_point = 0"}; let dequantized_data = ${Cs(h)}(quantized_data - zero_point) * scale; ${W.setByOffset("global_idx", "dequantized_data")}; }`; }; return { name: "GatherBlockQuantized", shaderCache: { hint: `${t.cacheKey};${e.filter((B, R) => R !== 1).map((B) => B.dims.join("_")).join(";")}`, inputDependencies: Array.from({ length: e.length }, (B, R) => "rank") }, getRunData: () => ({ outputs: [{ dims: c, dataType: h }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: u }), getShaderSource: k }; }, Wu = (e, t) => { let s = e.inputs; Uu(s, t), e.compute(Sc(e.inputs, t)); }, Gu = (e) => jt({ blockSize: e.blockSize, gatherAxis: e.gatherAxis, quantizeAxis: e.quantizeAxis }); }), yn, Ku, Hu, qu, Ac = y(() => { Ot(), At(), rs(), Kt(), yn = (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.`); }, Ku = (e, t) => { let s = e[0].dims, n = e[0].dataType, o = s.length, i = e[1].dims, a = e[1].dataType, c = De.normalizeAxis(t.axis, o), p = s[c], h = i.slice(0), C = De.size(h), u = qe("input", n, o), k = qe("indicesInput", a, i.length), B = St("output", n, h.length), R = [{ type: 12, data: C }, { type: 6, data: p }, { type: 12, data: c }]; return R.push(...Mt(s, i, h)), { name: "GatherElements", shaderCache: { inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: h, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(C / 64) }, programUniforms: R }), getShaderSource: (z) => ` ${z.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(u, k, B)} ${z.mainStart()} ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${B.offsetToIndices("global_idx")}; var idx = ${k.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")}; ${B.setByOffset("global_idx", "value")}; }` }; }, Hu = (e) => jt({ axis: e.axis }), qu = (e, t) => { let s = e.inputs; yn(s), e.compute(Ku(e.inputs, t)); }; }), Qu, Xu, Yu, xo, Lp = y(() => { Ot(), At(), Kt(), Qu = (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"); }, Xu = (e, t) => { let s = e[0].dims.slice(), n = e[1].dims.slice(), [o, i, a] = Cr.getShapeOfGemmResult(s, t.transA, n, t.transB, e.length === 3 ? e[2].dims : void 0), c = [o, i]; if (!c) throw new Error("Can't use gemm on the given tensors"); let p = 16, h = Math.ceil(i / p), C = Math.ceil(o / p), u = !0, k = De.size(c), B = [{ type: 12, data: u ? h : k }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: a }, { type: 1, data: t.alpha }, { type: 1, data: t.beta }], R = ["type", "type"]; e.length === 3 && (B.push(...Mt(e[2].dims)), R.push("rank")), B.push(...Mt(c)); let z = (Z) => { 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 ue = t.alpha === 1 ? "" : "value *= uniforms.alpha;", he = qe("a", e[0].dataType, e[0].dims), Me = qe("b", e[1].dataType, e[1].dims), Le = he.type.value, Ae = null, it = [he, Me]; e.length === 3 && (Ae = qe("c", e[2].dataType, e[2].dims.length), it.push(Ae)); let dt = St("output", e[0].dataType, c.length); it.push(dt); let kt = [{ 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 ` ${Z.registerUniforms(kt).declareVariables(...it)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${Le}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${W} } ${ue} ${Ae != null ? `let cOffset = ${Ae.broadcastedIndicesToOffset("vec2(m, n)", dt)}; value += ${Le}(uniforms.beta) * ${Ae.getByOffset("cOffset")};` : ""} output[global_idx] = value; }`; }, ne = (Z) => { let W = qe("a", e[0].dataType, e[0].dims), ue = qe("b", e[1].dataType, e[1].dims), he = null, Me = [W, ue]; e.length === 3 && (he = qe("c", e[2].dataType, e[2].dims.length), Me.push(he)); let Le = St("output", e[0].dataType, c.length); Me.push(Le); let Ae = [{ name: "num_tile_n", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }, { name: "alpha", type: "f32" }, { name: "beta", type: "f32" }], it = "", dt = ""; t.transA && t.transB ? (dt = ` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${W.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ue.type.value}(0); } `, it = "value += tile_a[k][local_id.y] * tile_b[local_id.x][k];") : t.transA && !t.transB ? (dt = ` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${W.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ue.type.value}(0); } `, it = "value += tile_a[k][local_id.y] * tile_b[k][local_id.x];") : !t.transA && t.transB ? (dt = ` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${W.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${ue.type.value}(0); } `, it = "value += tile_a[local_id.y][k] * tile_b[local_id.x][k];") : !t.transA && !t.transB && (dt = ` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${W.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${ue.type.value}(0); } `, it = "value += tile_a[local_id.y][k] * tile_b[k][local_id.x];"); let kt = t.alpha === 1 ? "" : "value *= uniforms.alpha;"; return ` ${Z.registerUniforms(Ae).declareVariables(...Me)} var tile_a: array, ${p}>; var tile_b: array, ${p}>; ${Z.mainStart([p, p, 1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; let num_tiles = (uniforms.K - 1) / ${p} + 1; var k_start = 0u; var value = ${Le.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${dt} k_start = k_start + ${p}; workgroupBarrier(); for (var k: u32 = 0u; k < ${p}; k++) { ${it} } workgroupBarrier(); } ${kt} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${he != null ? `let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)", Le)}; value += ${Le.type.value}(uniforms.beta) * ${he.getByOffset("cOffset")};` : ""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`; }; return u ? { name: "GemmShared", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: R }, getRunData: () => ({ outputs: [{ dims: c, dataType: e[0].dataType }], dispatchGroup: { x: h * C }, programUniforms: B }), getShaderSource: ne } : { name: "Gemm", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: R }, getRunData: () => ({ outputs: [{ dims: c, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k / 64) }, programUniforms: B }), getShaderSource: z }; }, Yu = (e) => { let t = e.transA, s = e.transB, n = e.alpha, o = e.beta; return { transA: t, transB: s, alpha: n, beta: o, cacheKey: `${e.transA};${e.transB};${e.alpha === 1}` }; }, xo = (e, t) => { Qu(e.inputs), e.compute(Xu(e.inputs, t)); }; }), br, Sr, tn, sn, Ju, Ji, Zu, ed, Zi, td, sd, ea, rd, nd, ta = y(() => { Ot(), At(), rs(), Kt(), [br, Sr, tn, sn] = [0, 1, 2, 3], Ju = (e) => { if (e[0].dims.length !== 4) throw new Error("only 4-D tensor is supported."); if (e[0].dims.length !== e[1].dims.length) throw new Error("input dimensions must be equal to grid dimensions"); if (e[0].dims.length - 2 !== e[1].dims[e[1].dims.length - 1]) throw new Error(`last dimension of grid must be equal to ${e[0].dims.length - 2}`); if (e[0].dims[0] !== e[1].dims[0]) throw new Error("grid batch size must match input batch size"); }, Ji = ` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); var coeffs: vec4; coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } `, Zu = (e) => ` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); for (var i = 0; i < 4; i++) { v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; } coeffs = gs_get_cubic_coeffs(y); let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } `, ed = (e) => ` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners === 0 ? ` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] return ((n + 1.0) * f32(length) - 1.0) / 2.0; ` : ` // alignCorners: true => [-1, 1] to [0, length - 1] return (n + 1.0) / 2.0 * (f32(length - 1)); `} } `, Zi = (e) => ` ${e.paddingMode === "reflection" ? ` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; var fx = f32(x); let range = x_max - x_min; if (fx < x_min) { dx = x_min - fx; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_min + r; } else { fx = x_max - r; } } else if (fx > x_max) { dx = fx - x_max; let n = u32(dx / range); let r = dx - f32(n) * range; if (n % 2 == 0) { fx = x_max - r; } else { fx = x_min + r; } } return u32(fx); }` : ""} `, td = (e, t, s) => ` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); indices[${br}] = batch; indices[${Sr}] = channel;` + (() => { switch (s.paddingMode) { case "zeros": return ` if (r >= 0 && r < H && c >=0 && c < W) { indices[${tn}] = u32(r); indices[${sn}] = u32(c); } `; case "border": return ` indices[${tn}] = u32(clamp(r, 0, H - 1)); indices[${sn}] = u32(clamp(c, 0, W - 1)); `; case "reflection": return ` indices[${tn}] = gs_reflect(r, border[1], border[3]); indices[${sn}] = gs_reflect(c, border[0], border[2]); `; default: throw new Error(`padding mode ${s.paddingMode} is not supported`); } })() + ` return ${e.getByIndices("indices")}; } `, sd = (e, t, s) => (() => { switch (s.mode) { case "nearest": return ` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${br}], indices[${Sr}], border); `; case "bilinear": return ` let x1 = i32(floor(x)); let y1 = i32(floor(y)); let x2 = x1 + 1; let y2 = y1 + 1; let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${br}], indices[${Sr}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${br}], indices[${Sr}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${br}], indices[${Sr}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${br}], indices[${Sr}], border); let dx2 = ${t}(f32(x2) - x); let dx1 = ${t}(x - f32(x1)); let dy2 = ${t}(f32(y2) - y); let dy1 = ${t}(y - f32(y1)); let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); `; case "bicubic": return ` let x0 = i32(floor(x)) - 1; let y0 = i32(floor(y)) - 1; var p: mat4x4<${t}>; for (var h = 0; h < 4; h++) { for (var w = 0; w < 4; w++) { p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${br}], indices[${Sr}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); `; default: throw new Error(`mode ${s.mode} is not supported`); } })() + `${e.setByOffset("global_idx", "result")}`, ea = (e, t) => { let s = qe("x", e[0].dataType, e[0].dims.length), n = [e[1].dims[0], e[1].dims[1], e[1].dims[2]], o = qe("grid", e[1].dataType, n.length, 2), i = [e[0].dims[0], e[0].dims[1], e[1].dims[1], e[1].dims[2]]; t.format === "NHWC" && (i = [e[0].dims[0], e[1].dims[1], e[1].dims[2], e[0].dims[3]], [br, Sr, tn, sn] = [0, 3, 1, 2]); let a = St("output", e[0].dataType, i.length), c = s.type.value, p = De.size(i), h = [{ type: 12, data: p }, ...Mt(e[0].dims, n, i)], C = (u) => ` ${u.registerUniform("output_size", "u32").declareVariables(s, o, a)} ${Ji} ${Zu(c)} ${ed(t)} ${Zi(t)} ${td(s, c, t)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${tn}]); let W_in = i32(uniforms.x_shape[${sn}]); ${t.alignCorners === 0 ? ` let x_min = -0.5; let x_max = f32(W_in) - 0.5; let y_min = -0.5; let y_max = f32(H_in) - 0.5; ` : ` let x_min = 0.0; let x_max = f32(W_in) - 1.0; let y_min = 0.0; let y_max = f32(H_in) - 1.0; `}; let border = vec4(x_min, y_min, x_max, y_max); let indices = ${a.offsetToIndices("global_idx")}; var grid_indices = vec3(indices[${br}], indices[${tn}], indices[${sn}]); let nxy = ${o.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${sd(a, c, t)} }`; return { name: "GridSample", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: ["type", "type"] }, getRunData: (u) => { let k = De.size(i); return { outputs: [{ dims: i, dataType: u[0].dataType }], dispatchGroup: { x: Math.ceil(k / 64) }, programUniforms: h }; }, getShaderSource: C }; }, rd = (e, t) => { Ju(e.inputs), e.compute(ea(e.inputs, t)); }, nd = (e) => jt({ alignCorners: e.align_corners, mode: e.mode, paddingMode: e.padding_mode, format: e.format }); }), sr, od, id, sa, ra, rn, Ic, ad = y(() => { Ot(), At(), rs(), ce(), si(), Kt(), Nr(), sr = (e, t) => e.length > t && e[t].dims.length > 0 ? e[t] : void 0, od = (e, t) => { let s = e[0], n = sr(e, 1), o = sr(e, 2), i = sr(e, 3), a = sr(e, 4), c = sr(e, 5), p = sr(e, 6), h = sr(e, 7); if (s.dims.length !== 3 && s.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); let C = s.dims[0], u = s.dims[1], k = s.dims.length === 3 ? s.dims[2] : t.numHeads * s.dims[4], B = u, R = 0, z = 0, ne = Math.floor(k / t.numHeads); if (p && h && De.size(p.dims) && De.size(h.dims)) { if (p.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions'); if (p.dims[0] !== C || p.dims[1] !== t.numHeads || p.dims[3] !== ne) throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)'); if (h.dims[0] !== C || h.dims[1] !== t.numHeads || h.dims[3] !== ne) throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)'); if (p.dims[2] !== h.dims[2]) throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)'); if (h.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions'); R = p.dims[2], z = p.dims[2]; } else if (p && De.size(p.dims) || h && De.size(h.dims)) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); let Z; if (n && De.size(n.dims) > 0) { if (s.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 (s.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] !== s.dims[2]) throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)'); Z = 2, B = n.dims[1]; } else if (n.dims.length === 5) { if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== ne) 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.'); Z = 5, B = n.dims[1]; } else { if (n.dims[1] !== t.numHeads || n.dims[3] !== ne) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); Z = 0, B = n.dims[2]; } } else { if (s.dims.length !== 5) throw new Error('Input "query" is expected to have 5 dimensions when key is empty'); if (s.dims[2] !== t.numHeads || s.dims[3] !== 3) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); Z = 3; } if (i && De.size(i.dims) > 0) { if (i.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimension'); if (n && n.dims.length === 5 && n.dims[3] === 2) throw new Error("bias is not allowed for packed kv."); } let W = R + B, ue = 0; if (a && De.size(a.dims) > 0) { ue = 8; let Ae = a.dims; throw Ae.length === 1 ? Ae[0] === C ? ue = 1 : Ae[0] === 3 * C + 2 && (ue = 3) : Ae.length === 2 && Ae[0] === C && Ae[1] === W && (ue = 5), ue === 8 ? new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)') : new Error("Mask not supported"); } let he = !1, Me = k; if (o && De.size(o.dims) > 0) { if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); if (s.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 (B !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)'); Me = o.dims[2]; } else { if (B !== o.dims[2]) throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)'); Me = o.dims[1] * o.dims[3], he = !0; } } let Le = !1; if (a && De.size(a.dims) > 0) throw new Error("Key padding mask is not supported"); if (c && De.size(c.dims) > 0) { if (c.dims.length !== 4) throw new Error('Input "attention_bias" is expected to have 4 dimensions'); if (c.dims[0] !== C || c.dims[1] !== t.numHeads || c.dims[2] !== u || c.dims[3] !== W) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)'); } return { batchSize: C, sequenceLength: u, pastSequenceLength: R, kvSequenceLength: B, totalSequenceLength: W, maxSequenceLength: z, inputHiddenSize: 0, hiddenSize: k, vHiddenSize: Me, headSize: ne, vHeadSize: Math.floor(Me / t.numHeads), numHeads: t.numHeads, isUnidirectional: !1, pastPresentShareBuffer: !1, maskFilterValue: t.maskFilterValue, maskType: ue, scale: t.scale, broadcastResPosBias: Le, passPastInKv: he, qkvFormat: Z }; }, id = (e) => jt({ ...e }), sa = jt({ perm: [0, 2, 1, 3] }), ra = (e, t, s, n, o, i, a) => { let c = [n, o, i], p = De.size(c), h = [{ type: 12, data: p }, { type: 12, data: a }, { type: 12, data: i }], C = (u) => { let k = St("qkv_with_bias", t.dataType, c), B = qe("qkv", t.dataType, c), R = qe("bias", s.dataType, c), z = [{ name: "output_size", type: "u32" }, { name: "bias_offset", type: "u32" }, { name: "hidden_size", type: "u32" }]; return ` ${u.registerUniforms(z).declareVariables(B, R, k)} ${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: c, dataType: t.dataType, gpuDataType: 0 }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: h }), getShaderSource: C }, { inputs: [t, s], outputs: [-1] })[0]; }, rn = (e, t, s, n, o, i, a, c) => { let p = i; if (a && De.size(a.dims) > 0) { if (n === 1) throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV"); return p = ra(e, i, a, t, n, s * o, c), p = p.reshape([t, n, s, o]), s === 1 || n === 1 ? p : e.compute(ur(p, sa.perm), { inputs: [p], outputs: [-1] })[0]; } else return i.dims.length === 3 && (p = i.reshape([t, n, s, o])), s === 1 || n === 1 ? p : e.compute(ur(p, sa.perm), { inputs: [p], outputs: [-1] })[0]; }, Ic = (e, t) => { let s = od(e.inputs, t), n = e.inputs[0], o = sr(e.inputs, 1), i = sr(e.inputs, 2), a = sr(e.inputs, 3), c = sr(e.inputs, 4), p = sr(e.inputs, 5), h = sr(e.inputs, 6), C = sr(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, k = rn(e, s.batchSize, s.numHeads, s.sequenceLength, s.headSize, n, a, 0); if (u) return Dn(e, k, o, i, c, void 0, h, C, p, s); if (!o || !i) throw new Error("key and value must be provided"); let B = rn(e, s.batchSize, s.numHeads, s.kvSequenceLength, s.headSize, o, a, s.hiddenSize), R = rn(e, s.batchSize, s.numHeads, s.kvSequenceLength, s.vHeadSize, i, a, 2 * s.hiddenSize); Dn(e, k, B, R, c, void 0, h, C, p, s); }; }), ld, na, ud, dd, To, cd, pd, oa = y(() => { Ot(), At(), rs(), Kt(), ld = (e) => { if (!e || e.length < 1) throw new Error("too few inputs"); }, na = (e, t) => { let s = [], n = t.numOutputs; return e[1].dims[0] > 0 && (e[1].getBigInt64Array().forEach((o) => s.push(Number(o))), n = s.length), jt({ numOutputs: n, axis: t.axis, splitSizes: s }); }, ud = (e) => ` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Pt("uniforms.size_in_split_axis", "i", e)}) { return i; } } return ${e}u; }`, dd = (e) => { let t = e.length, s = []; for (let n = 0; n < t; ++n) { let o = e[n].setByIndices("indices", "input[global_idx]"); t === 1 ? s.push(o) : n === 0 ? s.push(`if (output_number == ${n}u) { ${o} }`) : n === t - 1 ? s.push(`else { ${o} }`) : s.push(`else if (output_number == ${n}) { ${o} }`); } return ` fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) { ${s.join(` `)} }`; }, To = (e, t) => { let s = e[0].dims, n = De.size(s), o = e[0].dataType, i = De.normalizeAxis(t.axis, s.length), a = new Array(t.numOutputs), c = qe("input", o, s.length), p = new Array(t.numOutputs), h = [], C = [], u = 0, k = [{ type: 12, data: n }]; for (let R = 0; R < t.numOutputs; R++) { u += t.splitSizes[R], p[R] = u; let z = s.slice(); z[i] = t.splitSizes[R], C.push(z), a[R] = St(`output${R}`, o, z.length), h.push({ dims: C[R], dataType: e[0].dataType }); } k.push({ type: 12, data: p }, ...Mt(s, ...C)); let B = (R) => ` ${R.registerUniform("input_size", "u32").registerUniform("size_in_split_axis", "u32", p.length).declareVariables(c, ...a)} ${ud(p.length)} ${dd(a)} ${R.mainStart()} ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${c.offsetToIndices("global_idx")}; var index = ${c.indicesGet("indices", i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Pt("uniforms.size_in_split_axis", "output_number - 1u", p.length)}; ${c.indicesSet("indices", i, "index")}; } writeBufferData(output_number, indices, global_idx); }`; return { name: "Split", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank"] }, getShaderSource: B, getRunData: () => ({ outputs: h, dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: k }) }; }, cd = (e, t) => { ld(e.inputs); let s = e.inputs.length === 1 ? t : na(e.inputs, t); e.compute(To(e.inputs, s), { inputs: [0] }); }, pd = (e) => { let t = e.axis, s = e.splitSizes, n = e.numOutputs < 0 ? s.length : e.numOutputs; if (n !== s.length) throw new Error("numOutputs and splitSizes lengh must be equal"); return jt({ axis: t, numOutputs: n, splitSizes: s }); }; }), Fc, Oc, Po, ia, Dc = y(() => { rs(), si(), ad(), oa(), Nr(), Fc = (e, t) => { if (t.doRotary) throw new Error("GroupQuerryAttention do_rotary attribute is not supported"); if (t.doRotary && e.length <= 7) throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified"); let s = e[0], n = e[1], o = e[2], i = e[3], a = e[4]; if (t.localWindowSize !== -1) throw new Error("Local attention is not supported"); if (t.softcap !== 0) throw new Error("Softcap is not supported"); if (t.rotaryInterleaved !== 0) throw new Error("Rotary interleaved is not supported"); if (t.smoothSoftmax) throw new Error("Smooth softmax is not supported"); if (s.dims.length !== 3 && s.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); let c = !1, p = s.dims[0], h = s.dims[1], C = s.dims.length === 3 ? c ? s.dims[2] / 3 : s.dims[2] : t.numHeads * s.dims[4], u = h, k = 0, B = !n || n.dims.length === 0, R = Math.floor(B ? C / (t.numHeads + 2 * t.kvNumHeads) : C / t.numHeads); B && (C = R * t.numHeads); let z = i && i.dims.length !== 0, ne = a && a.dims.length !== 0; if (z && i.dims.length === 4 && i.dims[0] === p && i.dims[1] !== t.kvNumHeads && i.dims[2] === t.kvNumHeads && i.dims[3] === R) throw new Error("BSNH pastKey/pastValue is not supported"); if (z && ne) { 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'); k = i.dims[2]; } else if (z || ne) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); let Z = 1; if (n && n.dims.length > 0) { if (s.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 (s.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 (s.dims[2] % n.dims[2] !== 0) throw new Error('Dimension 2 of "query" should be a multiple of "key"'); u = n.dims[1]; } else if (n.dims.length === 5) { if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== R) 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.'); u = n.dims[1]; } else { if (n.dims[1] !== t.numHeads || n.dims[3] !== R) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); u = n.dims[2]; } } else { if (s.dims.length !== 3 && s.dims.length !== 5) throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty'); if (s.dims.length === 5 && (s.dims[2] !== t.numHeads || s.dims[3] !== 3)) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); Z = 3; } let W = 0, ue = !1, he = t.kvNumHeads ? R * t.kvNumHeads : C; if (o && o.dims.length > 0) { if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); if (s.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)'); he = 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)'); he = o.dims[1] * o.dims[3], ue = !0; } } let Me = e.length > 4 ? e[5] : void 0; if (Me && Me.dims.length !== 1 && Me.dims[0] !== p) throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size'); return { batchSize: p, sequenceLength: h, pastSequenceLength: k, kvSequenceLength: u, totalSequenceLength: -1, maxSequenceLength: -1, inputHiddenSize: 0, hiddenSize: C, vHiddenSize: he, headSize: R, vHeadSize: Math.floor(he / t.kvNumHeads), numHeads: t.numHeads, kvNumHeads: t.kvNumHeads, nReps: t.numHeads / t.kvNumHeads, pastPresentShareBuffer: !1, maskType: W, scale: t.scale, broadcastResPosBias: !1, passPastInKv: ue, qkvFormat: Z }; }, Oc = jt({ perm: [0, 2, 1, 3] }), Po = (e, t, s) => { let n = t, o = s.kvNumHeads; return t.dims.length === 3 && s.kvSequenceLength !== 0 && (n = t.reshape([s.batchSize, s.kvSequenceLength, o, s.headSize]), n = e.compute(ur(n, Oc.perm), { inputs: [n], outputs: [-1] })[0]), n; }, ia = (e, t) => { let s = Fc(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 = e.inputs[0], o = e.inputs[1] && e.inputs[1].dims.length > 0 ? e.inputs[1] : void 0, i = e.inputs[2] && e.inputs[2].dims.length > 0 ? e.inputs[2] : void 0, a = e.inputs[3] && e.inputs[3].dims.length !== 0 ? e.inputs[3] : void 0, c = e.inputs[4] && e.inputs[4].dims.length !== 0 ? e.inputs[4] : void 0, p = e.inputs.length > 4 ? e.inputs[5] : void 0, h = e.inputs.length > 5 ? e.inputs[6] : void 0, C = s.kvNumHeads ? s.kvNumHeads : s.numHeads, u = jt({ axis: 2, numOutputs: 3, splitSizes: [s.numHeads * s.headSize, C * s.headSize, C * s.headSize] }), [k, B, R] = !o && !i ? e.compute(To([n], u), { inputs: [n], outputs: [-1, -1, -1] }) : [n, o, i], z = rn(e, s.batchSize, s.numHeads, s.sequenceLength, s.headSize, k, void 0, 0); Dn(e, z, Po(e, B, s), Po(e, R, s), void 0, void 0, a, c, void 0, s, p, h); }; }), aa, la, hd, md, _d = y(() => { Ot(), At(), Nr(), Kt(), aa = (e, t, s, n, o, i, a, c) => { let p = Wt(i), h = p === 1 ? "f32" : `vec${p}f`, C = p === 1 ? "vec2f" : `mat2x${p}f`, u = o * a, k = 64; u === 1 && (k = 256); let B = [o, a, i / p], R = [o, a, 2], z = ["rank", "type", "type"], ne = []; ne.push(...Mt(B, R)); let Z = (W) => { let ue = qe("x", t.dataType, 3, p), he = qe("scale", s.dataType, s.dims), Me = qe("bias", n.dataType, n.dims), Le = St("output", 1, 3, 2), Ae = [ue, he, Me, Le]; return ` var workgroup_shared : array<${C}, ${k}>; const workgroup_size = ${k}u; ${W.declareVariables(...Ae)} ${W.mainStart(k)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${h}(0); var squared_sum = ${h}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${h}(${ue.get("batch", "channel", "h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${C}(sum, squared_sum); workgroupBarrier(); for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { if (local_idx < currSize) { workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; } workgroupBarrier(); } if (local_idx == 0) { let sum_final = ${Us("workgroup_shared[0][0]", p)} / f32(hight * ${p}); let squared_sum_final = ${Us("workgroup_shared[0][1]", p)} / f32(hight * ${p}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`; }; return e.compute({ name: "InstanceNormComputeChannelScaleShift", shaderCache: { hint: `${p};${c};${k}`, inputDependencies: z }, getRunData: () => ({ outputs: [{ dims: R, dataType: 1 }], dispatchGroup: { x: u }, programUniforms: ne }), getShaderSource: Z }, { inputs: [t, s, n], outputs: [-1] })[0]; }, la = (e, t, s) => { let n = t[0].dims, o = n, i = 2, a = n[0], c = n[1], p = De.sizeFromDimension(n, i), h = Wt(p), C = De.size(o) / h, u = aa(e, t[0], t[1], t[2], a, p, c, s.epsilon), k = [a, c, p / h], B = [a, c], R = ["type", "none"], z = (ne) => { let Z = qe("x", t[0].dataType, k.length, h), W = qe("scale_shift", 1, B.length, 2), ue = St("output", t[0].dataType, k.length, h), he = [Z, W, ue]; return ` ${ne.registerUniform("output_size", "u32").declareVariables(...he)} ${ne.mainStart()} ${ne.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ue.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${W.getByIndices("vec2(batch, channel)")}; let value = ${Z.getByOffset("global_idx")} * ${ue.type.value}(scale_shift.x) + ${ue.type.value}(scale_shift.y); ${ue.setByOffset("global_idx", "value")}; }`; }; e.compute({ name: "InstanceNormalization", shaderCache: { hint: `${h}`, inputDependencies: R }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(C / 64) }, programUniforms: [{ type: 12, data: C }, ...Mt(k, B, k)] }), getShaderSource: z }, { inputs: [t[0], u] }); }, hd = (e, t, s) => { let n = t[0].dims, o = n, i = n[0], a = n[n.length - 1], c = De.sizeFromDimension(n, 1) / a, p = Wt(a), h = De.size(o) / p, C = [{ type: 12, data: c }, { type: 12, data: Math.floor(a / p) }], u = ["type", "type"], k = !1, B = [0, n.length - 1]; for (let Z = 0; Z < n.length - 2; Z++) k = k || n[Z + 1] !== 1, B.push(Z + 1); k = k && n[n.length - 1] !== 1; let R = k ? e.compute(ur(e.inputs[0], B), { inputs: [e.inputs[0]], outputs: [-1] })[0] : e.inputs[0].reshape(Array.from({ length: n.length }, (Z, W) => n[B[W]])), z = aa(e, R, t[1], t[2], i, c, a, s.epsilon), ne = (Z) => { let W = ds(t[0].dataType), ue = p === 1 ? "vec2f" : `mat${p}x2f`, he = (Ae) => { let it = Ae === 0 ? "x" : "y", dt = p === 1 ? "f32" : `vec${p}f`; switch (p) { case 1: return `${W}(${dt}(scale.${it}))`; case 2: return `vec2<${W}>(${dt}(scale[0].${it}, scale[1].${it}))`; case 4: return `vec4<${W}>(${dt}(scale[0].${it}, scale[1].${it}, scale[2].${it}, scale[3].${it}))`; default: throw new Error(`Not supported compoents ${p}`); } }, Me = qe("input", t[0].dataType, t[0].dims, p), Le = St("output", t[0].dataType, o, p); return ` @group(0) @binding(0) var input : array<${Me.type.storage}>; @group(0) @binding(1) var scale_input : array<${ue}>; @group(0) @binding(2) var output : array<${Le.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${Z.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${he(0)}, ${he(1)}); }`; }; e.compute({ name: "InstanceNormalizationNHWC", shaderCache: { hint: `${p}`, inputDependencies: u }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(h / 64) }, programUniforms: C }), getShaderSource: ne }, { inputs: [t[0], z] }); }, md = (e, t) => { t.format === "NHWC" ? hd(e, e.inputs, t) : la(e, e.inputs, t); }; }), fd, gd, ua, Lc = y(() => { Ot(), At(), Kt(), fd = (e) => { if (!e || e.length < 2) throw new Error("layerNorm requires at least 2 inputs."); }, gd = (e, t, s) => { let n = t.simplified, o = e[0].dims, i = e[1], a = !n && e[2], c = o, p = De.normalizeAxis(t.axis, o.length), h = De.sizeToDimension(o, p), C = De.sizeFromDimension(o, p), u = De.size(i.dims), k = a ? De.size(a.dims) : 0; if (u !== C || a && k !== C) throw new Error(`Size of X.shape()[axis:] == ${C}. Size of scale and bias (if provided) must match this. Got scale size of ${u} and bias size of ${k}`); let B = []; for (let Me = 0; Me < o.length; ++Me) Me < p ? B.push(o[Me]) : B.push(1); let R = Wt(C), z = ["type", "type"], ne = [{ type: 12, data: h }, { type: 1, data: C }, { type: 12, data: Math.floor(C / R) }, { type: 1, data: t.epsilon }]; a && z.push("type"); let Z = s > 1, W = s > 2, ue = (Me) => { let Le = ds(e[0].dataType), Ae = [qe("x", e[0].dataType, e[0].dims, R), qe("scale", i.dataType, i.dims, R)]; a && Ae.push(qe("bias", a.dataType, a.dims, R)), Ae.push(St("output", e[0].dataType, c, R)), Z && Ae.push(St("mean_data_output", 1, B)), W && Ae.push(St("inv_std_output", 1, B)); let it = [{ name: "norm_count", type: "u32" }, { name: "norm_size", type: "f32" }, { name: "norm_size_vectorized", type: "u32" }, { name: "epsilon", type: "f32" }]; return ` ${Me.registerUniforms(it).declareVariables(...Ae)} ${Me.mainStart()} ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Fs("f32", R)}; var mean_square_vector = ${Fs("f32", R)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${ks(Le, R, "x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Us("mean_vector", R)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Us("mean_square_vector", R)} / uniforms.norm_size ${n ? "" : "- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${ks(Le, R, "x[j + offset]")}; let f32scale = ${ks(Le, R, "scale[j]")}; output[j + offset] = ${Ae[0].type.value}((f32input ${n ? "" : "- mean"}) * inv_std_dev * f32scale ${a ? `+ ${ks(Le, R, "bias[j]")}` : ""} ); } ${Z ? "mean_data_output[global_idx] = mean" : ""}; ${W ? "inv_std_output[global_idx] = inv_std_dev" : ""}; }`; }, he = [{ dims: c, dataType: e[0].dataType }]; return Z && he.push({ dims: B, dataType: 1 }), W && he.push({ dims: B, dataType: 1 }), { name: "LayerNormalization", shaderCache: { hint: `${R};${s};${n}`, inputDependencies: z }, getRunData: () => ({ outputs: he, dispatchGroup: { x: Math.ceil(h / 64) }, programUniforms: ne }), getShaderSource: ue }; }, ua = (e, t) => { fd(e.inputs), e.compute(gd(e.inputs, t, e.outputCount)); }; }), wd, yd, zc = y(() => { At(), co(), Oi(), wd = (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."); }, yd = (e) => { wd(e.inputs); let t = er.calcShape(e.inputs[0].dims, e.inputs[1].dims, !0); if (!t) throw new Error("Can't use matmul on the given tensors"); let s = t[t.length - 1], n = e.inputs[0].dims[e.inputs[0].dims.length - 1]; if (s < 8 && n < 8) e.compute($i(e.inputs, { activation: "" }, t)); else { let o = t[t.length - 2], i = De.size(e.inputs[0].dims.slice(0, -2)), a = De.size(e.inputs[1].dims.slice(0, -2)); if (i !== 1 && o === 1 && a === 1) { let c = e.inputs[0].reshape([1, i, n]), p = e.inputs[1].reshape([1, n, s]), h = [1, i, s], C = [c, p]; e.compute(ho(C, { activation: "" }, t, h), { inputs: C }); } else e.compute(ho(e.inputs, { activation: "" }, t)); } }; }), Md, bd, vd, xd, Td, Pd = y(() => { Ot(), At(), rs(), Kt(), Md = (e, t) => { if (e.length < 3 || e.length > 4) throw new Error("MatMulNBits requires 3 or 4 inputs"); let s = e[0], n = s.dims.length; if (s.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 (!De.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 c = e[2].dims; if (De.size(c) !== t.n * o) throw new Error("scales input size error."); if (e.length === 4) { let p = e[3].dims, h = t.bits > 4 ? t.n * o : t.n * Math.floor((o + 1) / 2); if (De.size(p) !== h) throw new Error("zeroPoints input size error."); } }, bd = (e, t) => { let s = e[0].dims, n = s.length, o = s[n - 2], i = t.k, a = t.n, c = s.slice(0, n - 2), p = De.size(c), h = e[1].dims[2] / 4, C = e[0].dataType, u = Wt(t.k), k = Wt(h), B = Wt(a), R = c.concat([o, a]), z = o > 1 && a / B % 2 === 0 ? 2 : 1, ne = De.size(R) / B / z, Z = 64, W = [], ue = [p, o, i / u], he = De.convertShape(e[1].dims).slice(); he.splice(-1, 1, h / k), W.push(...Mt(ue)), W.push(...Mt(he)), W.push(...Mt(e[2].dims)), e.length === 4 && W.push(...Mt(De.convertShape(e[3].dims))); let Me = [p, o, a / B]; W.push(...Mt(Me)); let Le = (Ae) => { let it = ue.length, dt = qe("a", e[0].dataType, it, u), kt = qe("b", 12, he.length, k), Et = qe("scales", e[2].dataType, e[2].dims.length), Ut = [dt, kt, Et], pt = e.length === 4 ? qe("zero_points", 12, e[3].dims.length) : void 0; pt && Ut.push(pt); let zt = Me.length, ns = St("output", e[0].dataType, zt, B), Tt = ds(e[0].dataType), Yt = (() => { switch (u) { case 1: return `array<${Tt}, 8>`; case 2: return `mat4x2<${Tt}>`; case 4: return `mat2x4<${Tt}>`; default: throw new Error(`${u}-component is not supported.`); } })(), os = () => { let ut = ` // reuse a data var input_offset = ${dt.indicesToOffset(`${dt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Yt}; for (var j: u32 = 0; j < ${8 / u}; j++) { a_data[j] = ${dt.getByOffset("input_offset")}; input_offset++; } `; for (let xt = 0; xt < B * z; xt++) ut += ` b_value = ${k === 1 ? `b${xt}_data` : `b${xt}_data[i]`}; b_value_lower = unpack4xU8(b_value & b_mask); b_value_upper = unpack4xU8((b_value >> 4) & b_mask); b_quantized_values = ${Yt}(${Array.from({ length: 4 }, (hs, cs) => `${Tt}(b_value_lower[${cs}]), ${Tt}(b_value_upper[${cs}])`).join(", ")}); b_dequantized_values = ${u === 1 ? `${Yt}(${Array.from({ length: 8 }, (hs, cs) => `(b_quantized_values[${cs}] - ${pt ? `zero_point${xt}` : "zero_point"}) * scale${xt}`).join(", ")});` : `(b_quantized_values - ${Yt}(${Array(8).fill(`${pt ? `zero_point${xt}` : "zero_point"}`).join(",")})) * scale${xt};`}; workgroup_shared[local_id.x * ${z} + ${Math.floor(xt / B)}]${B > 1 ? `[${xt % B}]` : ""} += ${Array.from({ length: 8 / u }, (hs, cs) => `${u === 1 ? `a_data[${cs}] * b_dequantized_values[${cs}]` : `dot(a_data[${cs}], b_dequantized_values[${cs}])`}`).join(" + ")}; `; return ut; }, Vt = () => { let ut = ` var col_index = col * ${B}; ${pt ? ` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;` : ` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Tt}(8);`} `; for (let xt = 0; xt < B * z; xt++) ut += ` let scale${xt} = ${Et.getByOffset("col_index * nBlocksPerCol + block")}; ${pt ? ` zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${pt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${xt} = ${Tt}((zero_point_word) & 0xFu);` : ""} col_index += 1;`; return ut; }, As = () => { let ut = `col_index = col * ${B};`; for (let xt = 0; xt < B * z; xt++) ut += ` let b${xt}_data = ${kt.getByIndices(`${kt.type.indices}(col_index, block, word)`)}; col_index += 1;`; return ut += ` var b_value: u32; let b_mask: u32 = 0x0F0F0F0Fu; var b_value_lower: vec4; var b_value_upper: vec4; var b_quantized_values: ${Yt}; var b_dequantized_values: ${Yt};`, ut; }; return ` var workgroup_shared: array<${ns.type.value}, ${z * Z}>; ${Ae.declareVariables(...Ut, ns)} ${Ae.mainStart([Z, 1, 1])} let output_indices = ${ns.offsetToIndices(`(global_idx / ${Z}) * ${z}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${Z}) { //process one block var word_offset: u32 = block * ${t.blockSize / u}; ${Vt()} for (var word: u32 = 0; word < ${h}; word += ${k}) { ${As()} for (var i: u32 = 0; i < ${k}; i++) { ${os()} word_offset += ${8 / u}; } } } workgroupBarrier(); if (local_id.x < ${z}) { var output_value: ${ns.type.value} = ${ns.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${Z}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${z}; } ${ns.setByIndices(`${ns.type.indices}(batch, row, col + local_id.x)`, "output_value")}; } }`; }; return { name: "MatMulNBits", shaderCache: { hint: `${t.blockSize};${t.bits};${u};${k};${B};${z};${Z}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: R, dataType: C }], dispatchGroup: { x: ne }, programUniforms: W }), getShaderSource: Le }; }, vd = (e, t) => { let s = e[0].dims, n = s.length, o = s[n - 2], i = t.k, a = t.n, c = s.slice(0, n - 2), p = De.size(c), h = e[1].dims[2] / 4, C = e[0].dataType, u = Wt(t.k), k = Wt(h), B = c.concat([o, a]), R = 128, z = a % 8 === 0 ? 8 : a % 4 === 0 ? 4 : 1, ne = R / z, Z = ne * k * 8, W = Z / u, ue = Z / t.blockSize, he = De.size(B) / z, Me = [], Le = [p, o, i / u], Ae = De.convertShape(e[1].dims).slice(); Ae.splice(-1, 1, h / k), Me.push(...Mt(Le)), Me.push(...Mt(Ae)), Me.push(...Mt(e[2].dims)), e.length === 4 && Me.push(...Mt(De.convertShape(e[3].dims))); let it = [p, o, a]; Me.push(...Mt(it)); let dt = (kt) => { let Et = Le.length, Ut = qe("a", e[0].dataType, Et, u), pt = qe("b", 12, Ae.length, k), zt = qe("scales", e[2].dataType, e[2].dims.length), ns = [Ut, pt, zt], Tt = e.length === 4 ? qe("zero_points", 12, e[3].dims.length) : void 0; Tt && ns.push(Tt); let Yt = it.length, os = St("output", e[0].dataType, Yt), Vt = ds(e[0].dataType), As = () => { switch (u) { case 1: return ` let a_data0 = vec4<${Vt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Vt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`; case 2: return ` let a_data0 = vec4<${Vt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Vt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`; case 4: return ` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`; default: throw new Error(`${u}-component is not supported.`); } }; return ` var sub_a: array<${Ut.type.value}, ${W}>; var inter_results: array, ${z}>; ${kt.declareVariables(...ns, os)} ${kt.mainStart([ne, z, 1])} let output_indices = ${os.offsetToIndices(`workgroup_index * ${z}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; let num_tiles = (n_blocks_per_col - 1) / ${ue} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${W}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${W}; a_offset += ${R}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${Ut.getByIndices(`${Ut.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${Ut.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${ue} + local_id.x; ${Tt ? ` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); let zero_point_word = ${Tt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Vt}((zero_point_word) & 0xFu);` : ` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Vt}(8);`} let scale = ${zt.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${pt.getByIndices(`${pt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize / u}; for (var i: u32 = 0; i < ${k}; i++) { ${As()} let b_value = ${k === 1 ? "b_data" : "b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${Vt}>(${Array.from({ length: 4 }, (ut, xt) => `${Vt}(b_value_lower[${xt}]), ${Vt}(b_value_upper[${xt}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Vt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({ length: 2 }, (ut, xt) => `${`dot(a_data${xt}, b_dequantized_values[${xt}])`}`).join(" + ")}; word_offset += ${8 / u}; } workgroupBarrier(); } if (local_idx < ${z}) { var output_value: ${os.type.value} = ${os.type.value}(0); for (var b = 0u; b < ${ne}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${os.setByIndices(`${os.type.indices}(batch, row, col + local_idx)`, "output_value")} } } }`; }; return { name: "BlockwiseMatMulNBits32", shaderCache: { hint: `${t.blockSize};${u};${k};${ne};${z}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: B, dataType: C }], dispatchGroup: { x: he }, programUniforms: Me }), getShaderSource: dt }; }, xd = (e, t) => { Md(e.inputs, t), t.blockSize === 32 && e.adapterInfo.isVendor("intel") && e.adapterInfo.isArchitecture("gen-12lp") ? e.compute(vd(e.inputs, t)) : e.compute(bd(e.inputs, t)); }, Td = (e) => jt(e); }), Ed, Cd, da, kd, Sd, _s, Bc, Rc, Nc, $d = y(() => { Ot(), At(), Kt(), Ed = (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]."); } }, Cd = (e, t, s) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${Pt("uniforms.pads", o, s)}; if (k < 0) { break; } if (k >= i32(${Pt("uniforms.x_shape", o, t)})) { break; } offset += k * i32(${Pt("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]; } `; }, da = (e, t, s) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${Pt("uniforms.pads", o, s)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Pt("uniforms.x_shape", o, t)}) - 1); k = k % _2n_1; if(k >= i32(${Pt("uniforms.x_shape", o, t)})) { k = _2n_1 - k; } } offset += k * i32(${Pt("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, kd = (e, t, s) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${Pt("uniforms.pads", o, s)}; if (k < 0) { k = 0; } if (k >= i32(${Pt("uniforms.x_shape", o, t)})) { k = i32(${Pt("uniforms.x_shape", o, t)}) - 1; } offset += k * i32(${Pt("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, Sd = (e, t, s) => { let n = ""; for (let o = t - 1; o >= 0; --o) n += ` k = i32(${e.indicesGet("indices", o)}) - ${Pt("uniforms.pads", o, s)}; if (k < 0) { k += i32(${Pt("uniforms.x_shape", o, t)}]); } if (k >= i32(${Pt("uniforms.x_shape", o, t)})) { k -= i32(${Pt("uniforms.x_shape", o, t)}); } offset += k * i32(${Pt("uniforms.x_strides", o, t)}); `; return ` var offset = 0; var k = 0; ${n} value = x[offset]; `; }, _s = (e, t, s) => { switch (s.mode) { case 0: return Cd(e, t, s.pads.length); case 1: return da(e, t, s.pads.length); case 2: return kd(e, t, s.pads.length); case 3: return Sd(e, t, s.pads.length); default: throw new Error("Invalid mode"); } }, Bc = (e, t) => { let s = De.padShape(e[0].dims.slice(), t.pads), n = e[0].dims, o = De.size(s), i = [{ type: 12, data: o }, { type: 6, data: t.pads }], a = e.length >= 3 && e[2].data; t.mode === 0 && i.push({ type: a ? e[2].dataType : 1, data: t.value }), i.push(...Mt(e[0].dims, s)); let c = ["rank"], p = (h) => { let C = St("output", e[0].dataType, s.length), u = qe("x", e[0].dataType, n.length), k = u.type.value, B = _s(C, n.length, t), R = [{ name: "output_size", type: "u32" }, { name: "pads", type: "i32", length: t.pads.length }]; return t.mode === 0 && R.push({ name: "constant_value", type: a ? k : "f32" }), ` ${h.registerUniforms(R).declareVariables(u, C)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${C.offsetToIndices("global_idx")}; var value = ${k}(0); ${B} output[global_idx] = value; }`; }; return { name: "Pad", shaderCache: { hint: `${t.mode}${a}`, inputDependencies: c }, getRunData: () => ({ outputs: [{ dims: s, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(De.size(s) / 64) }, programUniforms: i }), getShaderSource: p }; }, Rc = (e, t) => { if (e.length > 1) { let s = e[1].getBigInt64Array(), n = e.length >= 3 && e[2].data ? e[2].dataType === 10 ? e[2].getUint16Array()[0] : e[2].getFloat32Array()[0] : 0, o = e[0].dims.length, i = new Int32Array(2 * o).fill(0); if (e.length >= 4) { let c = e[3].getBigInt64Array(); for (let p = 0; p < c.length; p++) i[Number(c[p])] = Number(s[p]), i[Number(c[p]) + o] = Number(s[p + c.length]); } else s.forEach((c, p) => i[Number(p)] = Number(c)); let a = []; return i.forEach((c) => a.push(c)), { mode: t.mode, value: n, pads: a }; } else return t; }, Nc = (e, t) => { Ed(e.inputs); let s = Rc(e.inputs, t); e.compute(Bc(e.inputs, s), { inputs: [0] }); }; }), jn, ca, pa, ha, Eo, ma, jc, _a, fa, ga, Vc, Ad, Id, Fd, wa, Od, Dd, Ld, zd, Uc = y(() => { ze(), Ot(), At(), Kt(), jn = (e) => { if (I.webgpu.validateInputContent && (!e || e.length !== 1)) throw new Error("Pool ops requires 1 input."); }, ca = (e, t, s) => { 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(), c = t.strides.slice(), p = i ? t.dilations.slice() : [], h = t.pads.slice(); Xs.adjustPoolAttributes(s, o, a, c, p, h); let C = Xs.computePoolOutputShape(s, o, c, p, a, h, t.autoPad), u = Object.assign({}, t); i ? Object.assign(u, { kernelShape: a, strides: c, pads: h, dilations: p, cacheKey: t.cacheKey }) : Object.assign(u, { kernelShape: a, strides: c, pads: h, cacheKey: t.cacheKey }); let k = C.slice(); return k.push(k.splice(1, 1)[0]), [u, n ? k : C]; }, pa = (e, t) => { let s = t.format === "NHWC", n = De.size(e), o = De.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 c = t.kernelShape[t.kernelShape.length - 1], p = t.strides[t.strides.length - 1], h = t.pads[t.pads.length / 2 - 1], C = t.pads[t.pads.length - 1], u = !!(h + C); i.push({ type: 12, data: c }, { type: 12, data: p }, { type: 12, data: h }, { type: 12, data: C }), a.push({ name: "kw", type: "u32" }, { name: "sw", type: "u32" }, { name: "pwStart", type: "u32" }, { name: "pwEnd", type: "u32" }); let k = !1; if (t.kernelShape.length === 2) { let B = t.kernelShape[t.kernelShape.length - 2], R = t.strides[t.strides.length - 2], z = t.pads[t.pads.length / 2 - 2], ne = t.pads[t.pads.length - 2]; k = !!(z + ne), i.push({ type: 12, data: B }, { type: 12, data: R }, { type: 12, data: z }, { type: 12, data: ne }), a.push({ name: "kh", type: "u32" }, { name: "sh", type: "u32" }, { name: "phStart", type: "u32" }, { name: "phEnd", type: "u32" }); } return [i, a, !0, u, k]; } else { if (s) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); let c = De.computeStrides(t.kernelShape); i.push({ type: 12, data: c }, { type: 12, data: t.pads }, { type: 12, data: t.strides }), a.push({ name: "kernelStrides", type: "u32", length: c.length }, { name: "pads", type: "u32", length: t.pads.length }, { name: "strides", type: "u32", length: t.strides.length }); let p = t.pads.reduce((h, C) => h + C); return [i, a, !!p, !1, !1]; } }, ha = (e, t, s, n, o, i, a, c, p, h, C, u) => { let k = o.format === "NHWC", B = t.type.value, R = St("output", t.type.tensor, n); if (o.kernelShape.length <= 2) { let z = "", ne = "", Z = "", W = s - (k ? 2 : 1); if (C ? z = ` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${W}] = indices[${W}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${W}] < 0 || xIndices[${W}] >= uniforms.x_shape[${W}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }` : z = ` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${W}] = indices[${W}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`, o.kernelShape.length === 2) { let ue = s - (k ? 3 : 2); u ? ne = ` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ue}] = indices[${ue}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${ue}] < 0 || xIndices[${ue}] >= uniforms.x_shape[${ue}]) { pad += i32(uniforms.kw); continue; } ` : ne = ` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${ue}] = indices[${ue}] * uniforms.sh - uniforms.phStart + j; `, Z = ` } `; } return ` ${e.registerUniforms(p).declareVariables(t, R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var value = ${B}(${c}); var pad = 0; ${ne} ${z} ${Z} ${a} output[global_idx] = value; }`; } else { if (k) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); let z = o.kernelShape.length, ne = o.pads.length, Z = ""; return h ? Z = ` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }` : Z = ` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `, ` ${e.registerUniforms(p).declareVariables(t, R)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${R.offsetToIndices("global_idx")}; var xIndices = ${R.offsetToIndices("global_idx")}; var offsets: array; var value = ${B}(${c}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${z - 1}u; j++) { offsets[j] = offset / ${Pt("uniforms.kernelStrides", "j", z)}; offset -= offsets[j] * ${Pt("uniforms.kernelStrides", "j", z)}; } offsets[${z - 1}] = offset; isPad = false; for (var j = ${s - z}u; j < ${s}u; j++) { xIndices[j] = indices[j] * ${Pt("uniforms.strides", `j - ${s - z}u`, z)} + offsets[j - ${s - z}u] - ${Pt("uniforms.pads", "j - 2u", ne)}; ${Z} } ${a} output[global_idx] = value; }`; } }, Eo = (e) => `${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`, ma = (e) => `${Eo(e)};${e.countIncludePad}`, jc = (e) => `${Eo(e)};${e.storageOrder};${e.dilations}`, _a = (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 }), fa = (e, t, s, n) => { let [o, i] = ca(t, n, s), a = qe("x", t.dataType, t.dims.length), c = a.type.value, p = "value += x_val;", h = ""; o.countIncludePad ? h += `value /= ${c}(uniforms.kernelSize);` : h += `value /= ${c}(i32(uniforms.kernelSize) - pad);`; let [C, u, k, B, R] = pa(i, o); C.push(...Mt(t.dims, i)); let z = ["rank"]; return { name: e, shaderCache: { hint: `${n.cacheKey};${k};${B};${R}`, inputDependencies: z }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(De.size(i) / 64) }, programUniforms: C }), getShaderSource: (ne) => ha(ne, a, t.dims.length, i.length, o, p, h, 0, u, k, B, R) }; }, ga = (e) => { let t = e.count_include_pad !== 0, s = _a(e); if (s.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); let n = { countIncludePad: t, ...s, cacheKey: "" }; return { ...n, cacheKey: ma(n) }; }, Vc = (e, t) => { jn(e.inputs), e.compute(fa("AveragePool", e.inputs[0], !1, t)); }, Ad = { autoPad: "", ceilMode: 0, countIncludePad: !1, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [] }, Id = (e) => { let t = e.format; return { format: t, ...Ad, cacheKey: t }; }, Fd = (e, t) => { jn(e.inputs), e.compute(fa("GlobalAveragePool", e.inputs[0], !0, t)); }, wa = (e, t, s, n) => { let [o, i] = ca(t, n, s), a = ` value = max(x_val, value); `, c = "", p = qe("x", t.dataType, t.dims.length), h = ["rank"], [C, u, k, B, R] = pa(i, o); return C.push(...Mt(t.dims, i)), { name: e, shaderCache: { hint: `${n.cacheKey};${k};${B};${R}`, inputDependencies: h }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(De.size(i) / 64) }, programUniforms: C }), getShaderSource: (z) => ha(z, p, t.dims.length, i.length, o, a, c, t.dataType === 10 ? -65504 : -1e5, u, k, B, R) }; }, Od = (e, t) => { jn(e.inputs), e.compute(wa("MaxPool", e.inputs[0], !1, t)); }, Dd = (e) => { let t = e.storage_order, s = e.dilations, n = _a(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: s, ...n, cacheKey: "" }; return { ...o, cacheKey: jc(o) }; }, Ld = (e) => { let t = e.format; return { format: t, ...Ad, cacheKey: t }; }, zd = (e, t) => { jn(e.inputs), e.compute(wa("GlobalMaxPool", e.inputs[0], !0, t)); }; }), Bd, Rd, Nd, jd, zp = y(() => { Ot(), At(), rs(), Kt(), Bd = (e, t) => { if (e.length < 2 || e.length > 3) throw new Error("DequantizeLinear requires 2 or 3 inputs."); if (e.length === 3 && e[1].dims === e[2].dims) throw new Error("x-scale and x-zero-point must have the same shape."); if (e.length === 3 && e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type."); if (e[0].dataType === 6 && e.length > 2) throw new Error("In the case of dequantizing int32 there is no zero point."); if (e[1].dims.length !== 0 && e[1].dims.length !== 1 && e[1].dims.length !== e[0].dims.length) throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor."); if (e.length > 2) { if (e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type."); if (e[1].dims.length !== e[2].dims.length) throw new Error("scale and zero-point inputs must have the same rank."); if (!e[1].dims.map((s, n) => s === e[2].dims[n]).reduce((s, n) => s && n, !0)) throw new Error("scale and zero-point inputs must have the same shape."); } if (t.blockSize > 0) { if (e[1].dims.length === 0 || e[1].dims.length === 1 && e[1].dims[0] === 1) throw new Error("blockSize must be set only for block quantization."); if (!e[1].dims.map((o, i) => i === t.axis || o === e[0].dims[i]).reduce((o, i) => o && i, !0)) throw new Error("For block qunatization, scale input shape to match the input shape except for the axis"); if (e[1].dims.length !== e[0].dims.length) throw new Error("For block qunatization the scale input rank must be the same as the x rank."); let s = e[0].dims[t.axis], n = e[1].dims[t.axis]; if (t.blockSize < Math.ceil(s / n) || t.blockSize > Math.ceil(s / (n - 1) - 1)) throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)]."); } }, Rd = (e, t) => { let s = De.normalizeAxis(t.axis, e[0].dims.length), n = e[0].dataType, o = n === 3, i = e[0].dims, a = e[1].dataType, c = De.size(i), p = n === 3 || n === 2, h = p ? [Math.ceil(De.size(e[0].dims) / 4)] : e[0].dims, C = e[1].dims, u = e.length > 2 ? e[2] : void 0, k = u ? p ? [Math.ceil(De.size(u.dims) / 4)] : u.dims : void 0, B = C.length === 0 || C.length === 1 && C[0] === 1, R = B === !1 && C.length === 1, z = Wt(c), ne = B && (!p || z === 4), Z = ne ? z : 1, W = ne && !p ? z : 1, ue = qe("input", p ? 12 : n, h.length, W), he = qe("scale", a, C.length), Me = u ? qe("zero_point", p ? 12 : n, k.length) : void 0, Le = St("output", a, i.length, Z), Ae = [ue, he]; Me && Ae.push(Me); let it = [h, C]; u && it.push(k); let dt = [{ type: 12, data: c / Z }, { type: 12, data: s }, { type: 12, data: t.blockSize }, ...Mt(...it, i)], kt = (Et) => { let Ut = [{ name: "output_size", type: "u32" }, { name: "axis", type: "u32" }, { name: "block_size", type: "u32" }]; return ` ${Et.registerUniforms(Ut).declareVariables(...Ae, Le)} ${Et.mainStart()} ${Et.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Le.offsetToIndices("global_idx")}; // Set input x ${p ? ` let input = ${ue.getByOffset("global_idx / 4")}; let x_vec = ${o ? "unpack4xI8(input)" : "unpack4xU8(input)"}; let x_value = ${Z === 1 ? "x_vec[global_idx % 4]" : "x_vec"};` : `let x_value = ${ue.getByOffset("global_idx")};`}; // Set scale input ${B ? `let scale_value= ${he.getByOffset("0")}` : R ? ` let scale_index = ${Le.indicesGet("output_indices", "uniforms.axis")}; let scale_value= ${he.getByOffset("scale_index")};` : ` var scale_indices: ${he.type.indices} = output_indices; let index = ${he.indicesGet("scale_indices", "uniforms.axis")} / uniforms.block_size; ${he.indicesSet("scale_indices", "uniforms.axis", "index")}; let scale_value= ${he.getByIndices("scale_indices")};`}; // Set zero-point input ${Me ? B ? p ? ` let zero_point_input = ${Me.getByOffset("0")}; let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]` : `let zero_point_value = ${Me.getByOffset("0")}` : R ? p ? ` let zero_point_index = ${Le.indicesGet("output_indices", "uniforms.axis")}; let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]` : ` let zero_point_index = ${Le.indicesGet("output_indices", "uniforms.axis")}; let zero_point_value = ${Me.getByOffset("zero_point_index")};` : p ? ` let zero_point_offset = ${he.indicesToOffset("scale_indices")}; let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];` : `let zero_point_value = ${Me.getByIndices("scale_indices")};` : `let zero_point_value = ${p ? o ? "i32" : "u32" : ue.type.value}(0);`}; // Compute and write output ${Le.setByOffset("global_idx", `${Le.type.value}(x_value - zero_point_value) * scale_value`)}; }`; }; return { name: "DequantizeLinear", shaderCache: { hint: t.cacheKey, inputDependencies: Me ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getShaderSource: kt, getRunData: () => ({ outputs: [{ dims: i, dataType: a }], dispatchGroup: { x: Math.ceil(c / Z / 64), y: 1, z: 1 }, programUniforms: dt }) }; }, Nd = (e, t) => { Bd(e.inputs, t), e.compute(Rd(e.inputs, t)); }, jd = (e) => jt({ axis: e.axis, blockSize: e.blockSize }); }), Vd, Ud, Wd, Wc = y(() => { ze(), Ot(), Kt(), Vd = (e, t, s) => { let n = e === t, o = e < t && s < 0, i = e > t && s > 0; if (n || o || i) throw new Error("Range these inputs' contents are invalid."); }, Ud = (e, t, s, n) => { let o = Math.abs(Math.ceil((t - e) / s)), i = [o], a = o, c = [{ type: 12, data: a }, { type: n, data: e }, { type: n, data: s }, ...Mt(i)], p = (h) => { let C = St("output", n, i.length), u = C.type.value, k = [{ name: "outputSize", type: "u32" }, { name: "start", type: u }, { name: "delta", type: u }]; return ` ${h.registerUniforms(k).declareVariables(C)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; }`; }; return { name: "Range", shaderCache: { hint: `${n}` }, getShaderSource: p, getRunData: () => ({ outputs: [{ dims: i, dataType: n }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: c }) }; }, Wd = (e) => { let t = 0, s = 0, n = 0; e.inputs[0].dataType === 6 ? (t = e.inputs[0].getInt32Array()[0], s = e.inputs[1].getInt32Array()[0], n = e.inputs[2].getInt32Array()[0]) : e.inputs[0].dataType === 1 && (t = e.inputs[0].getFloat32Array()[0], s = e.inputs[1].getFloat32Array()[0], n = e.inputs[2].getFloat32Array()[0]), I.webgpu.validateInputContent && Vd(t, s, n), e.compute(Ud(t, s, n, e.inputs[0].dataType), { inputs: [] }); }; }), Gd, Kd, Gc, Kc, Bp = y(() => { Ot(), At(), rs(), Kt(), Gd = (e, t, s, n) => { if (e !== "none" && n !== "i32" && n !== "u32" && n !== "f32") throw new Error(`Input ${n} is not supported with reduction ${e}.`); let o = `{ var oldValue = 0; loop { let newValueF32 =`, i = `; let newValue = bitcast(newValueF32); let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); if res.exchanged { break; } oldValue = res.old_value; } }`; switch (e) { case "none": return `${t}=${s};`; case "add": return n === "i32" || n === "u32" ? `atomicAdd(&${t}, bitcast<${n}>(${s}));` : ` ${o}bitcast<${n}>(oldValue) + (${s})${i}`; case "max": return n === "i32" || n === "u32" ? `atomicMax(&${t}, bitcast<${n}>(${s}));` : ` ${o}max(bitcast(oldValue), (${s}))${i}`; case "min": return n === "i32" || n === "u32" ? `atomicMin(&${t}, bitcast<${n}>(${s}));` : `${o}min(bitcast<${n}>(oldValue), (${s}))${i}`; case "mul": return `${o}(bitcast<${n}>(oldValue) * (${s}))${i}`; default: throw new Error(`Reduction ${e} is not supported.`); } }, Kd = (e, t) => { let s = e[0].dims, n = e[1].dims, o = s, i = 1, a = Math.ceil(De.size(n) / i), c = n[n.length - 1], p = De.sizeFromDimension(s, c), h = [{ type: 12, data: a }, { type: 12, data: c }, { type: 12, data: p }, ...Mt(e[1].dims, e[2].dims, o)], C = (u) => { let k = qe("indices", e[1].dataType, e[1].dims.length), B = qe("updates", e[2].dataType, e[2].dims.length, i), R = t.reduction !== "none" && t.reduction !== "" ? ka("output", e[0].dataType, o.length) : St("output", e[0].dataType, o.length, i); return ` ${u.registerUniform("output_size", "u32").registerUniform("last_index_dimension", "u32").registerUniform("num_updates_elements", "u32").declareVariables(k, B, R)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var data_offset = 0u; let indices_start = uniforms.last_index_dimension * global_idx; let indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${e[0].dims.length === 1 ? ` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;` : ` let element_count_dim = uniforms.output_strides[i - indices_start]; let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim)); } for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; ${Gd(t.reduction, "output[data_offset + i]", "value", R.type.value)} } }`; }; return { name: "ScatterND", shaderCache: { hint: `${t.cacheKey}_${t.reduction}`, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: h }), getShaderSource: C }; }, Gc = (e) => jt({ reduction: e.reduction }), Kc = (e, t) => { e.compute(Kd(e.inputs, t), { inputs: [e.inputs[1], e.inputs[2]], outputs: [] }); }; }), Hc, qc, Qc, Hd, Xc, Yc, Jc, Zc, ep, tp, sp, rp, qd, np, op, ip, ap, lp, up, dp, Rp = y(() => { Ot(), At(), rs(), Kt(), Hc = (e, t) => { if (e.every((s) => s > 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"); } }, qc = (e, t, s) => { t.every((o) => o >= 0 && o < s || (() => { throw new Error("Resize requires axes input values to be positive and less than rank"); })); let n = new Array(s).fill(1); return t.forEach((o, i) => n[o] = e[i]), n; }, Qc = (e, t, s, n, o, i) => { let [a, c, p] = s > 10 ? [1, 2, 3] : [-1, e.length > 1 ? 1 : -1, -1], h = e[0].dims.length; if (a > 0 && e.length > a && e[a].dims.length > 0) e[a].getFloat32Array().forEach((C) => i.push(C)); else if (t.coordinateTransformMode === "tf_crop_and_resize") throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize"); if (c > 0 && e.length > c && e[c].dims.length === 1 && e[c].dims[0] > 0) { if (e[c].getFloat32Array().forEach((C) => n.push(C)), n.length !== 0 && n.length !== h && s >= 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"); Hc(n, t), t.axes.length > 0 && qc(n, t.axes, h).forEach((C, u) => n[u] = C); } if (p > 0 && e.length > p && e[p].dims.length === 1 && e[p].dims[0] > 0 && (e[p].getBigInt64Array().forEach((C) => o.push(Number(C))), o.length !== 0 && o.length !== h && s >= 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 !== 0 && 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 !== 0 && 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 > h) throw new Error("Resize requires only of scales or sizes to be specified"); }, Hd = (e, t, s, n) => ` // 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 big = (${e}) * (${t}); let whole = ${n}(big / (${s})); let fract = ${n}(big % (${s})) / ${n}(${s}); return whole + fract; `, Xc = (e, t) => `fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { ` + (() => { switch (e) { case "asymmetric": return ` if (xScale < 1.0 || floor(xScale) != xScale) { return ${t}(xResized) / ${t}(xScale); } else { ${Hd("xResized", "lengthOriginal", "lengthResized", t)} } `; 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 { ${Hd("xResized", "lengthOriginal - 1", "lengthResized - 1", t)} }`; 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`); } })() + "}", Yc = (e, t, s) => `fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {` + (() => { 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`); } })() + "}", Jc = (e, t, s) => { let n = new Array(s).fill(0).concat(new Array(s).fill(1)), o = e.length === 0 ? n : e.slice(); return t.length > 0 ? (t.forEach((i, a) => { n[i] = o[a], n[a + s] = o[t.length + a]; }), n) : o; }, Zc = (e, t, s, n) => { let o = []; if (s.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] = s[a]); } else s.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; }, ep = (e, t, s) => { let n = (() => { switch (s.keepAspectRatioPolicy) { case "not_larger": return s.axes.length > 0 ? Math.min(...s.axes.map((i) => t[i]), Number.MAX_VALUE) : Math.min(...t, Number.MAX_VALUE); case "not_smaller": return s.axes.length > 0 ? Math.max(...s.axes.map((i) => t[i]), Number.MIN_VALUE) : Math.max(...t, Number.MIN_VALUE); default: throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`); } })(); t.fill(1, 0, t.length); let o = e.slice(); return s.axes.length > 0 ? (s.axes.forEach((i) => t[i] = n), s.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; }, tp = (e, t, s, n, o) => ` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { var original_indices: array<${e.type.value}, ${s.length}>; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${e.indicesGet("output_indices", "i")}; var scale = ${Pt("uniforms.scales", "i", n)}; var roi_low = ${Pt("uniforms.roi", "i", o)}; var roi_hi = ${Pt("uniforms.roi", `i + ${t.length}`, o)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Pt("uniforms.input_shape", "i", t.length)}; var output_shape_i = ${Pt("uniforms.output_shape", "i", s.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`, sp = (e, t, s, 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 = ${Pt("uniforms.scales", "i", o)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Pt("uniforms.roi", "i", i)}; var roi_hi = ${Pt("uniforms.roi", `i + ${s.length}`, i)}; var input_shape_i = ${Pt("uniforms.input_shape", "i", s.length)}; var output_shape_i = ${Pt("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; }`, rp = (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 >= ${Pt("uniforms.input_shape", "i", t.length)}) { return false; } } return true; }`, qd = (e, t, s, n) => e.rank > n ? ` ${e.indicesSet("input_indices", t, "channel")}; ${e.indicesSet("input_indices", s, "batch")}; ` : "", np = (e, t, s, n, o) => { let [i, a, c, p] = s.length === 2 ? [-1, 0, 1, -1] : [0, 2, 3, 1], h = e.type.value; return ` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices", a, `max(0, min(row, ${s[a]} - 1))`)}; ${e.indicesSet("input_indices", c, `max(0, min(col, ${s[c]} - 1))`)}; ${qd(e, p, i, 2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${a}]; var col:${h} = originalIndices[${c}]; ${n ? `if (row < 0 || row > (${s[a]} - 1) || col < 0 || col > (${s[c]} - 1)) { return ${o}; }` : ""}; row = max(0, min(row, ${s[a]} - 1)); col = max(0, min(col, ${s[c]} - 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 = ${s.length > 2 ? `u32(originalIndices[${p}])` : "0"}; var batch: u32 = ${s.length > 2 ? `u32(originalIndices[${i}])` : "0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(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); }`; }, op = (e, t, s, n, o, i, a, c, p, h) => { let C = s.length === 2, [u, k] = C ? [0, 1] : [2, 3], B = e.type.value, R = (z) => { let ne = z === u ? "row" : "col"; return ` fn ${ne}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { var output_index = ${t.indicesGet("output_indices", z)}; var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[z]}, ${n[z]}, ${s[z]}, ${i[z]}, ${i[z]} + ${s.length}); var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${c} && (originalIdx < 0 || originalIdx > (${s[z]} - 1))) { return ${p}; } var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${ne}: ${B} = originalIdx + ${B}(i); if (${ne} < 0 || ${ne} >= ${s[z]}) { ${h ? `coefs[i + 1] = 0.0; continue;` : c ? `return ${p};` : `${ne} = max(0, min(${ne}, ${s[z]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy", z, `u32(${ne})`)}; data[i + 1] = ${z === u ? e.getByIndices("input_indices_copy") : "rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`; }; return ` ${R(u)}; ${R(k)}; fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { var absS = abs(s); var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${B} = 1.0 - absS; var twoMinusAbsS: ${B} = 2.0 - absS; var onePlusAbsS: ${B} = 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<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { var coefsSum: ${B} = 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}) -> ${B} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `; }, ip = (e, t, s, n, o) => { let [i, a, c, p, h] = s.length === 3 ? [-1, 0, 1, 2, -1] : [0, 2, 3, 4, 1], C = e.type.value; return ` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${C} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices", a, `max(0, min(depth, ${s[a]} - 1))`)}; ${e.indicesSet("input_indices", c, `max(0, min(height, ${s[c]} - 1))`)}; ${e.indicesSet("input_indices", p, `max(0, min(width, ${s[p]} - 1))`)}; ${qd(e, h, i, 3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${C} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${C} = originalIndices[${a}]; var height:${C} = originalIndices[${c}]; var width:${C} = originalIndices[${p}]; ${n ? `if (depth < 0 || depth > (${s[a]} - 1) || height < 0 || height > (${s[c]} - 1) || width < 0 || (width > ${s[p]} - 1)) { return ${o}; }` : ""}; depth = max(0, min(depth, ${s[a]} - 1)); height = max(0, min(height, ${s[c]} - 1)); width = max(0, min(width, ${s[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 = ${s.length > 3 ? `u32(originalIndices[${h}])` : "0"}; var batch: u32 = ${s.length > 3 ? `u32(originalIndices[${i}])` : "0"}; var x111: ${C} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${C} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${C} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${C} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${C} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${C} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${C} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${C} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${C} = abs(depth - ${C}(depth1)); var dx2: ${C} = abs(${C}(depth2) - depth); var dy1: ${C} = abs(height - ${C}(height1)); var dy2: ${C} = abs(${C}(height2) - height); var dz1: ${C} = abs(width - ${C}(width1)); var dz2: ${C} = abs(${C}(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); }`; }, ap = (e, t, s, n, o, i) => { let a = e.dims, c = Jc(i, t.axes, a.length), p = Zc(a, n, o, t.axes), h = n.slice(); n.length === 0 && (h = a.map((W, ue) => W === 0 ? 1 : p[ue] / W), t.keepAspectRatioPolicy !== "stretch" && (p = ep(a, h, t))); let C = St("output", e.dataType, p.length), u = qe("input", e.dataType, a.length), k = De.size(p), B = a.length === p.length && a.every((W, ue) => W === p[ue]), R = t.coordinateTransformMode === "tf_crop_and_resize", z = t.extrapolationValue, ne = u.type.value, Z = (W) => ` ${B ? "" : ` ${Xc(t.coordinateTransformMode, ne)}; ${(() => { switch (t.mode) { case "nearest": return ` ${rp(u, a)}; ${Yc(t.nearestMode, s, ne)}; ${sp(u, C, a, p, h.length, c.length, R)}; `; case "linear": return ` ${tp(C, a, p, h.length, c.length)}; ${(() => { if (a.length === 2 || a.length === 4) return `${np(u, C, a, R, z)}`; if (a.length === 3 || a.length === 5) return `${ip(u, C, a, R, z)}`; 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 `${op(u, C, a, p, h, c, t.cubicCoeffA, R, 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"); } })()}; `} ${W.registerUniform("output_size", "u32").registerUniform("scales", "f32", h.length).registerUniform("roi", "f32", c.length).declareVariables(u, C)} ${W.mainStart()} ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${B ? "output[global_idx] = input[global_idx];" : ` let output_indices = ${C.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}|${s}|${h.length > 0 ? t.mode === "cubic" ? h : h.length : ""}|${o.length > 0 ? o : ""}|${c.length > 0 ? c : ""}|${B}|${t.mode === "nearest" ? a.length : a}`, inputDependencies: ["rank"] }, getShaderSource: Z, getRunData: () => ({ outputs: [{ dims: p, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(k / 64) }, programUniforms: [{ type: 12, data: k }, { type: 1, data: h }, { type: 1, data: c }, ...Mt(a, p)] }) }; }, lp = (e) => { let t = e.customDataBuffer; return new Uint32Array(t, t.byteOffset, 1)[0]; }, up = (e, t) => { let s = [], n = [], o = [], i = lp(e); if (t.antialias !== 0) throw Error("Only default value (0) for Antialias attribute is supported"); Qc(e.inputs, t, i, s, n, o), e.compute(ap(e.inputs[0], t, i, s, n, o), { inputs: [0] }); }, dp = (e) => { let t = e.antialias, s = e.axes, n = e.coordinateTransformMode, o = e.cubicCoeffA, i = e.excludeOutside !== 0, a = e.extrapolationValue, c = e.keepAspectRatioPolicy, p = e.mode, h = e.nearestMode === "" ? "simple" : e.nearestMode; return jt({ antialias: t, axes: s, coordinateTransformMode: n, cubicCoeffA: o, excludeOutside: i, extrapolationValue: a, keepAspectRatioPolicy: c, mode: p, nearestMode: h }); }; }), cp, pp, hp, Np = y(() => { Ot(), At(), rs(), Kt(), cp = (e, t) => { let [s, n, o, i] = e, { numHeads: a, rotaryEmbeddingDim: c } = t; if (s.dims.length !== 3 && s.dims.length !== 4) throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`); if (!De.areEqual(n.dims, []) && !De.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 (!De.areEqual(o.dims, i.dims)) throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape"); if (c > 0 && a === 0) throw new Error("num_heads must be provided if rotary_embedding_dim is specified"); let p = s.dims[0], h = s.dims[s.dims.length - 2], C = o.dims[0], u = De.sizeFromDimension(s.dims, 1) / h, k = c === 0 ? o.dims[1] * 2 : u / a; if (c > k) throw new Error("rotary_embedding_dim must be less than or equal to head_size"); if (n.dims.length === 2) { if (p !== n.dims[0]) throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`); if (h !== n.dims[1]) throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`); } if (k / 2 !== o.dims[1] && c / 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 (h > C) throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported"); }, pp = (e, t) => { let { interleaved: s, numHeads: n, rotaryEmbeddingDim: o, scale: i } = t, a = e[0].dims[0], c = De.sizeFromDimension(e[0].dims, 1), p = e[0].dims[e[0].dims.length - 2], h = c / p, C = e[2].dims[1], u = o === 0 ? C * 2 : h / n, k = new Array(a, p, h / u, u - C), B = De.computeStrides(k), R = [{ type: 1, data: i }, { type: 12, data: k }, { type: 12, data: B }, ...e[0].dims.length === 3 ? new Array({ type: 12, data: [c, h, u, 1] }) : [], ...e[0].dims.length === 4 ? new Array({ type: 12, data: [c, u, p * u, 1] }) : [], ...Mt(e[0].dims, e[1].dims, e[2].dims, e[3].dims, e[0].dims)], z = (ne) => { let Z = qe("input", e[0].dataType, e[0].dims.length), W = qe("position_ids", e[1].dataType, e[1].dims.length), ue = qe("cos_cache", e[2].dataType, e[2].dims.length), he = qe("sin_cache", e[3].dataType, e[3].dims.length), Me = St("output", e[0].dataType, e[0].dims.length); return ne.registerUniforms([{ name: "scale", type: "f32" }, { name: "global_shape", type: "u32", length: k.length }, { name: "global_strides", type: "u32", length: B.length }, { name: "input_output_strides", type: "u32", length: B.length }]), ` ${ne.declareVariables(Z, W, ue, he, Me)} ${ne.mainStart(nr)} let half_rotary_emb_dim = uniforms.${ue.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${ne.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${W.broadcastedIndicesToOffset("bsnh.xy", St("", W.type.tensor, 2))}; let position_id = u32(${W.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); let j = i + select(half_rotary_emb_dim, 1, ${s}); let re = ${Z.getByOffset("i")} * ${ue.get("position_id", "bsnh[3]")} - ${Z.getByOffset("j")} * ${he.get("position_id", "bsnh[3]")}; ${Me.setByOffset("i", "re")} let im = ${Z.getByOffset("i")} * ${he.get("position_id", "bsnh[3]")} + ${Z.getByOffset("j")} * ${ue.get("position_id", "bsnh[3]")}; ${Me.setByOffset("j", "im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${Me.setByOffset("k", Z.getByOffset("k"))} } }`; }; return { name: "RotaryEmbedding", shaderCache: { hint: jt({ interleaved: s }).cacheKey, inputDependencies: ["rank", "rank", "rank", "rank"] }, getShaderSource: z, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(De.size(k) / nr) }, programUniforms: R }) }; }, hp = (e, t) => { cp(e.inputs, t), e.compute(pp(e.inputs, t)); }; }), mp, _p, fp, Ht = y(() => { Ot(), At(), Kt(), mp = (e) => { if (!e || e.length < 3) throw new Error("layerNorm requires at least 3 inputs."); let t = e[0], s = e[1], n = e[2]; if (t.dataType !== s.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 (s.dims.length !== 3 && s.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 (s.dims[s.dims.length - 1] !== o) throw new Error("Skip must have the same hidden size as input"); if (s.dims[s.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"); } }, _p = (e, t, s, n) => { let o = t.simplified, i = e[0].dims, a = De.size(i), c = i, p = a, h = i.slice(-1)[0], C = n ? i.slice(0, -1).concat(1) : [], u = !o && e.length > 3, k = e.length > 4, B = n && s > 1, R = n && s > 2, z = s > 3, ne = 64, Z = Wt(h), W = [{ type: 12, data: p }, { type: 12, data: Z }, { type: 12, data: h }, { type: 1, data: t.epsilon }], ue = (Me) => { let Le = [{ name: "output_size", type: "u32" }, { name: "components", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "epsilon", type: "f32" }], Ae = [qe("x", e[0].dataType, e[0].dims, Z), qe("skip", e[1].dataType, e[1].dims, Z), qe("gamma", e[2].dataType, e[2].dims, Z)]; u && Ae.push(qe("beta", e[3].dataType, e[3].dims, Z)), k && Ae.push(qe("bias", e[4].dataType, e[4].dims, Z)), Ae.push(St("output", e[0].dataType, c, Z)), B && Ae.push(St("mean_output", 1, C)), R && Ae.push(St("inv_std_output", 1, C)), z && Ae.push(St("input_skip_bias_sum", e[0].dataType, c, Z)); let it = ds(e[0].dataType), dt = ds(1, Z); return ` ${Me.registerUniforms(Le).declareVariables(...Ae)} var sum_shared : array<${dt}, ${ne}>; var sum_squared_shared : array<${dt}, ${ne}>; ${Me.mainStart([ne, 1, 1])} let ix = local_id.x; let iy = global_id.x / ${ne}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${ne}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${ne - 1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${k ? "bias[offset1d + i]" : it + "(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${z ? "input_skip_bias_sum[offset + i] = value;" : ""} output[offset + i] = value; let f32_value = ${ks(it, Z, "value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${ne}; 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 = ${Us("sum", Z)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Us("square_sum", Z)} / f32(uniforms.hidden_size) ${o ? "" : "- mean * mean"} + uniforms.epsilon); ${B ? "mean_output[global_idx] = mean;" : ""} ${R ? "inv_std_output[global_idx] = inv_std_dev;" : ""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${o ? "" : `- ${it}(mean)`}) * ${it}(inv_std_dev) * gamma[offset1d + i] ${u ? "+ beta[offset1d + i]" : ""}; } }`; }, he = [{ dims: c, dataType: e[0].dataType }]; return s > 1 && he.push({ dims: C, dataType: 1 }), s > 2 && he.push({ dims: C, dataType: 1 }), s > 3 && he.push({ dims: i, dataType: e[0].dataType }), { name: "SkipLayerNormalization", shaderCache: { hint: `${Z};${B};${R};${z}`, inputDependencies: e.map((Me, Le) => "type") }, getShaderSource: ue, getRunData: () => ({ outputs: he, dispatchGroup: { x: Math.ceil(p / h) }, programUniforms: W }) }; }, fp = (e, t) => { mp(e.inputs); let s = [0]; e.outputCount > 1 && s.push(-3), e.outputCount > 2 && s.push(-3), e.outputCount > 3 && s.push(3), e.compute(_p(e.inputs, t, e.outputCount, !1), { outputs: s }); }; }), Qd, Ss, Qs, Ys, nn, gp, Xd, Yd, f = y(() => { Ot(), At(), rs(), Kt(), Qd = (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((s, 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`); }); }, Ss = (e, t) => { let s = []; if (e.length > t) if (e[t].dataType === 7) e[t].getBigInt64Array().forEach((n) => s.push(Number(n))); else if (e[t].dataType === 6) e[t].getInt32Array().forEach((n) => s.push(Number(n))); else throw new Error(`Input ${t} must be an array of int32 or int64`); return s; }, Qs = (e, t) => { if (e.length > 1) { let s = Ss(e, 1), n = Ss(e, 2), o = Ss(e, 3); return o.length === 0 && (o = [...Array(e[0].dims.length).keys()]), jt({ starts: s, ends: n, axes: o }); } else return t; }, Ys = (e, t, s, n, o) => { let i = e; return e < 0 && (i += s[n[t]]), o[t] < 0 ? Math.max(0, Math.min(i, s[n[t]] - 1)) : Math.max(0, Math.min(i, s[n[t]])); }, nn = (e, t, s) => `fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${s.length}; i >= 0; i--) { let input_shape_i = ${Pt("uniforms.input_shape", "i", s.length)}; let steps_i = ${Pt("uniforms.steps", "i", s.length)}; let signs_i = ${Pt("uniforms.signs", "i", s.length)}; let starts_i = ${Pt("uniforms.starts", "i", s.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; }`, gp = (e, t) => { let s = e[0].dims, n = De.size(s), o = t.axes.length > 0 ? De.normalizeAxes(t.axes, s.length) : [...Array(s.length).keys()], i = Ss(e, 4); i.forEach((Z) => Z !== 0 || (() => { throw new Error("step cannot be 0"); })), i.length === 0 && (i = Array(o.length).fill(1)); let a = t.starts.map((Z, W) => Ys(Z, W, s, o, i)), c = t.ends.map((Z, W) => Ys(Z, W, s, o, i)); if (o.length !== a.length || o.length !== c.length) throw new Error("start, ends and axes should have the same number of elements"); if (o.length !== s.length) for (let Z = 0; Z < s.length; ++Z) o.includes(Z) || (a.splice(Z, 0, 0), c.splice(Z, 0, s[Z]), i.splice(Z, 0, 1)); let p = i.map((Z) => Math.sign(Z)); i.forEach((Z, W, ue) => { if (Z < 0) { let he = (c[W] - a[W]) / Z, Me = a[W], Le = Me + he * i[W]; a[W] = Le, c[W] = Me, ue[W] = -Z; } }); let h = s.slice(0); o.forEach((Z, W) => { h[Z] = Math.ceil((c[Z] - a[Z]) / i[Z]); }); let C = { dims: h, dataType: e[0].dataType }, u = St("output", e[0].dataType, h.length), k = qe("input", e[0].dataType, e[0].dims.length), B = De.size(h), R = [{ name: "outputSize", type: "u32" }, { name: "starts", type: "u32", length: a.length }, { name: "signs", type: "i32", length: p.length }, { name: "steps", type: "u32", length: i.length }], z = [{ type: 12, data: B }, { type: 12, data: a }, { type: 6, data: p }, { type: 12, data: i }, ...Mt(e[0].dims, h)], ne = (Z) => ` ${Z.registerUniforms(R).declareVariables(k, u)} ${nn(k, u, s)} ${Z.mainStart()} ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx", k.getByIndices("input_indices"))} }`; return { name: "Slice", shaderCache: { hint: `${p.length}_${a.length}_${i.length}`, inputDependencies: ["rank"] }, getShaderSource: ne, getRunData: () => ({ outputs: [C], dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: z }) }; }, Xd = (e, t) => { Qd(e.inputs, t); let s = Qs(e.inputs, t); e.compute(gp(e.inputs, s), { inputs: [0] }); }, Yd = (e) => { let t = e.starts, s = e.ends, n = e.axes; return jt({ starts: t, ends: s, axes: n }); }; }), _, Q, xe, Se, Be = y(() => { Ot(), At(), rs(), Nr(), Kt(), _ = (e) => { if (!e || e.length !== 1) throw new Error("Softmax op requires 1 input."); }, Q = (e, t) => { let s = e.inputs[0], n = s.dims, o = De.size(n), i = n.length, a = De.normalizeAxis(t.axis, i), c = a < n.length - 1, p, h = []; c ? (h = Array.from({ length: i }, (Ae, it) => it), h[a] = i - 1, h[i - 1] = a, p = e.compute(ur(s, h), { inputs: [s], outputs: [-1] })[0]) : p = s; let C = p.dims, u = C[i - 1], k = o / u, B = Wt(u), R = u / B, z = 64; k === 1 && (z = 256); let ne = (Ae, it) => it === 4 ? `max(max(${Ae}.x, ${Ae}.y), max(${Ae}.z, ${Ae}.w))` : it === 2 ? `max(${Ae}.x, ${Ae}.y)` : it === 3 ? `max(max(${Ae}.x, ${Ae}.y), ${Ae}.z)` : Ae, Z = qe("x", p.dataType, p.dims, B), W = St("result", p.dataType, p.dims, B), ue = Z.type.value, he = ds(p.dataType) === "f32" ? `var threadMax = ${ue}(-3.402823e+38f);` : `var threadMax = ${ue}(-65504.0h);`, Me = (Ae) => ` var rowMaxShared : ${ue}; var rowSumShared : ${ue}; var threadShared : array<${ue}, ${z}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ue} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ue}) { let index = row * row_stride + col; result[index] = value; } ${Ae.registerUniform("packedCols", "i32").declareVariables(Z, W)} ${Ae.mainStart(z)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${z}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${he} 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 = ${ue}(${ne("threadShared[0]", B)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ue}(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 = ${ue}(${Us("threadShared[0]", B)}); } 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); } }`, Le = e.compute({ name: "Softmax", shaderCache: { hint: `${B};${z}`, inputDependencies: ["type"] }, getRunData: () => ({ outputs: [{ dims: C, dataType: p.dataType }], dispatchGroup: { x: k }, programUniforms: [{ type: 6, data: R }] }), getShaderSource: Me }, { inputs: [p], outputs: [c ? -1 : 0] })[0]; c && e.compute(ur(Le, h), { inputs: [Le] }); }, xe = (e, t) => { _(e.inputs), Q(e, t); }, Se = (e) => jt({ axis: e.axis }); }), rt, ot, ft, $t, Jt, qt = y(() => { Ot(), At(), Kt(), rt = (e) => Array.from(e.getBigInt64Array(), Number), ot = (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 (rt(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"); }, ft = (e, t) => { let s = []; for (let n = 0; n < e.length; ++n) s.push(e[n] * t[n]); return s; }, $t = (e, t) => { let s = e[0].dims, n = t ?? rt(e[1]), o = ft(s, n), i = De.size(o), a = e[0].dataType, c = qe("input", a, s.length), p = St("output", a, o.length), h = (C) => ` const inputShape = ${c.indices(...s)}; ${C.registerUniform("output_size", "u32").declareVariables(c, p)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${c.type.indices}; for (var i = 0; i < ${s.length}; i++) { let input_dim_i = ${c.indicesGet("uniforms.input_shape", "i")}; let input_dim_value = ${p.indicesGet("output_indices", "i")} % input_dim_i; ${c.indicesSet("input_indices", "i", "input_dim_value")} } ${p.setByOffset("global_idx", c.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 }, ...Mt(e[0].dims, o)] }), getShaderSource: h }; }, Jt = (e) => { ot(e.inputs), e.compute($t(e.inputs), { inputs: [0] }); }; }), Dt, It, vs, Qt = y(() => { Ot(), At(), Kt(), Dt = (e, t, s, n, o) => { let i = St("output_data", o, s.length, 4), a = qe("a_data", t[1].dataType, t[1].dims.length, 4), c = qe("b_data", t[2].dataType, t[2].dims.length, 4), p = qe("c_data", t[0].dataType, t[0].dims.length, 4), h, C = (u, k, B) => `select(${k}, ${u}, ${B})`; if (!n) h = i.setByOffset("global_idx", C(a.getByOffset("global_idx"), c.getByOffset("global_idx"), p.getByOffset("global_idx"))); else { let u = (k, B, R = "") => { let z = `a_data[index_a${B}][component_a${B}]`, ne = `b_data[index_b${B}][component_b${B}]`, Z = `bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`; return ` let output_indices${B} = ${i.offsetToIndices(`global_idx * 4u + ${B}u`)}; let offset_a${B} = ${a.broadcastedIndicesToOffset(`output_indices${B}`, i)}; let offset_b${B} = ${c.broadcastedIndicesToOffset(`output_indices${B}`, i)}; let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`, i)}; let index_a${B} = offset_a${B} / 4u; let index_b${B} = offset_b${B} / 4u; let index_c${B} = offset_c${B} / 4u; let component_a${B} = offset_a${B} % 4u; let component_b${B} = offset_b${B} % 4u; let component_c${B} = offset_c${B} % 4u; ${k}[${B}] = ${R}(${C(z, ne, Z)}); `; }; o === 9 ? h = ` 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));` : h = ` ${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(p, a, c, i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`; }, It = (e) => { let t = e[1].dims, s = e[2].dims, n = e[0].dims, o = e[1].dataType, i = !(De.areEqual(t, s) && De.areEqual(s, n)), a = t, c = De.size(t); if (i) { let h = er.calcShape(er.calcShape(t, s, !1), n, !1); if (!h) throw new Error("Can't perform where op on the given tensors"); a = h, c = De.size(a); } let p = Math.ceil(c / 4); return { name: "Where", shaderCache: { inputDependencies: ["rank", "rank", "rank"] }, getShaderSource: (h) => Dt(h, e, a, i, o), getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(c / 64 / 4) }, programUniforms: [{ type: 12, data: p }, ...Mt(n, t, s, a)] }) }; }, vs = (e) => { e.compute(It(e.inputs)); }; }), Gt, fs = y(() => { cc(), si(), pc(), hc(), mc(), _c(), nu(), yc(), bc(), vc(), xc(), Tc(), Pc(), Ec(), Cc(), kc(), $c(), Ac(), Lp(), ta(), Dc(), _d(), Lc(), zc(), Pd(), ad(), $d(), Uc(), zp(), Wc(), Bp(), oo(), Rp(), Np(), Ht(), f(), Be(), oa(), qt(), Nr(), yi(), Qt(), Gt = /* @__PURE__ */ new Map([["Abs", [fl]], ["Acos", [ai]], ["Acosh", [gl]], ["Add", [bi]], ["ArgMax", [Yo, Jo]], ["ArgMin", [ll, Jo]], ["Asin", [wl]], ["Asinh", [li]], ["Atan", [yl]], ["Atanh", [Ml]], ["Attention", [cl]], ["AveragePool", [Vc, ga]], ["BatchNormalization", [ni]], ["BiasAdd", [_l]], ["BiasSplitGelu", [Mi]], ["Cast", [bl, ui]], ["Ceil", [xl]], ["Clip", [di]], ["Concat", [su, ru]], ["Conv", [go, Vi]], ["ConvTranspose", [bu, Gi]], ["Cos", [Tl]], ["Cosh", [ci]], ["CumSum", [vu, xu]], ["DepthToSpace", [Eu, Cu]], ["DequantizeLinear", [Nd, jd]], ["Div", [Hl]], ["Einsum", [Au, Iu]], ["Elu", [Pl, Ln]], ["Equal", [ql]], ["Erf", [El]], ["Exp", [pi]], ["Expand", [Lu]], ["FastGelu", [zu]], ["Floor", [Cl]], ["FusedConv", [go, Vi]], ["Gather", [Nu, Ru]], ["GatherElements", [qu, Hu]], ["GatherBlockQuantized", [Wu, Gu]], ["GatherND", [vo, Vu]], ["Gelu", [kl]], ["Gemm", [xo, Yu]], ["GlobalAveragePool", [Fd, Id]], ["GlobalMaxPool", [zd, Ld]], ["Greater", [Yl]], ["GreaterOrEqual", [xi]], ["GridSample", [rd, nd]], ["GroupQueryAttention", [ia]], ["HardSigmoid", [Fl, _i]], ["InstanceNormalization", [md]], ["LayerNormalization", [ua]], ["LeakyRelu", [hi, Ln]], ["Less", [Jl]], ["LessOrEqual", [Zl]], ["Log", [Nl]], ["MatMul", [yd]], ["MatMulNBits", [xd, Td]], ["MaxPool", [Od, Dd]], ["Mul", [Ql]], ["MultiHeadAttention", [Ic, id]], ["Neg", [$l]], ["Not", [Sl]], ["Pad", [Nc]], ["Pow", [Xl]], ["QuickGelu", [Vl, Ln]], ["Range", [Wd]], ["Reciprocal", [mi]], ["ReduceMin", [nl]], ["ReduceMean", [tl]], ["ReduceMax", [qo]], ["ReduceSum", [Qo]], ["ReduceProd", [ol]], ["ReduceL1", [Ho]], ["ReduceL2", [sl]], ["ReduceLogSum", [al]], ["ReduceLogSumExp", [rl]], ["ReduceSumSquare", [il]], ["Relu", [Al]], ["Resize", [up, dp]], ["RotaryEmbedding", [hp]], ["ScatterND", [Kc, Gc]], ["Sigmoid", [Il]], ["Sin", [Ol]], ["Sinh", [fi]], ["Slice", [Xd, Yd]], ["SkipLayerNormalization", [fp]], ["Split", [cd, pd]], ["Sqrt", [Dl]], ["Softmax", [xe, Se]], ["Sub", [vi]], ["Tan", [Ll]], ["Tanh", [zl]], ["ThresholdedRelu", [Rl, Ln]], ["Tile", [Jt]], ["Transpose", [Oa, Ro]], ["Where", [vs]]]); }), Ms, Zt = y(() => { ze(), Te(), Kt(), Ms = class { constructor(e) { this.backend = e, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = !1; } getArtifact(e) { return this.repo.get(e); } setArtifact(e, t) { this.repo.set(e, t); } run(e, t, s, n, o) { Ve(e.programInfo.name); let i = this.backend.device, a = this.backend.getComputePassEncoder(); this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2); let c = []; for (let h of t) c.push({ binding: c.length, resource: { buffer: h.buffer } }); for (let h of s) c.push({ binding: c.length, resource: { buffer: h.buffer } }); o && c.push({ binding: c.length, resource: o }); let p = i.createBindGroup({ layout: e.computePipeline.getBindGroupLayout(0), entries: c, label: e.programInfo.name }); if (this.backend.sessionStatus === "capturing") { let h = { kernelId: this.backend.currentKernelId, computePipeline: e.computePipeline, bindGroup: p, dispatchGroup: n }; this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h); } a.setPipeline(e.computePipeline), a.setBindGroup(0, p), a.dispatchWorkgroups(...n), 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(), Re(e.programInfo.name); } dispose() { } build(e, t) { Ve(e.name); let s = this.backend.device, n = []; [{ feature: "shader-f16", extension: "f16" }, { feature: "subgroups", extension: "subgroups" }, { feature: "subgroups-f16", extension: "subgroups_f16" }].forEach((h) => { s.features.has(h.feature) && n.push(`enable ${h.extension};`); }); let o = $a(t, this.backend.device.limits), i = e.getShaderSource(o), a = `${n.join(` `)} ${o.additionalImplementations} ${i}`, c = s.createShaderModule({ code: a, label: e.name }); as("verbose", () => `[WebGPU] ${e.name} shader code: ${a}`); let p = s.createComputePipeline({ compute: { module: c, entryPoint: "main" }, layout: "auto", label: e.name }); return Re(e.name), { programInfo: e, computePipeline: p, uniformVariablesInfo: o.variablesInfo }; } normalizeDispatchGroupSize(e) { let t = typeof e == "number" ? e : e.x, s = typeof e == "number" ? 1 : e.y || 1, n = typeof e == "number" ? 1 : e.z || 1, o = this.backend.device.limits.maxComputeWorkgroupsPerDimension; if (t <= o && s <= o && n <= o) return [t, s, n]; let i = t * s * n, a = Math.ceil(Math.sqrt(i)); if (a > o) { if (a = Math.ceil(Math.cbrt(i)), a > o) throw new Error("Total dispatch size exceeds WebGPU maximum."); return [a, a, a]; } else return [a, a, 1]; } }; }), Bs, Rs, $s, Ns, rr, wr = y(() => { ze(), Ot(), Te(), Y(), bs(), fs(), Zt(), Bs = (e, t) => { if (t.length !== e.length) throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`); let s = []; for (let n = 0; n < e.length; ++n) { let o = e[n].dataType; switch (t[n]) { case "none": { s.push(""); break; } case "type": { s.push(`${o}`); break; } case "rank": { let i = e[n].dims.length; s.push(`${o};${i}`); break; } case "dims": { let i = e[n].dims.join(","); s.push(`${o};${i}`); break; } default: throw new Error(`unsupported input dependency: ${t[n]}`); } } return s.join("|"); }, Rs = (e, t, s) => { let n = e.name; return e.shaderCache?.hint && (n += "[" + e.shaderCache.hint + "]"), n += ":" + s + `:${Bs(t, e.shaderCache?.inputDependencies ?? new Array(t.length).fill("dims"))}`, n; }, $s = class { constructor(e) { e && (this.architecture = e.architecture, this.vendor = e.vendor); } isArchitecture(e) { return this.architecture === e; } isVendor(e) { return this.vendor === e; } }, Ns = class { constructor(e) { this.subgroupsSupported = e.features.has("subgroups"), this.subgroupsF16Supported = e.features.has("subgroups"); let t = e.limits; !this.subgroupsSupported || !t.minSubgroupSize || !t.maxSubgroupSize ? this.subgroupSizeRange = void 0 : this.subgroupSizeRange = [t.minSubgroupSize, t.maxSubgroupSize]; } }, rr = 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 e = this.kernelCustomData.get(this.currentKernelId); return e || (e = {}, this.kernelCustomData.set(this.currentKernelId, e)), e; } async initialize(e, t) { this.env = e; let s = [], n = { requiredLimits: { maxComputeWorkgroupStorageSize: t.limits.maxComputeWorkgroupStorageSize, maxComputeWorkgroupsPerDimension: t.limits.maxComputeWorkgroupsPerDimension, maxStorageBufferBindingSize: t.limits.maxStorageBufferBindingSize, maxBufferSize: t.limits.maxBufferSize, maxComputeInvocationsPerWorkgroup: t.limits.maxComputeInvocationsPerWorkgroup, maxComputeWorkgroupSizeX: t.limits.maxComputeWorkgroupSizeX, maxComputeWorkgroupSizeY: t.limits.maxComputeWorkgroupSizeY, maxComputeWorkgroupSizeZ: t.limits.maxComputeWorkgroupSizeZ }, requiredFeatures: s }, o = (i) => t.features.has(i) && s.push(i) && !0; o("chromium-experimental-timestamp-query-inside-passes") || o("timestamp-query"), o("shader-f16"), o("subgroups") && o("subgroups-f16"), this.device = await t.requestDevice(n), this.deviceInfo = new Ns(this.device), this.adapterInfo = new $s(t.info || await t.requestAdapterInfo()), this.gpuDataManager = Xt(this), this.programManager = new Ms(this), this.kernels = /* @__PURE__ */ new Map(), this.kernelPersistentData = /* @__PURE__ */ new Map(), this.kernelCustomData = /* @__PURE__ */ new Map(), wn(e.logLevel, !!e.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: !1, enumerable: !0, configurable: !1 }), Object.defineProperty(this.env.webgpu, "adapter", { value: t, writable: !1, enumerable: !0, configurable: !1 }), 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 e = this.getCommandEncoder(), t = {}; this.queryType === "at-passes" && (t.timestampWrites = { querySet: this.querySet, beginningOfPassWriteIndex: this.pendingDispatchNumber * 2, endOfPassWriteIndex: this.pendingDispatchNumber * 2 + 1 }), this.computePassEncoder = e.beginComputePass(t); } return this.computePassEncoder; } endComputePass() { this.computePassEncoder && (this.computePassEncoder.end(), this.computePassEncoder = null); } flush() { if (!this.commandEncoder) return; Ve(), this.endComputePass(); let e; this.queryType !== "none" && (this.commandEncoder.resolveQuerySet(this.querySet, 0, this.pendingDispatchNumber * 2, this.queryResolveBuffer, 0), e = this.device.createBuffer({ size: this.pendingDispatchNumber * 2 * 8, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }), this.pendingQueries.set(e, this.pendingKernels), this.pendingKernels = [], this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer, 0, e, 0, this.pendingDispatchNumber * 2 * 8)), this.device.queue.submit([this.commandEncoder.finish()]), this.gpuDataManager.refreshPendingBuffers(), this.commandEncoder = null, this.pendingDispatchNumber = 0, this.queryType !== "none" && e.mapAsync(GPUMapMode.READ).then(() => { let t = new BigUint64Array(e.getMappedRange()), s = this.pendingQueries.get(e); for (let n = 0; n < t.length / 2; n++) { let o = s[n], i = o.kernelId, a = this.kernels.get(i), c = a.kernelType, p = a.kernelName, h = o.programName, C = o.inputTensorViews, u = o.outputTensorViews, k = t[n * 2], B = t[n * 2 + 1]; typeof this.queryTimeBase > "u" && (this.queryTimeBase = k); let R = Number(k - this.queryTimeBase), z = Number(B - this.queryTimeBase); if (!Number.isSafeInteger(R) || !Number.isSafeInteger(z)) throw new RangeError("incorrect timestamp range"); if (this.env.webgpu.profiling?.ondata) this.env.webgpu.profiling.ondata({ version: 1, inputsMetadata: C.map((ne) => ({ dims: ne.dims, dataType: pr(ne.dataType) })), outputsMetadata: u.map((ne) => ({ dims: ne.dims, dataType: pr(ne.dataType) })), kernelId: i, kernelType: c, kernelName: p, programName: h, startTime: R, endTime: z }); else { let ne = ""; C.forEach((W, ue) => { ne += `input[${ue}]: [${W.dims}] | ${pr(W.dataType)}, `; }); let Z = ""; u.forEach((W, ue) => { Z += `output[${ue}]: [${W.dims}] | ${pr(W.dataType)}, `; }), console.log(`[profiling] kernel "${i}|${c}|${p}|${h}" ${ne}${Z}execution time: ${z - R} ns`); } He("GPU", `${h}::${k}::${B}`); } e.unmap(), this.pendingQueries.delete(e); }), Re(); } run(e, t, s, n, o, i) { Ve(e.name); let a = []; for (let W = 0; W < t.length; ++W) { let ue = t[W].data; if (ue === 0) continue; let he = this.gpuDataManager.get(ue); if (!he) throw new Error(`no GPU data for input: ${ue}`); a.push(he); } let { outputs: c, dispatchGroup: p, programUniforms: h } = e.getRunData(t), C = s.length === 0 ? c.map((W, ue) => ue) : s; if (C.length !== c.length) throw new Error(`Output size ${C.length} must be equal to ${c.length}.`); let u = [], k = []; for (let W = 0; W < c.length; ++W) { if (!Number.isInteger(C[W]) || C[W] < -3 || C[W] >= i) throw new Error(`Invalid output index: ${C[W]}`); if (C[W] === -3) continue; let ue = C[W] === -1, he = C[W] === -2, Me = ue || he ? o(c[W].dataType, c[W].dims) : n(C[W], c[W].dataType, c[W].dims); if (u.push(Me), Me.data === 0) continue; let Le = this.gpuDataManager.get(Me.data); if (!Le) throw new Error(`no GPU data for output: ${Me.data}`); if (ue && this.temporaryData.push(Le), he) { let Ae = this.kernelPersistentData.get(this.currentKernelId); Ae || (Ae = [], this.kernelPersistentData.set(this.currentKernelId, Ae)), Ae.push(Le); } k.push(Le); } if (a.length !== t.length || k.length !== u.length) { if (k.length === 0) return Re(e.name), u; throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`); } let B; if (h) { let W = 0, ue = []; h.forEach((Ae) => { let it = typeof Ae.data == "number" ? [Ae.data] : Ae.data; if (it.length === 0) return; let dt = Ae.type === 10 ? 2 : 4, kt, Et; Ae.type === 10 ? (Et = it.length > 4 ? 16 : it.length > 2 ? 8 : it.length * dt, kt = it.length > 4 ? 16 : dt * it.length) : (Et = it.length <= 2 ? it.length * dt : 16, kt = 16), W = Math.ceil(W / Et) * Et, ue.push(W); let Ut = Ae.type === 10 ? 8 : 4; W += it.length > 4 ? Math.ceil(it.length / Ut) * kt : it.length * dt; }); let he = 16; W = Math.ceil(W / he) * he; let Me = new ArrayBuffer(W); h.forEach((Ae, it) => { let dt = ue[it], kt = typeof Ae.data == "number" ? [Ae.data] : Ae.data; if (Ae.type === 6) new Int32Array(Me, dt, kt.length).set(kt); else if (Ae.type === 12) new Uint32Array(Me, dt, kt.length).set(kt); else if (Ae.type === 10) new Uint16Array(Me, dt, kt.length).set(kt); else if (Ae.type === 1) new Float32Array(Me, dt, kt.length).set(kt); else throw new Error(`Unsupported uniform type: ${pr(Ae.type)}`); }); let Le = this.gpuDataManager.create(W, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM); this.device.queue.writeBuffer(Le.buffer, 0, Me, 0, W), this.gpuDataManager.release(Le.id), B = { offset: 0, size: W, buffer: Le.buffer }; } let R = this.programManager.normalizeDispatchGroupSize(p), z = R[1] === 1 && R[2] === 1, ne = Rs(e, t, z), Z = this.programManager.getArtifact(ne); if (Z || (Z = this.programManager.build(e, R), this.programManager.setArtifact(ne, Z), as("info", () => `[artifact] key: ${ne}, programName: ${e.name}`)), h && Z.uniformVariablesInfo) { if (h.length !== Z.uniformVariablesInfo.length) throw new Error(`Uniform variables count mismatch: expect ${Z.uniformVariablesInfo.length}, got ${h.length} in program "${Z.programInfo.name}".`); for (let W = 0; W < h.length; W++) { let ue = h[W], he = ue.type, Me = typeof ue.data == "number" ? 1 : ue.data.length, [Le, Ae] = Z.uniformVariablesInfo[W]; if (he !== Le || Me !== Ae) throw new Error(`Uniform variable ${W} mismatch: expect type ${Le} with size ${Ae}, got type ${he} with size ${Me} in program "${Z.programInfo.name}".`); } } if (as("info", () => `[ProgramManager] run "${e.name}" (key=${ne}) with ${R[0]}x${R[1]}x${R[2]}`), this.queryType !== "none" || this.sessionStatus === "capturing") { let W = { kernelId: this.currentKernelId, programName: Z.programInfo.name, inputTensorViews: t, outputTensorViews: u }; this.pendingKernels.push(W), this.sessionStatus === "capturing" && this.capturedPendingKernels.get(this.currentSessionId).push(W); } return this.programManager.run(Z, a, k, R, B), Re(e.name), u; } upload(e, t) { this.gpuDataManager.upload(e, t); } memcpy(e, t) { this.gpuDataManager.memcpy(e, t); } async download(e, t) { await this.gpuDataManager.download(e, t); } alloc(e) { return this.gpuDataManager.create(e).id; } free(e) { return this.gpuDataManager.release(e); } createKernel(e, t, s, n) { let o = Gt.get(e); if (!o) throw new Error(`kernel not implemented: ${e}`); let i = { kernelType: e, kernelName: n, kernelEntry: o[0], attributes: [o[1], s] }; this.kernels.set(t, i); } releaseKernel(e) { let t = this.kernelPersistentData.get(e); if (t) { for (let s of t) this.gpuDataManager.release(s.id); this.kernelPersistentData.delete(e); } this.kernelCustomData.delete(e), this.kernels.delete(e); } computeKernel(e, t, s) { let n = this.kernels.get(e); if (!n) throw new Error(`kernel not created: ${e}`); let o = n.kernelType, i = n.kernelName, a = n.kernelEntry, c = n.attributes; if (this.currentKernelId !== null) throw new Error(`kernel "[${o}] ${i}" is not allowed to be called recursively`); this.currentKernelId = e, c[0] && (c[1] = c[0](c[1]), c[0] = void 0), as("info", () => `[WebGPU] Start to run kernel "[${o}] ${i}"...`); let p = this.env.debug; this.temporaryData = []; try { return p && this.device.pushErrorScope("validation"), a(t, c[1]), 0; } catch (h) { return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${i}" failed. ${h}`)), 1; } finally { p && s.push(this.device.popErrorScope().then((h) => h ? `GPU validation error for kernel "[${o}] ${i}": ${h.message}` : null)); for (let h of this.temporaryData) this.gpuDataManager.release(h.id); this.temporaryData = [], this.currentKernelId = null; } } registerBuffer(e, t, s, n) { let o = this.sessionExternalDataMapping.get(e); o || (o = /* @__PURE__ */ new Map(), this.sessionExternalDataMapping.set(e, o)); let i = o.get(t), a = this.gpuDataManager.registerExternalBuffer(s, n, i); return o.set(t, [a, s]), a; } unregisterBuffers(e) { let t = this.sessionExternalDataMapping.get(e); t && (t.forEach((s) => this.gpuDataManager.unregisterExternalBuffer(s[0])), this.sessionExternalDataMapping.delete(e)); } getBuffer(e) { let t = this.gpuDataManager.get(e); if (!t) throw new Error(`no GPU data for buffer: ${e}`); return t.buffer; } createDownloader(e, t, s) { return async () => { let n = await ht(this, e, t); return M(n.buffer, s); }; } writeTimestamp(e) { this.queryType === "inside-passes" && this.computePassEncoder.writeTimestamp(this.querySet, e); } 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() { as("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() { as("info", "captureEnd"), this.flush(), this.sessionStatus = "default"; } replay() { as("info", "replay"), this.sessionStatus = "replaying"; let e = this.capturedCommandList.get(this.currentSessionId), t = this.capturedPendingKernels.get(this.currentSessionId), s = e.length; this.pendingKernels = []; for (let n = 0; n < s; n++) { let o = this.getComputePassEncoder(), i = e[n]; this.writeTimestamp(this.pendingDispatchNumber * 2), o.setPipeline(i.computePipeline), o.setBindGroup(0, i.bindGroup), o.dispatchWorkgroups(...i.dispatchGroup), this.writeTimestamp(this.pendingDispatchNumber * 2 + 1), this.pendingDispatchNumber++, this.queryType !== "none" && this.pendingKernels.push(t[n]), (this.pendingDispatchNumber >= this.maxDispatchNumber || this.queryType === "at-passes") && this.endComputePass(), this.pendingDispatchNumber >= this.maxDispatchNumber && this.flush(); } this.flush(), this.sessionStatus = "default"; } onCreateSession() { this.gpuDataManager.onCreateSession(); } onReleaseSession(e) { this.unregisterBuffers(e), this.capturedCommandList.has(e) && this.capturedCommandList.delete(e), this.capturedPendingKernels.has(e) && this.capturedPendingKernels.delete(e), this.gpuDataManager.onReleaseSession(e); } onRunStart(e) { this.currentSessionId = e, this.setQueryType(); } }; }), ya, or, $r, Mn, Co, Vn, Un, wp, xs = y(() => { Te(), ya = 1, or = () => ya++, $r = /* @__PURE__ */ new Map([["float32", 32], ["float16", 16], ["int32", 32], ["uint32", 32], ["int64", 64], ["uint64", 64], ["int8", 8], ["uint8", 8], ["int4", 4], ["uint4", 4]]), Mn = (e, t) => { let s = $r.get(e); if (!s) throw new Error("Unsupported data type."); return t.length > 0 ? Math.ceil(t.reduce((n, o) => n * o) * s / 8) : 0; }, Co = class { constructor(e) { this.sessionId = e.sessionId, this.mlContext = e.context, this.mlTensor = e.tensor, this.dataType = e.dataType, this.tensorShape = e.shape; } get tensor() { return this.mlTensor; } get type() { return this.dataType; } get shape() { return this.tensorShape; } get byteLength() { return Mn(this.dataType, this.tensorShape); } destroy() { as("verbose", () => "[WebNN] TensorWrapper.destroy"), this.mlTensor.destroy(); } write(e) { this.mlContext.writeTensor(this.mlTensor, e); } async read(e) { return e ? this.mlContext.readTensor(this.mlTensor, e) : this.mlContext.readTensor(this.mlTensor); } canReuseTensor(e, t, s) { return this.mlContext === e && this.dataType === t && this.tensorShape.length === s.length && this.tensorShape.every((n, o) => n === s[o]); } }, Vn = class { constructor(e, t) { this.tensorManager = e, this.wrapper = t; } get tensorWrapper() { return this.wrapper; } releaseTensor() { this.tensorWrapper && (this.tensorManager.releaseTensor(this.tensorWrapper), this.wrapper = void 0); } async ensureTensor(e, t, s, n) { if (this.wrapper) { if (this.wrapper.canReuseTensor(e, t, s)) return this.wrapper.tensor; if (n) { if (this.wrapper.byteLength !== Mn(t, s)) throw new Error("Unable to copy data to tensor with different size."); this.activeUpload = new Uint8Array(await this.wrapper.read()); } this.tensorManager.releaseTensor(this.wrapper); } let o = typeof MLTensorUsage > "u" ? void 0 : MLTensorUsage.READ | MLTensorUsage.WRITE; return this.wrapper = await this.tensorManager.getCachedTensor(t, s, o, !0, !0), n && this.activeUpload && (this.wrapper.write(this.activeUpload), this.activeUpload = void 0), this.wrapper.tensor; } upload(e) { if (this.wrapper) if (e.byteLength === this.wrapper.byteLength) { this.wrapper.write(e); return; } else as("verbose", () => "Data size does not match tensor size. Releasing tensor."), this.releaseTensor(); this.activeUpload ? this.activeUpload.set(e) : this.activeUpload = new Uint8Array(e); } async download(e) { if (this.activeUpload) if (e) { e instanceof ArrayBuffer ? new Uint8Array(e).set(this.activeUpload) : new Uint8Array(e.buffer, e.byteOffset, e.byteLength).set(this.activeUpload); return; } else return this.activeUpload.buffer; if (!this.wrapper) throw new Error("Tensor has not been created."); return e ? this.wrapper.read(e) : this.wrapper.read(); } }, Un = class { constructor(e) { this.backend = e, this.tensorTrackersById = /* @__PURE__ */ new Map(), this.freeTensors = [], this.externalTensors = /* @__PURE__ */ new Set(); } reserveTensorId() { let e = or(); return this.tensorTrackersById.set(e, new Vn(this)), e; } releaseTensorId(e) { let t = this.tensorTrackersById.get(e); t && (this.tensorTrackersById.delete(e), t.tensorWrapper && this.releaseTensor(t.tensorWrapper)); } async ensureTensor(e, t, s, n) { as("verbose", () => `[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`); let o = this.tensorTrackersById.get(e); if (!o) throw new Error("Tensor not found."); return o.ensureTensor(this.backend.currentContext, t, s, n); } upload(e, t) { let s = this.tensorTrackersById.get(e); if (!s) throw new Error("Tensor not found."); s.upload(t); } async download(e, t) { as("verbose", () => `[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`); let s = this.tensorTrackersById.get(e); if (!s) throw new Error("Tensor not found."); return s.download(t); } releaseTensorsForSession(e) { for (let t of this.freeTensors) t.sessionId === e && t.destroy(); this.freeTensors = this.freeTensors.filter((t) => t.sessionId !== e); } registerTensor(e, t, s, n) { let o = or(), i = new Co({ sessionId: this.backend.currentSessionId, context: e, tensor: t, dataType: s, shape: n }); return this.tensorTrackersById.set(o, new Vn(this, i)), this.externalTensors.add(i), o; } async getCachedTensor(e, t, s, n, o) { let i = this.backend.currentSessionId, a = this.backend.currentContext; for (let [p, h] of this.freeTensors.entries()) if (h.canReuseTensor(a, e, t)) { as("verbose", () => `[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`); let C = this.freeTensors.splice(p, 1)[0]; return C.sessionId = i, C; } as("verbose", () => `[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`); let c = await a.createTensor({ dataType: e, shape: t, dimensions: t, usage: s, writable: n, readable: o }); return new Co({ sessionId: i, context: a, tensor: c, dataType: e, shape: t }); } releaseTensor(e) { this.externalTensors.has(e) && this.externalTensors.delete(e), this.freeTensors.push(e); } }, wp = (...e) => new Un(...e); }), Os, Vr, on, Wn = y(() => { Ot(), Mr(), Y(), xs(), Te(), Os = /* @__PURE__ */ new Map([[1, "float32"], [10, "float16"], [6, "int32"], [12, "uint32"], [7, "int64"], [13, "uint64"], [22, "int4"], [21, "uint4"], [3, "int8"], [2, "uint8"], [9, "uint8"]]), Vr = (e, t) => { if (e === t) return !0; if (e === void 0 || t === void 0) return !1; let s = Object.keys(e).sort(), n = Object.keys(t).sort(); return s.length === n.length && s.every((o, i) => o === n[i] && e[o] === t[o]); }, on = class { constructor(e) { this.tensorManager = wp(this), this.mlContextBySessionId = /* @__PURE__ */ new Map(), this.sessionIdsByMLContext = /* @__PURE__ */ new Map(), this.mlContextCache = [], wn(e.logLevel, !!e.debug); } get currentSessionId() { if (this.activeSessionId === void 0) throw new Error("No active session"); return this.activeSessionId; } onRunStart(e) { this.activeSessionId = e; } async createMLContext(e) { if (e instanceof GPUDevice) { let s = this.mlContextCache.findIndex((n) => n.gpuDevice === e); if (s !== -1) return this.mlContextCache[s].mlContext; { let n = await navigator.ml.createContext(e); return this.mlContextCache.push({ gpuDevice: e, mlContext: n }), n; } } else if (e === void 0) { let s = this.mlContextCache.findIndex((n) => n.options === void 0 && n.gpuDevice === void 0); if (s !== -1) return this.mlContextCache[s].mlContext; { let n = await navigator.ml.createContext(); return this.mlContextCache.push({ mlContext: n }), n; } } let t = this.mlContextCache.findIndex((s) => Vr(s.options, e)); if (t !== -1) return this.mlContextCache[t].mlContext; { let s = await navigator.ml.createContext(e); return this.mlContextCache.push({ options: e, mlContext: s }), s; } } get currentContext() { let e = this.getMLContext(this.currentSessionId); if (!e) throw new Error(`No MLContext found for session ${this.currentSessionId}`); return e; } registerMLContext(e, t) { this.mlContextBySessionId.set(e, t); let s = this.sessionIdsByMLContext.get(t); s || (s = /* @__PURE__ */ new Set(), this.sessionIdsByMLContext.set(t, s)), s.add(e); } onReleaseSession(e) { let t = this.mlContextBySessionId.get(e); if (!t) return; this.tensorManager.releaseTensorsForSession(e), this.mlContextBySessionId.delete(e); let s = this.sessionIdsByMLContext.get(t); if (s.delete(e), s.size === 0) { this.sessionIdsByMLContext.delete(t); let n = this.mlContextCache.findIndex((o) => o.mlContext === t); n !== -1 && this.mlContextCache.splice(n, 1); } } getMLContext(e) { return this.mlContextBySessionId.get(e); } reserveTensorId() { return this.tensorManager.reserveTensorId(); } releaseTensorId(e) { as("verbose", () => `[WebNN] releaseTensorId {tensorId: ${e}}`), this.tensorManager.releaseTensorId(e); } async ensureTensor(e, t, s, n) { let o = Os.get(t); if (!o) throw new Error(`Unsupported ONNX data type: ${t}`); return this.tensorManager.ensureTensor(e, o, s, n); } uploadTensor(e, t) { if (!ws().shouldTransferToMLTensor) throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false"); as("verbose", () => `[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`), this.tensorManager.upload(e, t); } async downloadTensor(e, t) { return this.tensorManager.download(e, t); } createMLTensorDownloader(e, t) { return async () => { let s = await this.tensorManager.download(e); return M(s, t); }; } registerMLTensor(e, t, s) { let n = Os.get(t); if (!n) throw new Error(`Unsupported ONNX data type: ${t}`); let o = this.tensorManager.registerTensor(this.currentContext, e, n, s); return as("verbose", () => `[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`), o; } registerMLConstant(e, t, s, n, o, i) { if (!i) throw new Error("External mounted files are not available."); let a = e; e.startsWith("./") && (a = e.substring(2)); let c = i.get(a); if (!c) throw new Error(`File with name ${a} not found in preloaded files.`); if (t + s > c.byteLength) throw new Error("Out of bounds: data offset and length exceed the external file data size."); let p = c.slice(t, t + s).buffer, h; switch (o.dataType) { case "float32": h = new Float32Array(p); break; case "float16": h = new Uint16Array(p); break; case "int32": h = new Int32Array(p); break; case "uint32": h = new Uint32Array(p); break; case "int64": h = new BigInt64Array(p); break; case "uint64": h = new BigUint64Array(p); break; case "int8": h = new Int8Array(p); break; case "int4": case "uint4": case "uint8": h = new Uint8Array(p); break; default: throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`); } return as("verbose", () => `[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`), n.constant(o, h); } flush() { } }; }), ko = {}; T(ko, { init: () => ba }); var Gn, Ma, ba, jp = y(() => { Ot(), wr(), Te(), At(), Wn(), Gn = class Jm { constructor(t, s, n, o) { this.module = t, this.dataType = s, this.data = n, this.dims = o; } getFloat32Array() { if (this.dataType !== 1) throw new Error("Invalid data type"); let t = De.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 = De.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 = De.size(this.dims); return t === 0 ? new Int32Array() : new Int32Array(this.module.HEAP8.buffer, this.data, t); } getUint16Array() { if (this.dataType !== 10 && this.dataType !== 4) throw new Error("Invalid data type"); let t = De.size(this.dims); return t === 0 ? new Uint16Array() : new Uint16Array(this.module.HEAP8.buffer, this.data, t); } reshape(t) { if (De.size(t) !== De.size(this.dims)) throw new Error("Invalid new shape"); return new Jm(this.module, this.dataType, this.data, t); } }, Ma = class { constructor(e, t, s) { this.module = e, this.backend = t, this.customDataOffset = 0, this.customDataSize = 0, this.adapterInfo = t.adapterInfo, this.deviceInfo = t.deviceInfo; let n = e.PTR_SIZE, o = s / e.PTR_SIZE, i = n === 4 ? "i32" : "i64"; this.opKernelContext = Number(e.getValue(n * o++, i)); let a = Number(e.getValue(n * o++, i)); this.outputCount = Number(e.getValue(n * o++, i)), this.customDataOffset = Number(e.getValue(n * o++, "*")), this.customDataSize = Number(e.getValue(n * o++, i)); let c = []; for (let p = 0; p < a; p++) { let h = Number(e.getValue(n * o++, i)), C = Number(e.getValue(n * o++, "*")), u = Number(e.getValue(n * o++, i)), k = []; for (let B = 0; B < u; B++) k.push(Number(e.getValue(n * o++, i))); c.push(new Gn(e, h, C, k)); } this.inputs = c; } get kernelCustomData() { return this.backend.currentKernelCustomData; } get customDataBuffer() { return this.module.HEAPU8.subarray(this.customDataOffset, this.customDataOffset + this.customDataSize); } compute(e, t) { let s = t?.inputs?.map((a) => typeof a == "number" ? this.inputs[a] : a) ?? this.inputs, n = t?.outputs ?? [], o = (a, c, p) => new Gn(this.module, c, this.output(a, p), p), i = (a, c) => { let p = ar(a, c); if (!p) throw new Error(`Unsupported data type: ${a}`); let h = p > 0 ? this.backend.gpuDataManager.create(p).id : 0; return new Gn(this.module, a, h, c); }; return this.backend.run(e, s, n, o, i, this.outputCount); } output(e, t) { let s = this.module.stackSave(); try { let n = this.module.PTR_SIZE, o = n === 4 ? "i32" : "i64", i = this.module.stackAlloc((1 + t.length) * n); this.module.setValue(i, t.length, o); for (let a = 0; a < t.length; a++) this.module.setValue(i + n * (a + 1), t[a], o); return this.module._JsepOutput(this.opKernelContext, e, i); } catch (n) { throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`); } finally { this.module.stackRestore(s); } } }, ba = async (e, t, s, 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 rr(); await i.initialize(s, n), o("webgpu", [i, (a) => i.alloc(Number(a)), (a) => i.free(a), (a, c, p, h = !1) => { if (h) as("verbose", () => `[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(c)}, size=${Number(p)}`), i.memcpy(Number(a), Number(c)); else { as("verbose", () => `[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(c)}, size=${Number(p)}`); let C = t.HEAPU8.subarray(Number(a >>> 0), Number(a >>> 0) + Number(p)); i.upload(Number(c), C); } }, async (a, c, p) => { as("verbose", () => `[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`), await i.download(Number(a), () => t.HEAPU8.subarray(Number(c) >>> 0, Number(c + p) >>> 0)); }, (a, c, p) => i.createKernel(a, Number(c), p, t.UTF8ToString(t._JsepGetNodeName(Number(c)))), (a) => i.releaseKernel(a), (a, c, p, h) => { as("verbose", () => `[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`); let C = new Ma(t, i, Number(c)); return i.computeKernel(Number(a), C, h); }, () => i.captureBegin(), () => i.captureEnd(), () => i.replay()]); } else { let i = new on(s); o("webnn", [i, () => i.reserveTensorId(), (a) => i.releaseTensorId(a), async (a, c, p, h) => i.ensureTensor(a, c, p, h), (a, c) => { i.uploadTensor(a, c); }, async (a, c) => i.downloadTensor(a, c)]); } }; }), va, Kn, So, Ur, xa, bn, Jd, Zd, ec, Wr, cr, Vp, fh = y(() => { eo(), to(), Ot(), Mr(), pn(), $n(), va = (e, t) => { ws()._OrtInit(e, t) !== 0 && ss("Can't initialize onnxruntime."); }, Kn = async (e) => { va(e.wasm.numThreads, Qr(e.logLevel)); }, So = async (e, t) => { { let s = (jp(), b(ko)).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 s("webgpu", ws(), e, n); } if (t === "webnn") { if (typeof navigator > "u" || !navigator.ml) throw new Error("WebNN is not supported in current environment"); await s("webnn", ws(), e); } } }, Ur = /* @__PURE__ */ new Map(), xa = (e) => { let t = ws(), s = t.stackSave(); try { let n = t.PTR_SIZE, o = t.stackAlloc(2 * n); t._OrtGetInputOutputCount(e, o, o + n) !== 0 && ss("Can't get session input/output count."); let i = n === 4 ? "i32" : "i64"; return [Number(t.getValue(o, i)), Number(t.getValue(o + n, i))]; } finally { t.stackRestore(s); } }, bn = (e) => { let t = ws(), s = t._malloc(e.byteLength); if (s === 0) throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`); return t.HEAPU8.set(e, s), [s, e.byteLength]; }, Jd = async (e, t) => { let s, n, o = ws(); Array.isArray(e) ? [s, n] = e : e.buffer === o.HEAPU8.buffer ? [s, n] = [e.byteOffset, e.byteLength] : [s, n] = bn(e); let i = 0, a = 0, c = 0, p = [], h = [], C = []; try { if ([a, p] = Sn(t), t?.externalData && o.mountExternalData) { let W = []; for (let ue of t.externalData) { let he = typeof ue == "string" ? ue : ue.path; W.push(gn(typeof ue == "string" ? ue : ue.data).then((Me) => { o.mountExternalData(he, Me); })); } await Promise.all(W); } for (let W of t?.executionProviders ?? []) if ((typeof W == "string" ? W : W.name) === "webnn") { if (o.shouldTransferToMLTensor = !1, typeof W != "string") { let ue = W, he = ue?.context, Me = ue?.gpuDevice, Le = ue?.deviceType, Ae = ue?.powerPreference; he ? o.currentContext = he : Me ? o.currentContext = await o.jsepCreateMLContext(Me) : o.currentContext = await o.jsepCreateMLContext({ deviceType: Le, powerPreference: Ae }); } else o.currentContext = await o.jsepCreateMLContext(); break; } i = await o._OrtCreateSession(s, n, a), i === 0 && ss("Can't create a session."), o.jsepOnCreateSession?.(), o.currentContext && (o.jsepRegisterMLContext(i, o.currentContext), o.currentContext = void 0, o.shouldTransferToMLTensor = !0); let [u, k] = xa(i), B = !!t?.enableGraphCapture, R = [], z = [], ne = []; for (let W = 0; W < u; W++) { let ue = o._OrtGetInputName(i, W); ue === 0 && ss("Can't get an input name."), h.push(ue), R.push(o.UTF8ToString(ue)); } for (let W = 0; W < k; W++) { let ue = o._OrtGetOutputName(i, W); ue === 0 && ss("Can't get an output name."), C.push(ue); let he = o.UTF8ToString(ue); z.push(he); { if (B && t?.preferredOutputLocation === void 0) { ne.push("gpu-buffer"); continue; } let Me = typeof t?.preferredOutputLocation == "string" ? t.preferredOutputLocation : t?.preferredOutputLocation?.[he] ?? "cpu"; if (Me !== "cpu" && Me !== "cpu-pinned" && Me !== "gpu-buffer" && Me !== "ml-tensor") throw new Error(`Not supported preferred output location: ${Me}.`); if (B && Me !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${Me}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`); ne.push(Me); } } let Z = null; return ne.some((W) => W === "gpu-buffer" || W === "ml-tensor") && (c = o._OrtCreateBinding(i), c === 0 && ss("Can't create IO binding."), Z = { handle: c, outputPreferredLocations: ne, outputPreferredLocationsEncoded: ne.map((W) => fn(W)) }), Ur.set(i, [i, h, C, Z, B, !1]), [i, R, z]; } catch (u) { throw h.forEach((k) => o._OrtFree(k)), C.forEach((k) => o._OrtFree(k)), c !== 0 && o._OrtReleaseBinding(c) !== 0 && ss("Can't release IO binding."), i !== 0 && o._OrtReleaseSession(i) !== 0 && ss("Can't release session."), u; } finally { o._free(s), a !== 0 && o._OrtReleaseSessionOptions(a) !== 0 && ss("Can't release session options."), p.forEach((u) => o._free(u)), o.unmountExternalData?.(); } }, Zd = (e) => { let t = ws(), s = Ur.get(e); if (!s) throw new Error(`cannot release session. invalid session id: ${e}`); let [n, o, i, a, c] = s; a && (c && t._OrtClearBoundOutputs(a.handle) !== 0 && ss("Can't clear bound outputs."), t._OrtReleaseBinding(a.handle) !== 0 && ss("Can't release IO binding.")), t.jsepOnReleaseSession?.(e), o.forEach((p) => t._OrtFree(p)), i.forEach((p) => t._OrtFree(p)), t._OrtReleaseSession(n) !== 0 && ss("Can't release session."), Ur.delete(e); }, ec = (e, t, s, n, o, i = !1) => { if (!e) { t.push(0); return; } let a = ws(), c = a.PTR_SIZE, p = e[0], h = e[1], C = e[3], u, k; if (p === "string" && (C === "gpu-buffer" || C === "ml-tensor")) throw new Error("String tensor is not supported on GPU."); if (i && C !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`); if (C === "gpu-buffer") { let z = e[2].gpuBuffer; k = ar(Br(p), h); let ne = a.jsepRegisterBuffer; if (!ne) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.'); u = ne(n, o, z, k); } else if (C === "ml-tensor") { let z = e[2].mlTensor; k = ar(Br(p), h); let ne = a.jsepRegisterMLTensor; if (!ne) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.'); u = ne(z, Br(p), h); } else { let z = e[2]; if (Array.isArray(z)) { k = c * z.length, u = a._malloc(k), s.push(u); for (let ne = 0; ne < z.length; ne++) { if (typeof z[ne] != "string") throw new TypeError(`tensor data at index ${ne} is not a string`); a.setValue(u + ne * c, zs(z[ne], s), "*"); } } else k = z.byteLength, u = a._malloc(k), s.push(u), a.HEAPU8.set(new Uint8Array(z.buffer, z.byteOffset, k), u); } let B = a.stackSave(), R = a.stackAlloc(4 * h.length); try { h.forEach((ne, Z) => a.setValue(R + Z * c, ne, c === 4 ? "i32" : "i64")); let z = a._OrtCreateTensor(Br(p), u, k, R, h.length, fn(C)); z === 0 && ss(`Can't create tensor for input/output. session=${n}, index=${o}.`), t.push(z); } finally { a.stackRestore(B); } }, Wr = async (e, t, s, n, o, i) => { let a = ws(), c = a.PTR_SIZE, p = Ur.get(e); if (!p) throw new Error(`cannot run inference. invalid session id: ${e}`); let h = p[0], C = p[1], u = p[2], k = p[3], B = p[4], R = p[5], z = t.length, ne = n.length, Z = 0, W = [], ue = [], he = [], Me = [], Le = a.stackSave(), Ae = a.stackAlloc(z * c), it = a.stackAlloc(z * c), dt = a.stackAlloc(ne * c), kt = a.stackAlloc(ne * c); try { a.jsepOnRunStart?.(h), [Z, W] = Lr(i); for (let pt = 0; pt < z; pt++) ec(s[pt], ue, Me, e, t[pt], B); for (let pt = 0; pt < ne; pt++) ec(o[pt], he, Me, e, z + n[pt], B); for (let pt = 0; pt < z; pt++) a.setValue(Ae + pt * c, ue[pt], "*"), a.setValue(it + pt * c, C[t[pt]], "*"); for (let pt = 0; pt < ne; pt++) a.setValue(dt + pt * c, he[pt], "*"), a.setValue(kt + pt * c, u[n[pt]], "*"); if (k && !R) { let { handle: pt, outputPreferredLocations: zt, outputPreferredLocationsEncoded: ns } = k; if (C.length !== z) throw new Error(`input count from feeds (${z}) is expected to be always equal to model's input count (${C.length}).`); for (let Tt = 0; Tt < z; Tt++) { let Yt = t[Tt]; await a._OrtBindInput(pt, C[Yt], ue[Tt]) !== 0 && ss(`Can't bind input[${Tt}] for session=${e}.`); } for (let Tt = 0; Tt < ne; Tt++) { let Yt = n[Tt]; o[Tt]?.[3] ? a._OrtBindOutput(pt, u[Yt], he[Tt], 0) !== 0 && ss(`Can't bind pre-allocated output[${Tt}] for session=${e}.`) : a._OrtBindOutput(pt, u[Yt], 0, ns[Yt]) !== 0 && ss(`Can't bind output[${Tt}] to ${zt[Tt]} for session=${e}.`); } Ur.set(e, [h, C, u, k, B, !0]); } let Et; k ? Et = await a._OrtRunWithBinding(h, k.handle, ne, dt, Z) : Et = await a._OrtRun(h, it, Ae, z, kt, ne, dt, Z), Et !== 0 && ss("failed to call OrtRun()."); let Ut = []; for (let pt = 0; pt < ne; pt++) { let zt = Number(a.getValue(dt + pt * c, "*")); if (zt === he[pt]) { Ut.push(o[pt]); continue; } let ns = a.stackSave(), Tt = a.stackAlloc(4 * c), Yt = !1, os, Vt = 0; try { a._OrtGetTensorData(zt, Tt, Tt + c, Tt + 2 * c, Tt + 3 * c) !== 0 && ss(`Can't access output tensor data on index ${pt}.`); let As = c === 4 ? "i32" : "i64", ut = Number(a.getValue(Tt, As)); Vt = a.getValue(Tt + c, "*"); let xt = a.getValue(Tt + c * 2, "*"), hs = Number(a.getValue(Tt + c * 3, As)), cs = []; for (let Ds = 0; Ds < hs; Ds++) cs.push(Number(a.getValue(xt + Ds * c, As))); a._OrtFree(xt) !== 0 && ss("Can't free memory for tensor dims."); let Js = cs.reduce((Ds, ys) => Ds * ys, 1); os = pr(ut); let vn = k?.outputPreferredLocations[n[pt]]; if (os === "string") { if (vn === "gpu-buffer" || vn === "ml-tensor") throw new Error("String tensor is not supported on GPU."); let Ds = []; for (let ys = 0; ys < Js; ys++) { let qn = a.getValue(Vt + ys * c, "*"), rc = a.getValue(Vt + (ys + 1) * c, "*"), Hp = ys === Js - 1 ? void 0 : rc - qn; Ds.push(a.UTF8ToString(qn, Hp)); } Ut.push([os, cs, Ds, "cpu"]); } else if (vn === "gpu-buffer" && Js > 0) { let Ds = a.jsepGetBuffer; if (!Ds) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.'); let ys = Ds(Vt), qn = ar(ut, Js); if (qn === void 0 || !mn(os)) throw new Error(`Unsupported data type: ${os}`); Yt = !0, Ut.push([os, cs, { gpuBuffer: ys, download: a.jsepCreateDownloader(ys, qn, os), dispose: () => { a._OrtReleaseTensor(zt) !== 0 && ss("Can't release tensor."); } }, "gpu-buffer"]); } else if (vn === "ml-tensor" && Js > 0) { let Ds = a.jsepEnsureTensor; if (!Ds) throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.'); if (ar(ut, Js) === void 0 || !_n(os)) throw new Error(`Unsupported data type: ${os}`); let ys = await Ds(Vt, ut, cs, !1); Yt = !0, Ut.push([os, cs, { mlTensor: ys, download: a.jsepCreateMLTensorDownloader(Vt, os), dispose: () => { a.jsepReleaseTensorId(Vt), a._OrtReleaseTensor(zt); } }, "ml-tensor"]); } else { let Ds = hn(os), ys = new Ds(Js); new Uint8Array(ys.buffer, ys.byteOffset, ys.byteLength).set(a.HEAPU8.subarray(Vt, Vt + ys.byteLength)), Ut.push([os, cs, ys, "cpu"]); } } finally { a.stackRestore(ns), os === "string" && Vt && a._free(Vt), Yt || a._OrtReleaseTensor(zt); } } return k && !B && (a._OrtClearBoundOutputs(k.handle) !== 0 && ss("Can't clear bound outputs."), Ur.set(e, [h, C, u, k, B, !1])), Ut; } finally { a.stackRestore(Le), ue.forEach((Et) => a._OrtReleaseTensor(Et)), he.forEach((Et) => a._OrtReleaseTensor(Et)), Me.forEach((Et) => a._free(Et)), Z !== 0 && a._OrtReleaseRunOptions(Z), W.forEach((Et) => a._free(Et)); } }, cr = (e) => { let t = ws(), s = Ur.get(e); if (!s) throw new Error("invalid session id"); let n = s[0], o = t._OrtEndProfiling(n); o === 0 && ss("Can't get an profile file name."), t._OrtFree(o); }, Vp = (e) => { let t = []; for (let s of e) { let n = s[2]; !Array.isArray(n) && "buffer" in n && t.push(n.buffer); } return t; }; }), Hn, Ar, Ta, tc, sc, yp, Up, Mp, $o, Ao, gh, wh, yh, Mh, bh, vh, xh, Th, Ph = y(() => { ze(), fh(), Mr(), Dr(), Hn = () => !!I.wasm.proxy && typeof document < "u", Ta = !1, tc = !1, sc = !1, Mp = /* @__PURE__ */ new Map(), $o = (e, t) => { let s = Mp.get(e); s ? s.push(t) : Mp.set(e, [t]); }, Ao = () => { if (Ta || !tc || sc || !Ar) throw new Error("worker not ready"); }, gh = (e) => { switch (e.data.type) { case "init-wasm": Ta = !1, e.data.err ? (sc = !0, Up[1](e.data.err)) : (tc = !0, Up[0]()), yp && (URL.revokeObjectURL(yp), yp = void 0); break; case "init-ep": case "copy-from": case "create": case "release": case "run": case "end-profiling": { let t = Mp.get(e.data.type); e.data.err ? t.shift()[1](e.data.err) : t.shift()[0](e.data.out); break; } } }, wh = async () => { if (!tc) { if (Ta) throw new Error("multiple calls to 'initWasm()' detected."); if (sc) throw new Error("previous call to 'initWasm()' failed."); if (Ta = !0, Hn()) return new Promise((e, t) => { Ar?.terminate(), Fr().then(([s, n]) => { try { Ar = n, Ar.onerror = (i) => t(i), Ar.onmessage = gh, Up = [e, t]; let o = { type: "init-wasm", in: I }; !o.in.wasm.wasmPaths && (s || import.meta.url?.startsWith("file:")) && (o.in.wasm.wasmPaths = { wasm: new URL( /* asset import */ r( /*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm" ), r.b ).href }), Ar.postMessage(o), yp = s; } catch (o) { t(o); } }, t); }); try { await cn(I.wasm), await Kn(I), tc = !0; } catch (e) { throw sc = !0, e; } finally { Ta = !1; } } }, yh = async (e) => { if (Hn()) return Ao(), new Promise((t, s) => { $o("init-ep", [t, s]); let n = { type: "init-ep", in: { epName: e, env: I } }; Ar.postMessage(n); }); await So(I, e); }, Mh = async (e) => Hn() ? (Ao(), new Promise((t, s) => { $o("copy-from", [t, s]); let n = { type: "copy-from", in: { buffer: e } }; Ar.postMessage(n, [e.buffer]); })) : bn(e), bh = async (e, t) => { if (Hn()) { if (t?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); return Ao(), new Promise((s, n) => { $o("create", [s, n]); let o = { type: "create", in: { model: e, options: { ...t } } }, i = []; e instanceof Uint8Array && i.push(e.buffer), Ar.postMessage(o, i); }); } else return Jd(e, t); }, vh = async (e) => { if (Hn()) return Ao(), new Promise((t, s) => { $o("release", [t, s]); let n = { type: "release", in: e }; Ar.postMessage(n); }); Zd(e); }, xh = async (e, t, s, n, o, i) => { if (Hn()) { if (s.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 Ao(), new Promise((a, c) => { $o("run", [a, c]); let p = s, h = { type: "run", in: { sessionId: e, inputIndices: t, inputs: p, outputIndices: n, options: i } }; Ar.postMessage(h, Vp(p)); }); } else return Wr(e, t, s, n, o, i); }, Th = async (e) => { if (Hn()) return Ao(), new Promise((t, s) => { $o("end-profiling", [t, s]); let n = { type: "end-profiling", in: e }; Ar.postMessage(n); }); cr(e); }; }), Wp, Eh, Ch, Zm = y(() => { ze(), Ph(), Ot(), Ge(), $n(), Wp = (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"]; case "ml-tensor": return [e.type, e.dims, { mlTensor: e.mlTensor }, "ml-tensor"]; default: throw new Error(`invalid data location: ${e.location} for ${t()}`); } }, Eh = (e) => { switch (e[3]) { case "cpu": return new te(e[0], e[2], e[1]); case "gpu-buffer": { let t = e[0]; if (!mn(t)) throw new Error(`not supported data type: ${t} for deserializing GPU tensor`); let { gpuBuffer: s, download: n, dispose: o } = e[2]; return te.fromGpuBuffer(s, { dataType: t, dims: e[1], download: n, dispose: o }); } case "ml-tensor": { let t = e[0]; if (!_n(t)) throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`); let { mlTensor: s, download: n, dispose: o } = e[2]; return te.fromMLTensor(s, { dataType: t, dims: e[1], download: n, dispose: o }); } default: throw new Error(`invalid data location: ${e[3]}`); } }, Ch = class { async fetchModelAndCopyToWasmMemory(e) { return Mh(await gn(e)); } async loadModel(e, t) { Ve(); let s; typeof e == "string" ? s = await this.fetchModelAndCopyToWasmMemory(e) : s = e, [this.sessionId, this.inputNames, this.outputNames] = await bh(s, t), Re(); } async dispose() { return vh(this.sessionId); } async run(e, t, s) { Ve(); let n = [], o = []; Object.entries(e).forEach((u) => { let k = u[0], B = u[1], R = this.inputNames.indexOf(k); if (R === -1) throw new Error(`invalid input '${k}'`); n.push(B), o.push(R); }); let i = [], a = []; Object.entries(t).forEach((u) => { let k = u[0], B = u[1], R = this.outputNames.indexOf(k); if (R === -1) throw new Error(`invalid output '${k}'`); i.push(B), a.push(R); }); let c = n.map((u, k) => Wp(u, () => `input "${this.inputNames[o[k]]}"`)), p = i.map((u, k) => u ? Wp(u, () => `output "${this.outputNames[a[k]]}"`) : null), h = await xh(this.sessionId, o, c, a, p, s), C = {}; for (let u = 0; u < h.length; u++) C[this.outputNames[a[u]]] = i[u] ?? Eh(h[u]); return Re(), C; } startProfiling() { } endProfiling() { Th(this.sessionId); } }; }), kh = {}; T(kh, { OnnxruntimeWebAssemblyBackend: () => Kp, initializeFlags: () => Gp, wasmBackend: () => Sh }); var Gp, Kp, Sh, e_ = y(() => { ze(), Ph(), Zm(), Gp = () => { if ((typeof I.wasm.initTimeout != "number" || I.wasm.initTimeout < 0) && (I.wasm.initTimeout = 0), I.wasm.simd === !1 && 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 I.wasm.proxy != "boolean" && (I.wasm.proxy = !1), typeof I.wasm.trace != "boolean" && (I.wasm.trace = !1), typeof I.wasm.numThreads != "number" || !Number.isInteger(I.wasm.numThreads) || I.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) I.wasm.numThreads = 1; else { let e = typeof navigator > "u" ? N("node:os").cpus().length : navigator.hardwareConcurrency; I.wasm.numThreads = Math.min(4, Math.ceil((e || 1) / 2)); } }, Kp = class { async init(e) { Gp(), await wh(), await yh(e); } async createInferenceSessionHandler(e, t) { let s = new Ch(); return await s.loadModel(e, t), Promise.resolve(s); } }, Sh = new Kp(); }); ze(), ze(), ze(); var t_ = "1.21.0-dev.20250206-d981b153d3", s_ = ke; { let e = (e_(), b(kh)).wasmBackend; K("webgpu", e, 5), K("webnn", e, 5), K("cpu", e, 10), K("wasm", e, 10); } Object.defineProperty(I.versions, "web", { value: t_, enumerable: !0 }); /** * @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. * ============================================================================= */ } ), /***/ "./src/backends/onnx.js": ( /*!******************************!*\ !*** ./src/backends/onnx.js ***! \******************************/ /***/ (Ie, $, r) => { var g; r.r($), r.d($, { /* harmony export */ Tensor: () => ( /* reexport safe */ N.Tensor ), /* harmony export */ createInferenceSession: () => ( /* binding */ ie ), /* harmony export */ deviceToExecutionProviders: () => ( /* binding */ K ), /* harmony export */ isONNXProxy: () => ( /* binding */ q ), /* harmony export */ isONNXTensor: () => ( /* binding */ V ) /* harmony export */ }); var O = r( /*! ../env.js */ "./src/env.js" ), j = r( /*! onnxruntime-node */ "?2ce3" ), ee = r( /*! onnxruntime-web */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96" ), N = r( /*! onnxruntime-common */ "./node_modules/onnxruntime-common/dist/esm/index.js" ); const y = Object.freeze({ auto: null, // Auto-detect based on device and environment gpu: null, // Auto-detect GPU cpu: "cpu", // CPU wasm: "wasm", // WebAssembly webgpu: "webgpu", // WebGPU cuda: "cuda", // CUDA dml: "dml", // DirectML webnn: { name: "webnn", deviceType: "cpu" }, // WebNN (default) "webnn-npu": { name: "webnn", deviceType: "npu" }, // WebNN NPU "webnn-gpu": { name: "webnn", deviceType: "gpu" }, // WebNN GPU "webnn-cpu": { name: "webnn", deviceType: "cpu" } // WebNN CPU }), T = []; let v, b; const x = Symbol.for("onnxruntime"); if (x in globalThis) b = globalThis[x]; else if (O.apis.IS_NODE_ENV) { switch (b = j ?? (g || (g = r.t(j, 2))), process.platform) { case "win32": T.push("dml"); break; case "linux": process.arch === "x64" && T.push("cuda"); break; } T.push("cpu"), v = ["cpu"]; } else b = ee, O.apis.IS_WEBNN_AVAILABLE && T.push("webnn-npu", "webnn-gpu", "webnn-cpu", "webnn"), O.apis.IS_WEBGPU_AVAILABLE && T.push("webgpu"), T.push("wasm"), v = ["wasm"]; const L = b.InferenceSession; function K(A = null) { if (!A) return v; switch (A) { case "auto": return T; case "gpu": return T.filter( (S) => ["webgpu", "cuda", "dml", "webnn-gpu"].includes(S) ); } if (T.includes(A)) return [y[A] ?? A]; throw new Error(`Unsupported device: "${A}". Should be one of: ${T.join(", ")}.`); } let re = null; async function ie(A, S, w) { re && await re; const P = L.create(A, S); re ??= P; const I = await P; return I.config = w, I; } function V(A) { return A instanceof b.Tensor; } const U = b?.env; U?.wasm && (U.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${O.env.version}/dist/`, U.wasm.proxy = !1, (typeof crossOriginIsolated > "u" || !crossOriginIsolated) && (U.wasm.numThreads = 1)), U?.webgpu && (U.webgpu.powerPreference = "high-performance"); function q() { return U?.wasm?.proxy; } O.env.backends.onnx = U; } ), /***/ "./src/base/feature_extraction_utils.js": ( /*!**********************************************!*\ !*** ./src/base/feature_extraction_utils.js ***! \**********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ FeatureExtractor: () => ( /* binding */ ee ), /* harmony export */ validate_audio_inputs: () => ( /* binding */ N ) /* harmony export */ }); var g = r( /*! ../utils/constants.js */ "./src/utils/constants.js" ), O = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ), j = r( /*! ../utils/hub.js */ "./src/utils/hub.js" ); class ee extends O.Callable { /** * Constructs a new FeatureExtractor instance. * * @param {Object} config The configuration for the feature extractor. */ constructor(T) { super(), this.config = T; } /** * Instantiate one of the feature extractor classes of the library from a pretrained model. * * The feature extractor 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 feature_extractor 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 feature_extractor files, e.g., `./my_model_directory/`. * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the feature_extractor. * * @returns {Promise} A new instance of the Feature Extractor class. */ static async from_pretrained(T, v) { const b = await (0, j.getModelJSON)(T, g.FEATURE_EXTRACTOR_NAME, !0, v); return new this(b); } } function N(y, T) { if (!(y instanceof Float32Array || y instanceof Float64Array)) throw new Error( `${T} expects input to be a Float32Array or a Float64Array, but got ${y?.constructor?.name ?? typeof y} 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.` ); } } ), /***/ "./src/base/image_processors_utils.js": ( /*!********************************************!*\ !*** ./src/base/image_processors_utils.js ***! \********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ImageProcessor: () => ( /* binding */ A ), /* harmony export */ center_to_corners_format: () => ( /* binding */ b ), /* harmony export */ post_process_instance_segmentation: () => ( /* binding */ q ), /* harmony export */ post_process_object_detection: () => ( /* binding */ x ), /* harmony export */ post_process_panoptic_segmentation: () => ( /* binding */ U ), /* harmony export */ post_process_semantic_segmentation: () => ( /* binding */ L ) /* harmony export */ }); var g = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ), O = r( /*! ../utils/tensor.js */ "./src/utils/tensor.js" ), j = r( /*! ../utils/maths.js */ "./src/utils/maths.js" ); r( /*! ../utils/image.js */ "./src/utils/image.js" ); var ee = r( /*! ../utils/core.js */ "./src/utils/core.js" ), N = r( /*! ../utils/hub.js */ "./src/utils/hub.js" ), y = r( /*! ../utils/constants.js */ "./src/utils/constants.js" ); function T(S, w, P = 0, I = null) { const le = S / w; let oe = (0, j.bankers_round)(le) * w; return I !== null && oe > I && (oe = Math.floor(le) * w), oe < P && (oe = Math.ceil(le) * w), oe; } function v([S, w], P) { return [ Math.max(Math.floor(S / P), 1) * P, Math.max(Math.floor(w / P), 1) * P ]; } function b([S, w, P, I]) { return [ S - P / 2, w - I / 2, S + P / 2, w + I / 2 ]; } function x(S, w = 0.5, P = null, I = !1) { const le = S.logits, oe = S.pred_boxes, [ye, ge, se] = le.dims; if (P !== null && P.length !== ye) throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); let be = []; for (let pe = 0; pe < ye; ++pe) { let Ce = P !== null ? P[pe] : null, $e = { boxes: [], classes: [], scores: [] }, Pe = le[pe], Je = oe[pe]; for (let Ue = 0; Ue < ge; ++Ue) { let we = Pe[Ue], X = [], de; if (I) { de = we.sigmoid().data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] > w && X.push(Ee); } else { let Ee = (0, j.max)(we.data)[1]; if (Ee === se - 1 || (de = (0, j.softmax)(we.data), de[Ee] < w)) continue; X.push(Ee); } for (const Ee of X) { let Oe = Je[Ue].data; Oe = b(Oe), Ce !== null && (Oe = Oe.map((Xe, J) => Xe * Ce[(J + 1) % 2])), $e.boxes.push(Oe), $e.classes.push(Ee), $e.scores.push(de[Ee]); } } be.push($e); } return be; } function L(S, w = null) { const P = S.logits, I = P.dims[0]; if (w !== null && w.length !== I) throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); const le = []; for (let oe = 0; oe < I; ++oe) { const ye = w !== null ? w[oe] : null; let ge = P[oe]; ye !== null && (ge = (0, O.interpolate)(ge, ye, "bilinear", !1)); const [se, be] = ye ?? ge.dims.slice(-2), pe = new O.Tensor( "int32", new Int32Array(se * be), [se, be] ), Ce = ge[0].data, $e = pe.data; for (let Ue = 1; Ue < ge.dims[0]; ++Ue) { const we = ge[Ue].data; for (let X = 0; X < we.length; ++X) we[X] > Ce[X] && (Ce[X] = we[X], $e[X] = Ue); } const Pe = new Array(ge.dims[0]); for (let Ue = 0; Ue < $e.length; ++Ue) { const we = $e[Ue]; Pe[we] = we; } const Je = Pe.filter((Ue) => Ue !== void 0); le.push({ segmentation: pe, labels: Je }); } return le; } function K(S, w, P, I) { const le = [], oe = [], ye = []; for (let ge = 0; ge < S.dims[0]; ++ge) { const se = S[ge], be = w[ge], pe = (0, j.max)(se.data)[1]; if (pe === I) continue; const $e = (0, j.softmax)(se.data)[pe]; $e > P && (le.push(be), oe.push($e), ye.push(pe)); } return [le, oe, ye]; } function re(S, w, P, I = 0.5, le = 0.8) { const oe = []; let ye = 0, ge = 0; const se = w[P].data; for (let pe = 0; pe < S.length; ++pe) S[pe] === P && (oe.push(pe), ++ye), se[pe] >= I && ++ge; let be = ye > 0 && ge > 0; return be && (be = ye / ge > le), [be, oe]; } function ie(S, w, P, I, le, oe = null, ye = null) { const [ge, se] = ye ?? S[0].dims, be = new O.Tensor( "int32", new Int32Array(ge * se), [ge, se] ), pe = []; if (ye !== null) for (let Ue = 0; Ue < S.length; ++Ue) S[Ue] = (0, O.interpolate)(S[Ue], ye, "bilinear", !1); const Ce = new Int32Array(S[0].data.length), $e = new Float32Array(S[0].data.length); for (let Ue = 0; Ue < S.length; ++Ue) { let we = w[Ue]; const X = S[Ue].data; for (let de = 0; de < X.length; ++de) X[de] *= we, X[de] > $e[de] && (Ce[de] = Ue, $e[de] = X[de]); } let Pe = 0; const Je = be.data; for (let Ue = 0; Ue < P.length; ++Ue) { const we = P[Ue], [X, de] = re( Ce, S, Ue, I, le ); if (X) { ++Pe; for (const Ee of de) Je[Ee] = Pe; pe.push({ id: Pe, label_id: we, // was_fused: should_fuse, TODO score: w[Ue] }); } } return [be, pe]; } function V(S, w, P = 28, I = 3136, le = 1003520) { if (S < P || w < P) throw new Error(`height:${S} or width:${w} must be larger than factor:${P}`); if (Math.max(S, w) / Math.min(S, w) > 200) throw new Error( `absolute aspect ratio must be smaller than 200, got ${Math.max(S, w) / Math.min(S, w)}` ); let oe = Math.round(S / P) * P, ye = Math.round(w / P) * P; if (oe * ye > le) { const ge = Math.sqrt(S * w / le); oe = Math.floor(S / ge / P) * P, ye = Math.floor(w / ge / P) * P; } else if (oe * ye < I) { const ge = Math.sqrt(I / (S * w)); oe = Math.ceil(S * ge / P) * P, ye = Math.ceil(w * ge / P) * P; } return [oe, ye]; } function U(S, w = 0.5, P = 0.5, I = 0.8, le = null, oe = null) { le === null && (console.warn("`label_ids_to_fuse` unset. No instance will be fused."), le = /* @__PURE__ */ new Set()); const ye = S.class_queries_logits ?? S.logits, se = (S.masks_queries_logits ?? S.pred_masks).sigmoid(); let [be, pe, Ce] = ye.dims; if (Ce -= 1, oe !== null && oe.length !== be) throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); let $e = []; for (let Pe = 0; Pe < be; ++Pe) { let Je = oe !== null ? oe[Pe] : null, Ue = ye[Pe], we = se[Pe], [X, de, Ee] = K(Ue, we, w, Ce); if (Ee.length === 0) { let [J, We] = Je ?? we.dims.slice(-2), Ne = new O.Tensor( "int32", new Int32Array(J * We).fill(-1), [J, We] ); $e.push({ segmentation: Ne, segments_info: [] }); continue; } let [Oe, Xe] = ie( X, de, Ee, P, I, le, Je ); $e.push({ segmentation: Oe, segments_info: Xe }); } return $e; } function q(S, w = 0.5, P = null) { throw new Error("`post_process_instance_segmentation` is not yet implemented."); } class A extends g.Callable { /** * Constructs a new `ImageProcessor`. * @param {ImageProcessorConfig} config The configuration object. */ constructor(w) { super(), this.image_mean = w.image_mean ?? w.mean, this.image_std = w.image_std ?? w.std, this.resample = w.resample ?? 2, this.do_rescale = w.do_rescale ?? !0, this.rescale_factor = w.rescale_factor ?? 0.00392156862745098, this.do_normalize = w.do_normalize, this.do_thumbnail = w.do_thumbnail, this.size = w.size ?? w.image_size, this.do_resize = w.do_resize ?? this.size !== void 0, this.size_divisibility = w.size_divisibility ?? w.size_divisor, this.do_center_crop = w.do_center_crop, this.crop_size = w.crop_size, this.do_convert_rgb = w.do_convert_rgb ?? !0, this.do_crop_margin = w.do_crop_margin, this.pad_size = w.pad_size, this.do_pad = w.do_pad, 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 = w.do_flip_channel_order ?? !1, this.config = w; } /** * 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(w, P, I = 2) { const le = w.height, oe = w.width, ye = P.height, ge = P.width; let se = Math.min(le, ye), be = Math.min(oe, ge); return se === le && be === oe ? w : (le > oe ? be = Math.floor(oe * se / le) : oe > le && (se = Math.floor(le * be / oe)), await w.resize(be, se, { resample: I })); } /** * 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(w, P = 200) { const I = w.clone().grayscale(), le = (0, j.min)(I.data)[0], ye = (0, j.max)(I.data)[0] - le; if (ye === 0) return w; const ge = P / 255; let se = I.width, be = I.height, pe = 0, Ce = 0; const $e = I.data; for (let Pe = 0; Pe < I.height; ++Pe) { const Je = Pe * I.width; for (let Ue = 0; Ue < I.width; ++Ue) ($e[Je + Ue] - le) / ye < ge && (se = Math.min(se, Ue), be = Math.min(be, Pe), pe = Math.max(pe, Ue), Ce = Math.max(Ce, Pe)); } return w = await w.crop([se, be, pe, Ce]), w; } /** * 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|'square'} 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|number[]} [options.constant_values=0] The constant value to use for padding. * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. */ pad_image(w, P, I, { mode: le = "constant", center: oe = !1, constant_values: ye = 0 } = {}) { const [ge, se, be] = P; let pe, Ce; if (typeof I == "number" ? (pe = I, Ce = I) : I === "square" ? pe = Ce = Math.max(ge, se) : (pe = I.width, Ce = I.height), pe !== se || Ce !== ge) { const $e = new Float32Array(pe * Ce * be); if (Array.isArray(ye)) for (let Ue = 0; Ue < $e.length; ++Ue) $e[Ue] = ye[Ue % be]; else ye !== 0 && $e.fill(ye); const [Pe, Je] = oe ? [Math.floor((pe - se) / 2), Math.floor((Ce - ge) / 2)] : [0, 0]; for (let Ue = 0; Ue < ge; ++Ue) { const we = (Ue + Je) * pe, X = Ue * se; for (let de = 0; de < se; ++de) { const Ee = (we + de + Pe) * be, Oe = (X + de) * be; for (let Xe = 0; Xe < be; ++Xe) $e[Ee + Xe] = w[Oe + Xe]; } } if (le === "symmetric") { if (oe) throw new Error("`center` padding is not supported when `mode` is set to `symmetric`."); const Ue = ge - 1, we = se - 1; for (let X = 0; X < Ce; ++X) { const de = X * pe, Ee = (0, ee.calculateReflectOffset)(X, Ue) * se; for (let Oe = 0; Oe < pe; ++Oe) { if (X < ge && Oe < se) continue; const Xe = (de + Oe) * be, J = (Ee + (0, ee.calculateReflectOffset)(Oe, we)) * be; for (let We = 0; We < be; ++We) $e[Xe + We] = w[J + We]; } } } w = $e, P = [Ce, pe, be]; } return [w, P]; } /** * Rescale the image' pixel values by `this.rescale_factor`. * @param {Float32Array} pixelData The pixel data to rescale. * @returns {void} */ rescale(w) { for (let P = 0; P < w.length; ++P) w[P] = this.rescale_factor * w[P]; } /** * 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(w, P) { const [I, le] = w.size; let oe, ye; if (this.do_thumbnail) { const { height: ge, width: se } = P; oe = Math.min(ge, se); } else Number.isInteger(P) ? (oe = P, ye = this.config.max_size ?? oe) : P !== void 0 && (oe = P.shortest_edge, ye = P.longest_edge); if (oe !== void 0 || ye !== void 0) { const ge = oe === void 0 ? 1 : Math.max(oe / I, oe / le), se = I * ge, be = le * ge, pe = ye === void 0 ? 1 : Math.min(ye / se, ye / be); let Ce = Math.floor(Number((se * pe).toFixed(2))), $e = Math.floor(Number((be * pe).toFixed(2))); return this.size_divisibility !== void 0 && ([Ce, $e] = v([Ce, $e], this.size_divisibility)), [Ce, $e]; } else if (P !== void 0 && P.width !== void 0 && P.height !== void 0) { let ge = P.width, se = P.height; if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { let be = se / le, pe = ge / I; Math.abs(1 - pe) < Math.abs(1 - be) ? be = pe : pe = be, se = T(be * le, this.config.ensure_multiple_of), ge = T(pe * I, this.config.ensure_multiple_of); } return [ge, se]; } else { if (this.size_divisibility !== void 0) return v([I, le], this.size_divisibility); if (P.min_pixels !== void 0 && P.max_pixels !== void 0) { const { min_pixels: ge, max_pixels: se } = P, be = this.config.patch_size * this.config.merge_size; return V(le, I, be, ge, se); } else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(P)}`); } } /** * Resizes the image. * @param {RawImage} image The image to resize. * @returns {Promise} The resized image. */ async resize(w) { const [P, I] = this.get_resize_output_image_size(w, this.size); return await w.resize(P, I, { // @ts-expect-error TS2322 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(w, { do_normalize: P = null, do_pad: I = null, do_convert_rgb: le = null, do_convert_grayscale: oe = null, do_flip_channel_order: ye = null } = {}) { this.do_crop_margin && (w = await this.crop_margin(w)); const [ge, se] = w.size; if (le ?? this.do_convert_rgb ? w = w.rgb() : oe && (w = w.grayscale()), this.do_resize && (w = await this.resize(w)), this.do_thumbnail && (w = await this.thumbnail(w, this.size, this.resample)), this.do_center_crop) { let Pe, Je; Number.isInteger(this.crop_size) ? (Pe = this.crop_size, Je = this.crop_size) : (Pe = this.crop_size.width, Je = this.crop_size.height), w = await w.center_crop(Pe, Je); } const be = [w.height, w.width]; let pe = Float32Array.from(w.data), Ce = [w.height, w.width, w.channels]; if (this.do_rescale && this.rescale(pe), P ?? this.do_normalize) { let Pe = this.image_mean; Array.isArray(this.image_mean) || (Pe = new Array(w.channels).fill(Pe)); let Je = this.image_std; if (Array.isArray(this.image_std) || (Je = new Array(w.channels).fill(Pe)), Pe.length !== w.channels || Je.length !== w.channels) throw new Error(`When set to arrays, the length of \`image_mean\` (${Pe.length}) and \`image_std\` (${Je.length}) must match the number of channels in the image (${w.channels}).`); for (let Ue = 0; Ue < pe.length; Ue += w.channels) for (let we = 0; we < w.channels; ++we) pe[Ue + we] = (pe[Ue + we] - Pe[we]) / Je[we]; } if (I ?? this.do_pad) { if (this.pad_size) [pe, Ce] = this.pad_image(pe, [w.height, w.width, w.channels], this.pad_size); else if (this.size_divisibility) { const [Pe, Je] = v([Ce[1], Ce[0]], this.size_divisibility); [pe, Ce] = this.pad_image(pe, Ce, { width: Pe, height: Je }); } } if (ye ?? this.do_flip_channel_order) { if (Ce[2] !== 3) throw new Error("Flipping channel order is only supported for RGB images."); for (let Pe = 0; Pe < pe.length; Pe += 3) { const Je = pe[Pe]; pe[Pe] = pe[Pe + 2], pe[Pe + 2] = Je; } } const $e = new O.Tensor("float32", pe, Ce).permute(2, 0, 1); return { original_size: [se, ge], reshaped_input_size: be, pixel_values: $e }; } /** * 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(w, ...P) { Array.isArray(w) || (w = [w]); const I = await Promise.all(w.map((oe) => this.preprocess(oe))); return { pixel_values: (0, O.stack)(I.map((oe) => oe.pixel_values), 0), // Original sizes of images original_sizes: I.map((oe) => oe.original_size), // Reshaped sizes of images, before padding or cropping reshaped_input_sizes: I.map((oe) => oe.reshaped_input_size) }; } /** * Instantiate one of the processor classes of the library from a pretrained model. * * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) * 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(w, P) { const I = await (0, N.getModelJSON)(w, y.IMAGE_PROCESSOR_NAME, !0, P); return new this(I); } } } ), /***/ "./src/base/processing_utils.js": ( /*!**************************************!*\ !*** ./src/base/processing_utils.js ***! \**************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Processor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../utils/constants.js */ "./src/utils/constants.js" ), O = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ), j = r( /*! ../utils/hub.js */ "./src/utils/hub.js" ); class ee extends O.Callable { static classes = [ "image_processor_class", "tokenizer_class", "feature_extractor_class" ]; static uses_processor_config = !1; /** * Creates a new Processor with the given components * @param {Object} config * @param {Record} components */ constructor(y, T) { super(), this.config = y, this.components = T; } /** * @returns {import('./image_processors_utils.js').ImageProcessor|undefined} The image processor of the processor, if it exists. */ get image_processor() { return this.components.image_processor; } /** * @returns {PreTrainedTokenizer|undefined} The tokenizer of the processor, if it exists. */ get tokenizer() { return this.components.tokenizer; } /** * @returns {import('./feature_extraction_utils.js').FeatureExtractor|undefined} The feature extractor of the processor, if it exists. */ get feature_extractor() { return this.components.feature_extractor; } /** * @param {Parameters[0]} messages * @param {Parameters[1]} options * @returns {ReturnType} */ apply_chat_template(y, T = {}) { if (!this.tokenizer) throw new Error("Unable to apply chat template without a tokenizer."); return this.tokenizer.apply_chat_template(y, { tokenize: !1, // default to false ...T }); } /** * @param {Parameters} args * @returns {ReturnType} */ batch_decode(...y) { if (!this.tokenizer) throw new Error("Unable to decode without a tokenizer."); return this.tokenizer.batch_decode(...y); } /** * @param {Parameters} args * @returns {ReturnType} */ decode(...y) { if (!this.tokenizer) throw new Error("Unable to decode without a tokenizer."); return this.tokenizer.decode(...y); } /** * 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(y, ...T) { for (const v of [this.image_processor, this.feature_extractor, this.tokenizer]) if (v) return v(y, ...T); throw new Error("No image processor, feature extractor, or tokenizer found."); } /** * Instantiate one of the processor classes of the library from a pretrained model. * * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) * 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 {PretrainedProcessorOptions} options Additional options for loading the processor. * * @returns {Promise} A new instance of the Processor class. */ static async from_pretrained(y, T) { const [v, b] = await Promise.all([ // TODO: this.uses_processor_config ? (0, j.getModelJSON)(y, g.PROCESSOR_NAME, !0, T) : {}, Promise.all( this.classes.filter((x) => x in this).map(async (x) => { const L = await this[x].from_pretrained(y, T); return [x.replace(/_class$/, ""), L]; }) ).then(Object.fromEntries) ]); return new this(v, b); } } } ), /***/ "./src/configs.js": ( /*!************************!*\ !*** ./src/configs.js ***! \************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AutoConfig: () => ( /* binding */ T ), /* harmony export */ PretrainedConfig: () => ( /* binding */ y ), /* harmony export */ getKeyValueShapes: () => ( /* binding */ N ) /* harmony export */ }); var g = r( /*! ./utils/core.js */ "./src/utils/core.js" ), O = r( /*! ./utils/hub.js */ "./src/utils/hub.js" ); async function j(v, b) { return await (0, O.getModelJSON)(v, "config.json", !0, b); } function ee(v) { const b = {}; let x = {}; switch (v.model_type) { // Sub-configs case "llava": case "paligemma": case "florence2": case "llava_onevision": case "idefics3": x = ee(v.text_config); break; case "moondream1": x = ee(v.phi_config); break; case "musicgen": x = ee(v.decoder); break; case "multi_modality": x = ee(v.language_config); break; // Decoder-only models case "gpt2": case "gptj": case "jais": case "codegen": case "gpt_bigcode": b.num_heads = "n_head", b.num_layers = "n_layer", b.hidden_size = "n_embd"; break; case "gpt_neox": case "stablelm": case "opt": case "falcon": b.num_heads = "num_attention_heads", b.num_layers = "num_hidden_layers", b.hidden_size = "hidden_size"; break; case "llama": case "olmo": case "olmo2": case "mobilellm": case "granite": case "cohere": case "mistral": case "starcoder2": case "qwen2": case "qwen2_vl": case "phi": case "phi3": case "phi3_v": b.num_heads = "num_key_value_heads", b.num_layers = "num_hidden_layers", b.hidden_size = "hidden_size", b.num_attention_heads = "num_attention_heads"; break; case "gemma": case "gemma2": case "glm": case "helium": b.num_heads = "num_key_value_heads", b.num_layers = "num_hidden_layers", b.dim_kv = "head_dim"; break; case "openelm": b.num_heads = "num_kv_heads", b.num_layers = "num_transformer_layers", b.dim_kv = "head_dim"; break; case "gpt_neo": case "donut-swin": b.num_heads = "num_heads", b.num_layers = "num_layers", b.hidden_size = "hidden_size"; break; case "bloom": b.num_heads = "n_head", b.num_layers = "n_layer", b.hidden_size = "hidden_size"; break; case "mpt": b.num_heads = "n_heads", b.num_layers = "n_layers", b.hidden_size = "d_model"; break; case "exaone": b.num_heads = "num_key_value_heads", b.num_layers = "num_layers", b.dim_kv = "head_dim", b.num_attention_heads = "num_attention_heads"; break; // Encoder-decoder models case "t5": case "mt5": case "longt5": b.num_decoder_layers = "num_decoder_layers", b.num_decoder_heads = "num_heads", b.decoder_dim_kv = "d_kv", b.num_encoder_layers = "num_layers", b.num_encoder_heads = "num_heads", b.encoder_dim_kv = "d_kv"; break; case "bart": case "mbart": case "marian": case "whisper": case "m2m_100": case "blenderbot": case "blenderbot-small": case "florence2_language": b.num_decoder_layers = "decoder_layers", b.num_decoder_heads = "decoder_attention_heads", b.decoder_hidden_size = "d_model", b.num_encoder_layers = "encoder_layers", b.num_encoder_heads = "encoder_attention_heads", b.encoder_hidden_size = "d_model"; break; case "speecht5": b.num_decoder_layers = "decoder_layers", b.num_decoder_heads = "decoder_attention_heads", b.decoder_hidden_size = "hidden_size", b.num_encoder_layers = "encoder_layers", b.num_encoder_heads = "encoder_attention_heads", b.encoder_hidden_size = "hidden_size"; break; case "trocr": b.num_encoder_layers = b.num_decoder_layers = "decoder_layers", b.num_encoder_heads = b.num_decoder_heads = "decoder_attention_heads", b.encoder_hidden_size = b.decoder_hidden_size = "d_model"; break; case "musicgen_decoder": b.num_encoder_layers = b.num_decoder_layers = "num_hidden_layers", b.num_encoder_heads = b.num_decoder_heads = "num_attention_heads", b.encoder_hidden_size = b.decoder_hidden_size = "hidden_size"; break; case "moonshine": b.num_decoder_layers = "decoder_num_hidden_layers", b.num_decoder_heads = "decoder_num_key_value_heads", b.num_encoder_layers = "encoder_num_hidden_layers", b.num_encoder_heads = "encoder_num_key_value_heads", b.encoder_hidden_size = b.decoder_hidden_size = "hidden_size"; break; case "vision-encoder-decoder": const K = ee(v.decoder), re = "num_decoder_layers" in K, ie = (0, g.pick)(v, ["model_type", "is_encoder_decoder"]); return re ? (ie.num_decoder_layers = K.num_decoder_layers, ie.num_decoder_heads = K.num_decoder_heads, ie.decoder_hidden_size = K.decoder_hidden_size, ie.num_encoder_layers = K.num_encoder_layers, ie.num_encoder_heads = K.num_encoder_heads, ie.encoder_hidden_size = K.encoder_hidden_size) : (ie.num_layers = K.num_layers, ie.num_heads = K.num_heads, ie.hidden_size = K.hidden_size), ie; } const L = { ...x, ...(0, g.pick)(v, ["model_type", "multi_query", "is_encoder_decoder"]) }; for (const K in b) L[K] = v[b[K]]; return L; } function N(v, { prefix: b = "past_key_values", batch_size: x = 1 } = {}) { const L = {}, K = v.normalized_config; if (K.is_encoder_decoder && "num_encoder_heads" in K && "num_decoder_heads" in K) { const re = K.encoder_dim_kv ?? K.encoder_hidden_size / K.num_encoder_heads, ie = K.decoder_dim_kv ?? K.decoder_hidden_size / K.num_decoder_heads, V = [x, K.num_encoder_heads, 0, re], U = [x, K.num_decoder_heads, 0, ie]; for (let q = 0; q < K.num_decoder_layers; ++q) L[`${b}.${q}.encoder.key`] = V, L[`${b}.${q}.encoder.value`] = V, L[`${b}.${q}.decoder.key`] = U, L[`${b}.${q}.decoder.value`] = U; } else { const re = K.num_heads, ie = K.num_layers, V = K.dim_kv ?? K.hidden_size / (K.num_attention_heads ?? re); if (K.model_type === "falcon") { const U = [x * re, 0, V]; for (let q = 0; q < ie; ++q) L[`${b}.${q}.key`] = U, L[`${b}.${q}.value`] = U; } else if (K.multi_query) { const U = [x * re, 0, 2 * V]; for (let q = 0; q < ie; ++q) L[`${b}.${q}.key_value`] = U; } else if (K.model_type === "bloom") { const U = [x * re, V, 0], q = [x * re, 0, V]; for (let A = 0; A < ie; ++A) L[`${b}.${A}.key`] = U, L[`${b}.${A}.value`] = q; } else if (K.model_type === "openelm") for (let U = 0; U < ie; ++U) { const q = [x, re[U], 0, V]; L[`${b}.${U}.key`] = q, L[`${b}.${U}.value`] = q; } else { const U = [x, re, 0, V]; for (let q = 0; q < ie; ++q) L[`${b}.${q}.key`] = U, L[`${b}.${q}.value`] = U; } } return L; } class y { // NOTE: Typo in original /** @type {string|null} */ model_type = null; /** @type {boolean} */ is_encoder_decoder = !1; /** @type {number} */ max_position_embeddings; /** @type {TransformersJSConfig} */ "transformers.js_config"; /** * Create a new PreTrainedTokenizer instance. * @param {Object} configJSON The JSON of the config. */ constructor(b) { Object.assign(this, b), this.normalized_config = ee(this); } /** * 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(b, { progress_callback: x = null, config: L = null, cache_dir: K = null, local_files_only: re = !1, revision: ie = "main" } = {}) { L && !(L instanceof y) && (L = new y(L)); const V = L ?? await j(b, { progress_callback: x, config: L, cache_dir: K, local_files_only: re, revision: ie }); return new this(V); } } class T { /** @type {typeof PretrainedConfig.from_pretrained} */ static async from_pretrained(...b) { return y.from_pretrained(...b); } } } ), /***/ "./src/env.js": ( /*!********************!*\ !*** ./src/env.js ***! \********************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ apis: () => ( /* binding */ ie ), /* harmony export */ env: () => ( /* binding */ w ) /* harmony export */ }); var g = r( /*! fs */ "?569f" ), O = r( /*! path */ "?3f59" ), j = r( /*! url */ "?154a" ); const ee = "3.3.3", N = typeof window < "u" && typeof window.document < "u", y = typeof self < "u" && self.constructor?.name === "DedicatedWorkerGlobalScope", T = typeof self < "u" && "caches" in self, v = typeof navigator < "u" && "gpu" in navigator, b = typeof navigator < "u" && "ml" in navigator, x = typeof process < "u", L = x && process?.release?.name === "node", K = !P(g), re = !P(O), ie = Object.freeze({ /** Whether we are running in a browser environment (and not a web worker) */ IS_BROWSER_ENV: N, /** Whether we are running in a web worker environment */ IS_WEBWORKER_ENV: y, /** Whether the Cache API is available */ IS_WEB_CACHE_AVAILABLE: T, /** Whether the WebGPU API is available */ IS_WEBGPU_AVAILABLE: v, /** Whether the WebNN API is available */ IS_WEBNN_AVAILABLE: b, /** Whether the Node.js process API is available */ IS_PROCESS_AVAILABLE: x, /** Whether we are running in a Node.js environment */ IS_NODE_ENV: L, /** Whether the filesystem API is available */ IS_FS_AVAILABLE: K, /** Whether the path API is available */ IS_PATH_AVAILABLE: re }), V = K && re; let U = "./"; if (V) { const I = Object(import.meta).url; I ? U = O.dirname(O.dirname(j.fileURLToPath(I))) : typeof __dirname < "u" && (U = O.dirname(__dirname)); } const q = V ? O.join(U, "/.cache/") : null, A = "/models/", S = V ? O.join(U, A) : A, w = { version: ee, /////////////////// Backends settings /////////////////// // NOTE: These will be populated later by the backends themselves. backends: { // onnxruntime-web/onnxruntime-node onnx: {} }, /////////////////// Model settings /////////////////// allowRemoteModels: !0, remoteHost: "https://huggingface.co/", remotePathTemplate: "{model}/resolve/{revision}/", allowLocalModels: !(N || y), localModelPath: S, useFS: K, /////////////////// Cache settings /////////////////// useBrowserCache: T, useFSCache: K, cacheDir: q, useCustomCache: !1, customCache: null ////////////////////////////////////////////////////// }; function P(I) { return Object.keys(I).length === 0; } } ), /***/ "./src/generation/configuration_utils.js": ( /*!***********************************************!*\ !*** ./src/generation/configuration_utils.js ***! \***********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ GenerationConfig: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../utils/core.js */ "./src/utils/core.js" ); class O { // Parameters that control the length of the output /** * The maximum length the generated tokens can have. * Corresponds to the length of the input prompt + `max_new_tokens`. * Its effect is overridden by `max_new_tokens`, if also set. * @type {number} * @default 20 */ max_length = 20; /** * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. * @type {number} * @default null */ max_new_tokens = null; /** * The minimum length of the sequence to be generated. * Corresponds to the length of the input prompt + `min_new_tokens`. * Its effect is overridden by `min_new_tokens`, if also set. * @type {number} * @default 0 */ min_length = 0; /** * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. * @type {number} * @default null */ min_new_tokens = null; /** * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). * @type {boolean|"never"} * @default false */ early_stopping = !1; /** * The maximum amount of time you allow the computation to run for in seconds. * Generation will still finish the current pass after allocated time has been passed. * @type {number} * @default null */ max_time = null; // Parameters that control the generation strategy used /** * Whether or not to use sampling; use greedy decoding otherwise. * @type {boolean} * @default false */ do_sample = !1; /** * Number of beams for beam search. 1 means no beam search. * @type {number} * @default 1 */ num_beams = 1; /** * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. * See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details. * @type {number} * @default 1 */ num_beam_groups = 1; /** * The values balance the model confidence and the degeneration penalty in contrastive search decoding. * @type {number} * @default null */ penalty_alpha = null; /** * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. * @type {boolean} * @default true */ use_cache = !0; // Parameters for manipulation of the model output logits /** * The value used to modulate the next token probabilities. * @type {number} * @default 1.0 */ temperature = 1; /** * The number of highest probability vocabulary tokens to keep for top-k-filtering. * @type {number} * @default 50 */ top_k = 50; /** * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. * @type {number} * @default 1.0 */ top_p = 1; /** * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. * See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details. * @type {number} * @default 1.0 */ typical_p = 1; /** * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. * @type {number} * @default 0.0 */ epsilon_cutoff = 0; /** * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details. * @type {number} * @default 0.0 */ eta_cutoff = 0; /** * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. * Note that `diversity_penalty` is only effective if `group beam search` is enabled. * @type {number} * @default 0.0 */ diversity_penalty = 0; /** * The parameter for repetition penalty. 1.0 means no penalty. * See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. * @type {number} * @default 1.0 */ repetition_penalty = 1; /** * The paramater for encoder_repetition_penalty. * An exponential penalty on sequences that are not in the original input. * 1.0 means no penalty. * @type {number} * @default 1.0 */ encoder_repetition_penalty = 1; /** * Exponential penalty to the length that is used with beam-based generation. * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. * @type {number} * @default 1.0 */ length_penalty = 1; /** * If set to int > 0, all ngrams of that size can only occur once. * @type {number} * @default 0 */ no_repeat_ngram_size = 0; /** * List of token ids that are not allowed to be generated. * In order to get the token ids of the words that should not appear in the generated text, use * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`. * @type {number[][]} * @default null */ bad_words_ids = null; /** * List of token ids that must be generated. * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. * @type {number[][]|number[][][]} * @default null */ force_words_ids = null; /** * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. * @type {boolean} * @default false */ renormalize_logits = !1; /** * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. * @type {Object[]} * @default null */ constraints = null; /** * The id of the token to force as the first generated token after the `decoder_start_token_id`. * Useful for multilingual models like mBART where the first generated token needs to be the target language token. * @type {number} * @default null */ forced_bos_token_id = null; /** * The id of the token to force as the last generated token when `max_length` is reached. * Optionally, use a list to set multiple *end-of-sequence* tokens. * @type {number|number[]} * @default null */ forced_eos_token_id = null; /** * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. * @type {boolean} */ remove_invalid_values = !1; /** * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. * @type {[number, number]} * @default null */ exponential_decay_length_penalty = null; /** * A list of tokens that will be suppressed at generation. * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. * @type {number[]} * @default null */ suppress_tokens = null; /** * A streamer that will be used to stream the generation. * @type {import('./streamers.js').TextStreamer} * @default null */ streamer = null; /** * A list of tokens that will be suppressed at the beginning of the generation. * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. * @type {number[]} * @default null */ begin_suppress_tokens = null; /** * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. * For example, `[[1, 123]]` means the second generated token will always be a token of index 123. * @type {[number, number][]} * @default null */ forced_decoder_ids = null; /** * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. * Higher guidance scale encourages the model to generate samples that are more closely linked to the input * prompt, usually at the expense of poorer quality. * @type {number} * @default null */ guidance_scale = null; // Parameters that define the output variables of `generate` /** * The number of independently computed returned sequences for each element in the batch. * @type {number} * @default 1 */ num_return_sequences = 1; /** * Whether or not to return the attentions tensors of all attention layers. * See `attentions` under returned tensors for more details. * @type {boolean} * @default false */ output_attentions = !1; /** * Whether or not to return the hidden states of all layers. * See `hidden_states` under returned tensors for more details. * @type {boolean} * @default false */ output_hidden_states = !1; /** * Whether or not to return the prediction scores. * See `scores` under returned tensors for more details. * @type {boolean} * @default false */ output_scores = !1; /** * Whether or not to return a `ModelOutput` instead of a plain tuple. * @type {boolean} * @default false */ return_dict_in_generate = !1; // Special tokens that can be used at generation time /** * The id of the *padding* token. * @type {number} * @default null */ pad_token_id = null; /** * The id of the *beginning-of-sequence* token. * @type {number} * @default null */ bos_token_id = null; /** * The id of the *end-of-sequence* token. * Optionally, use a list to set multiple *end-of-sequence* tokens. * @type {number|number[]} * @default null */ eos_token_id = null; // Generation parameters exclusive to encoder-decoder models /** * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. * @type {number} * @default 0 */ encoder_no_repeat_ngram_size = 0; /** * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. * @type {number} * @default null */ decoder_start_token_id = null; // Wild card /** * Additional generation kwargs will be forwarded to the `generate` function of the model. * Kwargs that are not present in `generate`'s signature will be used in the model forward pass. * @type {Object} * @default {} */ generation_kwargs = {}; /** * * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config */ constructor(ee) { Object.assign(this, (0, g.pick)(ee, Object.getOwnPropertyNames(this))); } } } ), /***/ "./src/generation/logits_process.js": ( /*!******************************************!*\ !*** ./src/generation/logits_process.js ***! \******************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ClassifierFreeGuidanceLogitsProcessor: () => ( /* binding */ V ), /* harmony export */ ForcedBOSTokenLogitsProcessor: () => ( /* binding */ y ), /* harmony export */ ForcedEOSTokenLogitsProcessor: () => ( /* binding */ T ), /* harmony export */ LogitsProcessor: () => ( /* binding */ j ), /* harmony export */ LogitsProcessorList: () => ( /* binding */ N ), /* harmony export */ LogitsWarper: () => ( /* binding */ ee ), /* harmony export */ MinLengthLogitsProcessor: () => ( /* binding */ K ), /* harmony export */ MinNewTokensLengthLogitsProcessor: () => ( /* binding */ re ), /* harmony export */ NoBadWordsLogitsProcessor: () => ( /* binding */ ie ), /* harmony export */ NoRepeatNGramLogitsProcessor: () => ( /* binding */ x ), /* harmony export */ RepetitionPenaltyLogitsProcessor: () => ( /* binding */ L ), /* harmony export */ SuppressTokensAtBeginLogitsProcessor: () => ( /* binding */ v ), /* harmony export */ TemperatureLogitsWarper: () => ( /* binding */ U ), /* harmony export */ TopKLogitsWarper: () => ( /* binding */ A ), /* harmony export */ TopPLogitsWarper: () => ( /* binding */ q ), /* harmony export */ WhisperTimeStampLogitsProcessor: () => ( /* binding */ b ) /* harmony export */ }); var g = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ); r( /*! ../utils/tensor.js */ "./src/utils/tensor.js" ); var O = r( /*! ../utils/maths.js */ "./src/utils/maths.js" ); class j extends g.Callable { /** * Apply the processor to the input logits. * * @abstract * @param {bigint[][]} 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(w, P) { throw Error("`_call` should be implemented in a subclass"); } } class ee extends g.Callable { /** * Apply the processor to the input logits. * * @abstract * @param {bigint[][]} 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(w, P) { throw Error("`_call` should be implemented in a subclass"); } } class N extends g.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(w) { this.processors.push(w); } /** * Adds multiple logits processors to the list. * * @param {LogitsProcessor[]} items The logits processor functions to add. */ extend(w) { this.processors.push(...w); } /** * Applies all logits processors in the list to a batch of logits, modifying them in-place. * * @param {bigint[][]} input_ids The input IDs for the language model. * @param {Tensor} logits */ _call(w, P) { let I = P; for (const le of this.processors) I = le(w, I); return I; } [Symbol.iterator]() { return this.processors.values(); } } class y extends j { /** * Create a ForcedBOSTokenLogitsProcessor. * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. */ constructor(w) { super(), this.bos_token_id = w; } /** * Apply the BOS token forcing to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with BOS token forcing. */ _call(w, P) { for (let I = 0; I < w.length; ++I) if (w[I].length === 1) { const le = ( /** @type {Float32Array} */ P[I].data ); le.fill(-1 / 0), le[this.bos_token_id] = 0; } return P; } } class T extends j { /** * Create a ForcedEOSTokenLogitsProcessor. * @param {number} max_length The maximum length of the sequence to be generated. * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token. */ constructor(w, P) { super(), this.max_length = w, this.eos_token_id = Array.isArray(P) ? P : [P]; } /** * Apply the processor to input_ids and logits. * * @param {bigint[][]} input_ids The input ids. * @param {Tensor} logits The logits tensor. */ _call(w, P) { for (let I = 0; I < w.length; ++I) if (w[I].length === this.max_length - 1) { const le = ( /** @type {Float32Array} */ P[I].data ); le.fill(-1 / 0); for (const oe of this.eos_token_id) le[oe] = 0; } return P; } } class v extends j { /** * 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(w, P) { super(), this.begin_suppress_tokens = w, this.begin_index = P; } /** * Apply the BOS token forcing to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with BOS token forcing. */ _call(w, P) { for (let I = 0; I < w.length; ++I) if (w[I].length === this.begin_index) { const le = ( /** @type {Float32Array} */ P[I].data ); for (const oe of this.begin_suppress_tokens) le[oe] = -1 / 0; } return P; } } class b extends j { /** * Constructs a new WhisperTimeStampLogitsProcessor. * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model. * @param {number[]} init_tokens The initial tokens of the input sequence. */ constructor(w, P) { super(), this.eos_token_id = Array.isArray(w.eos_token_id) ? w.eos_token_id[0] : w.eos_token_id, this.no_timestamps_token_id = w.no_timestamps_token_id, this.timestamp_begin = this.no_timestamps_token_id + 1, this.begin_index = P.length, P.at(-1) === this.no_timestamps_token_id && (this.begin_index -= 1), this.max_initial_timestamp_index = w.max_initial_timestamp_index; } /** * Modify the logits to handle timestamp tokens. * @param {bigint[][]} input_ids The input sequence of tokens. * @param {Tensor} logits The logits output by the model. * @returns {Tensor} The modified logits. */ _call(w, P) { for (let I = 0; I < w.length; ++I) { const le = ( /** @type {Float32Array} */ P[I].data ); if (le[this.no_timestamps_token_id] = -1 / 0, w[I].length === this.begin_index - 1) { le.fill(-1 / 0), le[this.timestamp_begin] = 0; continue; } const oe = w[I].slice(this.begin_index), ye = oe.length >= 1 && oe[oe.length - 1] >= this.timestamp_begin, ge = oe.length < 2 || oe[oe.length - 2] >= this.timestamp_begin; if (ye && (ge ? le.subarray(this.timestamp_begin).fill(-1 / 0) : le.subarray(0, this.eos_token_id).fill(-1 / 0)), w[I].length === this.begin_index && this.max_initial_timestamp_index !== null) { const Ce = this.timestamp_begin + this.max_initial_timestamp_index; le.subarray(Ce + 1).fill(-1 / 0); } const se = (0, O.log_softmax)(le), be = Math.log(se.subarray(this.timestamp_begin).map(Math.exp).reduce((Ce, $e) => Ce + $e)), pe = (0, O.max)(se.subarray(0, this.timestamp_begin))[0]; be > pe && le.subarray(0, this.timestamp_begin).fill(-1 / 0); } return P; } } class x extends j { /** * Create a NoRepeatNGramLogitsProcessor. * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. */ constructor(w) { super(), this.no_repeat_ngram_size = w; } /** * Generate n-grams from a sequence of token ids. * @param {bigint[]} prevInputIds List of previous input ids * @returns {Map} Map of generated n-grams */ getNgrams(w) { const P = w.length, I = []; for (let oe = 0; oe < P + 1 - this.no_repeat_ngram_size; ++oe) { const ye = []; for (let ge = 0; ge < this.no_repeat_ngram_size; ++ge) ye.push(w[oe + ge]); I.push(ye.map(Number)); } const le = /* @__PURE__ */ new Map(); for (const oe of I) { const ye = oe.slice(0, oe.length - 1), ge = JSON.stringify(ye), se = le.get(ge) ?? []; se.push(oe[oe.length - 1]), le.set(ge, se); } return le; } /** * Generate n-grams from a sequence of token ids. * @param {Map} bannedNgrams Map of banned n-grams * @param {bigint[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ getGeneratedNgrams(w, P) { const I = P.slice(P.length + 1 - this.no_repeat_ngram_size, P.length); return w.get(JSON.stringify(I.map(Number))) ?? []; } /** * Calculate banned n-gram tokens * @param {bigint[]} prevInputIds List of previous input ids * @returns {number[]} Map of generated n-grams */ calcBannedNgramTokens(w) { const P = []; if (w.length + 1 < this.no_repeat_ngram_size) return P; { const I = this.getNgrams(w); return this.getGeneratedNgrams(I, w); } } /** * Apply the no-repeat-ngram processor to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with no-repeat-ngram processing. */ _call(w, P) { for (let I = 0; I < w.length; ++I) { const le = ( /** @type {Float32Array} */ P[I].data ), oe = this.calcBannedNgramTokens(w[I]); for (const ye of oe) le[ye] = -1 / 0; } return P; } } class L extends j { /** * Create a RepetitionPenaltyLogitsProcessor. * @param {number} penalty The parameter for repetition penalty. * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. * - Between 0.0 and 1.0 rewards previously generated tokens. */ constructor(w) { super(), this.penalty = w; } /** * Apply the repetition penalty to the logits. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The logits with repetition penalty processing. */ _call(w, P) { for (let I = 0; I < w.length; ++I) { const le = ( /** @type {Float32Array} */ P[I].data ); for (const oe of new Set(w[I])) { const ye = Number(oe); le[ye] < 0 ? le[ye] *= this.penalty : le[ye] /= this.penalty; } } return P; } } class K extends j { /** * 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(w, P) { super(), this.min_length = w, this.eos_token_id = Array.isArray(P) ? P : [P]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(w, P) { for (let I = 0; I < w.length; ++I) if (w[I].length < this.min_length) { const le = ( /** @type {Float32Array} */ P[I].data ); for (const oe of this.eos_token_id) le[oe] = -1 / 0; } return P; } } class re extends j { /** * 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(w, P, I) { super(), this.prompt_length_to_skip = w, this.min_new_tokens = P, this.eos_token_id = Array.isArray(I) ? I : [I]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(w, P) { for (let I = 0; I < w.length; ++I) if (w[I].length - this.prompt_length_to_skip < this.min_new_tokens) { const oe = ( /** @type {Float32Array} */ P[I].data ); for (const ye of this.eos_token_id) oe[ye] = -1 / 0; } return P; } } class ie extends j { /** * 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(w, P) { super(), this.bad_words_ids = w, this.eos_token_id = Array.isArray(P) ? P : [P]; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(w, P) { for (let I = 0; I < w.length; ++I) { const le = ( /** @type {Float32Array} */ P[I].data ), oe = w[I]; for (const ye of this.bad_words_ids) { let ge = !0; for (let se = 1; se <= ye.length - 1 && ye.length < oe.length; ++se) if (ye.at(-se - 1) != oe.at(-se)) { ge = !1; break; } ge && (le[ye.at(-1)] = -1 / 0); } } return P; } } class V extends j { /** * Create a `ClassifierFreeGuidanceLogitsProcessor`. * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. * Higher guidance scale encourages the model to generate samples that are more closely linked to the input * prompt, usually at the expense of poorer quality. */ constructor(w) { if (super(), w <= 1) throw new Error( `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${w}.` ); this.guidance_scale = w; } /** * Apply logit processor. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(w, P) { if (P.dims[0] !== 2 * w.length) throw new Error( `Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${P.dims[0]} for the logits and ${w.length} for the input ids.` ); const I = w.length, le = P.slice([0, I], null), oe = P.slice([I, P.dims[0]], null); for (let ye = 0; ye < oe.data.length; ++ye) oe.data[ye] += (le.data[ye] - oe.data[ye]) * this.guidance_scale; return oe; } } class U extends ee { /** * Create a `TemperatureLogitsWarper`. * @param {number} temperature Strictly positive float value used to modulate the logits distribution. * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting * all probability mass to the most likely token. */ constructor(w) { super(), this.temperature = w; } /** * Apply logit warper. * @param {bigint[][]} input_ids The input IDs. * @param {Tensor} logits The logits. * @returns {Tensor} The processed logits. */ _call(w, P) { const I = ( /** @type {Float32Array} */ P.data ); for (let le = 0; le < I.length; ++le) I[le] /= this.temperature; return P; } } class q extends ee { /** * Create a `TopPLogitsWarper`. * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with * probabilities that add up to `top_p` or higher are kept for generation. * @param {Object} options Additional options for the top-p sampling. * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. */ constructor(w, { filter_value: P = -1 / 0, min_tokens_to_keep: I = 1 } = {}) { if (super(), w < 0 || w > 1) throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`); if (!Number.isInteger(I) || I < 1) throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${I}`); this.top_p = w, this.filter_value = P, this.min_tokens_to_keep = I; } } class A extends ee { /** * Create a `TopKLogitsWarper`. * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation. * @param {Object} options Additional options for the top-k sampling. * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. */ constructor(w, { filter_value: P = -1 / 0, min_tokens_to_keep: I = 1 } = {}) { if (super(), !Number.isInteger(w) || w < 0) throw new Error(`\`top_k\` must be a positive integer, but is ${w}`); this.top_k = Math.max(w, I), this.filter_value = P; } } } ), /***/ "./src/generation/logits_sampler.js": ( /*!******************************************!*\ !*** ./src/generation/logits_sampler.js ***! \******************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ LogitsSampler: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ), O = r( /*! ../utils/tensor.js */ "./src/utils/tensor.js" ), j = r( /*! ../utils/maths.js */ "./src/utils/maths.js" ); r( /*! ../generation/configuration_utils.js */ "./src/generation/configuration_utils.js" ); class ee extends g.Callable { /** * Creates a new Sampler object with the specified generation config. * @param {GenerationConfig} generation_config The generation config. */ constructor(b) { super(), this.generation_config = b; } /** * Executes the sampler, using the specified logits. * @param {Tensor} logits * @returns {Promise<[bigint, number][]>} */ async _call(b) { return this.sample(b); } /** * Abstract method for sampling the logits. * @param {Tensor} logits * @throws {Error} If not implemented in subclass. * @returns {Promise<[bigint, number][]>} */ async sample(b) { 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(b, x) { let L = b.dims.at(-1), K = ( /** @type {Float32Array} */ b.data ); if (x === -1) K = K.slice(-L); else { let re = x * L; K = K.slice(re, re + L); } return K; } /** * Selects an item randomly based on the specified probabilities. * @param {import("../transformers.js").DataArray} probabilities An array of probabilities to use for selection. * @returns {number} The index of the selected item. */ randomSelect(b) { let x = 0; for (let K = 0; K < b.length; ++K) x += b[K]; let L = Math.random() * x; for (let K = 0; K < b.length; ++K) if (L -= b[K], L <= 0) return K; return 0; } /** * Returns a Sampler object based on the specified options. * @param {GenerationConfig} generation_config An object containing options for the sampler. * @returns {LogitsSampler} A Sampler object. */ static getSampler(b) { if (b.do_sample) return new y(b); if (b.num_beams > 1) return new T(b); if (b.num_return_sequences > 1) throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${b.num_return_sequences}.`); return new N(b); } } class N extends ee { /** * Sample the maximum probability of a given logits tensor. * @param {Tensor} logits * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). */ async sample(b) { const x = (0, j.max)(b.data)[1]; return [ [BigInt(x), 0] ]; } } class y extends ee { /** * Sample from the logits. * @param {Tensor} logits * @returns {Promise<[bigint, number][]>} */ async sample(b) { let x = b.dims.at(-1); this.generation_config.top_k > 0 && (x = Math.min(this.generation_config.top_k, x)); const [L, K] = await (0, O.topk)(b, x), re = (0, j.softmax)( /** @type {Float32Array} */ L.data ); return Array.from({ length: this.generation_config.num_beams }, () => { const ie = this.randomSelect(re); return [ K.data[ie], // token id Math.log(re[ie]) // score ]; }); } } class T extends ee { /** * Sample from the logits. * @param {Tensor} logits * @returns {Promise<[bigint, number][]>} */ async sample(b) { let x = b.dims.at(-1); this.generation_config.top_k > 0 && (x = Math.min(this.generation_config.top_k, x)); const [L, K] = await (0, O.topk)(b, x), re = (0, j.softmax)( /** @type {Float32Array} */ L.data ); return Array.from({ length: this.generation_config.num_beams }, (ie, V) => [ K.data[V], // token id Math.log(re[V]) // score ]); } } } ), /***/ "./src/generation/stopping_criteria.js": ( /*!*********************************************!*\ !*** ./src/generation/stopping_criteria.js ***! \*********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ EosTokenCriteria: () => ( /* binding */ N ), /* harmony export */ InterruptableStoppingCriteria: () => ( /* binding */ y ), /* harmony export */ MaxLengthCriteria: () => ( /* binding */ ee ), /* harmony export */ StoppingCriteria: () => ( /* binding */ O ), /* harmony export */ StoppingCriteriaList: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../utils/generic.js */ "./src/utils/generic.js" ); class O extends g.Callable { /** * * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): * Indices of input sequence tokens in the vocabulary. * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`): * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax * or scores for each vocabulary token after SoftMax. * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. */ _call(v, b) { throw Error("StoppingCriteria needs to be subclassed"); } } class j extends g.Callable { /** * Constructs a new instance of `StoppingCriteriaList`. */ constructor() { super(), this.criteria = []; } /** * Adds a new stopping criterion to the list. * * @param {StoppingCriteria} item The stopping criterion to add. */ push(v) { this.criteria.push(v); } /** * Adds multiple stopping criteria to the list. * * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add. */ extend(v) { v instanceof j ? v = v.criteria : v instanceof O && (v = [v]), this.criteria.push(...v); } _call(v, b) { const x = new Array(v.length).fill(!1); for (const L of this.criteria) { const K = L(v, b); for (let re = 0; re < x.length; ++re) x[re] ||= K[re]; } return x; } [Symbol.iterator]() { return this.criteria.values(); } } class ee extends O { /** * * @param {number} max_length The maximum length that the output sequence can have in number of tokens. * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute. */ constructor(v, b = null) { super(), this.max_length = v, this.max_position_embeddings = b; } _call(v) { return v.map((b) => b.length >= this.max_length); } } class N extends O { /** * * @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(v) { super(), Array.isArray(v) || (v = [v]), this.eos_token_id = v; } /** * * @param {number[][]} input_ids * @param {number[][]} scores * @returns {boolean[]} */ _call(v, b) { return v.map((x) => { const L = x.at(-1); return this.eos_token_id.some((K) => L == K); }); } } class y extends O { constructor() { super(), this.interrupted = !1; } interrupt() { this.interrupted = !0; } reset() { this.interrupted = !1; } _call(v, b) { return new Array(v.length).fill(this.interrupted); } } } ), /***/ "./src/generation/streamers.js": ( /*!*************************************!*\ !*** ./src/generation/streamers.js ***! \*************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ BaseStreamer: () => ( /* binding */ ee ), /* harmony export */ TextStreamer: () => ( /* binding */ y ), /* harmony export */ WhisperTextStreamer: () => ( /* binding */ T ) /* harmony export */ }); var g = r( /*! ../utils/core.js */ "./src/utils/core.js" ), O = r( /*! ../tokenizers.js */ "./src/tokenizers.js" ), j = r( /*! ../env.js */ "./src/env.js" ); class ee { /** * Function that is called by `.generate()` to push new tokens * @param {bigint[][]} value */ put(b) { throw Error("Not implemented"); } /** * Function that is called by `.generate()` to signal the end of generation */ end() { throw Error("Not implemented"); } } const N = j.apis.IS_PROCESS_AVAILABLE ? (v) => process.stdout.write(v) : (v) => console.log(v); class y extends ee { /** * * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer * @param {Object} options * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method */ constructor(b, { skip_prompt: x = !1, callback_function: L = null, token_callback_function: K = null, skip_special_tokens: re = !0, decode_kwargs: ie = {}, ...V } = {}) { super(), this.tokenizer = b, this.skip_prompt = x, this.callback_function = L ?? N, this.token_callback_function = K, this.decode_kwargs = { skip_special_tokens: re, ...ie, ...V }, this.token_cache = [], this.print_len = 0, this.next_tokens_are_prompt = !0; } /** * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. * @param {bigint[][]} value */ put(b) { if (b.length > 1) throw Error("TextStreamer only supports batch size of 1"); if (this.skip_prompt && this.next_tokens_are_prompt) { this.next_tokens_are_prompt = !1; return; } const x = b[0]; this.token_callback_function?.(x), this.token_cache = (0, g.mergeArrays)(this.token_cache, x); const L = this.tokenizer.decode(this.token_cache, this.decode_kwargs); let K; L.endsWith(` `) ? (K = L.slice(this.print_len), this.token_cache = [], this.print_len = 0) : L.length > 0 && (0, O.is_chinese_char)(L.charCodeAt(L.length - 1)) ? (K = L.slice(this.print_len), this.print_len += K.length) : (K = L.slice(this.print_len, L.lastIndexOf(" ") + 1), this.print_len += K.length), this.on_finalized_text(K, !1); } /** * Flushes any remaining cache and prints a newline to stdout. */ end() { let b; this.token_cache.length > 0 ? (b = this.tokenizer.decode(this.token_cache, this.decode_kwargs).slice(this.print_len), this.token_cache = [], this.print_len = 0) : b = "", this.next_tokens_are_prompt = !0, this.on_finalized_text(b, !0); } /** * Prints the new text to stdout. If the stream is ending, also prints a newline. * @param {string} text * @param {boolean} stream_end */ on_finalized_text(b, x) { b.length > 0 && this.callback_function?.(b), x && this.callback_function === N && j.apis.IS_PROCESS_AVAILABLE && this.callback_function?.(` `); } } class T extends y { /** * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer * @param {Object} options * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized * @param {number} [options.time_precision=0.02] Precision of the timestamps * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method */ constructor(b, { skip_prompt: x = !1, callback_function: L = null, token_callback_function: K = null, on_chunk_start: re = null, on_chunk_end: ie = null, on_finalize: V = null, time_precision: U = 0.02, skip_special_tokens: q = !0, decode_kwargs: A = {} } = {}) { super(b, { skip_prompt: x, skip_special_tokens: q, callback_function: L, token_callback_function: K, decode_kwargs: A }), this.timestamp_begin = b.timestamp_begin, this.on_chunk_start = re, this.on_chunk_end = ie, this.on_finalize = V, this.time_precision = U, this.waiting_for_timestamp = !1; } /** * @param {bigint[][]} value */ put(b) { if (b.length > 1) throw Error("WhisperTextStreamer only supports batch size of 1"); const x = b[0]; if (x.length === 1) { const L = Number(x[0]) - this.timestamp_begin; if (L >= 0) { const K = L * this.time_precision; this.waiting_for_timestamp ? this.on_chunk_end?.(K) : this.on_chunk_start?.(K), this.waiting_for_timestamp = !this.waiting_for_timestamp, b = [[]]; } } return super.put(b); } end() { super.end(), this.on_finalize?.(); } } } ), /***/ "./src/models.js": ( /*!***********************!*\ !*** ./src/models.js ***! \***********************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ASTForAudioClassification: () => ( /* binding */ Lo ), /* harmony export */ ASTModel: () => ( /* binding */ Aa ), /* harmony export */ ASTPreTrainedModel: () => ( /* binding */ Kt ), /* harmony export */ AlbertForMaskedLM: () => ( /* binding */ as ), /* harmony export */ AlbertForQuestionAnswering: () => ( /* binding */ On ), /* harmony export */ AlbertForSequenceClassification: () => ( /* binding */ wn ), /* harmony export */ AlbertModel: () => ( /* binding */ Fn ), /* harmony export */ AlbertPreTrainedModel: () => ( /* binding */ Rr ), /* harmony export */ AutoModel: () => ( /* binding */ Kc ), /* harmony export */ AutoModelForAudioClassification: () => ( /* binding */ lp ), /* harmony export */ AutoModelForAudioFrameClassification: () => ( /* binding */ dp ), /* harmony export */ AutoModelForCTC: () => ( /* binding */ ap ), /* harmony export */ AutoModelForCausalLM: () => ( /* binding */ Yc ), /* harmony export */ AutoModelForDepthEstimation: () => ( /* binding */ hp ), /* harmony export */ AutoModelForDocumentQuestionAnswering: () => ( /* binding */ Rp ), /* harmony export */ AutoModelForImageClassification: () => ( /* binding */ tp ), /* harmony export */ AutoModelForImageFeatureExtraction: () => ( /* binding */ _p ), /* harmony export */ AutoModelForImageMatting: () => ( /* binding */ cp ), /* harmony export */ AutoModelForImageSegmentation: () => ( /* binding */ sp ), /* harmony export */ AutoModelForImageToImage: () => ( /* binding */ pp ), /* harmony export */ AutoModelForMaskGeneration: () => ( /* binding */ ip ), /* harmony export */ AutoModelForMaskedLM: () => ( /* binding */ Jc ), /* harmony export */ AutoModelForNormalEstimation: () => ( /* binding */ Np ), /* harmony export */ AutoModelForObjectDetection: () => ( /* binding */ np ), /* harmony export */ AutoModelForPoseEstimation: () => ( /* binding */ mp ), /* harmony export */ AutoModelForQuestionAnswering: () => ( /* binding */ Zc ), /* harmony export */ AutoModelForSemanticSegmentation: () => ( /* binding */ rp ), /* harmony export */ AutoModelForSeq2SeqLM: () => ( /* binding */ qc ), /* harmony export */ AutoModelForSequenceClassification: () => ( /* binding */ Bp ), /* harmony export */ AutoModelForSpeechSeq2Seq: () => ( /* binding */ Qc ), /* harmony export */ AutoModelForTextToSpectrogram: () => ( /* binding */ Hd ), /* harmony export */ AutoModelForTextToWaveform: () => ( /* binding */ Xc ), /* harmony export */ AutoModelForTokenClassification: () => ( /* binding */ Hc ), /* harmony export */ AutoModelForUniversalSegmentation: () => ( /* binding */ qd ), /* harmony export */ AutoModelForVision2Seq: () => ( /* binding */ ep ), /* harmony export */ AutoModelForXVector: () => ( /* binding */ up ), /* harmony export */ AutoModelForZeroShotObjectDetection: () => ( /* binding */ op ), /* harmony export */ BartForConditionalGeneration: () => ( /* binding */ ts ), /* harmony export */ BartForSequenceClassification: () => ( /* binding */ Xt ), /* harmony export */ BartModel: () => ( /* binding */ ht ), /* harmony export */ BartPretrainedModel: () => ( /* binding */ yt ), /* harmony export */ BaseModelOutput: () => ( /* binding */ Ne ), /* harmony export */ BeitForImageClassification: () => ( /* binding */ Zr ), /* harmony export */ BeitModel: () => ( /* binding */ Jr ), /* harmony export */ BeitPreTrainedModel: () => ( /* binding */ nu ), /* harmony export */ BertForMaskedLM: () => ( /* binding */ He ), /* harmony export */ BertForQuestionAnswering: () => ( /* binding */ Re ), /* harmony export */ BertForSequenceClassification: () => ( /* binding */ je ), /* harmony export */ BertForTokenClassification: () => ( /* binding */ Ve ), /* harmony export */ BertModel: () => ( /* binding */ ve ), /* harmony export */ BertPreTrainedModel: () => ( /* binding */ te ), /* harmony export */ BlenderbotForConditionalGeneration: () => ( /* binding */ Xs ), /* harmony export */ BlenderbotModel: () => ( /* binding */ De ), /* harmony export */ BlenderbotPreTrainedModel: () => ( /* binding */ er ), /* harmony export */ BlenderbotSmallForConditionalGeneration: () => ( /* binding */ qs ), /* harmony export */ BlenderbotSmallModel: () => ( /* binding */ Es ), /* harmony export */ BlenderbotSmallPreTrainedModel: () => ( /* binding */ Cr ), /* harmony export */ BloomForCausalLM: () => ( /* binding */ Il ), /* harmony export */ BloomModel: () => ( /* binding */ Al ), /* harmony export */ BloomPreTrainedModel: () => ( /* binding */ mi ), /* harmony export */ CLIPModel: () => ( /* binding */ Ua ), /* harmony export */ CLIPPreTrainedModel: () => ( /* binding */ Yr ), /* harmony export */ CLIPSegForImageSegmentation: () => ( /* binding */ Xa ), /* harmony export */ CLIPSegModel: () => ( /* binding */ Qa ), /* harmony export */ CLIPSegPreTrainedModel: () => ( /* binding */ Uo ), /* harmony export */ CLIPTextModel: () => ( /* binding */ lc ), /* harmony export */ CLIPTextModelWithProjection: () => ( /* binding */ Wa ), /* harmony export */ CLIPVisionModel: () => ( /* binding */ uc ), /* harmony export */ CLIPVisionModelWithProjection: () => ( /* binding */ Ga ), /* harmony export */ CamembertForMaskedLM: () => ( /* binding */ Kr ), /* harmony export */ CamembertForQuestionAnswering: () => ( /* binding */ Hr ), /* harmony export */ CamembertForSequenceClassification: () => ( /* binding */ Tr ), /* harmony export */ CamembertForTokenClassification: () => ( /* binding */ Pr ), /* harmony export */ CamembertModel: () => ( /* binding */ Lt ), /* harmony export */ CamembertPreTrainedModel: () => ( /* binding */ yr ), /* harmony export */ CausalLMOutput: () => ( /* binding */ nn ), /* harmony export */ CausalLMOutputWithPast: () => ( /* binding */ gp ), /* harmony export */ ChineseCLIPModel: () => ( /* binding */ mr ), /* harmony export */ ChineseCLIPPreTrainedModel: () => ( /* binding */ dc ), /* harmony export */ ClapAudioModelWithProjection: () => ( /* binding */ id ), /* harmony export */ ClapModel: () => ( /* binding */ sr ), /* harmony export */ ClapPreTrainedModel: () => ( /* binding */ ta ), /* harmony export */ ClapTextModelWithProjection: () => ( /* binding */ od ), /* harmony export */ CodeGenForCausalLM: () => ( /* binding */ ll ), /* harmony export */ CodeGenModel: () => ( /* binding */ Xo ), /* harmony export */ CodeGenPreTrainedModel: () => ( /* binding */ oo ), /* harmony export */ CohereForCausalLM: () => ( /* binding */ wl ), /* harmony export */ CohereModel: () => ( /* binding */ gl ), /* harmony export */ CoherePreTrainedModel: () => ( /* binding */ ai ), /* harmony export */ ConvBertForMaskedLM: () => ( /* binding */ Nt ), /* harmony export */ ConvBertForQuestionAnswering: () => ( /* binding */ ms ), /* harmony export */ ConvBertForSequenceClassification: () => ( /* binding */ es ), /* harmony export */ ConvBertForTokenClassification: () => ( /* binding */ Ts ), /* harmony export */ ConvBertModel: () => ( /* binding */ mt ), /* harmony export */ ConvBertPreTrainedModel: () => ( /* binding */ et ), /* harmony export */ ConvNextForImageClassification: () => ( /* binding */ Wi ), /* harmony export */ ConvNextModel: () => ( /* binding */ yu ), /* harmony export */ ConvNextPreTrainedModel: () => ( /* binding */ Ui ), /* harmony export */ ConvNextV2ForImageClassification: () => ( /* binding */ Ki ), /* harmony export */ ConvNextV2Model: () => ( /* binding */ Mu ), /* harmony export */ ConvNextV2PreTrainedModel: () => ( /* binding */ Gi ), /* harmony export */ DPTForDepthEstimation: () => ( /* binding */ wc ), /* harmony export */ DPTModel: () => ( /* binding */ du ), /* harmony export */ DPTPreTrainedModel: () => ( /* binding */ Ni ), /* harmony export */ DebertaForMaskedLM: () => ( /* binding */ Er ), /* harmony export */ DebertaForQuestionAnswering: () => ( /* binding */ ir ), /* harmony export */ DebertaForSequenceClassification: () => ( /* binding */ Or ), /* harmony export */ DebertaForTokenClassification: () => ( /* binding */ Dr ), /* harmony export */ DebertaModel: () => ( /* binding */ Fr ), /* harmony export */ DebertaPreTrainedModel: () => ( /* binding */ lr ), /* harmony export */ DebertaV2ForMaskedLM: () => ( /* binding */ Ft ), /* harmony export */ DebertaV2ForQuestionAnswering: () => ( /* binding */ cn ), /* harmony export */ DebertaV2ForSequenceClassification: () => ( /* binding */ Zs ), /* harmony export */ DebertaV2ForTokenClassification: () => ( /* binding */ Pn ), /* harmony export */ DebertaV2Model: () => ( /* binding */ vt ), /* harmony export */ DebertaV2PreTrainedModel: () => ( /* binding */ nt ), /* harmony export */ DecisionTransformerModel: () => ( /* binding */ zc ), /* harmony export */ DecisionTransformerPreTrainedModel: () => ( /* binding */ yd ), /* harmony export */ DeiTForImageClassification: () => ( /* binding */ Ii ), /* harmony export */ DeiTModel: () => ( /* binding */ au ), /* harmony export */ DeiTPreTrainedModel: () => ( /* binding */ po ), /* harmony export */ DepthAnythingForDepthEstimation: () => ( /* binding */ pu ), /* harmony export */ DepthAnythingPreTrainedModel: () => ( /* binding */ cu ), /* harmony export */ DepthProForDepthEstimation: () => ( /* binding */ Vi ), /* harmony export */ DepthProPreTrainedModel: () => ( /* binding */ _o ), /* harmony export */ DetrForObjectDetection: () => ( /* binding */ en ), /* harmony export */ DetrForSegmentation: () => ( /* binding */ Ws ), /* harmony export */ DetrModel: () => ( /* binding */ Ei ), /* harmony export */ DetrObjectDetectionOutput: () => ( /* binding */ Ci ), /* harmony export */ DetrPreTrainedModel: () => ( /* binding */ kr ), /* harmony export */ DetrSegmentationOutput: () => ( /* binding */ ki ), /* harmony export */ Dinov2ForImageClassification: () => ( /* binding */ bc ), /* harmony export */ Dinov2Model: () => ( /* binding */ bu ), /* harmony export */ Dinov2PreTrainedModel: () => ( /* binding */ Hi ), /* harmony export */ Dinov2WithRegistersForImageClassification: () => ( /* binding */ xu ), /* harmony export */ Dinov2WithRegistersModel: () => ( /* binding */ vu ), /* harmony export */ Dinov2WithRegistersPreTrainedModel: () => ( /* binding */ qi ), /* harmony export */ DistilBertForMaskedLM: () => ( /* binding */ pn ), /* harmony export */ DistilBertForQuestionAnswering: () => ( /* binding */ ss ), /* harmony export */ DistilBertForSequenceClassification: () => ( /* binding */ zs ), /* harmony export */ DistilBertForTokenClassification: () => ( /* binding */ qr ), /* harmony export */ DistilBertModel: () => ( /* binding */ Mr ), /* harmony export */ DistilBertPreTrainedModel: () => ( /* binding */ ws ), /* harmony export */ DonutSwinModel: () => ( /* binding */ wu ), /* harmony export */ DonutSwinPreTrainedModel: () => ( /* binding */ Mc ), /* harmony export */ EfficientNetForImageClassification: () => ( /* binding */ pd ), /* harmony export */ EfficientNetModel: () => ( /* binding */ cd ), /* harmony export */ EfficientNetPreTrainedModel: () => ( /* binding */ To ), /* harmony export */ ElectraForMaskedLM: () => ( /* binding */ tr ), /* harmony export */ ElectraForQuestionAnswering: () => ( /* binding */ Vs ), /* harmony export */ ElectraForSequenceClassification: () => ( /* binding */ xr ), /* harmony export */ ElectraForTokenClassification: () => ( /* binding */ Gr ), /* harmony export */ ElectraModel: () => ( /* binding */ Is ), /* harmony export */ ElectraPreTrainedModel: () => ( /* binding */ Ps ), /* harmony export */ EsmForMaskedLM: () => ( /* binding */ En ), /* harmony export */ EsmForSequenceClassification: () => ( /* binding */ Cn ), /* harmony export */ EsmForTokenClassification: () => ( /* binding */ kn ), /* harmony export */ EsmModel: () => ( /* binding */ eo ), /* harmony export */ EsmPreTrainedModel: () => ( /* binding */ Lr ), /* harmony export */ ExaoneForCausalLM: () => ( /* binding */ si ), /* harmony export */ ExaoneModel: () => ( /* binding */ cl ), /* harmony export */ ExaonePreTrainedModel: () => ( /* binding */ ti ), /* harmony export */ FalconForCausalLM: () => ( /* binding */ nd ), /* harmony export */ FalconModel: () => ( /* binding */ rd ), /* harmony export */ FalconPreTrainedModel: () => ( /* binding */ ea ), /* harmony export */ FastViTForImageClassification: () => ( /* binding */ ql ), /* harmony export */ FastViTModel: () => ( /* binding */ Hl ), /* harmony export */ FastViTPreTrainedModel: () => ( /* binding */ bi ), /* harmony export */ Florence2ForConditionalGeneration: () => ( /* binding */ Ba ), /* harmony export */ Florence2PreTrainedModel: () => ( /* binding */ za ), /* harmony export */ GLPNForDepthEstimation: () => ( /* binding */ gu ), /* harmony export */ GLPNModel: () => ( /* binding */ yc ), /* harmony export */ GLPNPreTrainedModel: () => ( /* binding */ go ), /* harmony export */ GPT2LMHeadModel: () => ( /* binding */ Ja ), /* harmony export */ GPT2Model: () => ( /* binding */ Ya ), /* harmony export */ GPT2PreTrainedModel: () => ( /* binding */ Wo ), /* harmony export */ GPTBigCodeForCausalLM: () => ( /* binding */ al ), /* harmony export */ GPTBigCodeModel: () => ( /* binding */ il ), /* harmony export */ GPTBigCodePreTrainedModel: () => ( /* binding */ Qo ), /* harmony export */ GPTJForCausalLM: () => ( /* binding */ ol ), /* harmony export */ GPTJModel: () => ( /* binding */ nl ), /* harmony export */ GPTJPreTrainedModel: () => ( /* binding */ qo ), /* harmony export */ GPTNeoForCausalLM: () => ( /* binding */ tl ), /* harmony export */ GPTNeoModel: () => ( /* binding */ fr ), /* harmony export */ GPTNeoPreTrainedModel: () => ( /* binding */ Ko ), /* harmony export */ GPTNeoXForCausalLM: () => ( /* binding */ rl ), /* harmony export */ GPTNeoXModel: () => ( /* binding */ sl ), /* harmony export */ GPTNeoXPreTrainedModel: () => ( /* binding */ Ho ), /* harmony export */ Gemma2ForCausalLM: () => ( /* binding */ vl ), /* harmony export */ Gemma2Model: () => ( /* binding */ bl ), /* harmony export */ Gemma2PreTrainedModel: () => ( /* binding */ ui ), /* harmony export */ GemmaForCausalLM: () => ( /* binding */ Ml ), /* harmony export */ GemmaModel: () => ( /* binding */ yl ), /* harmony export */ GemmaPreTrainedModel: () => ( /* binding */ li ), /* harmony export */ GlmForCausalLM: () => ( /* binding */ Dn ), /* harmony export */ GlmModel: () => ( /* binding */ dl ), /* harmony export */ GlmPreTrainedModel: () => ( /* binding */ ei ), /* harmony export */ GraniteForCausalLM: () => ( /* binding */ fl ), /* harmony export */ GraniteModel: () => ( /* binding */ ls ), /* harmony export */ GranitePreTrainedModel: () => ( /* binding */ ii ), /* harmony export */ GroundingDinoForObjectDetection: () => ( /* binding */ Tu ), /* harmony export */ GroundingDinoPreTrainedModel: () => ( /* binding */ vc ), /* harmony export */ GroupViTModel: () => ( /* binding */ gr ), /* harmony export */ GroupViTPreTrainedModel: () => ( /* binding */ Kl ), /* harmony export */ HeliumForCausalLM: () => ( /* binding */ ul ), /* harmony export */ HeliumModel: () => ( /* binding */ io ), /* harmony export */ HeliumPreTrainedModel: () => ( /* binding */ Zo ), /* harmony export */ HieraForImageClassification: () => ( /* binding */ Oi ), /* harmony export */ HieraModel: () => ( /* binding */ ho ), /* harmony export */ HieraPreTrainedModel: () => ( /* binding */ Fi ), /* harmony export */ HubertForCTC: () => ( /* binding */ Gu ), /* harmony export */ HubertForSequenceClassification: () => ( /* binding */ $c ), /* harmony export */ HubertModel: () => ( /* binding */ Wu ), /* harmony export */ HubertPreTrainedModel: () => ( /* binding */ Sc ), /* harmony export */ IJepaForImageClassification: () => ( /* binding */ Rl ), /* harmony export */ IJepaModel: () => ( /* binding */ Bl ), /* harmony export */ IJepaPreTrainedModel: () => ( /* binding */ uo ), /* harmony export */ Idefics3ForConditionalGeneration: () => ( /* binding */ No ), /* harmony export */ Idefics3PreTrainedModel: () => ( /* binding */ ja ), /* harmony export */ ImageMattingOutput: () => ( /* binding */ Xd ), /* harmony export */ JAISLMHeadModel: () => ( /* binding */ el ), /* harmony export */ JAISModel: () => ( /* binding */ Za ), /* harmony export */ JAISPreTrainedModel: () => ( /* binding */ Go ), /* harmony export */ JinaCLIPModel: () => ( /* binding */ no ), /* harmony export */ JinaCLIPPreTrainedModel: () => ( /* binding */ ro ), /* harmony export */ JinaCLIPTextModel: () => ( /* binding */ Vo ), /* harmony export */ JinaCLIPVisionModel: () => ( /* binding */ _r ), /* harmony export */ LlamaForCausalLM: () => ( /* binding */ cc ), /* harmony export */ LlamaModel: () => ( /* binding */ Jo ), /* harmony export */ LlamaPreTrainedModel: () => ( /* binding */ Yo ), /* harmony export */ LlavaForConditionalGeneration: () => ( /* binding */ so ), /* harmony export */ LlavaOnevisionForConditionalGeneration: () => ( /* binding */ Da ), /* harmony export */ LlavaPreTrainedModel: () => ( /* binding */ Nr ), /* harmony export */ LongT5ForConditionalGeneration: () => ( /* binding */ Fe ), /* harmony export */ LongT5Model: () => ( /* binding */ _e ), /* harmony export */ LongT5PreTrainedModel: () => ( /* binding */ ce ), /* harmony export */ M2M100ForConditionalGeneration: () => ( /* binding */ Yi ), /* harmony export */ M2M100Model: () => ( /* binding */ $u ), /* harmony export */ M2M100PreTrainedModel: () => ( /* binding */ Xi ), /* harmony export */ MBartForCausalLM: () => ( /* binding */ Hs ), /* harmony export */ MBartForConditionalGeneration: () => ( /* binding */ jt ), /* harmony export */ MBartForSequenceClassification: () => ( /* binding */ rs ), /* harmony export */ MBartModel: () => ( /* binding */ Ks ), /* harmony export */ MBartPreTrainedModel: () => ( /* binding */ bs ), /* harmony export */ MPNetForMaskedLM: () => ( /* binding */ Qr ), /* harmony export */ MPNetForQuestionAnswering: () => ( /* binding */ fn ), /* harmony export */ MPNetForSequenceClassification: () => ( /* binding */ mn ), /* harmony export */ MPNetForTokenClassification: () => ( /* binding */ _n ), /* harmony export */ MPNetModel: () => ( /* binding */ hn ), /* harmony export */ MPNetPreTrainedModel: () => ( /* binding */ ar ), /* harmony export */ MT5ForConditionalGeneration: () => ( /* binding */ wt ), /* harmony export */ MT5Model: () => ( /* binding */ gt ), /* harmony export */ MT5PreTrainedModel: () => ( /* binding */ Ye ), /* harmony export */ MarianMTModel: () => ( /* binding */ Su ), /* harmony export */ MarianModel: () => ( /* binding */ ku ), /* harmony export */ MarianPreTrainedModel: () => ( /* binding */ yo ), /* harmony export */ MaskFormerForInstanceSegmentation: () => ( /* binding */ fu ), /* harmony export */ MaskFormerModel: () => ( /* binding */ _u ), /* harmony export */ MaskFormerPreTrainedModel: () => ( /* binding */ fo ), /* harmony export */ MaskedLMOutput: () => ( /* binding */ Qs ), /* harmony export */ MgpstrForSceneTextRecognition: () => ( /* binding */ Td ), /* harmony export */ MgpstrModelOutput: () => ( /* binding */ vd ), /* harmony export */ MgpstrPreTrainedModel: () => ( /* binding */ xd ), /* harmony export */ MistralForCausalLM: () => ( /* binding */ ed ), /* harmony export */ MistralModel: () => ( /* binding */ Zu ), /* harmony export */ MistralPreTrainedModel: () => ( /* binding */ Ji ), /* harmony export */ MobileBertForMaskedLM: () => ( /* binding */ to ), /* harmony export */ MobileBertForQuestionAnswering: () => ( /* binding */ pr ), /* harmony export */ MobileBertForSequenceClassification: () => ( /* binding */ Br ), /* harmony export */ MobileBertModel: () => ( /* binding */ Sn ), /* harmony export */ MobileBertPreTrainedModel: () => ( /* binding */ zr ), /* harmony export */ MobileLLMForCausalLM: () => ( /* binding */ hl ), /* harmony export */ MobileLLMModel: () => ( /* binding */ pl ), /* harmony export */ MobileLLMPreTrainedModel: () => ( /* binding */ ri ), /* harmony export */ MobileNetV1ForImageClassification: () => ( /* binding */ aa ), /* harmony export */ MobileNetV1Model: () => ( /* binding */ Dc ), /* harmony export */ MobileNetV1PreTrainedModel: () => ( /* binding */ ia ), /* harmony export */ MobileNetV2ForImageClassification: () => ( /* binding */ md ), /* harmony export */ MobileNetV2Model: () => ( /* binding */ hd ), /* harmony export */ MobileNetV2PreTrainedModel: () => ( /* binding */ la ), /* harmony export */ MobileNetV3ForImageClassification: () => ( /* binding */ gd ), /* harmony export */ MobileNetV3Model: () => ( /* binding */ fd ), /* harmony export */ MobileNetV3PreTrainedModel: () => ( /* binding */ _d ), /* harmony export */ MobileNetV4ForImageClassification: () => ( /* binding */ wd ), /* harmony export */ MobileNetV4Model: () => ( /* binding */ Lc ), /* harmony export */ MobileNetV4PreTrainedModel: () => ( /* binding */ ua ), /* harmony export */ MobileViTForImageClassification: () => ( /* binding */ Jl ), /* harmony export */ MobileViTModel: () => ( /* binding */ Yl ), /* harmony export */ MobileViTPreTrainedModel: () => ( /* binding */ vi ), /* harmony export */ MobileViTV2ForImageClassification: () => ( /* binding */ _c ), /* harmony export */ MobileViTV2Model: () => ( /* binding */ Zl ), /* harmony export */ MobileViTV2PreTrainedModel: () => ( /* binding */ xi ), /* harmony export */ ModelOutput: () => ( /* binding */ We ), /* harmony export */ ModernBertForMaskedLM: () => ( /* binding */ _t ), /* harmony export */ ModernBertForSequenceClassification: () => ( /* binding */ lt ), /* harmony export */ ModernBertForTokenClassification: () => ( /* binding */ ct ), /* harmony export */ ModernBertModel: () => ( /* binding */ at ), /* harmony export */ ModernBertPreTrainedModel: () => ( /* binding */ Ze ), /* harmony export */ Moondream1ForConditionalGeneration: () => ( /* binding */ La ), /* harmony export */ MoonshineForConditionalGeneration: () => ( /* binding */ Oa ), /* harmony export */ MoonshineModel: () => ( /* binding */ ur ), /* harmony export */ MoonshinePreTrainedModel: () => ( /* binding */ Bo ), /* harmony export */ MptForCausalLM: () => ( /* binding */ Ol ), /* harmony export */ MptModel: () => ( /* binding */ Fl ), /* harmony export */ MptPreTrainedModel: () => ( /* binding */ _i ), /* harmony export */ MultiModalityCausalLM: () => ( /* binding */ bd ), /* harmony export */ MultiModalityPreTrainedModel: () => ( /* binding */ Md ), /* harmony export */ MusicgenForCausalLM: () => ( /* binding */ Oc ), /* harmony export */ MusicgenForConditionalGeneration: () => ( /* binding */ Po ), /* harmony export */ MusicgenModel: () => ( /* binding */ Fc ), /* harmony export */ MusicgenPreTrainedModel: () => ( /* binding */ oa ), /* harmony export */ NomicBertModel: () => ( /* binding */ ae ), /* harmony export */ NomicBertPreTrainedModel: () => ( /* binding */ F ), /* harmony export */ OPTForCausalLM: () => ( /* binding */ Ll ), /* harmony export */ OPTModel: () => ( /* binding */ Dl ), /* harmony export */ OPTPreTrainedModel: () => ( /* binding */ fi ), /* harmony export */ Olmo2ForCausalLM: () => ( /* binding */ hc ), /* harmony export */ Olmo2Model: () => ( /* binding */ _l ), /* harmony export */ Olmo2PreTrainedModel: () => ( /* binding */ oi ), /* harmony export */ OlmoForCausalLM: () => ( /* binding */ ml ), /* harmony export */ OlmoModel: () => ( /* binding */ pc ), /* harmony export */ OlmoPreTrainedModel: () => ( /* binding */ ni ), /* harmony export */ OpenELMForCausalLM: () => ( /* binding */ Tl ), /* harmony export */ OpenELMModel: () => ( /* binding */ xl ), /* harmony export */ OpenELMPreTrainedModel: () => ( /* binding */ di ), /* harmony export */ OwlViTForObjectDetection: () => ( /* binding */ tu ), /* harmony export */ OwlViTModel: () => ( /* binding */ eu ), /* harmony export */ OwlViTPreTrainedModel: () => ( /* binding */ Ti ), /* harmony export */ Owlv2ForObjectDetection: () => ( /* binding */ ru ), /* harmony export */ Owlv2Model: () => ( /* binding */ su ), /* harmony export */ Owlv2PreTrainedModel: () => ( /* binding */ Pi ), /* harmony export */ PaliGemmaForConditionalGeneration: () => ( /* binding */ Na ), /* harmony export */ PaliGemmaPreTrainedModel: () => ( /* binding */ Ra ), /* harmony export */ PatchTSMixerForPrediction: () => ( /* binding */ Sd ), /* harmony export */ PatchTSMixerModel: () => ( /* binding */ kd ), /* harmony export */ PatchTSMixerPreTrainedModel: () => ( /* binding */ da ), /* harmony export */ PatchTSTForPrediction: () => ( /* binding */ Cd ), /* harmony export */ PatchTSTModel: () => ( /* binding */ Ed ), /* harmony export */ PatchTSTPreTrainedModel: () => ( /* binding */ Pd ), /* harmony export */ Phi3ForCausalLM: () => ( /* binding */ $l ), /* harmony export */ Phi3Model: () => ( /* binding */ Sl ), /* harmony export */ Phi3PreTrainedModel: () => ( /* binding */ hi ), /* harmony export */ Phi3VForCausalLM: () => ( /* binding */ dr ), /* harmony export */ Phi3VPreTrainedModel: () => ( /* binding */ Va ), /* harmony export */ PhiForCausalLM: () => ( /* binding */ kl ), /* harmony export */ PhiModel: () => ( /* binding */ Cl ), /* harmony export */ PhiPreTrainedModel: () => ( /* binding */ pi ), /* harmony export */ PreTrainedModel: () => ( /* binding */ J ), /* harmony export */ PretrainedMixin: () => ( /* binding */ _s ), /* harmony export */ PvtForImageClassification: () => ( /* binding */ yi ), /* harmony export */ PvtModel: () => ( /* binding */ Vl ), /* harmony export */ PvtPreTrainedModel: () => ( /* binding */ wi ), /* harmony export */ PyAnnoteForAudioFrameClassification: () => ( /* binding */ Du ), /* harmony export */ PyAnnoteModel: () => ( /* binding */ Ou ), /* harmony export */ PyAnnotePreTrainedModel: () => ( /* binding */ Mo ), /* harmony export */ QuestionAnsweringModelOutput: () => ( /* binding */ Ys ), /* harmony export */ Qwen2ForCausalLM: () => ( /* binding */ Pl ), /* harmony export */ Qwen2Model: () => ( /* binding */ Ln ), /* harmony export */ Qwen2PreTrainedModel: () => ( /* binding */ ci ), /* harmony export */ Qwen2VLForConditionalGeneration: () => ( /* binding */ El ), /* harmony export */ Qwen2VLPreTrainedModel: () => ( /* binding */ ao ), /* harmony export */ RTDetrForObjectDetection: () => ( /* binding */ zn ), /* harmony export */ RTDetrModel: () => ( /* binding */ fc ), /* harmony export */ RTDetrObjectDetectionOutput: () => ( /* binding */ $i ), /* harmony export */ RTDetrPreTrainedModel: () => ( /* binding */ Si ), /* harmony export */ ResNetForImageClassification: () => ( /* binding */ gc ), /* harmony export */ ResNetModel: () => ( /* binding */ lu ), /* harmony export */ ResNetPreTrainedModel: () => ( /* binding */ Di ), /* harmony export */ RoFormerForMaskedLM: () => ( /* binding */ ke ), /* harmony export */ RoFormerForQuestionAnswering: () => ( /* binding */ tt ), /* harmony export */ RoFormerForSequenceClassification: () => ( /* binding */ ze ), /* harmony export */ RoFormerForTokenClassification: () => ( /* binding */ Ge ), /* harmony export */ RoFormerModel: () => ( /* binding */ me ), /* harmony export */ RoFormerPreTrainedModel: () => ( /* binding */ H ), /* harmony export */ RobertaForMaskedLM: () => ( /* binding */ hr ), /* harmony export */ RobertaForQuestionAnswering: () => ( /* binding */ Mt ), /* harmony export */ RobertaForSequenceClassification: () => ( /* binding */ ds ), /* harmony export */ RobertaForTokenClassification: () => ( /* binding */ Cs ), /* harmony export */ RobertaModel: () => ( /* binding */ nr ), /* harmony export */ RobertaPreTrainedModel: () => ( /* binding */ At ), /* harmony export */ SamImageSegmentationOutput: () => ( /* binding */ Rn ), /* harmony export */ SamModel: () => ( /* binding */ wo ), /* harmony export */ SamPreTrainedModel: () => ( /* binding */ xc ), /* harmony export */ SapiensForDepthEstimation: () => ( /* binding */ mo ), /* harmony export */ SapiensForNormalEstimation: () => ( /* binding */ mu ), /* harmony export */ SapiensForSemanticSegmentation: () => ( /* binding */ hu ), /* harmony export */ SapiensPreTrainedModel: () => ( /* binding */ ji ), /* harmony export */ SegformerForImageClassification: () => ( /* binding */ ad ), /* harmony export */ SegformerForSemanticSegmentation: () => ( /* binding */ ld ), /* harmony export */ SegformerModel: () => ( /* binding */ Ic ), /* harmony export */ SegformerPreTrainedModel: () => ( /* binding */ rn ), /* harmony export */ Seq2SeqLMOutput: () => ( /* binding */ fp ), /* harmony export */ SequenceClassifierOutput: () => ( /* binding */ Ht ), /* harmony export */ SiglipModel: () => ( /* binding */ Ka ), /* harmony export */ SiglipPreTrainedModel: () => ( /* binding */ jo ), /* harmony export */ SiglipTextModel: () => ( /* binding */ Ha ), /* harmony export */ SiglipVisionModel: () => ( /* binding */ qa ), /* harmony export */ SpeechT5ForSpeechToText: () => ( /* binding */ br ), /* harmony export */ SpeechT5ForTextToSpeech: () => ( /* binding */ Sr ), /* harmony export */ SpeechT5HifiGan: () => ( /* binding */ tn ), /* harmony export */ SpeechT5Model: () => ( /* binding */ Lp ), /* harmony export */ SpeechT5PreTrainedModel: () => ( /* binding */ xo ), /* harmony export */ SqueezeBertForMaskedLM: () => ( /* binding */ $n ), /* harmony export */ SqueezeBertForQuestionAnswering: () => ( /* binding */ In ), /* harmony export */ SqueezeBertForSequenceClassification: () => ( /* binding */ An ), /* harmony export */ SqueezeBertModel: () => ( /* binding */ gn ), /* harmony export */ SqueezeBertPreTrainedModel: () => ( /* binding */ Ot ), /* harmony export */ StableLmForCausalLM: () => ( /* binding */ dd ), /* harmony export */ StableLmModel: () => ( /* binding */ ud ), /* harmony export */ StableLmPreTrainedModel: () => ( /* binding */ na ), /* harmony export */ Starcoder2ForCausalLM: () => ( /* binding */ sd ), /* harmony export */ Starcoder2Model: () => ( /* binding */ td ), /* harmony export */ Starcoder2PreTrainedModel: () => ( /* binding */ Zi ), /* harmony export */ StyleTextToSpeech2Model: () => ( /* binding */ Yu ), /* harmony export */ StyleTextToSpeech2PreTrainedModel: () => ( /* binding */ Xu ), /* harmony export */ Swin2SRForImageSuperResolution: () => ( /* binding */ uu ), /* harmony export */ Swin2SRModel: () => ( /* binding */ Ri ), /* harmony export */ Swin2SRPreTrainedModel: () => ( /* binding */ Bi ), /* harmony export */ SwinForImageClassification: () => ( /* binding */ Bn ), /* harmony export */ SwinModel: () => ( /* binding */ zi ), /* harmony export */ SwinPreTrainedModel: () => ( /* binding */ Li ), /* harmony export */ T5ForConditionalGeneration: () => ( /* binding */ Y ), /* harmony export */ T5Model: () => ( /* binding */ M ), /* harmony export */ T5PreTrainedModel: () => ( /* binding */ Te ), /* harmony export */ TableTransformerForObjectDetection: () => ( /* binding */ iu ), /* harmony export */ TableTransformerModel: () => ( /* binding */ ou ), /* harmony export */ TableTransformerObjectDetectionOutput: () => ( /* binding */ Ai ), /* harmony export */ TableTransformerPreTrainedModel: () => ( /* binding */ co ), /* harmony export */ TokenClassifierOutput: () => ( /* binding */ Ss ), /* harmony export */ TrOCRForCausalLM: () => ( /* binding */ Ju ), /* harmony export */ TrOCRPreTrainedModel: () => ( /* binding */ sn ), /* harmony export */ UniSpeechForCTC: () => ( /* binding */ Ec ), /* harmony export */ UniSpeechForSequenceClassification: () => ( /* binding */ Bu ), /* harmony export */ UniSpeechModel: () => ( /* binding */ zu ), /* harmony export */ UniSpeechPreTrainedModel: () => ( /* binding */ bo ), /* harmony export */ UniSpeechSatForAudioFrameClassification: () => ( /* binding */ ju ), /* harmony export */ UniSpeechSatForCTC: () => ( /* binding */ Nu ), /* harmony export */ UniSpeechSatForSequenceClassification: () => ( /* binding */ Cc ), /* harmony export */ UniSpeechSatModel: () => ( /* binding */ Ru ), /* harmony export */ UniSpeechSatPreTrainedModel: () => ( /* binding */ Nn ), /* harmony export */ ViTForImageClassification: () => ( /* binding */ gi ), /* harmony export */ ViTMAEModel: () => ( /* binding */ Wl ), /* harmony export */ ViTMAEPreTrainedModel: () => ( /* binding */ Ul ), /* harmony export */ ViTMSNForImageClassification: () => ( /* binding */ Gl ), /* harmony export */ ViTMSNModel: () => ( /* binding */ mc ), /* harmony export */ ViTMSNPreTrainedModel: () => ( /* binding */ Mi ), /* harmony export */ ViTModel: () => ( /* binding */ zl ), /* harmony export */ ViTPreTrainedModel: () => ( /* binding */ lo ), /* harmony export */ VisionEncoderDecoderModel: () => ( /* binding */ Ro ), /* harmony export */ VitMatteForImageMatting: () => ( /* binding */ Xl ), /* harmony export */ VitMattePreTrainedModel: () => ( /* binding */ Ql ), /* harmony export */ VitPoseForPoseEstimation: () => ( /* binding */ jl ), /* harmony export */ VitPosePreTrainedModel: () => ( /* binding */ Nl ), /* harmony export */ VitsModel: () => ( /* binding */ ra ), /* harmony export */ VitsModelOutput: () => ( /* binding */ Yd ), /* harmony export */ VitsPreTrainedModel: () => ( /* binding */ sa ), /* harmony export */ Wav2Vec2BertForCTC: () => ( /* binding */ kc ), /* harmony export */ Wav2Vec2BertForSequenceClassification: () => ( /* binding */ Uu ), /* harmony export */ Wav2Vec2BertModel: () => ( /* binding */ Vu ), /* harmony export */ Wav2Vec2BertPreTrainedModel: () => ( /* binding */ vo ), /* harmony export */ Wav2Vec2ForAudioFrameClassification: () => ( /* binding */ Fu ), /* harmony export */ Wav2Vec2ForCTC: () => ( /* binding */ Iu ), /* harmony export */ Wav2Vec2ForSequenceClassification: () => ( /* binding */ Tc ), /* harmony export */ Wav2Vec2Model: () => ( /* binding */ Au ), /* harmony export */ Wav2Vec2PreTrainedModel: () => ( /* binding */ jr ), /* harmony export */ WavLMForAudioFrameClassification: () => ( /* binding */ Qu ), /* harmony export */ WavLMForCTC: () => ( /* binding */ Hu ), /* harmony export */ WavLMForSequenceClassification: () => ( /* binding */ qu ), /* harmony export */ WavLMForXVector: () => ( /* binding */ Ac ), /* harmony export */ WavLMModel: () => ( /* binding */ Ku ), /* harmony export */ WavLMPreTrainedModel: () => ( /* binding */ yn ), /* harmony export */ WeSpeakerResNetModel: () => ( /* binding */ Pc ), /* harmony export */ WeSpeakerResNetPreTrainedModel: () => ( /* binding */ Lu ), /* harmony export */ WhisperForConditionalGeneration: () => ( /* binding */ Fa ), /* harmony export */ WhisperModel: () => ( /* binding */ Ia ), /* harmony export */ WhisperPreTrainedModel: () => ( /* binding */ zo ), /* harmony export */ XLMForQuestionAnswering: () => ( /* binding */ Xr ), /* harmony export */ XLMForSequenceClassification: () => ( /* binding */ Us ), /* harmony export */ XLMForTokenClassification: () => ( /* binding */ Pt ), /* harmony export */ XLMModel: () => ( /* binding */ Fs ), /* harmony export */ XLMPreTrainedModel: () => ( /* binding */ Wt ), /* harmony export */ XLMRobertaForMaskedLM: () => ( /* binding */ ka ), /* harmony export */ XLMRobertaForQuestionAnswering: () => ( /* binding */ $a ), /* harmony export */ XLMRobertaForSequenceClassification: () => ( /* binding */ Do ), /* harmony export */ XLMRobertaForTokenClassification: () => ( /* binding */ Sa ), /* harmony export */ XLMRobertaModel: () => ( /* binding */ St ), /* harmony export */ XLMRobertaPreTrainedModel: () => ( /* binding */ qe ), /* harmony export */ XLMWithLMHeadModel: () => ( /* binding */ ks ), /* harmony export */ XVectorOutput: () => ( /* binding */ Qd ), /* harmony export */ YolosForObjectDetection: () => ( /* binding */ Eu ), /* harmony export */ YolosModel: () => ( /* binding */ Pu ), /* harmony export */ YolosObjectDetectionOutput: () => ( /* binding */ Cu ), /* harmony export */ YolosPreTrainedModel: () => ( /* binding */ Qi ) /* harmony export */ }); var g = r( /*! ./configs.js */ "./src/configs.js" ), O = r( /*! ./backends/onnx.js */ "./src/backends/onnx.js" ), j = r( /*! ./utils/dtypes.js */ "./src/utils/dtypes.js" ), ee = r( /*! ./utils/generic.js */ "./src/utils/generic.js" ), N = r( /*! ./utils/core.js */ "./src/utils/core.js" ), y = r( /*! ./utils/hub.js */ "./src/utils/hub.js" ), T = r( /*! ./utils/constants.js */ "./src/utils/constants.js" ), v = r( /*! ./generation/logits_process.js */ "./src/generation/logits_process.js" ), b = r( /*! ./generation/configuration_utils.js */ "./src/generation/configuration_utils.js" ), x = r( /*! ./utils/tensor.js */ "./src/utils/tensor.js" ), L = r( /*! ./utils/image.js */ "./src/utils/image.js" ), K = r( /*! ./utils/maths.js */ "./src/utils/maths.js" ), re = r( /*! ./generation/stopping_criteria.js */ "./src/generation/stopping_criteria.js" ), ie = r( /*! ./generation/logits_sampler.js */ "./src/generation/logits_sampler.js" ), V = r( /*! ./env.js */ "./src/env.js" ), U = r( /*! ./models/whisper/generation_whisper.js */ "./src/models/whisper/generation_whisper.js" ), q = r( /*! ./models/whisper/common_whisper.js */ "./src/models/whisper/common_whisper.js" ); const A = { EncoderOnly: 0, EncoderDecoder: 1, Seq2Seq: 2, Vision2Seq: 3, DecoderOnly: 4, MaskGeneration: 5, ImageTextToText: 6, Musicgen: 7, MultiModality: 8, Phi3V: 9 }, S = /* @__PURE__ */ new Map(), w = /* @__PURE__ */ new Map(), P = /* @__PURE__ */ new Map(); async function I(f, _, Q) { const xe = Q.config?.["transformers.js_config"] ?? {}; let Se = Q.device ?? xe.device; Se && typeof Se != "string" && (Se.hasOwnProperty(_) ? Se = Se[_] : (console.warn(`device not specified for "${_}". Using the default device.`), Se = null)); const Be = ( /** @type {import("./utils/devices.js").DeviceType} */ Se ?? (V.apis.IS_NODE_ENV ? "cpu" : "wasm") ), rt = (0, O.deviceToExecutionProviders)(Be); let ot = Q.dtype ?? xe.dtype; if (typeof ot != "string" && (ot && ot.hasOwnProperty(_) ? ot = ot[_] : (ot = j.DEFAULT_DEVICE_DTYPE_MAPPING[Be] ?? j.DATA_TYPES.fp32, console.warn(`dtype not specified for "${_}". Using the default dtype (${ot}) for this device (${Be}).`))), ot === j.DATA_TYPES.auto) { let Zt = xe.dtype; typeof Zt != "string" && (Zt = Zt[_]), Zt && Zt !== j.DATA_TYPES.auto && j.DATA_TYPES.hasOwnProperty(Zt) ? ot = Zt : ot = j.DEFAULT_DEVICE_DTYPE_MAPPING[Be] ?? j.DATA_TYPES.fp32; } const ft = ( /** @type {import("./utils/dtypes.js").DataType} */ ot ); if (j.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ft)) { if (ft === j.DATA_TYPES.fp16 && Be === "webgpu" && !await (0, j.isWebGpuFp16Supported)()) throw new Error(`The device (${Be}) does not support fp16.`); } else throw new Error(`Invalid dtype: ${ft}. Should be one of: ${Object.keys(j.DATA_TYPES).join(", ")}`); const $t = xe.kv_cache_dtype ? typeof xe.kv_cache_dtype == "string" ? xe.kv_cache_dtype : xe.kv_cache_dtype[ft] ?? "float32" : void 0; if ($t && !["float32", "float16"].includes($t)) throw new Error(`Invalid kv_cache_dtype: ${$t}. Should be one of: float32, float16`); const Jt = { dtype: ft, kv_cache_dtype: $t }, qt = j.DEFAULT_DTYPE_SUFFIX_MAPPING[ft], Dt = `${Q.subfolder ?? ""}/${_}${qt}.onnx`, It = { ...Q.session_options }; It.executionProviders ??= rt; const vs = xe.free_dimension_overrides; vs ? It.freeDimensionOverrides ??= vs : Be.startsWith("webnn") && !It.freeDimensionOverrides && console.warn( 'WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.' ); const Qt = (0, y.getModelFile)(f, Dt, !0, Q), Gt = Q.use_external_data_format ?? xe.use_external_data_format; let fs = []; if (Gt && (Gt === !0 || typeof Gt == "object" && Gt.hasOwnProperty(_) && Gt[_] === !0)) { if (V.apis.IS_NODE_ENV) throw new Error("External data format is not yet supported in Node.js"); const Zt = `${_}${qt}.onnx_data`, Bs = `${Q.subfolder ?? ""}/${Zt}`; fs.push(new Promise(async (Rs, $s) => { const Ns = await (0, y.getModelFile)(f, Bs, !0, Q); Rs({ path: Zt, data: Ns }); })); } else It.externalData !== void 0 && (fs = It.externalData.map(async (Zt) => { if (typeof Zt.data == "string") { const Bs = await (0, y.getModelFile)(f, Zt.data, !0, Q); return { ...Zt, data: Bs }; } return Zt; })); if (fs.length > 0 && (It.externalData = await Promise.all(fs)), Be === "webgpu") { const Zt = (0, g.getKeyValueShapes)(Q.config, { prefix: "present" }); if (Object.keys(Zt).length > 0 && !(0, O.isONNXProxy)()) { const Bs = {}; for (const Rs in Zt) Bs[Rs] = "gpu-buffer"; It.preferredOutputLocation = Bs; } } return { buffer: await Qt, session_options: It, session_config: Jt }; } async function le(f, _, Q) { return Object.fromEntries(await Promise.all( Object.keys(_).map(async (xe) => { const { buffer: Se, session_options: Be, session_config: rt } = await I(f, _[xe], Q), ot = await (0, O.createInferenceSession)(Se, Be, rt); return [xe, ot]; }) )); } async function oe(f, _, Q) { return Object.fromEntries(await Promise.all( Object.keys(_).map(async (xe) => { const Se = await (0, y.getModelJSON)(f, _[xe], !1, Q); return [xe, Se]; }) )); } function ye(f, _) { const Q = /* @__PURE__ */ Object.create(null), xe = []; for (const rt of f.inputNames) { const ot = _[rt]; if (!(ot instanceof x.Tensor)) { xe.push(rt); continue; } Q[rt] = (0, O.isONNXProxy)() ? ot.clone() : ot; } if (xe.length > 0) throw new Error( `An error occurred during model execution: "Missing the following inputs: ${xe.join(", ")}.` ); const Se = Object.keys(_).length, Be = f.inputNames.length; if (Se > Be) { let rt = Object.keys(_).filter((ot) => !f.inputNames.includes(ot)); console.warn(`WARNING: Too many inputs were provided (${Se} > ${Be}). The following inputs will be ignored: "${rt.join(", ")}".`); } return Q; } async function ge(f, _) { const Q = ye(f, _); try { const xe = Object.fromEntries(Object.entries(Q).map(([Be, rt]) => [Be, rt.ort_tensor])); let Se = await f.run(xe); return Se = se(Se), Se; } catch (xe) { const Se = Object.fromEntries(Object.entries(Q).map(([Be, { type: rt, dims: ot, data: ft }]) => [Be, { // Extract these properties from the underlying ORT tensor type: rt, dims: ot, data: ft }])); throw console.error(`An error occurred during model execution: "${xe}".`), console.error("Inputs given to model:", Se), xe; } } function se(f) { for (let _ in f) (0, O.isONNXTensor)(f[_]) ? f[_] = new x.Tensor(f[_]) : typeof f[_] == "object" && se(f[_]); return f; } function be(f) { if (f instanceof x.Tensor) return f; if (f.length === 0) throw Error("items must be non-empty"); if (Array.isArray(f[0])) { if (f.some((_) => _.length !== f[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 x.Tensor( "int64", BigInt64Array.from(f.flat().map((_) => BigInt(_))), [f.length, f[0].length] ); } else return new x.Tensor( "int64", BigInt64Array.from(f.map((_) => BigInt(_))), [1, f.length] ); } function pe(f) { return new x.Tensor("bool", [f], [1]); } async function Ce(f, _) { let { encoder_outputs: Q, input_ids: xe, decoder_input_ids: Se, ...Be } = _; if (!Q) { const ot = (0, N.pick)(_, f.sessions.model.inputNames); Q = (await $e(f, ot)).last_hidden_state; } return Be.input_ids = Se, Be.encoder_hidden_states = Q, f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask") && (Be.encoder_attention_mask = _.attention_mask), await Pe(f, Be, !0); } async function $e(f, _) { const Q = f.sessions.model, xe = (0, N.pick)(_, Q.inputNames); if (Q.inputNames.includes("inputs_embeds") && !xe.inputs_embeds) { if (!_.input_ids) throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs."); xe.inputs_embeds = await f.encode_text({ input_ids: _.input_ids }); } if (Q.inputNames.includes("token_type_ids") && !xe.token_type_ids) { if (!xe.input_ids) throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs."); xe.token_type_ids = (0, x.zeros_like)(xe.input_ids); } if (Q.inputNames.includes("pixel_mask") && !xe.pixel_mask) { if (!xe.pixel_values) throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs."); const Se = xe.pixel_values.dims; xe.pixel_mask = (0, x.ones)([Se[0], Se[2], Se[3]]); } return await ge(Q, xe); } async function Pe(f, _, Q = !1) { const xe = f.sessions[Q ? "decoder_model_merged" : "model"], { past_key_values: Se, ...Be } = _; if (xe.inputNames.includes("use_cache_branch") && (Be.use_cache_branch = pe(!!Se)), xe.inputNames.includes("position_ids") && Be.attention_mask && !Be.position_ids) { const ot = f.config.model_type === "paligemma" ? 1 : 0; Be.position_ids = X(Be, Se, ot); } f.addPastKeyValues(Be, Se); const rt = (0, N.pick)(Be, xe.inputNames); return await ge(xe, rt); } function Je({ image_token_id: f, inputs_embeds: _, image_features: Q, input_ids: xe, attention_mask: Se }) { const Be = xe.tolist().map( ($t) => $t.reduce((Jt, qt, Dt) => (qt == f && Jt.push(Dt), Jt), []) ), rt = Be.reduce(($t, Jt) => $t + Jt.length, 0), ot = Q.dims[0]; if (rt !== ot) throw new Error(`Image features and image tokens do not match: tokens: ${rt}, features ${ot}`); let ft = 0; for (let $t = 0; $t < Be.length; ++$t) { const Jt = Be[$t], qt = _[$t]; for (let Dt = 0; Dt < Jt.length; ++Dt) qt[Jt[Dt]].data.set(Q[ft++].data); } return { inputs_embeds: _, attention_mask: Se }; } async function Ue(f, { // Produced by the tokenizer/processor: input_ids: _ = null, attention_mask: Q = null, pixel_values: xe = null, // Used during generation: position_ids: Se = null, inputs_embeds: Be = null, past_key_values: rt = null, // Generic generation parameters generation_config: ot = null, logits_processor: ft = null, // TODO: needed? ...$t }) { if (!Be) { if (Be = await f.encode_text({ input_ids: _, ...$t }), xe && _.dims[1] !== 1) { const qt = await f.encode_image({ pixel_values: xe, ...$t }); ({ inputs_embeds: Be, attention_mask: Q } = f._merge_input_ids_with_image_features({ image_features: qt, inputs_embeds: Be, input_ids: _, attention_mask: Q })); } else if (rt && xe && _.dims[1] === 1) { const qt = _.dims[1], Dt = Object.values(rt)[0].dims.at(-2); Q = (0, x.cat)([ (0, x.ones)([_.dims[0], Dt]), Q.slice(null, [Q.dims[1] - qt, Q.dims[1]]) ], 1); } } if (!Se && f.config.model_type === "qwen2_vl") { const { image_grid_thw: qt, video_grid_thw: Dt } = $t; [Se] = f.get_rope_index(_, qt, Dt, Q); } return await Pe(f, { inputs_embeds: Be, past_key_values: rt, attention_mask: Q, position_ids: Se, generation_config: ot, logits_processor: ft }, !0); } function we(f, _ = 0) { const [Q, xe] = f.dims, Se = f.data, Be = new BigInt64Array(Se.length); for (let rt = 0; rt < Q; ++rt) { const ot = rt * xe; let ft = BigInt(_); for (let $t = 0; $t < xe; ++$t) { const Jt = ot + $t; Se[Jt] === 0n ? Be[Jt] = BigInt(1) : (Be[Jt] = ft, ft += Se[Jt]); } } return { data: Be, dims: f.dims }; } function X(f, _ = null, Q = 0) { const { input_ids: xe, inputs_embeds: Se, attention_mask: Be } = f, { data: rt, dims: ot } = we(Be, Q); let ft = new x.Tensor("int64", rt, ot); if (_) { const $t = -(xe ?? Se).dims.at(1); ft = ft.slice(null, [$t, null]); } return ft; } function de(f, _, Q, xe) { if (Q.past_key_values) { const Se = Object.values(Q.past_key_values)[0].dims.at(-2), { input_ids: Be, attention_mask: rt } = Q; if (!(rt && rt.dims[1] > Be.dims[1])) { if (Se < Be.dims[1]) Q.input_ids = Be.slice(null, [Se, null]); else if ( // NOTE: Only used by VLMs (!= so that null matches undefined) f.config.image_token_index != null && // Equivalent to `self.config.image_token_index in input_ids` (== so that int matches bigint) Be.data.some((ot) => ot == f.config.image_token_index) ) { const ot = f.config.num_image_tokens; if (!ot) throw new Error("`num_image_tokens` is missing in the model configuration."); const ft = Be.dims[1] - (Se - ot); Q.input_ids = Be.slice(null, [-ft, null]), Q.attention_mask = (0, x.ones)([1, Se + ft]); } } } return Q; } function Ee(f, _, Q, xe) { return Q.past_key_values && (_ = _.map((Se) => [Se.at(-1)])), { ...Q, decoder_input_ids: be(_) }; } function Oe(f, ..._) { return f.config.is_encoder_decoder ? Ee(f, ..._) : de(f, ..._); } function Xe(f, _, Q, xe) { const Se = !!Q.past_key_values; return xe.guidance_scale !== null && xe.guidance_scale > 1 && (Se ? Q.input_ids = (0, x.cat)([ Q.input_ids, Q.input_ids ], 0) : (Q.input_ids = (0, x.cat)([ Q.input_ids, (0, x.full_like)(Q.input_ids, BigInt(xe.pad_token_id)) ], 0), Q.attention_mask = (0, x.cat)([ Q.attention_mask, (0, x.full_like)(Q.attention_mask, 0n) ], 0))), (Se || !Q.pixel_values) && (Q.pixel_values = (0, x.full)([0, 0, 3, 384, 384], 1)), Se && (Q.images_seq_mask = new x.Tensor( "bool", new Array(1).fill(!0).fill(!1, 0, 1), [1, 1] ), Q.images_emb_mask = new x.Tensor( "bool", new Array(0).fill(!1), [1, 1, 0] )), Q; } class J extends ee.Callable { main_input_name = "input_ids"; forward_params = ["input_ids", "attention_mask"]; /** * Creates a new instance of the `PreTrainedModel` class. * @param {import('./configs.js').PretrainedConfig} config The model configuration. * @param {Record} sessions The inference sessions for the model. * @param {Record} configs Additional configuration files (e.g., generation_config.json). */ constructor(_, Q, xe) { super(), this.config = _, this.sessions = Q, this.configs = xe; const Se = P.get(this.constructor), Be = S.get(Se); switch (this.can_generate = !1, this._forward = null, this._prepare_inputs_for_generation = null, Be) { case A.DecoderOnly: this.can_generate = !0, this._forward = Pe, this._prepare_inputs_for_generation = de; break; case A.Seq2Seq: case A.Vision2Seq: case A.Musicgen: this.can_generate = !0, this._forward = Ce, this._prepare_inputs_for_generation = Ee; break; case A.EncoderDecoder: this._forward = Ce; break; case A.ImageTextToText: this.can_generate = !0, this._forward = Ue, this._prepare_inputs_for_generation = Oe; break; case A.Phi3V: this.can_generate = !0, this._prepare_inputs_for_generation = Oe; break; case A.MultiModality: this.can_generate = !0, this._prepare_inputs_for_generation = Xe; break; default: this._forward = $e; break; } this.can_generate && this.forward_params.push("past_key_values"), this.custom_config = this.config["transformers.js_config"] ?? {}; } /** * 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 _ = []; for (const Q of Object.values(this.sessions)) Q?.handler?.dispose && _.push(Q.handler.dispose()); return await Promise.all(_); } /** * 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').PretrainedModelOptions} options Additional options for loading the model. * * @returns {Promise} A new instance of the `PreTrainedModel` class. */ static async from_pretrained(_, { progress_callback: Q = null, config: xe = null, cache_dir: Se = null, local_files_only: Be = !1, revision: rt = "main", model_file_name: ot = null, subfolder: ft = "onnx", device: $t = null, dtype: Jt = null, use_external_data_format: qt = null, session_options: Dt = {} } = {}) { let It = { progress_callback: Q, config: xe, cache_dir: Se, local_files_only: Be, revision: rt, model_file_name: ot, subfolder: ft, device: $t, dtype: Jt, use_external_data_format: qt, session_options: Dt }; const vs = P.get(this), Qt = S.get(vs); xe = It.config = await g.AutoConfig.from_pretrained(_, It); let Gt; if (Qt === A.DecoderOnly) Gt = await Promise.all([ le(_, { model: It.model_file_name ?? "model" }, It), oe(_, { generation_config: "generation_config.json" }, It) ]); else if (Qt === A.Seq2Seq || Qt === A.Vision2Seq) Gt = await Promise.all([ le(_, { model: "encoder_model", decoder_model_merged: "decoder_model_merged" }, It), oe(_, { generation_config: "generation_config.json" }, It) ]); else if (Qt === A.MaskGeneration) Gt = await Promise.all([ le(_, { model: "vision_encoder", prompt_encoder_mask_decoder: "prompt_encoder_mask_decoder" }, It) ]); else if (Qt === A.EncoderDecoder) Gt = await Promise.all([ le(_, { model: "encoder_model", decoder_model_merged: "decoder_model_merged" }, It) ]); else if (Qt === A.ImageTextToText) { const fs = { embed_tokens: "embed_tokens", vision_encoder: "vision_encoder", decoder_model_merged: "decoder_model_merged" }; xe.is_encoder_decoder && (fs.model = "encoder_model"), Gt = await Promise.all([ le(_, fs, It), oe(_, { generation_config: "generation_config.json" }, It) ]); } else if (Qt === A.Musicgen) Gt = await Promise.all([ le(_, { model: "text_encoder", decoder_model_merged: "decoder_model_merged", encodec_decode: "encodec_decode" }, It), oe(_, { generation_config: "generation_config.json" }, It) ]); else if (Qt === A.MultiModality) Gt = await Promise.all([ le(_, { prepare_inputs_embeds: "prepare_inputs_embeds", model: "language_model", lm_head: "lm_head", gen_head: "gen_head", gen_img_embeds: "gen_img_embeds", image_decode: "image_decode" }, It), oe(_, { generation_config: "generation_config.json" }, It) ]); else if (Qt === A.Phi3V) Gt = await Promise.all([ le(_, { prepare_inputs_embeds: "prepare_inputs_embeds", model: "model", vision_encoder: "vision_encoder" }, It), oe(_, { generation_config: "generation_config.json" }, It) ]); else { if (Qt !== A.EncoderOnly) { const fs = vs ?? xe?.model_type; fs !== "custom" && console.warn(`Model type for '${fs}' not found, assuming encoder-only architecture. Please report this at ${T.GITHUB_ISSUE_URL}.`); } Gt = await Promise.all([ le(_, { model: It.model_file_name ?? "model" }, It) ]); } return new this(xe, ...Gt); } /** * Runs the model with the provided inputs * @param {Object} model_inputs Object containing input tensors * @returns {Promise} Object containing output tensors */ async _call(_) { return await this.forward(_); } /** * 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(_) { return await this._forward(this, _); } /** * Get the model's generation config, if it exists. * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`. */ get generation_config() { return this.configs?.generation_config ?? null; } /** * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`] * instances used for multinomial sampling. * @param {GenerationConfig} generation_config The generation config. * @returns {LogitsProcessorList} generation_config */ _get_logits_warper(_) { const Q = new v.LogitsProcessorList(); return _.temperature !== null && _.temperature !== 1 && Q.push(new v.TemperatureLogitsWarper(_.temperature)), _.top_k !== null && _.top_k !== 0 && Q.push(new v.TopKLogitsWarper(_.top_k)), _.top_p !== null && _.top_p < 1 && Q.push(new v.TopPLogitsWarper(_.top_p)), Q; } /** * @param {GenerationConfig} generation_config * @param {number} input_ids_seq_length The starting sequence length for the input ids. * @returns {LogitsProcessorList} * @private */ _get_logits_processor(_, Q, xe = null) { const Se = new v.LogitsProcessorList(); if (_.repetition_penalty !== null && _.repetition_penalty !== 1 && Se.push(new v.RepetitionPenaltyLogitsProcessor(_.repetition_penalty)), _.no_repeat_ngram_size !== null && _.no_repeat_ngram_size > 0 && Se.push(new v.NoRepeatNGramLogitsProcessor(_.no_repeat_ngram_size)), _.bad_words_ids !== null && Se.push(new v.NoBadWordsLogitsProcessor(_.bad_words_ids, _.eos_token_id)), _.min_length !== null && _.eos_token_id !== null && _.min_length > 0 && Se.push(new v.MinLengthLogitsProcessor(_.min_length, _.eos_token_id)), _.min_new_tokens !== null && _.eos_token_id !== null && _.min_new_tokens > 0 && Se.push(new v.MinNewTokensLengthLogitsProcessor( Q, _.min_new_tokens, _.eos_token_id )), _.forced_bos_token_id !== null && Se.push(new v.ForcedBOSTokenLogitsProcessor(_.forced_bos_token_id)), _.forced_eos_token_id !== null && Se.push(new v.ForcedEOSTokenLogitsProcessor( _.max_length, _.forced_eos_token_id )), _.begin_suppress_tokens !== null) { const Be = Q > 1 || _.forced_bos_token_id === null ? Q : Q + 1; Se.push(new v.SuppressTokensAtBeginLogitsProcessor(_.begin_suppress_tokens, Be)); } return _.guidance_scale !== null && _.guidance_scale > 1 && Se.push(new v.ClassifierFreeGuidanceLogitsProcessor(_.guidance_scale)), xe !== null && Se.extend(xe), Se; } /** * 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 {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters. * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object. * @returns {GenerationConfig} The final generation config object to be used by the model for text generation. */ _prepare_generation_config(_, Q, xe = b.GenerationConfig) { const Se = { ...this.config }; for (const rt of ["decoder", "generator", "text_config"]) rt in Se && Object.assign(Se, Se[rt]); const Be = new xe(Se); return Object.assign(Be, this.generation_config ?? {}), _ && Object.assign(Be, _), Q && Object.assign(Be, (0, N.pick)(Q, Object.getOwnPropertyNames(Be))), Be; } /** * * @param {GenerationConfig} generation_config * @param {StoppingCriteriaList} [stopping_criteria=null] */ _get_stopping_criteria(_, Q = null) { const xe = new re.StoppingCriteriaList(); return _.max_length !== null && xe.push(new re.MaxLengthCriteria( _.max_length, this.config.max_position_embeddings ?? null )), _.eos_token_id !== null && xe.push(new re.EosTokenCriteria(_.eos_token_id)), Q && xe.extend(Q), xe; } /** * Confirms that the model class is compatible with generation. * If not, raises an exception that points to the right class to use. */ _validate_model_class() { if (!this.can_generate) { const _ = [ ma, // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO ga, Eo, $d ], Q = P.get(this.constructor), xe = /* @__PURE__ */ new Set(), Se = this.config.model_type; for (const rt of _) { const ot = rt.get(Se); ot && xe.add(ot[0]); } let Be = `The current model class (${Q}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; throw xe.size > 0 && (Be += ` Please use the following class instead: ${[...xe].join(", ")}`), Error(Be); } } prepare_inputs_for_generation(..._) { return this._prepare_inputs_for_generation(this, ..._); } /** * * @param {Object} inputs * @param {bigint[][]} inputs.generated_input_ids * @param {Object} inputs.outputs * @param {Object} inputs.model_inputs * @param {boolean} inputs.is_encoder_decoder * @returns {Object} The updated model inputs for the next generation iteration. */ _update_model_kwargs_for_generation({ generated_input_ids: _, outputs: Q, model_inputs: xe, is_encoder_decoder: Se }) { return xe.past_key_values = this.getPastKeyValues(Q, xe.past_key_values), xe.input_ids = new x.Tensor("int64", _.flat(), [_.length, 1]), Se || (xe.attention_mask = (0, x.cat)( [ xe.attention_mask, (0, x.ones)([xe.attention_mask.dims[0], 1]) ], 1 )), xe.position_ids = null, xe; } /** * This function extracts the model-specific `inputs` for generation. * @param {Object} params * @param {Tensor} [params.inputs=null] * @param {number} [params.bos_token_id=null] * @param {Record} [params.model_kwargs] * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation. */ _prepare_model_inputs({ inputs: _, bos_token_id: Q, model_kwargs: xe }) { const Se = (0, N.pick)(xe, this.forward_params), Be = this.main_input_name; if (Be in Se) { if (_) throw new Error( "`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=..." ); } else Se[Be] = _; return { inputs_tensor: Se[Be], model_inputs: Se, model_input_name: Be }; } async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor: _, model_inputs: Q, model_input_name: xe, generation_config: Se }) { if (this.sessions.model.inputNames.includes("inputs_embeds") && !Q.inputs_embeds && "_prepare_inputs_embeds" in this) { const { input_ids: rt, pixel_values: ot, attention_mask: ft, ...$t } = Q, Jt = await this._prepare_inputs_embeds(Q); Q = { ...$t, ...(0, N.pick)(Jt, ["inputs_embeds", "attention_mask"]) }; } let { last_hidden_state: Be } = await $e(this, Q); if (Se.guidance_scale !== null && Se.guidance_scale > 1) Be = (0, x.cat)([ Be, (0, x.full_like)(Be, 0) ], 0), "attention_mask" in Q && (Q.attention_mask = (0, x.cat)([ Q.attention_mask, (0, x.zeros_like)(Q.attention_mask) ], 0)); else if (Q.decoder_input_ids) { const rt = be(Q.decoder_input_ids).dims[0]; if (rt !== Be.dims[0]) { if (Be.dims[0] !== 1) throw new Error( `The encoder outputs have a different batch size (${Be.dims[0]}) than the decoder inputs (${rt}).` ); Be = (0, x.cat)(Array.from({ length: rt }, () => Be), 0); } } return Q.encoder_outputs = Be, Q; } /** * Prepares `decoder_input_ids` for generation with encoder-decoder models * @param {*} param0 */ _prepare_decoder_input_ids_for_generation({ batch_size: _, model_input_name: Q, model_kwargs: xe, decoder_start_token_id: Se, bos_token_id: Be, generation_config: rt }) { let { decoder_input_ids: ot, ...ft } = xe; if (!(ot instanceof x.Tensor)) { if (ot) Array.isArray(ot[0]) || (ot = Array.from({ length: _ }, () => ot)); else if (Se ??= Be, this.config.model_type === "musicgen") ot = Array.from({ // @ts-expect-error TS2339 length: _ * this.config.decoder.num_codebooks }, () => [Se]); else if (Array.isArray(Se)) { if (Se.length !== _) throw new Error( `\`decoder_start_token_id\` expcted to have length ${_} but got ${Se.length}` ); ot = Se; } else ot = Array.from({ length: _ }, () => [Se]); ot = be(ot); } return xe.decoder_attention_mask = (0, x.ones_like)(ot), { input_ids: ot, model_inputs: ft }; } /** * Generates sequences of token ids for models with a language modeling head. * @param {import('./generation/parameters.js').GenerationFunctionParameters} options * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. */ async generate({ inputs: _ = null, generation_config: Q = null, logits_processor: xe = null, stopping_criteria: Se = null, streamer: Be = null, // inputs_attention_mask = null, ...rt }) { this._validate_model_class(), Q = this._prepare_generation_config(Q, rt); let { inputs_tensor: ot, model_inputs: ft, model_input_name: $t } = this._prepare_model_inputs({ inputs: _, model_kwargs: rt }); const Jt = this.config.is_encoder_decoder; Jt && ("encoder_outputs" in ft || (ft = await this._prepare_encoder_decoder_kwargs_for_generation( { inputs_tensor: ot, model_inputs: ft, model_input_name: $t, generation_config: Q } ))); let qt; Jt ? { input_ids: qt, model_inputs: ft } = this._prepare_decoder_input_ids_for_generation({ batch_size: ft[$t].dims.at(0), model_input_name: $t, model_kwargs: ft, decoder_start_token_id: Q.decoder_start_token_id, bos_token_id: Q.bos_token_id, generation_config: Q }) : qt = ft[$t]; let Dt = qt.dims.at(-1); Q.max_new_tokens !== null && (Q.max_length = Dt + Q.max_new_tokens); const It = this._get_logits_processor( Q, Dt, xe ), vs = this._get_stopping_criteria( Q, Se ), Qt = ft[$t].dims.at(0), Gt = ie.LogitsSampler.getSampler(Q), fs = new Array(Qt).fill(0), Ms = qt.tolist(); Be && Be.put(Ms); let Zt, Bs = {}; for (; ; ) { if (ft = this.prepare_inputs_for_generation(Ms, ft, Q), Zt = await this.forward(ft), Q.output_attentions && Q.return_dict_in_generate) { const or = this.getAttentions(Zt); for (const $r in or) $r in Bs || (Bs[$r] = []), Bs[$r].push(or[$r]); } const Ns = Zt.logits.slice(null, -1, null), rr = It(Ms, Ns), wr = []; for (let or = 0; or < rr.dims.at(0); ++or) { const $r = rr[or], Mn = await Gt($r); for (const [Co, Vn] of Mn) { const Un = BigInt(Co); fs[or] += Vn, Ms[or].push(Un), wr.push([Un]); break; } } if (Be && Be.put(wr), vs(Ms).every((or) => or)) break; ft = this._update_model_kwargs_for_generation({ generated_input_ids: wr, outputs: Zt, model_inputs: ft, is_encoder_decoder: Jt }); } Be && Be.end(); const Rs = this.getPastKeyValues(Zt, ft.past_key_values, !0), $s = new x.Tensor("int64", Ms.flat(), [Ms.length, Ms[0].length]); if (Q.return_dict_in_generate) return { sequences: $s, past_key_values: Rs, ...Bs // TODO: // scores, // logits, }; for (const Ns of Object.values(Zt)) Ns.location === "gpu-buffer" && Ns.dispose(); return $s; } /** * 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(_, Q, xe = !1) { const Se = /* @__PURE__ */ Object.create(null); for (const Be in _) if (Be.startsWith("present")) { const rt = Be.replace("present", "past_key_values"), ot = Be.includes("encoder"); if (ot && Q ? Se[rt] = Q[rt] : Se[rt] = _[Be], Q && (!ot || xe)) { const ft = Q[rt]; ft.location === "gpu-buffer" && ft.dispose(); } } return Se; } /** * Returns an object containing attentions from the given model output object. * * @param {Object} model_output The output of the model. * @returns {{cross_attentions?: Tensor[]}} An object containing attentions. */ getAttentions(_) { const Q = {}; for (const xe of ["cross_attentions", "encoder_attentions", "decoder_attentions"]) for (const Se in _) Se.startsWith(xe) && (xe in Q || (Q[xe] = []), Q[xe].push(_[Se])); return Q; } /** * 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(_, Q) { if (Q) Object.assign(_, Q); else { const Se = (this.sessions.decoder_model_merged ?? this.sessions.model)?.config?.kv_cache_dtype ?? "float32", Be = Se === "float16" ? new Uint16Array() : [], rt = (_[this.main_input_name] ?? _.attention_mask)?.dims?.[0] ?? 1, ot = (0, g.getKeyValueShapes)(this.config, { batch_size: rt }); for (const ft in ot) _[ft] = new x.Tensor(Se, Be, ot[ft]); } } async encode_image({ pixel_values: _ }) { const Q = (await ge(this.sessions.vision_encoder, { pixel_values: _ })).image_features; return this.config.num_image_tokens || (console.warn( `The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${Q.dims[1]}).` ), this.config.num_image_tokens = Q.dims[1]), Q; } async encode_text({ input_ids: _ }) { return (await ge(this.sessions.embed_tokens, { input_ids: _ })).inputs_embeds; } } class We { } class Ne extends We { /** * @param {Object} output The output of the model. * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. */ constructor({ last_hidden_state: _, hidden_states: Q = null, attentions: xe = null }) { super(), this.last_hidden_state = _, this.hidden_states = Q, this.attentions = xe; } } class te extends J { } class ve extends te { } class He extends te { /** * 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(_) { return new Qs(await super._call(_)); } } class je extends te { /** * 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(_) { return new Ht(await super._call(_)); } } class Ve extends te { /** * 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(_) { return new Ss(await super._call(_)); } } class Re extends te { /** * 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(_) { return new Ys(await super._call(_)); } } class Ze extends J { } class at extends Ze { } class _t extends Ze { /** * 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(_) { return new Qs(await super._call(_)); } } class lt extends Ze { /** * 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(_) { return new Ht(await super._call(_)); } } class ct extends Ze { /** * 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(_) { return new Ss(await super._call(_)); } } class F extends J { } class ae extends F { } class H extends J { } class me extends H { } class ke extends H { /** * 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(_) { return new Qs(await super._call(_)); } } class ze extends H { /** * 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(_) { return new Ht(await super._call(_)); } } class Ge extends H { /** * 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(_) { return new Ss(await super._call(_)); } } class tt extends H { /** * 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(_) { return new Ys(await super._call(_)); } } class et extends J { } class mt extends et { } class Nt extends et { /** * 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(_) { return new Qs(await super._call(_)); } } class es extends et { /** * 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(_) { return new Ht(await super._call(_)); } } class Ts extends et { /** * 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(_) { return new Ss(await super._call(_)); } } class ms extends et { /** * 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(_) { return new Ys(await super._call(_)); } } class Ps extends J { } class Is extends Ps { } class tr extends Ps { /** * 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(_) { return new Qs(await super._call(_)); } } class xr extends Ps { /** * 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(_) { return new Ht(await super._call(_)); } } class Gr extends Ps { /** * 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(_) { return new Ss(await super._call(_)); } } class Vs extends Ps { /** * 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(_) { return new Ys(await super._call(_)); } } class yr extends J { } class Lt extends yr { } class Kr extends yr { /** * 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(_) { return new Qs(await super._call(_)); } } class Tr extends yr { /** * 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(_) { return new Ht(await super._call(_)); } } class Pr extends yr { /** * 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(_) { return new Ss(await super._call(_)); } } class Hr extends yr { /** * 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(_) { return new Ys(await super._call(_)); } } class lr extends J { } class Fr extends lr { } class Er extends lr { /** * 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(_) { return new Qs(await super._call(_)); } } class Or extends lr { /** * 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(_) { return new Ht(await super._call(_)); } } class Dr extends lr { /** * 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(_) { return new Ss(await super._call(_)); } } class ir extends lr { /** * 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(_) { return new Ys(await super._call(_)); } } class nt extends J { } class vt extends nt { } class Ft extends nt { /** * 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(_) { return new Qs(await super._call(_)); } } class Zs extends nt { /** * 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(_) { return new Ht(await super._call(_)); } } class Pn extends nt { /** * 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(_) { return new Ss(await super._call(_)); } } class cn extends nt { /** * 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(_) { return new Ys(await super._call(_)); } } class ws extends J { } class Mr extends ws { } class zs extends ws { /** * 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(_) { return new Ht(await super._call(_)); } } class qr extends ws { /** * 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(_) { return new Ss(await super._call(_)); } } class ss extends ws { /** * 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(_) { return new Ys(await super._call(_)); } } class pn extends ws { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class Lr extends J { } class eo extends Lr { } class En extends Lr { /** * 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(_) { return new Qs(await super._call(_)); } } class Cn extends Lr { /** * 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(_) { return new Ht(await super._call(_)); } } class kn extends Lr { /** * 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(_) { return new Ss(await super._call(_)); } } class zr extends J { } class Sn extends zr { } class to extends zr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class Br extends zr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class pr extends zr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class ar extends J { } class hn extends ar { } class Qr extends ar { /** * 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(_) { return new Qs(await super._call(_)); } } class mn extends ar { /** * 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(_) { return new Ht(await super._call(_)); } } class _n extends ar { /** * 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(_) { return new Ss(await super._call(_)); } } class fn extends ar { /** * 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(_) { return new Ys(await super._call(_)); } } class Ot extends J { } class gn extends Ot { } class $n extends Ot { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class An extends Ot { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class In extends Ot { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class Rr extends J { } class Fn extends Rr { } class wn extends Rr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class On extends Rr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class as extends Rr { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class Te extends J { forward_params = [ "input_ids", "attention_mask", "encoder_outputs", "decoder_input_ids", "decoder_attention_mask", "past_key_values" ]; } class M extends Te { } class Y extends Te { } class ce extends J { } class _e extends ce { } class Fe extends ce { } class Ye extends J { } class gt extends Ye { } class wt extends Ye { } class yt extends J { } class ht extends yt { } class ts extends yt { } class Xt extends yt { /** * 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(_) { return new Ht(await super._call(_)); } } class bs extends J { } class Ks extends bs { } class jt extends bs { } class rs extends bs { /** * 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(_) { return new Ht(await super._call(_)); } } class Hs extends bs { } class er extends J { } class De extends er { } class Xs extends er { } class Cr extends J { } class Es extends Cr { } class qs extends Cr { } class At extends J { } class nr extends At { } class hr extends At { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class ds extends At { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class Cs extends At { /** * 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(_) { return new Ss(await super._call(_)); } } class Mt extends At { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class Wt extends J { } class Fs extends Wt { } class ks extends Wt { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class Us extends Wt { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class Pt extends Wt { /** * 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(_) { return new Ss(await super._call(_)); } } class Xr extends Wt { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class qe extends J { } class St extends qe { } class ka extends qe { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Qs(await super._call(_)); } } class Do extends qe { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ht(await super._call(_)); } } class Sa extends qe { /** * 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(_) { return new Ss(await super._call(_)); } } class $a extends qe { /** * Calls the model on new inputs. * * @param {Object} model_inputs The inputs to the model. * @returns {Promise} returned object */ async _call(_) { return new Ys(await super._call(_)); } } class Kt extends J { } class Aa extends Kt { } class Lo extends Kt { } class zo extends J { requires_attention_mask = !1; main_input_name = "input_features"; forward_params = [ "input_features", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "past_key_values" ]; } class Ia extends zo { } class Fa extends zo { _prepare_generation_config(_, Q) { return ( /** @type {WhisperGenerationConfig} */ super._prepare_generation_config(_, Q, U.WhisperGenerationConfig) ); } /** * * @param {WhisperGenerationConfig} generation_config */ _retrieve_init_tokens(_) { const Q = [_.decoder_start_token_id]; let xe = _.language; const Se = _.task; if (_.is_multilingual) { xe || (console.warn("No language specified - defaulting to English (en)."), xe = "en"); const rt = `<|${(0, q.whisper_language_to_code)(xe)}|>`; Q.push(_.lang_to_id[rt]), Q.push(_.task_to_id[Se ?? "transcribe"]); } else if (xe || Se) throw new Error( "Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config." ); return !_.return_timestamps && _.no_timestamps_token_id && Q.at(-1) !== _.no_timestamps_token_id ? Q.push(_.no_timestamps_token_id) : _.return_timestamps && Q.at(-1) === _.no_timestamps_token_id && (console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."), Q.pop()), Q.filter((Be) => Be != null); } /** * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. */ async generate({ inputs: _ = null, generation_config: Q = null, logits_processor: xe = null, stopping_criteria: Se = null, // Whisper-specific options (passed to kwargs) // prompt_ids = null, // language = null, // task = null, ...Be }) { Q = this._prepare_generation_config(Q, Be); const rt = Be.decoder_input_ids ?? this._retrieve_init_tokens(Q); if (Q.return_timestamps && (xe ??= new v.LogitsProcessorList(), xe.push( new v.WhisperTimeStampLogitsProcessor(Q, rt) )), Q.begin_suppress_tokens && (xe ??= new v.LogitsProcessorList(), xe.push( new v.SuppressTokensAtBeginLogitsProcessor(Q.begin_suppress_tokens, rt.length) )), Q.return_token_timestamps) { if (!Q.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." ); Q.task === "translate" && console.warn("Token-level timestamps may not be reliable for task 'translate'."), Q.output_attentions = !0, Q.return_dict_in_generate = !0; } const ot = await super.generate({ inputs: _, generation_config: Q, logits_processor: xe, decoder_input_ids: rt, ...Be }); return Q.return_token_timestamps && (ot.token_timestamps = this._extract_token_timestamps( // @ts-expect-error TS2345 ot, Q.alignment_heads, Q.num_frames )), ot; } /** * 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. * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. * @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.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(_, Q, xe = null, Se = 0.02) { if (!_.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`." ); xe == null && console.warn( "`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds)." ); let Be = this.config.median_filter_width; Be === void 0 && (console.warn("Model config has no `median_filter_width`, using default value of 7."), Be = 7); const rt = _.cross_attentions, ot = Array.from( { length: this.config.decoder_layers }, // Concatenate the cross attentions for each layer across sequence length dimension. (Qt, Gt) => (0, x.cat)(rt.map((fs) => fs[Gt]), 2) ), ft = (0, x.stack)(Q.map(([Qt, Gt]) => { if (Qt >= ot.length) throw new Error(`Layer index ${Qt} is out of bounds for cross attentions (length ${ot.length}).`); return xe ? ot[Qt].slice(null, Gt, null, [0, xe]) : ot[Qt].slice(null, Gt); })).transpose(1, 0, 2, 3), [$t, Jt] = (0, x.std_mean)(ft, -2, 0, !0), qt = ft.clone(); for (let Qt = 0; Qt < qt.dims[0]; ++Qt) { const Gt = qt[Qt]; for (let fs = 0; fs < Gt.dims[0]; ++fs) { const Ms = Gt[fs], Zt = $t[Qt][fs][0].data, Bs = Jt[Qt][fs][0].data; for (let Rs = 0; Rs < Ms.dims[0]; ++Rs) { let $s = Ms[Rs].data; for (let Ns = 0; Ns < $s.length; ++Ns) $s[Ns] = ($s[Ns] - Bs[Ns]) / Zt[Ns]; $s.set((0, K.medianFilter)($s, Be)); } } } const Dt = [(0, x.mean)(qt, 1)], It = _.sequences.dims, vs = new x.Tensor( "float32", new Float32Array(It[0] * It[1]), It ); for (let Qt = 0; Qt < It[0]; ++Qt) { const Gt = Dt[Qt].neg().squeeze_(0), [fs, Ms] = (0, K.dynamic_time_warping)(Gt.tolist()), Zt = Array.from({ length: fs.length - 1 }, ($s, Ns) => fs[Ns + 1] - fs[Ns]), Bs = (0, N.mergeArrays)([1], Zt).map(($s) => !!$s), Rs = []; for (let $s = 0; $s < Bs.length; ++$s) Bs[$s] && Rs.push(Ms[$s] * Se); vs[Qt].data.set(Rs, 1); } return vs; } } class Bo extends J { requires_attention_mask = !1; main_input_name = "input_values"; forward_params = [ "input_values", "decoder_input_ids", "past_key_values" ]; } class ur extends Bo { } class Oa extends Bo { } class Ro extends J { main_input_name = "pixel_values"; forward_params = [ // Encoder inputs "pixel_values", // Decoder inpputs "decoder_input_ids", "encoder_hidden_states", "past_key_values" ]; } class Nr extends J { forward_params = [ "input_ids", "attention_mask", "pixel_values", "position_ids", "past_key_values" ]; } class so extends Nr { _merge_input_ids_with_image_features({ inputs_embeds: _, image_features: Q, input_ids: xe, attention_mask: Se }) { const Be = this.config.image_token_index, ot = xe.tolist().map((Dt) => Dt.findIndex((It) => It == Be)), ft = ot.every((Dt) => Dt === -1), $t = ot.every((Dt) => Dt !== -1); if (!ft && !$t) throw new Error("Every input should contain either 0 or 1 image token."); if (ft) return { inputs_embeds: _, attention_mask: Se }; const Jt = [], qt = []; for (let Dt = 0; Dt < ot.length; ++Dt) { const It = ot[Dt], vs = _[Dt], Qt = Q[Dt], Gt = Se[Dt]; Jt.push( (0, x.cat)([ vs.slice([0, It]), Qt, vs.slice([It + 1, vs.dims[0]]) ], 0) ), qt.push( (0, x.cat)([ Gt.slice([0, It]), (0, x.ones)([Qt.dims[0]]), Gt.slice([It + 1, Gt.dims[0]]) ], 0) ); } return { inputs_embeds: (0, x.stack)(Jt, 0), attention_mask: (0, x.stack)(qt, 0) }; } } class Da extends so { } class La extends so { } class za extends J { forward_params = [ // Encoder inputs "input_ids", "inputs_embeds", "attention_mask", "pixel_values", // Decoder inputs "encoder_outputs", "decoder_input_ids", "decoder_inputs_embeds", "decoder_attention_mask", "past_key_values" ]; main_input_name = "inputs_embeds"; } class Ba extends za { _merge_input_ids_with_image_features({ inputs_embeds: _, image_features: Q, input_ids: xe, attention_mask: Se }) { return { inputs_embeds: (0, x.cat)([ Q, // image embeds _ // task prefix embeds ], 1), attention_mask: (0, x.cat)([ (0, x.ones)(Q.dims.slice(0, 2)), // image attention mask Se // task prefix attention mask ], 1) }; } async _prepare_inputs_embeds({ input_ids: _, pixel_values: Q, inputs_embeds: xe, attention_mask: Se }) { if (!_ && !Q) throw new Error("Either `input_ids` or `pixel_values` should be provided."); let Be, rt; return _ && (Be = await this.encode_text({ input_ids: _ })), Q && (rt = await this.encode_image({ pixel_values: Q })), Be && rt ? { inputs_embeds: xe, attention_mask: Se } = this._merge_input_ids_with_image_features({ inputs_embeds: Be, image_features: rt, input_ids: _, attention_mask: Se }) : xe = Be || rt, { inputs_embeds: xe, attention_mask: Se }; } async forward({ input_ids: _, pixel_values: Q, attention_mask: xe, decoder_input_ids: Se, decoder_attention_mask: Be, encoder_outputs: rt, past_key_values: ot, inputs_embeds: ft, decoder_inputs_embeds: $t }) { if (ft || ({ inputs_embeds: ft, attention_mask: xe } = await this._prepare_inputs_embeds({ input_ids: _, pixel_values: Q, inputs_embeds: ft, attention_mask: xe })), !rt) { let { last_hidden_state: Dt } = await $e(this, { inputs_embeds: ft, attention_mask: xe }); rt = Dt; } if (!$t) { if (!Se) throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided."); $t = await this.encode_text({ input_ids: Se }); } return await Pe(this, { inputs_embeds: $t, attention_mask: Be, encoder_attention_mask: xe, encoder_hidden_states: rt, past_key_values: ot }, !0); } } class Ra extends J { forward_params = [ "input_ids", // 'inputs_embeds', "attention_mask", "pixel_values", "position_ids", "past_key_values" ]; } class Na extends Ra { _merge_input_ids_with_image_features(_) { const Q = _.image_features.dims.at(-1), xe = _.image_features.view(-1, Q); return Je({ // @ts-ignore image_token_id: this.config.image_token_index, ..._, image_features: xe }); } } class ja extends J { forward_params = [ "input_ids", "attention_mask", "pixel_values", "pixel_attention_mask", "position_ids", "past_key_values" ]; } class No extends ja { async encode_image({ pixel_values: _, pixel_attention_mask: Q }) { return (await ge(this.sessions.vision_encoder, { pixel_values: _, pixel_attention_mask: Q })).image_features; } _merge_input_ids_with_image_features(_) { const Q = _.image_features.dims.at(-1), xe = _.image_features.view(-1, Q); return Je({ // @ts-ignore image_token_id: this.config.image_token_id, ..._, image_features: xe }); } } class Va extends J { forward_params = [ "input_ids", "inputs_embeds", "attention_mask", "position_ids", "pixel_values", "image_sizes", "past_key_values" ]; } class dr extends Va { async forward({ // Produced by the tokenizer/processor: input_ids: _ = null, attention_mask: Q = null, pixel_values: xe = null, image_sizes: Se = null, // Used during generation: position_ids: Be = null, inputs_embeds: rt = null, past_key_values: ot = null, // Generic generation parameters generation_config: ft = null, logits_processor: $t = null, // TODO: needed? ...Jt }) { if (!rt) { let Dt; if (xe && _.dims[1] !== 1) { if (!Se) throw new Error("`image_sizes` must be provided when `pixel_values` is provided."); ({ image_features: Dt } = await ge(this.sessions.vision_encoder, { pixel_values: xe, image_sizes: Se })); } else { const It = this.config.normalized_config.hidden_size; Dt = new x.Tensor( "float32", [], [0, It] ); } ({ inputs_embeds: rt } = await ge(this.sessions.prepare_inputs_embeds, { input_ids: _, image_features: Dt })); } return await Pe(this, { inputs_embeds: rt, past_key_values: ot, attention_mask: Q, position_ids: Be, generation_config: ft, logits_processor: $t }, !1); } } class Yr extends J { } class Ua extends Yr { } class lc extends Yr { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "text_model" }); } } class Wa extends Yr { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "text_model" }); } } class uc extends Yr { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "vision_model" }); } } class Ga extends Yr { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "vision_model" }); } } class jo extends J { } class Ka extends jo { } class Ha extends jo { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "text_model" }); } } class qa extends Yr { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "vision_model" }); } } class dc extends J { } class mr extends dc { } class ro extends J { } class no extends ro { async forward(_) { const Q = !_.input_ids, xe = !_.pixel_values; if (Q && xe) throw new Error("Either `input_ids` or `pixel_values` should be provided."); if (Q && (_.input_ids = (0, x.ones)([_.pixel_values.dims[0], 1])), xe) { const { image_size: $t } = this.config.vision_config; _.pixel_values = (0, x.full)([0, 3, $t, $t], 0); } const { text_embeddings: Se, image_embeddings: Be, l2norm_text_embeddings: rt, l2norm_image_embeddings: ot } = await super.forward(_), ft = {}; return Q || (ft.text_embeddings = Se, ft.l2norm_text_embeddings = rt), xe || (ft.image_embeddings = Be, ft.l2norm_image_embeddings = ot), ft; } } class Vo extends ro { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "text_model" }); } } class _r extends ro { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "vision_model" }); } } class Uo extends J { } class Qa extends Uo { } class Xa extends Uo { } class Wo extends J { } class Ya extends Wo { } class Ja extends Wo { } class Go extends J { } class Za extends Go { } class el extends Go { } class Ko extends J { } class fr extends Ko { } class tl extends Ko { } class Ho extends J { } class sl extends Ho { } class rl extends Ho { } class qo extends J { } class nl extends qo { } class ol extends qo { } class Qo extends J { } class il extends Qo { } class al extends Qo { } class oo extends J { } class Xo extends oo { } class ll extends oo { } class Yo extends J { } class Jo extends Yo { } class cc extends Yo { } class Zo extends J { } class io extends Zo { } class ul extends Zo { } class ei extends J { } class dl extends ei { } class Dn extends ei { } class ti extends J { } class cl extends ti { } class si extends ti { } class ri extends J { } class pl extends ri { } class hl extends ri { } class ni extends J { } class pc extends ni { } class ml extends ni { } class oi extends J { } class _l extends oi { } class hc extends oi { } class ii extends J { } class ls extends ii { } class fl extends ii { } class ai extends J { } class gl extends ai { } class wl extends ai { } class li extends J { } class yl extends li { } class Ml extends li { } class ui extends J { } class bl extends ui { } class vl extends ui { } class di extends J { } class xl extends di { } class Tl extends di { } class ci extends J { } class Ln extends ci { } class Pl extends ci { } class ao extends J { forward_params = [ // Text inputs "input_ids", "attention_mask", "position_ids", "past_key_values", // Vision inputs "pixel_values", "image_grid_thw" ]; } class El extends ao { /** * Calculate the 3D rope index based on image and video's temporal, height and width in LLM. * * Explanation: * Each embedding sequence contains vision embedding and text embedding or just contains text embedding. * * For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs. * Examples: * input_ids: [T T T T T], here T is for text. * temporal position_ids: [0, 1, 2, 3, 4] * height position_ids: [0, 1, 2, 3, 4] * width position_ids: [0, 1, 2, 3, 4] * * For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part * and 1D rotary position embeddin for text part. * Examples: * Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. * input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. * vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] * vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] * vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] * text temporal position_ids: [3, 4, 5, 6, 7] * text height position_ids: [3, 4, 5, 6, 7] * text width position_ids: [3, 4, 5, 6, 7] * Here we calculate the text start position_ids as the max vision position_ids plus 1. * * @param {Tensor} input_ids Indices of input sequence tokens in the vocabulary. Tensor of shape `(batch_size, sequence_length)`. * @param {Tensor} image_grid_thw (Optional) The temporal, height and width of feature shape of each image in LLM. Tensor of shape `(num_images, 3)`. * @param {Tensor} video_grid_thw (Optional) The temporal, height and width of feature shape of each video in LLM. Tensor of shape `(num_videos, 3)`. * @param {Tensor} attention_mask (Optional) Mask to avoid performing attention on padding token indices. Tensor of shape `(batch_size, sequence_length)`. Mask values selected in `[0, 1]`: * - 1 for tokens that are **not masked**, * - 0 for tokens that are **masked**. * @returns {[Tensor, Tensor]} [position_ids, mrope_position_deltas] with: * - position_ids: Tensor of shape `(3, batch_size, sequence_length)`. * - mrope_position_deltas: Tensor of shape `(batch_size)`. */ get_rope_index(_, Q, xe, Se) { const { vision_config: Be, image_token_id: rt, video_token_id: ot, vision_start_token_id: ft } = this.config, $t = Be.spatial_merge_size ?? 2, Jt = []; if (Q || xe) { let qt = _.tolist(); Se || (Se = (0, x.ones_like)(_)); const Dt = Se.tolist(), It = Array.from({ length: 3 }, (Ms) => Array.from({ length: _.dims[0] }, (Zt) => Array.from({ length: _.dims[1] }, (Bs) => 1))), vs = Q ? Q.tolist() : [], Qt = xe ? xe.tolist() : []; let Gt = 0, fs = 0; for (let Ms = 0; Ms < qt.length; ++Ms) { const Zt = qt[Ms].filter((xs, Os) => Dt[Ms][Os] == 1), Rs = Zt.reduce((xs, Os, Vr) => (Os == ft && xs.push(Vr), xs), []).map((xs) => Zt[xs + 1]), $s = Rs.filter((xs) => xs == rt).length, Ns = Rs.filter((xs) => xs == ot).length; let rr = [], wr = 0, ya = $s, or = Ns; for (let xs = 0; xs < Rs.length; ++xs) { const Os = Zt.findIndex((Wr, cr) => cr > wr && Wr == rt), Vr = Zt.findIndex((Wr, cr) => cr > wr && Wr == ot), on = ya > 0 && Os !== -1 ? Os : Zt.length + 1, Wn = or > 0 && Vr !== -1 ? Vr : Zt.length + 1; let ko, Gn, Ma, ba; on < Wn ? ([Gn, Ma, ba] = vs[Gt], ++Gt, --ya, ko = on) : ([Gn, Ma, ba] = Qt[fs], ++fs, --or, ko = Wn); const [jp, va, Kn] = [ Number(Gn), Math.floor(Number(Ma) / $t), Math.floor(Number(ba) / $t) ], So = ko - wr, Ur = rr.length > 0 ? (0, K.max)(rr.at(-1))[0] + 1 : 0; rr.push( Array.from({ length: 3 * So }, (Wr, cr) => Ur + cr % So) ); const xa = So + Ur, bn = jp * va * Kn, Jd = Array.from({ length: bn }, (Wr, cr) => xa + Math.floor(cr / (va * Kn))), Zd = Array.from({ length: bn }, (Wr, cr) => xa + Math.floor(cr / Kn) % va), ec = Array.from({ length: bn }, (Wr, cr) => xa + cr % Kn); rr.push([Jd, Zd, ec].flat()), wr = ko + bn; } if (wr < Zt.length) { const xs = rr.length > 0 ? (0, K.max)(rr.at(-1))[0] + 1 : 0, Os = Zt.length - wr; rr.push( Array.from({ length: 3 * Os }, (Vr, on) => xs + on % Os) ); } const $r = rr.reduce((xs, Os) => xs + Os.length, 0), Mn = new Array($r); let Co = 0; for (let xs = 0; xs < 3; ++xs) for (let Os = 0; Os < rr.length; ++Os) { const Vr = rr[Os], on = Vr.length / 3; for (let Wn = xs * on; Wn < (xs + 1) * on; ++Wn) Mn[Co++] = Vr[Wn]; } let Vn = 0; const Un = Dt[Ms]; for (let xs = 0; xs < Un.length; ++xs) if (Un[xs] == 1) { for (let Os = 0; Os < 3; ++Os) It[Os][Ms][xs] = Mn[Os * $r / 3 + Vn]; ++Vn; } const wp = (0, K.max)(Mn)[0]; Jt.push(wp + 1 - qt[Ms].length); } return [ new x.Tensor("int64", It.flat(1 / 0), [3, _.dims[0], _.dims[1]]), new x.Tensor("int64", Jt, [Jt.length, 1]) ]; } else if (Se) { const { data: qt, dims: Dt } = we(Se), It = BigInt64Array.from( { length: 3 * qt.length }, (Qt, Gt) => qt[Gt % qt.length] ), vs = Array.from( { length: Dt[0] }, (Qt, Gt) => (0, K.max)(qt.subarray(Dt[1] * Gt, Dt[1] * (Gt + 1)))[0] + 1n + BigInt(Dt[1]) ); return [ new x.Tensor("int64", It, [3, ...Dt]), new x.Tensor("int64", vs, [vs.length, 1]) ]; } else { const [qt, Dt] = _.dims, It = BigInt64Array.from( { length: 3 * qt * Dt }, (vs, Qt) => BigInt(Math.floor(Qt % Dt / qt)) ); return [ new x.Tensor("int64", It, [3, ..._.dims]), (0, x.zeros)([qt, 1]) ]; } } async encode_image({ pixel_values: _, image_grid_thw: Q }) { return (await ge(this.sessions.vision_encoder, { pixel_values: _, grid_thw: Q })).image_features; } _merge_input_ids_with_image_features(_) { return Je({ // @ts-ignore image_token_id: this.config.image_token_id, ..._ }); } prepare_inputs_for_generation(_, Q, xe) { if (Q.attention_mask && !Q.position_ids) if (!Q.past_key_values) [Q.position_ids, Q.rope_deltas] = this.get_rope_index( Q.input_ids, Q.image_grid_thw, Q.video_grid_thw, Q.attention_mask ); else { Q.pixel_values = null; const Se = BigInt(Object.values(Q.past_key_values)[0].dims.at(-2)), Be = Q.rope_deltas.map((rt) => Se + rt); Q.position_ids = (0, x.stack)([Be, Be, Be], 0); } return Q; } } class pi extends J { } class Cl extends pi { } class kl extends pi { } class hi extends J { } class Sl extends hi { } class $l extends hi { } class mi extends J { } class Al extends mi { } class Il extends mi { } class _i extends J { } class Fl extends _i { } class Ol extends _i { } class fi extends J { } class Dl extends fi { } class Ll extends fi { } class lo extends J { } class zl extends lo { } class gi extends lo { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class uo extends J { } class Bl extends uo { } class Rl extends uo { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Nl extends J { } class jl extends Nl { } class wi extends J { } class Vl extends wi { } class yi extends wi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Ul extends J { } class Wl extends Ul { } class Mi extends J { } class mc extends Mi { } class Gl extends Mi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Kl extends J { } class gr extends Kl { } class bi extends J { } class Hl extends bi { } class ql extends bi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Ql extends J { } class Xl extends Ql { /** * @param {any} model_inputs */ async _call(_) { return new Xd(await super._call(_)); } } class vi extends J { } class Yl extends vi { } class Jl extends vi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class xi extends J { } class Zl extends xi { } class _c extends xi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Ti extends J { } class eu extends Ti { } class tu extends Ti { } class Pi extends J { } class su extends Pi { } class ru extends Pi { } class nu extends J { } class Jr extends nu { } class Zr extends nu { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class kr extends J { } class Ei extends kr { } class en extends kr { /** * @param {any} model_inputs */ async _call(_) { return new Ci(await super._call(_)); } } class Ws extends kr { /** * Runs the model with the provided inputs * @param {Object} model_inputs Model inputs * @returns {Promise} Object containing segmentation outputs */ async _call(_) { return new ki(await super._call(_)); } } class Ci extends We { /** * @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: Q }) { super(), this.logits = _, this.pred_boxes = Q; } } class ki extends We { /** * @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: Q, pred_masks: xe }) { super(), this.logits = _, this.pred_boxes = Q, this.pred_masks = xe; } } class Si extends J { } class fc extends Si { } class zn extends Si { /** * @param {any} model_inputs */ async _call(_) { return new $i(await super._call(_)); } } class $i extends We { /** * @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: Q }) { super(), this.logits = _, this.pred_boxes = Q; } } class co extends J { } class ou extends co { } class iu extends co { /** * @param {any} model_inputs */ async _call(_) { return new Ai(await super._call(_)); } } class Ai extends Ci { } class po extends J { } class au extends po { } class Ii extends po { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Fi extends J { } class ho extends Fi { } class Oi extends Fi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Di extends J { } class lu extends Di { } class gc extends Di { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Li extends J { } class zi extends Li { } class Bn extends Li { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Bi extends J { } class Ri extends Bi { } class uu extends Bi { } class Ni extends J { } class du extends Ni { } class wc extends Ni { } class cu extends J { } class pu extends cu { } class ji extends J { } class hu extends ji { } class mo extends ji { } class mu extends ji { } class _o extends J { } class Vi extends _o { } class fo extends J { } class _u extends fo { } class fu extends fo { } class go extends J { } class yc extends go { } class gu extends go { } class Mc extends J { } class wu extends Mc { } class Ui extends J { } class yu extends Ui { } class Wi extends Ui { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Gi extends J { } class Mu extends Gi { } class Ki extends Gi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class Hi extends J { } class bu extends Hi { } class bc extends Hi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class qi extends J { } class vu extends qi { } class xu extends qi { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class vc extends J { } class Tu extends vc { } class Qi extends J { } class Pu extends Qi { } class Eu extends Qi { /** * @param {any} model_inputs */ async _call(_) { return new Cu(await super._call(_)); } } class Cu extends We { /** * @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: Q }) { super(), this.logits = _, this.pred_boxes = Q; } } class xc extends J { } class wo extends xc { /** * 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 $e(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} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`. * @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(_) { if ((!_.image_embeddings || !_.image_positional_embeddings) && (_ = { ..._, ...await this.get_image_embeddings(_) }), !_.input_labels && _.input_points) { const xe = _.input_points.dims.slice(0, -1), Se = xe.reduce((Be, rt) => Be * rt, 1); _.input_labels = new x.Tensor( "int64", new BigInt64Array(Se).fill(1n), xe ); } const Q = { image_embeddings: _.image_embeddings, image_positional_embeddings: _.image_positional_embeddings }; return _.input_points && (Q.input_points = _.input_points), _.input_labels && (Q.input_labels = _.input_labels), _.input_boxes && (Q.input_boxes = _.input_boxes), await ge(this.sessions.prompt_encoder_mask_decoder, Q); } /** * Runs the model with the provided inputs * @param {Object} model_inputs Model inputs * @returns {Promise} Object containing segmentation outputs */ async _call(_) { return new Rn(await super._call(_)); } } class Rn extends We { /** * @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: Q }) { super(), this.iou_scores = _, this.pred_masks = Q; } } class yo extends J { } class ku extends yo { } class Su extends yo { } class Xi extends J { } class $u extends Xi { } class Yi extends Xi { } class jr extends J { } class Au extends jr { } class Iu extends jr { /** * @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(_) { return new nn(await super._call(_)); } } class Tc extends jr { /** * 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(_) { return new Ht(await super._call(_)); } } class Fu extends jr { /** * 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(_) { return new Ss(await super._call(_)); } } class Mo extends J { } class Ou extends Mo { } class Du extends Mo { /** * 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(_) { return new Ss(await super._call(_)); } } class Lu extends J { } class Pc extends Lu { } class bo extends J { } class zu extends bo { } class Ec extends bo { /** * @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(_) { return new nn(await super._call(_)); } } class Bu extends bo { /** * 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(_) { return new Ht(await super._call(_)); } } class Nn extends J { } class Ru extends Nn { } class Nu extends Nn { /** * @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(_) { return new nn(await super._call(_)); } } class Cc extends Nn { /** * 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(_) { return new Ht(await super._call(_)); } } class ju extends Nn { /** * 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(_) { return new Ss(await super._call(_)); } } class vo extends J { } class Vu extends vo { } class kc extends vo { /** * @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(_) { return new nn(await super._call(_)); } } class Uu extends vo { /** * 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(_) { return new Ht(await super._call(_)); } } class Sc extends J { } class Wu extends jr { } class Gu extends jr { /** * @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(_) { return new nn(await super._call(_)); } } class $c extends jr { /** * 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(_) { return new Ht(await super._call(_)); } } class yn extends J { } class Ku extends yn { } class Hu extends yn { /** * @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(_) { return new nn(await super._call(_)); } } class qu extends yn { /** * 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(_) { return new Ht(await super._call(_)); } } class Ac extends yn { /** * 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(_) { return new Qd(await super._call(_)); } } class Qu extends yn { /** * 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(_) { return new Ss(await super._call(_)); } } class Xu extends J { } class Yu extends Xu { } class xo extends J { } class Lp extends xo { } class br extends xo { } class Sr extends xo { /** * @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(_, Q, { threshold: xe = 0.5, minlenratio: Se = 0, maxlenratio: Be = 20, vocoder: rt = null // output_cross_attentions = false, // TODO add } = {}) { const ot = { input_ids: _ }, { encoder_outputs: ft, encoder_attention_mask: $t } = await $e(this, ot), Jt = ft.dims[1] / this.config.reduction_factor, qt = Math.floor(Jt * Be), Dt = Math.floor(Jt * Se), It = this.config.num_mel_bins; let vs = [], Qt = null, Gt = null, fs = 0; for (; ; ) { ++fs; const Bs = pe(!!Gt); let Rs; Gt ? Rs = Gt.output_sequence_out : Rs = new x.Tensor( "float32", new Float32Array(It), [1, 1, It] ); let $s = { use_cache_branch: Bs, output_sequence: Rs, encoder_attention_mask: $t, speaker_embeddings: Q, encoder_hidden_states: ft }; this.addPastKeyValues($s, Qt), Gt = await ge(this.sessions.decoder_model_merged, $s), Qt = this.getPastKeyValues(Gt, Qt); const { prob: Ns, spectrum: rr } = Gt; if (vs.push(rr), fs >= Dt && // Finished when stop token or maximum length is reached. (Array.from(Ns.data).filter((wr) => wr >= xe).length > 0 || fs >= qt)) break; } const Ms = (0, x.cat)(vs), { waveform: Zt } = await ge(rt.sessions.model, { spectrogram: Ms }); return { spectrogram: Ms, waveform: Zt // cross_attentions: null, // TODO add }; } } class tn extends J { main_input_name = "spectrogram"; } class sn extends J { } class Ju extends sn { } class Ji extends J { } class Zu extends Ji { } class ed extends Ji { } class Zi extends J { } class td extends Zi { } class sd extends Zi { } class ea extends J { } class rd extends ea { } class nd extends ea { } class ta extends J { } class sr extends ta { } class od extends ta { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "text_model" }); } } class id extends ta { /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, Q = {}) { return super.from_pretrained(_, { ...Q, // Update default model file name if not provided model_file_name: Q.model_file_name ?? "audio_model" }); } } class sa extends J { } class ra extends sa { /** * 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(_) { return new Yd(await super._call(_)); } } class rn extends J { } class Ic extends rn { } class ad extends rn { } class ld extends rn { } class na extends J { } class ud extends na { } class dd extends na { } class To extends J { } class cd extends To { } class pd extends To { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class oa extends J { } class Fc extends oa { } class Oc extends oa { } class Po extends J { // NOTE: not MusicgenPreTrainedModel forward_params = [ "input_ids", "attention_mask", "encoder_outputs", "decoder_input_ids", "decoder_attention_mask", "past_key_values" ]; /** * Apply the pattern mask to the final ids, * then revert the pattern delay mask by filtering the pad token id in a single step. * @param {Tensor} outputs The output tensor from the model. * @returns {Tensor} The filtered output tensor. */ _apply_and_filter_by_delay_pattern_mask(_) { const [Q, xe] = _.dims, Se = this.config.decoder.num_codebooks, Be = xe - Se; let rt = 0; for (let $t = 0; $t < _.size; ++$t) { if (_.data[$t] === this.config.decoder.pad_token_id) continue; const Jt = $t % xe, qt = Math.floor($t / xe) % Se, Dt = Jt - qt; Dt > 0 && Dt <= Be && (_.data[rt++] = _.data[$t]); } const ot = Math.floor(Q / Se), ft = rt / (ot * Se); return new x.Tensor( _.type, _.data.slice(0, rt), [ot, Se, ft] ); } prepare_inputs_for_generation(_, Q, xe) { let Se = structuredClone(_); for (let rt = 0; rt < Se.length; ++rt) for (let ot = 0; ot < Se[rt].length; ++ot) rt % this.config.decoder.num_codebooks >= ot && (Se[rt][ot] = BigInt(this.config.decoder.pad_token_id)); return xe.guidance_scale !== null && xe.guidance_scale > 1 && (Se = Se.concat(Se)), super.prepare_inputs_for_generation(Se, Q, xe); } /** * Generates sequences of token ids for models with a language modeling head. * @param {import('./generation/parameters.js').GenerationFunctionParameters} options * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. */ async generate(_) { const Q = await super.generate(_), xe = this._apply_and_filter_by_delay_pattern_mask( /** @type {Tensor} */ Q ).unsqueeze_(0), { audio_values: Se } = await ge(this.sessions.encodec_decode, { audio_codes: xe }); return Se; } } class ia extends J { } class Dc extends ia { } class aa extends ia { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class la extends J { } class hd extends la { } class md extends la { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class _d extends J { } class fd extends _d { } class gd extends _d { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class ua extends J { } class Lc extends ua { } class wd extends ua { /** * @param {any} model_inputs */ async _call(_) { return new Ht(await super._call(_)); } } class yd extends J { } class zc extends yd { } class Md extends J { } class bd extends Md { forward_params = [ // prepare_inputs_embeds "input_ids", "pixel_values", "images_seq_mask", "images_emb_mask", // language_model "attention_mask", "position_ids", "past_key_values" ]; /** * @param {ConstructorParameters} args */ constructor(..._) { super(..._), this._generation_mode = "text"; } async forward(_) { const Q = this._generation_mode ?? "text"; let xe; if (Q === "text" || !_.past_key_values) { const ft = this.sessions.prepare_inputs_embeds, $t = (0, N.pick)(_, ft.inputNames); xe = await ge(ft, $t); } else { const ft = this.sessions.gen_img_embeds, $t = (0, N.pick)({ image_ids: _.input_ids }, ft.inputNames); xe = await ge(ft, $t); } const Se = { ..._, ...xe }, Be = await Pe(this, Se), rt = this.sessions[Q === "text" ? "lm_head" : "gen_head"]; if (!rt) throw new Error(`Unable to find "${rt}" generation head`); const ot = await ge(rt, (0, N.pick)(Be, rt.inputNames)); return { ...xe, ...Be, ...ot }; } /** * @param {import('./generation/parameters.js').GenerationFunctionParameters} options */ async generate(_) { return this._generation_mode = "text", super.generate(_); } /** * @param {import('./generation/parameters.js').GenerationFunctionParameters} options */ async generate_images(_) { this._generation_mode = "image"; const Q = (_.inputs ?? _[this.main_input_name]).dims[1], Se = ( /** @type {Tensor} */ (await super.generate(_)).slice(null, [Q, null]) ), Be = this.sessions.image_decode, { decoded_image: rt } = await ge(Be, { generated_tokens: Se }), ot = rt.add_(1).mul_(255 / 2).clamp_(0, 255).to("uint8"), ft = []; for (const $t of ot) { const Jt = L.RawImage.fromTensor($t); ft.push(Jt); } return ft; } } class vd extends We { constructor({ char_logits: _, bpe_logits: Q, wp_logits: xe }) { super(), this.char_logits = _, this.bpe_logits = Q, this.wp_logits = xe; } get logits() { return [this.char_logits, this.bpe_logits, this.wp_logits]; } } class xd extends J { } class Td extends xd { /** * @param {any} model_inputs */ async _call(_) { return new vd(await super._call(_)); } } class Pd extends J { } class Ed extends Pd { } class Cd extends Pd { } class da extends J { } class kd extends da { } class Sd extends da { } class _s { /** * 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 = !1; /** @type {typeof PreTrainedModel.from_pretrained} */ static async from_pretrained(_, { progress_callback: Q = null, config: xe = null, cache_dir: Se = null, local_files_only: Be = !1, revision: rt = "main", model_file_name: ot = null, subfolder: ft = "onnx", device: $t = null, dtype: Jt = null, use_external_data_format: qt = null, session_options: Dt = {} } = {}) { const It = { progress_callback: Q, config: xe, cache_dir: Se, local_files_only: Be, revision: rt, model_file_name: ot, subfolder: ft, device: $t, dtype: Jt, use_external_data_format: qt, session_options: Dt }; if (It.config = await g.AutoConfig.from_pretrained(_, It), !this.MODEL_CLASS_MAPPINGS) throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); for (const vs of this.MODEL_CLASS_MAPPINGS) { const Qt = vs.get(It.config.model_type); if (Qt) return await Qt[1].from_pretrained(_, It); } if (this.BASE_IF_FAIL) return console.warn(`Unknown model class "${It.config.model_type}", attempting to construct from base class.`), await J.from_pretrained(_, It); throw Error(`Unsupported model type: ${It.config.model_type}`); } } const Bc = /* @__PURE__ */ new Map([ ["bert", ["BertModel", ve]], ["modernbert", ["ModernBertModel", at]], ["nomic_bert", ["NomicBertModel", ae]], ["roformer", ["RoFormerModel", me]], ["electra", ["ElectraModel", Is]], ["esm", ["EsmModel", eo]], ["convbert", ["ConvBertModel", mt]], ["camembert", ["CamembertModel", Lt]], ["deberta", ["DebertaModel", Fr]], ["deberta-v2", ["DebertaV2Model", vt]], ["mpnet", ["MPNetModel", hn]], ["albert", ["AlbertModel", Fn]], ["distilbert", ["DistilBertModel", Mr]], ["roberta", ["RobertaModel", nr]], ["xlm", ["XLMModel", Fs]], ["xlm-roberta", ["XLMRobertaModel", St]], ["clap", ["ClapModel", sr]], ["clip", ["CLIPModel", Ua]], ["clipseg", ["CLIPSegModel", Qa]], ["chinese_clip", ["ChineseCLIPModel", mr]], ["siglip", ["SiglipModel", Ka]], ["jina_clip", ["JinaCLIPModel", no]], ["mobilebert", ["MobileBertModel", Sn]], ["squeezebert", ["SqueezeBertModel", gn]], ["wav2vec2", ["Wav2Vec2Model", Au]], ["wav2vec2-bert", ["Wav2Vec2BertModel", Vu]], ["unispeech", ["UniSpeechModel", zu]], ["unispeech-sat", ["UniSpeechSatModel", Ru]], ["hubert", ["HubertModel", Wu]], ["wavlm", ["WavLMModel", Ku]], ["audio-spectrogram-transformer", ["ASTModel", Aa]], ["vits", ["VitsModel", ra]], ["pyannote", ["PyAnnoteModel", Ou]], ["wespeaker-resnet", ["WeSpeakerResNetModel", Pc]], ["detr", ["DetrModel", Ei]], ["rt_detr", ["RTDetrModel", fc]], ["table-transformer", ["TableTransformerModel", ou]], ["vit", ["ViTModel", zl]], ["ijepa", ["IJepaModel", Bl]], ["pvt", ["PvtModel", Vl]], ["vit_msn", ["ViTMSNModel", mc]], ["vit_mae", ["ViTMAEModel", Wl]], ["groupvit", ["GroupViTModel", gr]], ["fastvit", ["FastViTModel", Hl]], ["mobilevit", ["MobileViTModel", Yl]], ["mobilevitv2", ["MobileViTV2Model", Zl]], ["owlvit", ["OwlViTModel", eu]], ["owlv2", ["Owlv2Model", su]], ["beit", ["BeitModel", Jr]], ["deit", ["DeiTModel", au]], ["hiera", ["HieraModel", ho]], ["convnext", ["ConvNextModel", yu]], ["convnextv2", ["ConvNextV2Model", Mu]], ["dinov2", ["Dinov2Model", bu]], ["dinov2_with_registers", ["Dinov2WithRegistersModel", vu]], ["resnet", ["ResNetModel", lu]], ["swin", ["SwinModel", zi]], ["swin2sr", ["Swin2SRModel", Ri]], ["donut-swin", ["DonutSwinModel", wu]], ["yolos", ["YolosModel", Pu]], ["dpt", ["DPTModel", du]], ["glpn", ["GLPNModel", yc]], ["hifigan", ["SpeechT5HifiGan", tn]], ["efficientnet", ["EfficientNetModel", cd]], ["decision_transformer", ["DecisionTransformerModel", zc]], ["patchtst", ["PatchTSTForPrediction", Ed]], ["patchtsmixer", ["PatchTSMixerForPrediction", kd]], ["mobilenet_v1", ["MobileNetV1Model", Dc]], ["mobilenet_v2", ["MobileNetV2Model", hd]], ["mobilenet_v3", ["MobileNetV3Model", fd]], ["mobilenet_v4", ["MobileNetV4Model", Lc]], ["maskformer", ["MaskFormerModel", _u]], ["mgp-str", ["MgpstrForSceneTextRecognition", Td]], ["style_text_to_speech_2", ["StyleTextToSpeech2Model", Yu]] ]), Rc = /* @__PURE__ */ new Map([ ["t5", ["T5Model", M]], ["longt5", ["LongT5Model", _e]], ["mt5", ["MT5Model", gt]], ["bart", ["BartModel", ht]], ["mbart", ["MBartModel", Ks]], ["marian", ["MarianModel", ku]], ["whisper", ["WhisperModel", Ia]], ["m2m_100", ["M2M100Model", $u]], ["blenderbot", ["BlenderbotModel", De]], ["blenderbot-small", ["BlenderbotSmallModel", Es]] ]), Nc = /* @__PURE__ */ new Map([ ["bloom", ["BloomModel", Al]], ["jais", ["JAISModel", Za]], ["gpt2", ["GPT2Model", Ya]], ["gptj", ["GPTJModel", nl]], ["gpt_bigcode", ["GPTBigCodeModel", il]], ["gpt_neo", ["GPTNeoModel", fr]], ["gpt_neox", ["GPTNeoXModel", sl]], ["codegen", ["CodeGenModel", Xo]], ["llama", ["LlamaModel", Jo]], ["exaone", ["ExaoneModel", cl]], ["olmo", ["OlmoModel", pc]], ["olmo2", ["Olmo2Model", _l]], ["mobilellm", ["MobileLLMModel", pl]], ["granite", ["GraniteModel", ls]], ["cohere", ["CohereModel", gl]], ["gemma", ["GemmaModel", yl]], ["gemma2", ["Gemma2Model", bl]], ["helium", ["HeliumModel", io]], ["glm", ["GlmModel", dl]], ["openelm", ["OpenELMModel", xl]], ["qwen2", ["Qwen2Model", Ln]], ["phi", ["PhiModel", Cl]], ["phi3", ["Phi3Model", Sl]], ["mpt", ["MptModel", Fl]], ["opt", ["OPTModel", Dl]], ["mistral", ["MistralModel", Zu]], ["starcoder2", ["Starcoder2Model", td]], ["falcon", ["FalconModel", rd]], ["stablelm", ["StableLmModel", ud]] ]), $d = /* @__PURE__ */ new Map([ ["speecht5", ["SpeechT5ForSpeechToText", br]], ["whisper", ["WhisperForConditionalGeneration", Fa]], ["moonshine", ["MoonshineForConditionalGeneration", Oa]] ]), jn = /* @__PURE__ */ new Map([ ["speecht5", ["SpeechT5ForTextToSpeech", Sr]] ]), ca = /* @__PURE__ */ new Map([ ["vits", ["VitsModel", ra]], ["musicgen", ["MusicgenForConditionalGeneration", Po]] ]), pa = /* @__PURE__ */ new Map([ ["bert", ["BertForSequenceClassification", je]], ["modernbert", ["ModernBertForSequenceClassification", lt]], ["roformer", ["RoFormerForSequenceClassification", ze]], ["electra", ["ElectraForSequenceClassification", xr]], ["esm", ["EsmForSequenceClassification", Cn]], ["convbert", ["ConvBertForSequenceClassification", es]], ["camembert", ["CamembertForSequenceClassification", Tr]], ["deberta", ["DebertaForSequenceClassification", Or]], ["deberta-v2", ["DebertaV2ForSequenceClassification", Zs]], ["mpnet", ["MPNetForSequenceClassification", mn]], ["albert", ["AlbertForSequenceClassification", wn]], ["distilbert", ["DistilBertForSequenceClassification", zs]], ["roberta", ["RobertaForSequenceClassification", ds]], ["xlm", ["XLMForSequenceClassification", Us]], ["xlm-roberta", ["XLMRobertaForSequenceClassification", Do]], ["bart", ["BartForSequenceClassification", Xt]], ["mbart", ["MBartForSequenceClassification", rs]], ["mobilebert", ["MobileBertForSequenceClassification", Br]], ["squeezebert", ["SqueezeBertForSequenceClassification", An]] ]), ha = /* @__PURE__ */ new Map([ ["bert", ["BertForTokenClassification", Ve]], ["modernbert", ["ModernBertForTokenClassification", ct]], ["roformer", ["RoFormerForTokenClassification", Ge]], ["electra", ["ElectraForTokenClassification", Gr]], ["esm", ["EsmForTokenClassification", kn]], ["convbert", ["ConvBertForTokenClassification", Ts]], ["camembert", ["CamembertForTokenClassification", Pr]], ["deberta", ["DebertaForTokenClassification", Dr]], ["deberta-v2", ["DebertaV2ForTokenClassification", Pn]], ["mpnet", ["MPNetForTokenClassification", _n]], ["distilbert", ["DistilBertForTokenClassification", qr]], ["roberta", ["RobertaForTokenClassification", Cs]], ["xlm", ["XLMForTokenClassification", Pt]], ["xlm-roberta", ["XLMRobertaForTokenClassification", Sa]] ]), Eo = /* @__PURE__ */ new Map([ ["t5", ["T5ForConditionalGeneration", Y]], ["longt5", ["LongT5ForConditionalGeneration", Fe]], ["mt5", ["MT5ForConditionalGeneration", wt]], ["bart", ["BartForConditionalGeneration", ts]], ["mbart", ["MBartForConditionalGeneration", jt]], ["marian", ["MarianMTModel", Su]], ["m2m_100", ["M2M100ForConditionalGeneration", Yi]], ["blenderbot", ["BlenderbotForConditionalGeneration", Xs]], ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", qs]] ]), ma = /* @__PURE__ */ new Map([ ["bloom", ["BloomForCausalLM", Il]], ["gpt2", ["GPT2LMHeadModel", Ja]], ["jais", ["JAISLMHeadModel", el]], ["gptj", ["GPTJForCausalLM", ol]], ["gpt_bigcode", ["GPTBigCodeForCausalLM", al]], ["gpt_neo", ["GPTNeoForCausalLM", tl]], ["gpt_neox", ["GPTNeoXForCausalLM", rl]], ["codegen", ["CodeGenForCausalLM", ll]], ["llama", ["LlamaForCausalLM", cc]], ["exaone", ["ExaoneForCausalLM", si]], ["olmo", ["OlmoForCausalLM", ml]], ["olmo2", ["Olmo2ForCausalLM", hc]], ["mobilellm", ["MobileLLMForCausalLM", hl]], ["granite", ["GraniteForCausalLM", fl]], ["cohere", ["CohereForCausalLM", wl]], ["gemma", ["GemmaForCausalLM", Ml]], ["gemma2", ["Gemma2ForCausalLM", vl]], ["helium", ["HeliumForCausalLM", ul]], ["glm", ["GlmForCausalLM", Dn]], ["openelm", ["OpenELMForCausalLM", Tl]], ["qwen2", ["Qwen2ForCausalLM", Pl]], ["phi", ["PhiForCausalLM", kl]], ["phi3", ["Phi3ForCausalLM", $l]], ["mpt", ["MptForCausalLM", Ol]], ["opt", ["OPTForCausalLM", Ll]], ["mbart", ["MBartForCausalLM", Hs]], ["mistral", ["MistralForCausalLM", ed]], ["starcoder2", ["Starcoder2ForCausalLM", sd]], ["falcon", ["FalconForCausalLM", nd]], ["trocr", ["TrOCRForCausalLM", Ju]], ["stablelm", ["StableLmForCausalLM", dd]], // Also image-text-to-text ["phi3_v", ["Phi3VForCausalLM", dr]] ]), jc = /* @__PURE__ */ new Map([ ["multi_modality", ["MultiModalityCausalLM", bd]] ]), _a = /* @__PURE__ */ new Map([ ["bert", ["BertForMaskedLM", He]], ["modernbert", ["ModernBertForMaskedLM", _t]], ["roformer", ["RoFormerForMaskedLM", ke]], ["electra", ["ElectraForMaskedLM", tr]], ["esm", ["EsmForMaskedLM", En]], ["convbert", ["ConvBertForMaskedLM", Nt]], ["camembert", ["CamembertForMaskedLM", Kr]], ["deberta", ["DebertaForMaskedLM", Er]], ["deberta-v2", ["DebertaV2ForMaskedLM", Ft]], ["mpnet", ["MPNetForMaskedLM", Qr]], ["albert", ["AlbertForMaskedLM", as]], ["distilbert", ["DistilBertForMaskedLM", pn]], ["roberta", ["RobertaForMaskedLM", hr]], ["xlm", ["XLMWithLMHeadModel", ks]], ["xlm-roberta", ["XLMRobertaForMaskedLM", ka]], ["mobilebert", ["MobileBertForMaskedLM", to]], ["squeezebert", ["SqueezeBertForMaskedLM", $n]] ]), fa = /* @__PURE__ */ new Map([ ["bert", ["BertForQuestionAnswering", Re]], ["roformer", ["RoFormerForQuestionAnswering", tt]], ["electra", ["ElectraForQuestionAnswering", Vs]], ["convbert", ["ConvBertForQuestionAnswering", ms]], ["camembert", ["CamembertForQuestionAnswering", Hr]], ["deberta", ["DebertaForQuestionAnswering", ir]], ["deberta-v2", ["DebertaV2ForQuestionAnswering", cn]], ["mpnet", ["MPNetForQuestionAnswering", fn]], ["albert", ["AlbertForQuestionAnswering", On]], ["distilbert", ["DistilBertForQuestionAnswering", ss]], ["roberta", ["RobertaForQuestionAnswering", Mt]], ["xlm", ["XLMForQuestionAnswering", Xr]], ["xlm-roberta", ["XLMRobertaForQuestionAnswering", $a]], ["mobilebert", ["MobileBertForQuestionAnswering", pr]], ["squeezebert", ["SqueezeBertForQuestionAnswering", In]] ]), ga = /* @__PURE__ */ new Map([ ["vision-encoder-decoder", ["VisionEncoderDecoderModel", Ro]], ["idefics3", ["Idefics3ForConditionalGeneration", No]] ]), Vc = /* @__PURE__ */ new Map([ ["llava", ["LlavaForConditionalGeneration", so]], ["llava_onevision", ["LlavaOnevisionForConditionalGeneration", Da]], ["moondream1", ["Moondream1ForConditionalGeneration", La]], ["florence2", ["Florence2ForConditionalGeneration", Ba]], ["qwen2-vl", ["Qwen2VLForConditionalGeneration", El]], ["idefics3", ["Idefics3ForConditionalGeneration", No]], ["paligemma", ["PaliGemmaForConditionalGeneration", Na]] ]), Ad = /* @__PURE__ */ new Map([ ["vision-encoder-decoder", ["VisionEncoderDecoderModel", Ro]] ]), Id = /* @__PURE__ */ new Map([ ["vit", ["ViTForImageClassification", gi]], ["ijepa", ["IJepaForImageClassification", Rl]], ["pvt", ["PvtForImageClassification", yi]], ["vit_msn", ["ViTMSNForImageClassification", Gl]], ["fastvit", ["FastViTForImageClassification", ql]], ["mobilevit", ["MobileViTForImageClassification", Jl]], ["mobilevitv2", ["MobileViTV2ForImageClassification", _c]], ["beit", ["BeitForImageClassification", Zr]], ["deit", ["DeiTForImageClassification", Ii]], ["hiera", ["HieraForImageClassification", Oi]], ["convnext", ["ConvNextForImageClassification", Wi]], ["convnextv2", ["ConvNextV2ForImageClassification", Ki]], ["dinov2", ["Dinov2ForImageClassification", bc]], ["dinov2_with_registers", ["Dinov2WithRegistersForImageClassification", xu]], ["resnet", ["ResNetForImageClassification", gc]], ["swin", ["SwinForImageClassification", Bn]], ["segformer", ["SegformerForImageClassification", ad]], ["efficientnet", ["EfficientNetForImageClassification", pd]], ["mobilenet_v1", ["MobileNetV1ForImageClassification", aa]], ["mobilenet_v2", ["MobileNetV2ForImageClassification", md]], ["mobilenet_v3", ["MobileNetV3ForImageClassification", gd]], ["mobilenet_v4", ["MobileNetV4ForImageClassification", wd]] ]), Fd = /* @__PURE__ */ new Map([ ["detr", ["DetrForObjectDetection", en]], ["rt_detr", ["RTDetrForObjectDetection", zn]], ["table-transformer", ["TableTransformerForObjectDetection", iu]], ["yolos", ["YolosForObjectDetection", Eu]] ]), wa = /* @__PURE__ */ new Map([ ["owlvit", ["OwlViTForObjectDetection", tu]], ["owlv2", ["Owlv2ForObjectDetection", ru]], ["grounding-dino", ["GroundingDinoForObjectDetection", Tu]] ]), Od = /* @__PURE__ */ new Map([ // TODO: Do not add new models here ["detr", ["DetrForSegmentation", Ws]], ["clipseg", ["CLIPSegForImageSegmentation", Xa]] ]), Dd = /* @__PURE__ */ new Map([ ["segformer", ["SegformerForSemanticSegmentation", ld]], ["sapiens", ["SapiensForSemanticSegmentation", hu]] ]), Ld = /* @__PURE__ */ new Map([ ["detr", ["DetrForSegmentation", Ws]], ["maskformer", ["MaskFormerForInstanceSegmentation", fu]] ]), zd = /* @__PURE__ */ new Map([ ["sam", ["SamModel", wo]] ]), Uc = /* @__PURE__ */ new Map([ ["wav2vec2", ["Wav2Vec2ForCTC", Iu]], ["wav2vec2-bert", ["Wav2Vec2BertForCTC", kc]], ["unispeech", ["UniSpeechForCTC", Ec]], ["unispeech-sat", ["UniSpeechSatForCTC", Nu]], ["wavlm", ["WavLMForCTC", Hu]], ["hubert", ["HubertForCTC", Gu]] ]), Bd = /* @__PURE__ */ new Map([ ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Tc]], ["wav2vec2-bert", ["Wav2Vec2BertForSequenceClassification", Uu]], ["unispeech", ["UniSpeechForSequenceClassification", Bu]], ["unispeech-sat", ["UniSpeechSatForSequenceClassification", Cc]], ["wavlm", ["WavLMForSequenceClassification", qu]], ["hubert", ["HubertForSequenceClassification", $c]], ["audio-spectrogram-transformer", ["ASTForAudioClassification", Lo]] ]), Rd = /* @__PURE__ */ new Map([ ["wavlm", ["WavLMForXVector", Ac]] ]), Nd = /* @__PURE__ */ new Map([ ["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", ju]], ["wavlm", ["WavLMForAudioFrameClassification", Qu]], ["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Fu]], ["pyannote", ["PyAnnoteForAudioFrameClassification", Du]] ]), jd = /* @__PURE__ */ new Map([ ["vitmatte", ["VitMatteForImageMatting", Xl]] ]), zp = /* @__PURE__ */ new Map([ ["patchtst", ["PatchTSTForPrediction", Cd]], ["patchtsmixer", ["PatchTSMixerForPrediction", Sd]] ]), Vd = /* @__PURE__ */ new Map([ ["swin2sr", ["Swin2SRForImageSuperResolution", uu]] ]), Ud = /* @__PURE__ */ new Map([ ["dpt", ["DPTForDepthEstimation", wc]], ["depth_anything", ["DepthAnythingForDepthEstimation", pu]], ["glpn", ["GLPNForDepthEstimation", gu]], ["sapiens", ["SapiensForDepthEstimation", mo]], ["depth_pro", ["DepthProForDepthEstimation", Vi]] ]), Wd = /* @__PURE__ */ new Map([ ["sapiens", ["SapiensForNormalEstimation", mu]] ]), Wc = /* @__PURE__ */ new Map([ ["vitpose", ["VitPoseForPoseEstimation", jl]] ]), Gd = /* @__PURE__ */ new Map([ ["clip", ["CLIPVisionModelWithProjection", Ga]], ["siglip", ["SiglipVisionModel", qa]], ["jina_clip", ["JinaCLIPVisionModel", _r]] ]), Kd = [ [Bc, A.EncoderOnly], [Rc, A.EncoderDecoder], [Nc, A.DecoderOnly], [pa, A.EncoderOnly], [ha, A.EncoderOnly], [Eo, A.Seq2Seq], [$d, A.Seq2Seq], [ma, A.DecoderOnly], [jc, A.MultiModality], [_a, A.EncoderOnly], [fa, A.EncoderOnly], [ga, A.Vision2Seq], [Vc, A.ImageTextToText], [Id, A.EncoderOnly], [Od, A.EncoderOnly], [Ld, A.EncoderOnly], [Dd, A.EncoderOnly], [jd, A.EncoderOnly], [zp, A.EncoderOnly], [Vd, A.EncoderOnly], [Ud, A.EncoderOnly], [Wd, A.EncoderOnly], [Wc, A.EncoderOnly], [Fd, A.EncoderOnly], [wa, A.EncoderOnly], [zd, A.MaskGeneration], [Uc, A.EncoderOnly], [Bd, A.EncoderOnly], [jn, A.Seq2Seq], [ca, A.EncoderOnly], [Rd, A.EncoderOnly], [Nd, A.EncoderOnly], // Custom: [Gd, A.EncoderOnly] ]; for (const [f, _] of Kd) for (const [Q, xe] of f.values()) S.set(Q, _), P.set(xe, Q), w.set(Q, xe); const Gc = [ // OVERRIDE: // TODO: Refactor to allow class to specify model ["MusicgenForConditionalGeneration", Po, A.Musicgen], ["Phi3VForCausalLM", dr, A.Phi3V], ["CLIPTextModelWithProjection", Wa, A.EncoderOnly], ["SiglipTextModel", Ha, A.EncoderOnly], ["JinaCLIPTextModel", Vo, A.EncoderOnly], ["ClapTextModelWithProjection", od, A.EncoderOnly], ["ClapAudioModelWithProjection", id, A.EncoderOnly] ]; for (const [f, _, Q] of Gc) S.set(f, Q), P.set(_, f), w.set(f, _); class Kc extends _s { /** @type {Map[]} */ // @ts-ignore static MODEL_CLASS_MAPPINGS = Kd.map((_) => _[0]); static BASE_IF_FAIL = !0; } class Bp extends _s { static MODEL_CLASS_MAPPINGS = [pa]; } class Hc extends _s { static MODEL_CLASS_MAPPINGS = [ha]; } class qc extends _s { static MODEL_CLASS_MAPPINGS = [Eo]; } class Qc extends _s { static MODEL_CLASS_MAPPINGS = [$d]; } class Hd extends _s { static MODEL_CLASS_MAPPINGS = [jn]; } class Xc extends _s { static MODEL_CLASS_MAPPINGS = [ca]; } class Yc extends _s { static MODEL_CLASS_MAPPINGS = [ma]; } class Jc extends _s { static MODEL_CLASS_MAPPINGS = [_a]; } class Zc extends _s { static MODEL_CLASS_MAPPINGS = [fa]; } class ep extends _s { static MODEL_CLASS_MAPPINGS = [ga]; } class tp extends _s { static MODEL_CLASS_MAPPINGS = [Id]; } class sp extends _s { static MODEL_CLASS_MAPPINGS = [Od]; } class rp extends _s { static MODEL_CLASS_MAPPINGS = [Dd]; } class qd extends _s { static MODEL_CLASS_MAPPINGS = [Ld]; } class np extends _s { static MODEL_CLASS_MAPPINGS = [Fd]; } class op extends _s { static MODEL_CLASS_MAPPINGS = [wa]; } class ip extends _s { static MODEL_CLASS_MAPPINGS = [zd]; } class ap extends _s { static MODEL_CLASS_MAPPINGS = [Uc]; } class lp extends _s { static MODEL_CLASS_MAPPINGS = [Bd]; } class up extends _s { static MODEL_CLASS_MAPPINGS = [Rd]; } class dp extends _s { static MODEL_CLASS_MAPPINGS = [Nd]; } class Rp extends _s { static MODEL_CLASS_MAPPINGS = [Ad]; } class cp extends _s { static MODEL_CLASS_MAPPINGS = [jd]; } class pp extends _s { static MODEL_CLASS_MAPPINGS = [Vd]; } class hp extends _s { static MODEL_CLASS_MAPPINGS = [Ud]; } class Np extends _s { static MODEL_CLASS_MAPPINGS = [Wd]; } class mp extends _s { static MODEL_CLASS_MAPPINGS = [Wc]; } class _p extends _s { static MODEL_CLASS_MAPPINGS = [Gd]; } class fp extends We { /** * @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: Q, encoder_outputs: xe, decoder_attentions: Se = null, cross_attentions: Be = null }) { super(), this.logits = _, this.past_key_values = Q, this.encoder_outputs = xe, this.decoder_attentions = Se, this.cross_attentions = Be; } } class Ht extends We { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). * @param {Record} [output.attentions] Object of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. * Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. */ constructor({ logits: _, ...Q }) { super(), this.logits = _; const xe = Object.values(Q); xe.length > 0 && (this.attentions = xe); } } class Qd extends We { /** * @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: Q }) { super(), this.logits = _, this.embeddings = Q; } } class Ss extends We { /** * @param {Object} output The output of the model. * @param {Tensor} output.logits Classification scores (before SoftMax). */ constructor({ logits: _ }) { super(), this.logits = _; } } class Qs extends We { /** * @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 = _; } } class Ys extends We { /** * @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: Q }) { super(), this.start_logits = _, this.end_logits = Q; } } class nn extends We { /** * @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 = _; } } class gp extends We { /** * @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). * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) * that can be used (see `past_key_values` input) to speed up sequential decoding. */ constructor({ logits: _, past_key_values: Q }) { super(), this.logits = _, this.past_key_values = Q; } } class Xd extends We { /** * @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 = _; } } class Yd extends We { /** * @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: Q }) { super(), this.waveform = _, this.spectrogram = Q; } } } ), /***/ "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js": ( /*!******************************************************************************************************!*\ !*** ./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js ***! \******************************************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ASTFeatureExtractor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); var O = r( /*! ../../utils/audio.js */ "./src/utils/audio.js" ); class j extends g.FeatureExtractor { constructor(N) { super(N); const y = this.config.sampling_rate, T = (0, O.mel_filter_bank)( 256, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(y / 2), // max_frequency y, // sampling_rate null, // norm "kaldi", // mel_scale !0 // triangularize_in_mel_space ); for (let v = 0; v < T.length; ++v) T[v].push(0); this.mel_filters = T, this.window = (0, O.window_function)(400, "hann", { periodic: !1 }), 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 {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(N, y) { return (0, O.spectrogram)( N, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2, center: !1, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: "log", mel_floor: 1192092955078125e-22, remove_dc_offset: !0, // Custom max_num_frames: y, transpose: !0 } ); } /** * 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(N) { (0, g.validate_audio_inputs)(N, "ASTFeatureExtractor"); const y = await this._extract_fbank_features(N, this.config.max_length); if (this.config.do_normalize) { const T = this.std * 2, v = y.data; for (let b = 0; b < v.length; ++b) v[b] = (v[b] - this.mean) / T; } return { input_values: y.unsqueeze_(0) }; } } } ), /***/ "./src/models/auto/feature_extraction_auto.js": ( /*!****************************************************!*\ !*** ./src/models/auto/feature_extraction_auto.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AutoFeatureExtractor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../utils/constants.js */ "./src/utils/constants.js" ), O = r( /*! ../../utils/hub.js */ "./src/utils/hub.js" ); r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); var j = r( /*! ../feature_extractors.js */ "./src/models/feature_extractors.js" ); class ee { /** @type {typeof FeatureExtractor.from_pretrained} */ static async from_pretrained(y, T = {}) { const v = await (0, O.getModelJSON)(y, g.FEATURE_EXTRACTOR_NAME, !0, T), b = v.feature_extractor_type, x = j[b]; if (!x) throw new Error(`Unknown feature_extractor_type: '${b}'. Please report this at ${g.GITHUB_ISSUE_URL}.`); return new x(v); } } } ), /***/ "./src/models/auto/image_processing_auto.js": ( /*!**************************************************!*\ !*** ./src/models/auto/image_processing_auto.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AutoImageProcessor: () => ( /* binding */ N ) /* harmony export */ }); var g = r( /*! ../../utils/constants.js */ "./src/utils/constants.js" ), O = r( /*! ../../utils/hub.js */ "./src/utils/hub.js" ), j = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), ee = r( /*! ../image_processors.js */ "./src/models/image_processors.js" ); class N { /** @type {typeof ImageProcessor.from_pretrained} */ static async from_pretrained(T, v = {}) { const b = await (0, O.getModelJSON)(T, g.IMAGE_PROCESSOR_NAME, !0, v), x = b.image_processor_type ?? b.feature_extractor_type; let L = ee[x]; return L || (x !== void 0 && console.warn(`Image processor type '${x}' not found, assuming base ImageProcessor. Please report this at ${g.GITHUB_ISSUE_URL}.`), L = j.ImageProcessor), new L(b); } } } ), /***/ "./src/models/auto/processing_auto.js": ( /*!********************************************!*\ !*** ./src/models/auto/processing_auto.js ***! \********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AutoProcessor: () => ( /* binding */ T ) /* harmony export */ }); var g = r( /*! ../../utils/constants.js */ "./src/utils/constants.js" ), O = r( /*! ../../utils/hub.js */ "./src/utils/hub.js" ), j = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), ee = r( /*! ../processors.js */ "./src/models/processors.js" ), N = r( /*! ../image_processors.js */ "./src/models/image_processors.js" ), y = r( /*! ../feature_extractors.js */ "./src/models/feature_extractors.js" ); class T { /** @type {typeof Processor.from_pretrained} */ static async from_pretrained(b, x = {}) { const L = await (0, O.getModelJSON)(b, g.IMAGE_PROCESSOR_NAME, !0, x), { image_processor_type: K, feature_extractor_type: re, processor_class: ie } = L; if (ie && ee[ie]) return ee[ie].from_pretrained(b, x); if (!K && !re) throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config."); const V = {}; if (K) { const q = N[K]; if (!q) throw new Error(`Unknown image_processor_type: '${K}'.`); V.image_processor = new q(L); } if (re) { const q = N[re]; if (q) V.image_processor = new q(L); else { const A = y[re]; if (!A) throw new Error(`Unknown feature_extractor_type: '${re}'.`); V.feature_extractor = new A(L); } } const U = {}; return new j.Processor(U, V); } } } ), /***/ "./src/models/beit/image_processing_beit.js": ( /*!**************************************************!*\ !*** ./src/models/beit/image_processing_beit.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ BeitFeatureExtractor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/bit/image_processing_bit.js": ( /*!************************************************!*\ !*** ./src/models/bit/image_processing_bit.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ BitImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/chinese_clip/image_processing_chinese_clip.js": ( /*!******************************************************************!*\ !*** ./src/models/chinese_clip/image_processing_chinese_clip.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ChineseCLIPFeatureExtractor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/clap/feature_extraction_clap.js": ( /*!****************************************************!*\ !*** ./src/models/clap/feature_extraction_clap.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ClapFeatureExtractor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); var O = r( /*! ../../utils/audio.js */ "./src/utils/audio.js" ); class j extends g.FeatureExtractor { constructor(N) { super(N), this.mel_filters = (0, O.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 = (0, O.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 = (0, O.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 {Promise} 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. * @private */ async _get_input_mel(N, y, T, v) { let b; const x = N.length - y; if (x > 0) if (T === "rand_trunc") { const L = Math.floor(Math.random() * (x + 1)); N = N.subarray(L, L + y), b = await this._extract_fbank_features(N, this.mel_filters_slaney, this.config.nb_max_samples); } else throw new Error(`Truncation strategy "${T}" not implemented`); else { if (x < 0) { let L = new Float64Array(y); if (L.set(N), v === "repeat") for (let K = N.length; K < y; K += N.length) L.set(N.subarray(0, Math.min(N.length, y - K)), K); else if (v === "repeatpad") for (let K = N.length; K < -x; K += N.length) L.set(N, K); N = L; } if (T === "fusion") throw new Error(`Truncation strategy "${T}" not implemented`); b = await this._extract_fbank_features(N, this.mel_filters_slaney, this.config.nb_max_samples); } return b.unsqueeze_(0); } /** * 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 {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(N, y, T = null) { return (0, O.spectrogram)( N, this.window, // window this.config.fft_window_size, // frame_length this.config.hop_length, // hop_length { power: 2, mel_filters: y, log_mel: "dB", // Custom max_num_frames: T, do_pad: !1, transpose: !0 } ); } /** * 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(N, { max_length: y = null } = {}) { return (0, g.validate_audio_inputs)(N, "ClapFeatureExtractor"), { input_features: (await this._get_input_mel( N, y ?? this.config.nb_max_samples, this.config.truncation, this.config.padding )).unsqueeze_(0) }; } } } ), /***/ "./src/models/clip/image_processing_clip.js": ( /*!**************************************************!*\ !*** ./src/models/clip/image_processing_clip.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ CLIPFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ CLIPImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/convnext/image_processing_convnext.js": ( /*!**********************************************************!*\ !*** ./src/models/convnext/image_processing_convnext.js ***! \**********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ConvNextFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ ConvNextImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { constructor(N) { super(N), this.crop_pct = this.config.crop_pct ?? 0.875; } async resize(N) { const y = this.size?.shortest_edge; if (y === void 0) throw new Error("Size dictionary must contain 'shortest_edge' key."); if (y < 384) { const T = Math.floor(y / this.crop_pct), [v, b] = this.get_resize_output_image_size(N, { shortest_edge: T }); N = await N.resize(v, b, { resample: this.resample }), N = await N.center_crop(y, y); } else N = await N.resize(y, y, { resample: this.resample }); return N; } } class j extends O { } } ), /***/ "./src/models/deit/image_processing_deit.js": ( /*!**************************************************!*\ !*** ./src/models/deit/image_processing_deit.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DeiTFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ DeiTImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/detr/image_processing_detr.js": ( /*!**************************************************!*\ !*** ./src/models/detr/image_processing_detr.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DetrFeatureExtractor: () => ( /* binding */ ee ), /* harmony export */ DetrImageProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.ImageProcessor { /** * Calls the feature extraction process on an array of images, preprocesses * each image, and concatenates the resulting features into a single Tensor. * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. */ async _call(y) { const T = await super._call(y), v = [T.pixel_values.dims[0], 64, 64], b = (0, O.full)(v, 1n); return { ...T, pixel_mask: b }; } /** @type {typeof post_process_object_detection} */ post_process_object_detection(...y) { return (0, g.post_process_object_detection)(...y); } /** @type {typeof post_process_panoptic_segmentation} */ post_process_panoptic_segmentation(...y) { return (0, g.post_process_panoptic_segmentation)(...y); } /** @type {typeof post_process_instance_segmentation} */ post_process_instance_segmentation(...y) { return (0, g.post_process_instance_segmentation)(...y); } } class ee extends j { } } ), /***/ "./src/models/donut/image_processing_donut.js": ( /*!****************************************************!*\ !*** ./src/models/donut/image_processing_donut.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DonutFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ DonutImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { pad_image(N, y, T, v = {}) { const [b, x, L] = y; let K = this.image_mean; Array.isArray(this.image_mean) || (K = new Array(L).fill(K)); let re = this.image_std; Array.isArray(re) || (re = new Array(L).fill(K)); const ie = K.map((V, U) => -V / re[U]); return super.pad_image(N, y, T, { center: !0, // 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: ie, ...v }); } } class j extends O { } } ), /***/ "./src/models/dpt/image_processing_dpt.js": ( /*!************************************************!*\ !*** ./src/models/dpt/image_processing_dpt.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DPTFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ DPTImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/efficientnet/image_processing_efficientnet.js": ( /*!******************************************************************!*\ !*** ./src/models/efficientnet/image_processing_efficientnet.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ EfficientNetImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { constructor(ee) { super(ee), this.include_top = this.config.include_top ?? !0, this.include_top && (this.image_std = this.image_std.map((N) => N * N)); } } } ), /***/ "./src/models/feature_extractors.js": ( /*!******************************************!*\ !*** ./src/models/feature_extractors.js ***! \******************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ASTFeatureExtractor: () => ( /* reexport safe */ g.ASTFeatureExtractor ), /* harmony export */ ClapFeatureExtractor: () => ( /* reexport safe */ O.ClapFeatureExtractor ), /* harmony export */ ImageFeatureExtractor: () => ( /* reexport safe */ x.ImageProcessor ), /* harmony export */ MoonshineFeatureExtractor: () => ( /* reexport safe */ j.MoonshineFeatureExtractor ), /* harmony export */ PyAnnoteFeatureExtractor: () => ( /* reexport safe */ ee.PyAnnoteFeatureExtractor ), /* harmony export */ SeamlessM4TFeatureExtractor: () => ( /* reexport safe */ N.SeamlessM4TFeatureExtractor ), /* harmony export */ SpeechT5FeatureExtractor: () => ( /* reexport safe */ y.SpeechT5FeatureExtractor ), /* harmony export */ Wav2Vec2FeatureExtractor: () => ( /* reexport safe */ T.Wav2Vec2FeatureExtractor ), /* harmony export */ WeSpeakerFeatureExtractor: () => ( /* reexport safe */ v.WeSpeakerFeatureExtractor ), /* harmony export */ WhisperFeatureExtractor: () => ( /* reexport safe */ b.WhisperFeatureExtractor ) /* harmony export */ }); var g = r( /*! ./audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js */ "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js" ), O = r( /*! ./clap/feature_extraction_clap.js */ "./src/models/clap/feature_extraction_clap.js" ), j = r( /*! ./moonshine/feature_extraction_moonshine.js */ "./src/models/moonshine/feature_extraction_moonshine.js" ), ee = r( /*! ./pyannote/feature_extraction_pyannote.js */ "./src/models/pyannote/feature_extraction_pyannote.js" ), N = r( /*! ./seamless_m4t/feature_extraction_seamless_m4t.js */ "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js" ), y = r( /*! ./speecht5/feature_extraction_speecht5.js */ "./src/models/speecht5/feature_extraction_speecht5.js" ), T = r( /*! ./wav2vec2/feature_extraction_wav2vec2.js */ "./src/models/wav2vec2/feature_extraction_wav2vec2.js" ), v = r( /*! ./wespeaker/feature_extraction_wespeaker.js */ "./src/models/wespeaker/feature_extraction_wespeaker.js" ), b = r( /*! ./whisper/feature_extraction_whisper.js */ "./src/models/whisper/feature_extraction_whisper.js" ), x = r( /*! ../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); } ), /***/ "./src/models/florence2/processing_florence2.js": ( /*!******************************************************!*\ !*** ./src/models/florence2/processing_florence2.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Florence2Processor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); class ee extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; constructor(y, T) { super(y, T); const { // @ts-expect-error TS2339 tasks_answer_post_processing_type: v, // @ts-expect-error TS2339 task_prompts_without_inputs: b, // @ts-expect-error TS2339 task_prompts_with_input: x } = this.image_processor.config; this.tasks_answer_post_processing_type = new Map(Object.entries(v ?? {})), this.task_prompts_without_inputs = new Map(Object.entries(b ?? {})), this.task_prompts_with_input = new Map(Object.entries(x ?? {})), this.regexes = { quad_boxes: /(.+?)/gm, bboxes: /([^<]+)?/gm }, this.size_per_bin = 1e3; } /** * Helper function to construct prompts from input texts * @param {string|string[]} text * @returns {string[]} */ construct_prompts(y) { typeof y == "string" && (y = [y]); const T = []; for (const v of y) if (this.task_prompts_without_inputs.has(v)) T.push(this.task_prompts_without_inputs.get(v)); else { for (const [b, x] of this.task_prompts_with_input) if (v.includes(b)) { T.push(x.replaceAll("{input}", v).replaceAll(b, "")); break; } T.length !== y.length && T.push(v); } return T; } /** * Post-process the output of the model to each of the task outputs. * @param {string} text The text to post-process. * @param {string} task The task to post-process the text for. * @param {[number, number]} image_size The size of the image. height x width. */ post_process_generation(y, T, v) { const b = this.tasks_answer_post_processing_type.get(T) ?? "pure_text"; y = y.replaceAll("", "").replaceAll("", ""); let x; switch (b) { case "pure_text": x = y; break; case "description_with_bboxes": case "bboxes": case "phrase_grounding": case "ocr": const L = b === "ocr" ? "quad_boxes" : "bboxes", K = y.matchAll(this.regexes[L]), re = [], ie = []; for (const [V, U, ...q] of K) re.push(U ? U.trim() : re.at(-1) ?? ""), ie.push( q.map((A, S) => ( // NOTE: Add 0.5 to use the center position of the bin as the coordinate. (Number(A) + 0.5) / this.size_per_bin * v[S % 2] )) ); x = { labels: re, [L]: ie }; break; default: throw new Error(`Task "${T}" (of type "${b}") not yet implemented.`); } return { [T]: x }; } // NOTE: images and text are switched from the python version // `images` is required, `text` is optional async _call(y, T = null, v = {}) { if (!y && !T) throw new Error("Either text or images must be provided"); const b = await this.image_processor(y, v), x = T ? this.tokenizer(T, v) : {}; return { ...b, ...x }; } } } ), /***/ "./src/models/glpn/image_processing_glpn.js": ( /*!**************************************************!*\ !*** ./src/models/glpn/image_processing_glpn.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ GLPNFeatureExtractor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/grounding_dino/image_processing_grounding_dino.js": ( /*!**********************************************************************!*\ !*** ./src/models/grounding_dino/image_processing_grounding_dino.js ***! \**********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ GroundingDinoImageProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.ImageProcessor { /** * Calls the feature extraction process on an array of images, preprocesses * each image, and concatenates the resulting features into a single Tensor. * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. */ async _call(N) { const y = await super._call(N), T = y.pixel_values.dims, v = (0, O.ones)([T[0], T[2], T[3]]); return { ...y, pixel_mask: v }; } } } ), /***/ "./src/models/grounding_dino/processing_grounding_dino.js": ( /*!****************************************************************!*\ !*** ./src/models/grounding_dino/processing_grounding_dino.js ***! \****************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ GroundingDinoProcessor: () => ( /* binding */ y ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), ee = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); function N(T, v) { const x = T.dims.at(-1) - 1, L = T.tolist(); L.fill(!1, 0, 1), L.fill(!1, x); const K = v.tolist(); return L.map((re, ie) => re ? ie : null).filter((re) => re !== null).map((re) => K[re]); } class y extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; /** * @typedef {import('../../utils/image.js').RawImage} RawImage */ /** * * @param {RawImage|RawImage[]|RawImage[][]} images * @param {string|string[]} text * @returns {Promise} */ async _call(v, b, x = {}) { const L = v ? await this.image_processor(v, x) : {}; return { ...b ? this.tokenizer(b, x) : {}, ...L }; } post_process_grounded_object_detection(v, b, { box_threshold: x = 0.25, text_threshold: L = 0.25, target_sizes: K = null } = {}) { const { logits: re, pred_boxes: ie } = v, V = re.dims[0]; if (K !== null && K.length !== V) throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); const U = re.dims.at(1), q = re.sigmoid(), A = q.max(-1).tolist(), S = ie.tolist().map((P) => P.map((I) => (0, ee.center_to_corners_format)(I))), w = []; for (let P = 0; P < V; ++P) { const I = K !== null ? K[P] : null; I !== null && (S[P] = S[P].map((se) => se.map((be, pe) => be * I[(pe + 1) % 2]))); const le = A[P], oe = [], ye = [], ge = []; for (let se = 0; se < U; ++se) { const be = le[se]; if (be <= x) continue; const pe = S[P][se], Ce = q[P][se]; oe.push(be), ge.push(pe); const $e = N(Ce.gt(L), b[P]); ye.push($e); } w.push({ scores: oe, boxes: ge, labels: this.batch_decode(ye) }); } return w; } } } ), /***/ "./src/models/idefics3/image_processing_idefics3.js": ( /*!**********************************************************!*\ !*** ./src/models/idefics3/image_processing_idefics3.js ***! \**********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Idefics3ImageProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.ImageProcessor { constructor(N) { super(N), this.do_image_splitting = N.do_image_splitting ?? !0, this.max_image_size = N.max_image_size; } /** * @typedef {import('../../utils/image.js').RawImage} RawImage * @typedef {import('../../utils/tensor.js').Tensor} Tensor */ /** * Calculate size to resize images to, to be multiples of `vision_encoder_max_size` while preserving the aspect ratio. * @param {Tensor} pixel_values Tensor of the image to resize. * @param {number} vision_encoder_max_size Maximum size of the output image. If the image is larger than this size, * it will be split into patches of this size, and the original image will be concatenated with the patches, resized to max_size. */ get_resize_for_vision_encoder(N, y) { let [T, v] = N.dims.slice(-2); const b = v / T; return v >= T ? (v = Math.ceil(v / y) * y, T = Math.floor(v / b), T = Math.ceil(T / y) * y) : (T = Math.ceil(T / y) * y, v = Math.floor(T * b), v = Math.ceil(v / y) * y), { height: T, width: v }; } /** @param {RawImage|RawImage[]|RawImage[][]} images */ async _call(N, { do_image_splitting: y = null, return_row_col_info: T = !1 } = {}) { let v; if (!Array.isArray(N)) v = [[N]]; else { if (N.length === 0 || !N[0]) throw new Error("No images provided."); Array.isArray(N[0]) ? v = /** @type {RawImage[][]} */ N : v = [ /** @type {RawImage[]} */ N ]; } let b = [], x = [], L = []; const K = [], re = []; for (const P of v) { let I = await Promise.all(P.map((ye) => this.preprocess(ye))); K.push(...I.map((ye) => ye.original_size)), re.push(...I.map((ye) => ye.reshaped_input_size)), I.forEach((ye) => ye.pixel_values.unsqueeze_(0)); const { longest_edge: le } = this.max_image_size; let oe; if (y ?? this.do_image_splitting) { let ye = new Array(I.length), ge = new Array(I.length); oe = await Promise.all(I.map(async (se, be) => { const pe = this.get_resize_for_vision_encoder(se.pixel_values, le), Ce = await (0, O.interpolate_4d)(se.pixel_values, { size: [pe.height, pe.width] }), { frames: $e, num_splits_h: Pe, num_splits_w: Je } = await this.split_image(Ce, this.max_image_size); return ye[be] = Pe, ge[be] = Je, (0, O.cat)($e, 0); })), x.push(ye), L.push(ge); } else { const ye = [le, le]; oe = await Promise.all( I.map((ge) => (0, O.interpolate_4d)(ge.pixel_values, { size: ye })) ), x.push(new Array(I.length).fill(0)), L.push(new Array(I.length).fill(0)); } b.push((0, O.cat)(oe, 0)); } const ie = b.length, [V, U, q, A] = b[0].dims; let S, w; if (ie === 1) S = b[0].unsqueeze_(0), w = (0, O.full)([ie, V, q, A], !0); else { const P = Math.max(...b.map((oe) => oe.dims.at(0))); w = (0, O.full)([ie, P, q, A], !0); const I = w.data, le = P * q * A; for (let oe = 0; oe < ie; ++oe) { const ye = b[oe].dims[0]; if (ye < P) { b[oe] = (0, O.cat)([ b[oe], (0, O.full)([P - ye, U, q, A], 0) ], 0); const ge = oe * le + ye * q * A, se = (oe + 1) * le; I.fill(!1, ge, se); } } S = (0, O.stack)(b, 0); } return { pixel_values: S, pixel_attention_mask: w, original_sizes: K, reshaped_input_sizes: re, ...T ? { rows: x, cols: L } : {} }; } async split_image(N, { longest_edge: y }) { const T = y, v = y, b = [], [x, L] = N.dims.slice(-2); let K = 0, re = 0; if (x > T || L > v) { K = Math.ceil(x / T), re = Math.ceil(L / v); const ie = Math.ceil(x / K), V = Math.ceil(L / re); for (let A = 0; A < K; ++A) for (let S = 0; S < re; ++S) { let w, P, I, le; A === K - 1 ? (P = x - ie, le = x) : (P = A * ie, le = (A + 1) * ie), S === re - 1 ? (w = L - V, I = L) : (w = S * V, I = (S + 1) * V); const oe = [P, w], ye = [le, I], ge = await (0, O.slice)(N, oe, ye, [2, 3]); b.push(ge); } const U = T, q = v; (x !== U || L !== q) && (N = await (0, O.interpolate_4d)(N, { size: [U, q] })); } return b.push(N), { frames: b, num_splits_h: K, num_splits_w: re }; } } } ), /***/ "./src/models/idefics3/processing_idefics3.js": ( /*!****************************************************!*\ !*** ./src/models/idefics3/processing_idefics3.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Idefics3Processor: () => ( /* binding */ v ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); r( /*! ../../utils/image.js */ "./src/utils/image.js" ); var ee = r( /*! ../../utils/core.js */ "./src/utils/core.js" ); function N(b, x, L, K, re, ie) { let V = ""; for (let U = 0; U < x; ++U) { for (let q = 0; q < L; ++q) V += K + `` + re.repeat(b); V += ` `; } return V += ` ${K}${ie}` + re.repeat(b) + `${K}`, V; } function y(b, x, L, K) { return `${x}${K}` + L.repeat(b) + `${x}`; } function T(b, x, L, K, re, ie) { return b === 0 && x === 0 ? y( L, K, re, ie ) : N( L, b, x, K, re, ie ); } class v extends g.Processor { static image_processor_class = O.AutoImageProcessor; static tokenizer_class = j.AutoTokenizer; static uses_processor_config = !0; fake_image_token = ""; image_token = ""; global_img_token = ""; /** * * @param {string|string[]} text * @param {RawImage|RawImage[]|RawImage[][]} images * @returns {Promise} */ async _call(x, L = null, K = {}) { K.return_row_col_info ??= !0; let re; L && (re = await this.image_processor(L, K)), Array.isArray(x) || (x = [x]); const ie = re.rows ?? [new Array(x.length).fill(0)], V = re.cols ?? [new Array(x.length).fill(0)], U = this.config.image_seq_len, q = [], A = []; for (let w = 0; w < x.length; ++w) { const P = x[w], I = ie[w], le = V[w]; q.push((0, ee.count)(P, this.image_token)); const oe = I.map( (se, be) => T( se, le[be], U, this.fake_image_token, this.image_token, this.global_img_token ) ), ye = P.split(this.image_token); if (ye.length === 0) throw new Error("The image token should be present in the text."); let ge = ye[0]; for (let se = 0; se < oe.length; ++se) ge += oe[se] + ye[se + 1]; A.push(ge); } return { ...this.tokenizer(A), ...re }; } } } ), /***/ "./src/models/image_processors.js": ( /*!****************************************!*\ !*** ./src/models/image_processors.js ***! \****************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ BeitFeatureExtractor: () => ( /* reexport safe */ g.BeitFeatureExtractor ), /* harmony export */ BitImageProcessor: () => ( /* reexport safe */ O.BitImageProcessor ), /* harmony export */ CLIPFeatureExtractor: () => ( /* reexport safe */ ee.CLIPFeatureExtractor ), /* harmony export */ CLIPImageProcessor: () => ( /* reexport safe */ ee.CLIPImageProcessor ), /* harmony export */ ChineseCLIPFeatureExtractor: () => ( /* reexport safe */ j.ChineseCLIPFeatureExtractor ), /* harmony export */ ConvNextFeatureExtractor: () => ( /* reexport safe */ N.ConvNextFeatureExtractor ), /* harmony export */ ConvNextImageProcessor: () => ( /* reexport safe */ N.ConvNextImageProcessor ), /* harmony export */ DPTFeatureExtractor: () => ( /* reexport safe */ b.DPTFeatureExtractor ), /* harmony export */ DPTImageProcessor: () => ( /* reexport safe */ b.DPTImageProcessor ), /* harmony export */ DeiTFeatureExtractor: () => ( /* reexport safe */ y.DeiTFeatureExtractor ), /* harmony export */ DeiTImageProcessor: () => ( /* reexport safe */ y.DeiTImageProcessor ), /* harmony export */ DetrFeatureExtractor: () => ( /* reexport safe */ T.DetrFeatureExtractor ), /* harmony export */ DetrImageProcessor: () => ( /* reexport safe */ T.DetrImageProcessor ), /* harmony export */ DonutFeatureExtractor: () => ( /* reexport safe */ v.DonutFeatureExtractor ), /* harmony export */ DonutImageProcessor: () => ( /* reexport safe */ v.DonutImageProcessor ), /* harmony export */ EfficientNetImageProcessor: () => ( /* reexport safe */ x.EfficientNetImageProcessor ), /* harmony export */ GLPNFeatureExtractor: () => ( /* reexport safe */ L.GLPNFeatureExtractor ), /* harmony export */ GroundingDinoImageProcessor: () => ( /* reexport safe */ K.GroundingDinoImageProcessor ), /* harmony export */ Idefics3ImageProcessor: () => ( /* reexport safe */ re.Idefics3ImageProcessor ), /* harmony export */ JinaCLIPImageProcessor: () => ( /* reexport safe */ V.JinaCLIPImageProcessor ), /* harmony export */ LlavaOnevisionImageProcessor: () => ( /* reexport safe */ U.LlavaOnevisionImageProcessor ), /* harmony export */ Mask2FormerImageProcessor: () => ( /* reexport safe */ q.Mask2FormerImageProcessor ), /* harmony export */ MaskFormerFeatureExtractor: () => ( /* reexport safe */ A.MaskFormerFeatureExtractor ), /* harmony export */ MaskFormerImageProcessor: () => ( /* reexport safe */ A.MaskFormerImageProcessor ), /* harmony export */ MobileNetV1FeatureExtractor: () => ( /* reexport safe */ S.MobileNetV1FeatureExtractor ), /* harmony export */ MobileNetV1ImageProcessor: () => ( /* reexport safe */ S.MobileNetV1ImageProcessor ), /* harmony export */ MobileNetV2FeatureExtractor: () => ( /* reexport safe */ w.MobileNetV2FeatureExtractor ), /* harmony export */ MobileNetV2ImageProcessor: () => ( /* reexport safe */ w.MobileNetV2ImageProcessor ), /* harmony export */ MobileNetV3FeatureExtractor: () => ( /* reexport safe */ P.MobileNetV3FeatureExtractor ), /* harmony export */ MobileNetV3ImageProcessor: () => ( /* reexport safe */ P.MobileNetV3ImageProcessor ), /* harmony export */ MobileNetV4FeatureExtractor: () => ( /* reexport safe */ I.MobileNetV4FeatureExtractor ), /* harmony export */ MobileNetV4ImageProcessor: () => ( /* reexport safe */ I.MobileNetV4ImageProcessor ), /* harmony export */ MobileViTFeatureExtractor: () => ( /* reexport safe */ le.MobileViTFeatureExtractor ), /* harmony export */ MobileViTImageProcessor: () => ( /* reexport safe */ le.MobileViTImageProcessor ), /* harmony export */ NougatImageProcessor: () => ( /* reexport safe */ oe.NougatImageProcessor ), /* harmony export */ OwlViTFeatureExtractor: () => ( /* reexport safe */ ge.OwlViTFeatureExtractor ), /* harmony export */ OwlViTImageProcessor: () => ( /* reexport safe */ ge.OwlViTImageProcessor ), /* harmony export */ Owlv2ImageProcessor: () => ( /* reexport safe */ ye.Owlv2ImageProcessor ), /* harmony export */ Phi3VImageProcessor: () => ( /* reexport safe */ se.Phi3VImageProcessor ), /* harmony export */ PvtImageProcessor: () => ( /* reexport safe */ be.PvtImageProcessor ), /* harmony export */ Qwen2VLImageProcessor: () => ( /* reexport safe */ pe.Qwen2VLImageProcessor ), /* harmony export */ RTDetrImageProcessor: () => ( /* reexport safe */ Ce.RTDetrImageProcessor ), /* harmony export */ SamImageProcessor: () => ( /* reexport safe */ $e.SamImageProcessor ), /* harmony export */ SegformerFeatureExtractor: () => ( /* reexport safe */ Pe.SegformerFeatureExtractor ), /* harmony export */ SegformerImageProcessor: () => ( /* reexport safe */ Pe.SegformerImageProcessor ), /* harmony export */ SiglipImageProcessor: () => ( /* reexport safe */ Je.SiglipImageProcessor ), /* harmony export */ Swin2SRImageProcessor: () => ( /* reexport safe */ Ue.Swin2SRImageProcessor ), /* harmony export */ VLMImageProcessor: () => ( /* reexport safe */ ie.VLMImageProcessor ), /* harmony export */ ViTFeatureExtractor: () => ( /* reexport safe */ we.ViTFeatureExtractor ), /* harmony export */ ViTImageProcessor: () => ( /* reexport safe */ we.ViTImageProcessor ), /* harmony export */ VitMatteImageProcessor: () => ( /* reexport safe */ X.VitMatteImageProcessor ), /* harmony export */ VitPoseImageProcessor: () => ( /* reexport safe */ de.VitPoseImageProcessor ), /* harmony export */ YolosFeatureExtractor: () => ( /* reexport safe */ Ee.YolosFeatureExtractor ), /* harmony export */ YolosImageProcessor: () => ( /* reexport safe */ Ee.YolosImageProcessor ) /* harmony export */ }); var g = r( /*! ./beit/image_processing_beit.js */ "./src/models/beit/image_processing_beit.js" ), O = r( /*! ./bit/image_processing_bit.js */ "./src/models/bit/image_processing_bit.js" ), j = r( /*! ./chinese_clip/image_processing_chinese_clip.js */ "./src/models/chinese_clip/image_processing_chinese_clip.js" ), ee = r( /*! ./clip/image_processing_clip.js */ "./src/models/clip/image_processing_clip.js" ), N = r( /*! ./convnext/image_processing_convnext.js */ "./src/models/convnext/image_processing_convnext.js" ), y = r( /*! ./deit/image_processing_deit.js */ "./src/models/deit/image_processing_deit.js" ), T = r( /*! ./detr/image_processing_detr.js */ "./src/models/detr/image_processing_detr.js" ), v = r( /*! ./donut/image_processing_donut.js */ "./src/models/donut/image_processing_donut.js" ), b = r( /*! ./dpt/image_processing_dpt.js */ "./src/models/dpt/image_processing_dpt.js" ), x = r( /*! ./efficientnet/image_processing_efficientnet.js */ "./src/models/efficientnet/image_processing_efficientnet.js" ), L = r( /*! ./glpn/image_processing_glpn.js */ "./src/models/glpn/image_processing_glpn.js" ), K = r( /*! ./grounding_dino/image_processing_grounding_dino.js */ "./src/models/grounding_dino/image_processing_grounding_dino.js" ), re = r( /*! ./idefics3/image_processing_idefics3.js */ "./src/models/idefics3/image_processing_idefics3.js" ), ie = r( /*! ./janus/image_processing_janus.js */ "./src/models/janus/image_processing_janus.js" ), V = r( /*! ./jina_clip/image_processing_jina_clip.js */ "./src/models/jina_clip/image_processing_jina_clip.js" ), U = r( /*! ./llava_onevision/image_processing_llava_onevision.js */ "./src/models/llava_onevision/image_processing_llava_onevision.js" ), q = r( /*! ./mask2former/image_processing_mask2former.js */ "./src/models/mask2former/image_processing_mask2former.js" ), A = r( /*! ./maskformer/image_processing_maskformer.js */ "./src/models/maskformer/image_processing_maskformer.js" ), S = r( /*! ./mobilenet_v1/image_processing_mobilenet_v1.js */ "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js" ), w = r( /*! ./mobilenet_v2/image_processing_mobilenet_v2.js */ "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js" ), P = r( /*! ./mobilenet_v3/image_processing_mobilenet_v3.js */ "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js" ), I = r( /*! ./mobilenet_v4/image_processing_mobilenet_v4.js */ "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js" ), le = r( /*! ./mobilevit/image_processing_mobilevit.js */ "./src/models/mobilevit/image_processing_mobilevit.js" ), oe = r( /*! ./nougat/image_processing_nougat.js */ "./src/models/nougat/image_processing_nougat.js" ), ye = r( /*! ./owlv2/image_processing_owlv2.js */ "./src/models/owlv2/image_processing_owlv2.js" ), ge = r( /*! ./owlvit/image_processing_owlvit.js */ "./src/models/owlvit/image_processing_owlvit.js" ), se = r( /*! ./phi3_v/image_processing_phi3_v.js */ "./src/models/phi3_v/image_processing_phi3_v.js" ), be = r( /*! ./pvt/image_processing_pvt.js */ "./src/models/pvt/image_processing_pvt.js" ), pe = r( /*! ./qwen2_vl/image_processing_qwen2_vl.js */ "./src/models/qwen2_vl/image_processing_qwen2_vl.js" ), Ce = r( /*! ./rt_detr/image_processing_rt_detr.js */ "./src/models/rt_detr/image_processing_rt_detr.js" ), $e = r( /*! ./sam/image_processing_sam.js */ "./src/models/sam/image_processing_sam.js" ), Pe = r( /*! ./segformer/image_processing_segformer.js */ "./src/models/segformer/image_processing_segformer.js" ), Je = r( /*! ./siglip/image_processing_siglip.js */ "./src/models/siglip/image_processing_siglip.js" ), Ue = r( /*! ./swin2sr/image_processing_swin2sr.js */ "./src/models/swin2sr/image_processing_swin2sr.js" ), we = r( /*! ./vit/image_processing_vit.js */ "./src/models/vit/image_processing_vit.js" ), X = r( /*! ./vitmatte/image_processing_vitmatte.js */ "./src/models/vitmatte/image_processing_vitmatte.js" ), de = r( /*! ./vitpose/image_processing_vitpose.js */ "./src/models/vitpose/image_processing_vitpose.js" ), Ee = r( /*! ./yolos/image_processing_yolos.js */ "./src/models/yolos/image_processing_yolos.js" ); } ), /***/ "./src/models/janus/image_processing_janus.js": ( /*!****************************************************!*\ !*** ./src/models/janus/image_processing_janus.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ VLMImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { constructor(ee) { super({ do_pad: !0, pad_size: { width: ee.image_size, height: ee.image_size }, ...ee }), this.constant_values = this.config.background_color.map((N) => N * this.rescale_factor); } pad_image(ee, N, y, T) { return super.pad_image(ee, N, y, { constant_values: this.constant_values, center: !0, ...T }); } } } ), /***/ "./src/models/janus/processing_janus.js": ( /*!**********************************************!*\ !*** ./src/models/janus/processing_janus.js ***! \**********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ VLChatProcessor: () => ( /* binding */ T ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), ee = r( /*! ../../utils/core.js */ "./src/utils/core.js" ), N = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ), y = r( /*! ../../utils/image.js */ "./src/utils/image.js" ); class T extends g.Processor { static image_processor_class = O.AutoImageProcessor; static tokenizer_class = j.AutoTokenizer; static uses_processor_config = !0; constructor(b, x) { super(b, x), this.image_tag = this.config.image_tag, this.image_start_tag = this.config.image_start_tag, this.image_end_tag = this.config.image_end_tag, this.num_image_tokens = this.config.num_image_tokens; } /** * @typedef {Object} MultimodalMessageProperties Additional properties for multimodal messages. * @property {(RawImage | string | URL)[]} [images] The images in the message. * @typedef {(import('../../tokenizers.js').Message & MultimodalMessageProperties)[]} MultimodalConversation The conversation possibly containing multimodal inputs. */ /** * @typedef {Object} VLCChatProcessorResult The processed input. * @property {Tensor} input_ids The input IDs. * @property {Tensor} attention_mask The attention mask. * @property {Tensor} images_seq_mask The image sequence mask. * @property {Tensor} images_emb_mask The image embedding mask. */ /** * @param {MultimodalConversation} conversation The chat messages to process. * @param {Object} options Additional options for processing. * @param {RawImage|RawImage[]} [options.images] The images to process, if not set in the conversation. * @param {string} [options.chat_template="default"] The chat template to use. * @returns {Promise} The processed input. */ async _call(b, { images: x = null, chat_template: L = "default" } = {}) { x ? Array.isArray(x) || (x = [x]) : x = await Promise.all( b.filter((oe) => oe.images).flatMap((oe) => oe.images).map((oe) => y.RawImage.read(oe)) ); const K = this.tokenizer, re = K.apply_chat_template(b, { tokenize: !1, add_generation_prompt: !0, chat_template: L }), ie = (oe) => K.encode(oe, { add_special_tokens: !1 }), V = ( /** @type {string} */ re.split(this.image_tag) ), U = V.length - 1; if (x.length !== U) throw new Error(`Number of images provided (${x.length}) does not match number of "${this.image_tag}" image tags (${U})`); const [ q, A, S ] = K.model.convert_tokens_to_ids([ this.image_tag, this.image_start_tag, this.image_end_tag ]); let w = ie(V[0]), P = new Array(w.length).fill(!1); for (let oe = 1; oe < V.length; ++oe) { const ye = new Array(this.num_image_tokens).fill(q), ge = ie(V[oe]); w = (0, ee.mergeArrays)( w, [A], ye, [S], ge ); const se = new Array(this.num_image_tokens).fill(!0); P = (0, ee.mergeArrays)( P, [!1], se, [!1], new Array(ge.length).fill(!1) ); } const I = [1, w.length], le = { input_ids: new N.Tensor("int64", w, I), attention_mask: new N.Tensor("int64", new Array(w.length).fill(1), I), images_seq_mask: new N.Tensor("bool", P, I), images_emb_mask: new N.Tensor( "bool", new Array(U * this.num_image_tokens).fill(!0), [1, U, this.num_image_tokens] ) }; if (x && x.length > 0) { const oe = await this.image_processor(x); return oe.pixel_values.unsqueeze_(0), { ...le, ...oe }; } return le; } } } ), /***/ "./src/models/jina_clip/image_processing_jina_clip.js": ( /*!************************************************************!*\ !*** ./src/models/jina_clip/image_processing_jina_clip.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ JinaCLIPImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { constructor(ee) { const { resize_mode: N, fill_color: y, interpolation: T, size: v, ...b } = ee, x = N === "squash" ? { width: v, height: v } : N === "shortest" ? { shortest_edge: v } : { longest_edge: v }, L = T === "bicubic" ? 3 : 2; super({ ...b, size: x, resample: L, do_center_crop: !0, crop_size: v, do_normalize: !0 }); } } } ), /***/ "./src/models/jina_clip/processing_jina_clip.js": ( /*!******************************************************!*\ !*** ./src/models/jina_clip/processing_jina_clip.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ JinaCLIPProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); class ee extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; async _call(y = null, T = null, v = {}) { if (!y && !T) throw new Error("Either text or images must be provided"); const b = y ? this.tokenizer(y, v) : {}, x = T ? await this.image_processor(T, v) : {}; return { ...b, ...x }; } } } ), /***/ "./src/models/llava_onevision/image_processing_llava_onevision.js": ( /*!************************************************************************!*\ !*** ./src/models/llava_onevision/image_processing_llava_onevision.js ***! \************************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ LlavaOnevisionImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/mask2former/image_processing_mask2former.js": ( /*!****************************************************************!*\ !*** ./src/models/mask2former/image_processing_mask2former.js ***! \****************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Mask2FormerImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../maskformer/image_processing_maskformer.js */ "./src/models/maskformer/image_processing_maskformer.js" ); class O extends g.MaskFormerImageProcessor { } } ), /***/ "./src/models/maskformer/image_processing_maskformer.js": ( /*!**************************************************************!*\ !*** ./src/models/maskformer/image_processing_maskformer.js ***! \**************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MaskFormerFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MaskFormerImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** @type {typeof post_process_panoptic_segmentation} */ post_process_panoptic_segmentation(...N) { return (0, g.post_process_panoptic_segmentation)(...N); } /** @type {typeof post_process_instance_segmentation} */ post_process_instance_segmentation(...N) { return (0, g.post_process_instance_segmentation)(...N); } } class j extends O { } } ), /***/ "./src/models/mgp_str/processing_mgp_str.js": ( /*!**************************************************!*\ !*** ./src/models/mgp_str/processing_mgp_str.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MgpstrProcessor: () => ( /* binding */ y ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), ee = r( /*! ../../utils/maths.js */ "./src/utils/maths.js" ); const N = { char: ["char_decode", 1], bpe: ["bpe_decode", 2], wp: ["wp_decode", 102] }; class y extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; /** * @returns {import('../../tokenizers.js').MgpstrTokenizer} The character tokenizer. */ get char_tokenizer() { return this.components.char_tokenizer; } /** * @returns {import('../../tokenizers.js').GPT2Tokenizer} The BPE tokenizer. */ get bpe_tokenizer() { return this.components.bpe_tokenizer; } /** * @returns {import('../../tokenizers.js').BertTokenizer} The WordPiece tokenizer. */ get wp_tokenizer() { return this.components.wp_tokenizer; } /** * Helper function to decode the model prediction logits. * @param {import('../../utils/tensor.js').Tensor} pred_logits Model prediction logits. * @param {string} format Type of model prediction. Must be one of ['char', 'bpe', 'wp']. * @returns {[string[], number[]]} The decoded sentences and their confidence scores. */ _decode_helper(v, b) { if (!N.hasOwnProperty(b)) throw new Error(`Format ${b} is not supported.`); const [x, L] = N[b], K = this[x].bind(this), [re, ie] = v.dims, V = [], U = [], q = v.tolist(); for (let S = 0; S < re; ++S) { const w = q[S], P = [], I = []; for (let oe = 1; oe < ie; ++oe) { const [ye, ge] = (0, ee.max)((0, ee.softmax)(w[oe])); if (I.push(ye), ge == L) break; P.push(ge); } const le = I.length > 0 ? I.reduce((oe, ye) => oe * ye, 1) : 0; U.push(P), V.push(le); } return [K(U), V]; } /** * Convert a list of lists of char token ids into a list of strings by calling char tokenizer. * @param {number[][]} sequences List of tokenized input ids. * @returns {string[]} The list of char decoded sentences. */ char_decode(v) { return this.char_tokenizer.batch_decode(v).map((b) => b.replaceAll(" ", "")); } /** * Convert a list of lists of BPE token ids into a list of strings by calling BPE tokenizer. * @param {number[][]} sequences List of tokenized input ids. * @returns {string[]} The list of BPE decoded sentences. */ bpe_decode(v) { return this.bpe_tokenizer.batch_decode(v); } /** * Convert a list of lists of word piece token ids into a list of strings by calling word piece tokenizer. * @param {number[][]} sequences List of tokenized input ids. * @returns {string[]} The list of wp decoded sentences. */ wp_decode(v) { return this.wp_tokenizer.batch_decode(v).map((b) => b.replaceAll(" ", "")); } /** * Convert a list of lists of token ids into a list of strings by calling decode. * @param {import('../../utils/tensor.js').Tensor[]} sequences List of tokenized input ids. * @returns {{generated_text: string[], scores: number[], char_preds: string[], bpe_preds: string[], wp_preds: string[]}} * Dictionary of all the outputs of the decoded results. * - generated_text: The final results after fusion of char, bpe, and wp. * - scores: The final scores after fusion of char, bpe, and wp. * - char_preds: The list of character decoded sentences. * - bpe_preds: The list of BPE decoded sentences. * - wp_preds: The list of wp decoded sentences. */ // @ts-expect-error The type of this method is not compatible with the one // in the base class. It might be a good idea to fix this. batch_decode([v, b, x]) { const [L, K] = this._decode_helper(v, "char"), [re, ie] = this._decode_helper(b, "bpe"), [V, U] = this._decode_helper(x, "wp"), q = [], A = []; for (let S = 0; S < L.length; ++S) { const [w, P] = (0, ee.max)([K[S], ie[S], U[S]]); q.push([L[S], re[S], V[S]][P]), A.push(w); } return { generated_text: q, scores: A, char_preds: L, bpe_preds: re, wp_preds: V }; } /** @type {typeof Processor.from_pretrained} */ static async from_pretrained(...v) { const b = await super.from_pretrained(...v), x = await j.AutoTokenizer.from_pretrained("Xenova/gpt2"), L = await j.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased"); return b.components = { image_processor: b.image_processor, char_tokenizer: b.tokenizer, bpe_tokenizer: x, wp_tokenizer: L }, b; } async _call(v, b = null) { const x = await this.image_processor(v); return b && (x.labels = this.tokenizer(b).input_ids), x; } } } ), /***/ "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js": ( /*!******************************************************************!*\ !*** ./src/models/mobilenet_v1/image_processing_mobilenet_v1.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MobileNetV1FeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MobileNetV1ImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js": ( /*!******************************************************************!*\ !*** ./src/models/mobilenet_v2/image_processing_mobilenet_v2.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MobileNetV2FeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MobileNetV2ImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js": ( /*!******************************************************************!*\ !*** ./src/models/mobilenet_v3/image_processing_mobilenet_v3.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MobileNetV3FeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MobileNetV3ImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js": ( /*!******************************************************************!*\ !*** ./src/models/mobilenet_v4/image_processing_mobilenet_v4.js ***! \******************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MobileNetV4FeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MobileNetV4ImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/mobilevit/image_processing_mobilevit.js": ( /*!************************************************************!*\ !*** ./src/models/mobilevit/image_processing_mobilevit.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MobileViTFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ MobileViTImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/moonshine/feature_extraction_moonshine.js": ( /*!**************************************************************!*\ !*** ./src/models/moonshine/feature_extraction_moonshine.js ***! \**************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MoonshineFeatureExtractor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.FeatureExtractor { /** * Asynchronously extracts input values from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. */ async _call(N) { (0, g.validate_audio_inputs)(N, "MoonshineFeatureExtractor"), N instanceof Float64Array && (N = new Float32Array(N)); const y = [ 1, /* batch_size */ N.length /* num_samples */ ]; return { input_values: new O.Tensor("float32", N, y) }; } } } ), /***/ "./src/models/moonshine/processing_moonshine.js": ( /*!******************************************************!*\ !*** ./src/models/moonshine/processing_moonshine.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ MoonshineProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ), O = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), j = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ); class ee extends j.Processor { static tokenizer_class = O.AutoTokenizer; static feature_extractor_class = g.AutoFeatureExtractor; /** * 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(y) { return await this.feature_extractor(y); } } } ), /***/ "./src/models/nougat/image_processing_nougat.js": ( /*!******************************************************!*\ !*** ./src/models/nougat/image_processing_nougat.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ NougatImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../donut/image_processing_donut.js */ "./src/models/donut/image_processing_donut.js" ); class O extends g.DonutImageProcessor { } } ), /***/ "./src/models/owlv2/image_processing_owlv2.js": ( /*!****************************************************!*\ !*** ./src/models/owlv2/image_processing_owlv2.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Owlv2ImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../owlvit/image_processing_owlvit.js */ "./src/models/owlvit/image_processing_owlvit.js" ); class O extends g.OwlViTImageProcessor { } } ), /***/ "./src/models/owlvit/image_processing_owlvit.js": ( /*!******************************************************!*\ !*** ./src/models/owlvit/image_processing_owlvit.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ OwlViTFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ OwlViTImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** @type {typeof post_process_object_detection} */ post_process_object_detection(...N) { return (0, g.post_process_object_detection)(...N); } } class j extends O { } } ), /***/ "./src/models/owlvit/processing_owlvit.js": ( /*!************************************************!*\ !*** ./src/models/owlvit/processing_owlvit.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ OwlViTProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); class ee extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; } } ), /***/ "./src/models/paligemma/processing_paligemma.js": ( /*!******************************************************!*\ !*** ./src/models/paligemma/processing_paligemma.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ PaliGemmaProcessor: () => ( /* binding */ y ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); const ee = ""; function N(T, v, b, x, L) { return `${x.repeat(b * L)}${v}${T} `; } class y extends g.Processor { static tokenizer_class = j.AutoTokenizer; static image_processor_class = O.AutoImageProcessor; static uses_processor_config = !1; /** * @typedef {import('../../utils/image.js').RawImage} RawImage */ // `images` is required, `text` is optional async _call(v, b = null, x = {}) { b || (console.warn( "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model." ), b = ""), Array.isArray(v) || (v = [v]), Array.isArray(b) || (b = [b]); const L = this.tokenizer.bos_token, K = this.image_processor.config.image_seq_length; let re; b.some((U) => U.includes(ee)) ? re = b.map( (U) => { const q = U.replaceAll(ee, ee.repeat(K)), A = q.lastIndexOf(ee), S = A === -1 ? 0 : A + ee.length; return q.slice(0, S) + L + q.slice(S) + ` `; } ) : (console.warn( "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens." ), re = b.map( (U) => N( U, L, K, ee, v.length ) )); const ie = this.tokenizer(re, x); return { ...await this.image_processor(v, x), ...ie }; } } } ), /***/ "./src/models/phi3_v/image_processing_phi3_v.js": ( /*!******************************************************!*\ !*** ./src/models/phi3_v/image_processing_phi3_v.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Phi3VImageProcessor: () => ( /* binding */ v ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); const j = 336, ee = [2, 3], { ceil: N, floor: y, sqrt: T } = Math; class v extends g.ImageProcessor { constructor(x) { super({ ...x, do_normalize: !0, do_pad: !0, pad_size: "custom", do_convert_rgb: !0, do_resize: !0 // Smart resizing "hd_transform" }), this._num_crops = x.num_crops; } calc_num_image_tokens_from_image_size(x, L) { const { num_img_tokens: K } = this.config; return y((y(L / j) * y(x / j) + 1) * K + 1 + (y(L / j) + 1) * T(K)); } /** @type {ImageProcessor['get_resize_output_image_size']} */ get_resize_output_image_size(x, L) { const K = this._num_crops, [re, ie] = x.size; let V = re / ie, U = 1; for (; U * Math.ceil(U / V) <= K; ) U += 1; U -= 1; const q = Math.floor(U * 336), A = Math.floor(q / V); return [q, A]; } /** @type {ImageProcessor['pad_image']} */ pad_image(x, L, K, re = {}) { const [ie, V] = L, U = j * N(ie / j), q = j * N(V / j), A = [1, 1, 1].map((S, w) => (S - this.image_mean[w]) / this.image_std[w]); return super.pad_image(x, L, { width: q, height: U }, { center: !0, constant_values: A, ...re }); } async _call(x, { num_crops: L = null } = {}) { if (this._num_crops = L ??= this.config.num_crops, L < 4 || T(L) % 1 !== 0) throw new Error("num_crops must be a square number >= 4"); Array.isArray(x) || (x = [x]); const K = x.length, re = await Promise.all(x.map((P) => this.preprocess(P))), ie = re.map((P) => P.original_size), V = re.map((P) => P.reshaped_input_size), U = []; for (const { pixel_values: P } of re) { P.unsqueeze_(0); const [I, le] = P.dims.slice(-2), oe = await (0, O.interpolate_4d)(P, { size: [j, j], mode: "bicubic" }); if (L > 0) { const ye = [], ge = T(L), se = y(le / ge), be = y(I / ge); for (let Ce = 0; Ce < ge; ++Ce) for (let $e = 0; $e < ge; ++$e) { let Pe, Je, Ue, we; Ce === ge - 1 ? (Je = I - be, we = I) : (Je = Ce * be, we = (Ce + 1) * be), $e === ge - 1 ? (Pe = le - se, Ue = le) : (Pe = $e * se, Ue = ($e + 1) * se); const X = [Je, Pe], de = [we, Ue], Ee = await (0, O.slice)(P, X, de, ee); ye.push(Ee); } const pe = await (0, O.interpolate_4d)((0, O.cat)(ye, 0), { size: [j, j], mode: "bicubic" }); U.push((0, O.cat)([oe, pe], 0)); } else U.push(oe); } const q = (0, O.stack)(U, 0), A = V.map((P) => P.map((I) => j * N(I / j))), S = new O.Tensor( "int64", A.flat(), [K, 2] ), w = A.map( ([P, I]) => this.calc_num_image_tokens_from_image_size(I, P) ); return { pixel_values: q, original_sizes: ie, reshaped_input_sizes: V, image_sizes: S, num_img_tokens: w }; } } } ), /***/ "./src/models/phi3_v/processing_phi3_v.js": ( /*!************************************************!*\ !*** ./src/models/phi3_v/processing_phi3_v.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Phi3VProcessor: () => ( /* binding */ y ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); r( /*! ../../utils/image.js */ "./src/utils/image.js" ); const ee = "<|image|>", N = /<\|image_\d+\|>/g; class y extends g.Processor { static image_processor_class = O.AutoImageProcessor; static tokenizer_class = j.AutoTokenizer; /** * * @param {string|string[]} text * @param {RawImage|RawImage[]} images * @param { { padding?: boolean, truncation?: boolean, num_crops?: number } | undefined } options * @returns {Promise} */ async _call(v, b = null, { padding: x = !0, truncation: L = !0, num_crops: K = null } = {}) { Array.isArray(v) || (v = [v]); let re, ie; if (b) { ie = await this.image_processor(b, { num_crops: K }); const { num_img_tokens: V } = ie, U = v.map((A, S) => A.split(N).join(ee.repeat(V[S]))); re = this.tokenizer(U, { padding: x, truncation: L }); const q = this.tokenizer.model.convert_tokens_to_ids([ee])[0]; re.input_ids.map_((A) => A == q ? -A : A); } else re = this.tokenizer(v); return { ...re, ...ie }; } } } ), /***/ "./src/models/processors.js": ( /*!**********************************!*\ !*** ./src/models/processors.js ***! \**********************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Florence2Processor: () => ( /* reexport safe */ g.Florence2Processor ), /* harmony export */ GroundingDinoProcessor: () => ( /* reexport safe */ O.GroundingDinoProcessor ), /* harmony export */ Idefics3Processor: () => ( /* reexport safe */ j.Idefics3Processor ), /* harmony export */ JinaCLIPProcessor: () => ( /* reexport safe */ N.JinaCLIPProcessor ), /* harmony export */ MgpstrProcessor: () => ( /* reexport safe */ y.MgpstrProcessor ), /* harmony export */ MoonshineProcessor: () => ( /* reexport safe */ T.MoonshineProcessor ), /* harmony export */ OwlViTProcessor: () => ( /* reexport safe */ v.OwlViTProcessor ), /* harmony export */ PaliGemmaProcessor: () => ( /* reexport safe */ x.PaliGemmaProcessor ), /* harmony export */ Phi3VProcessor: () => ( /* reexport safe */ b.Phi3VProcessor ), /* harmony export */ PyAnnoteProcessor: () => ( /* reexport safe */ L.PyAnnoteProcessor ), /* harmony export */ Qwen2VLProcessor: () => ( /* reexport safe */ K.Qwen2VLProcessor ), /* harmony export */ SamProcessor: () => ( /* reexport safe */ re.SamProcessor ), /* harmony export */ SpeechT5Processor: () => ( /* reexport safe */ ie.SpeechT5Processor ), /* harmony export */ VLChatProcessor: () => ( /* reexport safe */ ee.VLChatProcessor ), /* harmony export */ Wav2Vec2Processor: () => ( /* reexport safe */ V.Wav2Vec2Processor ), /* harmony export */ Wav2Vec2ProcessorWithLM: () => ( /* reexport safe */ U.Wav2Vec2ProcessorWithLM ), /* harmony export */ WhisperProcessor: () => ( /* reexport safe */ q.WhisperProcessor ) /* harmony export */ }); var g = r( /*! ./florence2/processing_florence2.js */ "./src/models/florence2/processing_florence2.js" ), O = r( /*! ./grounding_dino/processing_grounding_dino.js */ "./src/models/grounding_dino/processing_grounding_dino.js" ), j = r( /*! ./idefics3/processing_idefics3.js */ "./src/models/idefics3/processing_idefics3.js" ), ee = r( /*! ./janus/processing_janus.js */ "./src/models/janus/processing_janus.js" ), N = r( /*! ./jina_clip/processing_jina_clip.js */ "./src/models/jina_clip/processing_jina_clip.js" ), y = r( /*! ./mgp_str/processing_mgp_str.js */ "./src/models/mgp_str/processing_mgp_str.js" ), T = r( /*! ./moonshine/processing_moonshine.js */ "./src/models/moonshine/processing_moonshine.js" ), v = r( /*! ./owlvit/processing_owlvit.js */ "./src/models/owlvit/processing_owlvit.js" ), b = r( /*! ./phi3_v/processing_phi3_v.js */ "./src/models/phi3_v/processing_phi3_v.js" ), x = r( /*! ./paligemma/processing_paligemma.js */ "./src/models/paligemma/processing_paligemma.js" ), L = r( /*! ./pyannote/processing_pyannote.js */ "./src/models/pyannote/processing_pyannote.js" ), K = r( /*! ./qwen2_vl/processing_qwen2_vl.js */ "./src/models/qwen2_vl/processing_qwen2_vl.js" ), re = r( /*! ./sam/processing_sam.js */ "./src/models/sam/processing_sam.js" ), ie = r( /*! ./speecht5/processing_speecht5.js */ "./src/models/speecht5/processing_speecht5.js" ), V = r( /*! ./wav2vec2/processing_wav2vec2.js */ "./src/models/wav2vec2/processing_wav2vec2.js" ), U = r( /*! ./wav2vec2_with_lm/processing_wav2vec2_with_lm.js */ "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js" ), q = r( /*! ./whisper/processing_whisper.js */ "./src/models/whisper/processing_whisper.js" ); } ), /***/ "./src/models/pvt/image_processing_pvt.js": ( /*!************************************************!*\ !*** ./src/models/pvt/image_processing_pvt.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ PvtImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/pyannote/feature_extraction_pyannote.js": ( /*!************************************************************!*\ !*** ./src/models/pyannote/feature_extraction_pyannote.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ PyAnnoteFeatureExtractor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ), j = r( /*! ../../utils/maths.js */ "./src/utils/maths.js" ); class ee extends g.FeatureExtractor { /** * 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; }>} The extracted input features. */ async _call(y) { (0, g.validate_audio_inputs)(y, "PyAnnoteFeatureExtractor"), y instanceof Float64Array && (y = new Float32Array(y)); const T = [ 1, /* batch_size */ 1, /* num_channels */ y.length /* num_samples */ ]; return { input_values: new O.Tensor("float32", y, T) }; } /** * NOTE: Can return fractional values. `Math.ceil` will ensure correct value. * @param {number} samples The number of frames in the audio. * @returns {number} The number of frames in the audio. */ samples_to_frames(y) { return (y - this.config.offset) / this.config.step; } /** * Post-processes the speaker diarization logits output by the model. * @param {import('../../utils/tensor.js').Tensor} logits The speaker diarization logits output by the model. * @param {number} num_samples Number of samples in the input audio. * @returns {Array>} The post-processed speaker diarization results. */ post_process_speaker_diarization(y, T) { const v = T / this.samples_to_frames(T) / this.config.sampling_rate, b = []; for (const x of y.tolist()) { const L = []; let K = -1; for (let re = 0; re < x.length; ++re) { const ie = (0, j.softmax)(x[re]), [V, U] = (0, j.max)(ie), [q, A] = [re, re + 1]; U !== K ? (K = U, L.push({ id: U, start: q, end: A, score: V })) : (L.at(-1).end = A, L.at(-1).score += V); } b.push(L.map( // Convert frame-space to time-space // and compute the confidence ({ id: re, start: ie, end: V, score: U }) => ({ id: re, start: ie * v, end: V * v, confidence: U / (V - ie) }) )); } return b; } } } ), /***/ "./src/models/pyannote/processing_pyannote.js": ( /*!****************************************************!*\ !*** ./src/models/pyannote/processing_pyannote.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ PyAnnoteProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ./feature_extraction_pyannote.js */ "./src/models/pyannote/feature_extraction_pyannote.js" ); class j extends g.Processor { static feature_extractor_class = O.PyAnnoteFeatureExtractor; /** * 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(N) { return await this.feature_extractor(N); } /** @type {PyAnnoteFeatureExtractor['post_process_speaker_diarization']} */ post_process_speaker_diarization(...N) { return ( /** @type {PyAnnoteFeatureExtractor} */ this.feature_extractor.post_process_speaker_diarization(...N) ); } get sampling_rate() { return this.feature_extractor.config.sampling_rate; } } } ), /***/ "./src/models/qwen2_vl/image_processing_qwen2_vl.js": ( /*!**********************************************************!*\ !*** ./src/models/qwen2_vl/image_processing_qwen2_vl.js ***! \**********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Qwen2VLImageProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.ImageProcessor { async _call(N, ...y) { const { pixel_values: T, original_sizes: v, reshaped_input_sizes: b } = await super._call(N, ...y); let x = T; const { temporal_patch_size: L, merge_size: K, patch_size: re } = this.config; x.dims[0] === 1 && (x = (0, O.cat)(Array.from({ length: L }, () => x), 0)); const ie = x.dims[0] / L, V = x.dims[1], U = Math.floor(x.dims[2] / re), q = Math.floor(x.dims[3] / re), A = x.view( ie, L, V, Math.floor(U / K), K, re, Math.floor(q / K), K, re ).permute(0, 3, 6, 4, 7, 2, 1, 5, 8).view( ie * U * q, V * L * re * re ), S = new O.Tensor("int64", [ie, U, q], [1, 3]); return { pixel_values: A, image_grid_thw: S, original_sizes: v, reshaped_input_sizes: b }; } } } ), /***/ "./src/models/qwen2_vl/processing_qwen2_vl.js": ( /*!****************************************************!*\ !*** ./src/models/qwen2_vl/processing_qwen2_vl.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Qwen2VLProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), j = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ); r( /*! ../../utils/image.js */ "./src/utils/image.js" ); class ee extends g.Processor { static image_processor_class = O.AutoImageProcessor; static tokenizer_class = j.AutoTokenizer; /** * * @param {string|string[]} text * @param {RawImage|RawImage[]} images * @param {...any} args * @returns {Promise} */ async _call(y, T = null, ...v) { Array.isArray(y) || (y = [y]); let b, x; if (T && (b = await this.image_processor(T), x = b.image_grid_thw), x) { let K = this.image_processor.config.merge_size ** 2, re = 0; const ie = x.tolist(); y = y.map((V) => { for (; V.includes("<|image_pad|>"); ) { const U = Number(ie[re++].reduce((q, A) => q * A, 1n)); V = V.replace("<|image_pad|>", "<|placeholder|>".repeat(Math.floor(U / K))); } return V.replaceAll("<|placeholder|>", "<|image_pad|>"); }); } return { ...this.tokenizer(y), ...b // TODO: ...videos_inputs, }; } } } ), /***/ "./src/models/rt_detr/image_processing_rt_detr.js": ( /*!********************************************************!*\ !*** ./src/models/rt_detr/image_processing_rt_detr.js ***! \********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ RTDetrImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** @type {typeof post_process_object_detection} */ post_process_object_detection(...ee) { return (0, g.post_process_object_detection)(...ee); } } } ), /***/ "./src/models/sam/image_processing_sam.js": ( /*!************************************************!*\ !*** ./src/models/sam/image_processing_sam.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SamImageProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/core.js */ "./src/utils/core.js" ), j = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class ee extends g.ImageProcessor { /** * * @param {any} input_points * @param {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes * @param {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes * @returns {Tensor} */ reshape_input_points(y, T, v, b = !1) { y = structuredClone(y); let x = (0, O.calculateDimensions)(y); if (x.length === 3) b || (x = [1, ...x]), y = [y]; else if (x.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 L = 0; L < y.length; ++L) { let K = T[L], re = v[L], ie = [ re[0] / K[0], re[1] / K[1] ]; for (let V = 0; V < y[L].length; ++V) for (let U = 0; U < y[L][V].length; ++U) for (let q = 0; q < y[L][V][U].length; ++q) y[L][V][U][q] *= ie[q % 2]; } return new j.Tensor( "float32", Float32Array.from(y.flat(1 / 0)), x ); } /** * * @param {any} input_labels * @param {Tensor} input_points * @returns {Tensor} */ add_input_labels(y, T) { let v = (0, O.calculateDimensions)(y); if (v.length === 2) v = [1, ...v], y = [y]; else if (v.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 (v.some((b, x) => b !== T.dims[x])) throw Error(`The first ${v.length} dimensions of 'input_points' and 'input_labels' must be the same.`); return new j.Tensor( "int64", y.flat(1 / 0).map(BigInt), v ); } /** * @param {any[]} images The URL(s) of the image(s) to extract features from. * @param {Object} [options] Additional options for the processor. * @param {any} [options.input_points=null] 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} [options.input_labels=null] 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]`. * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user. * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size, * the number of boxes per image and the coordinates of the top left and botton right point of the box. * In the order (`x1`, `y1`, `x2`, `y2`): * - `x1`: the x coordinate of the top left point of the input box * - `y1`: the y coordinate of the top left point of the input box * - `x2`: the x coordinate of the bottom right point of the input box * - `y2`: the y coordinate of the bottom right point of the input box * @returns {Promise} */ async _call(y, { input_points: T = null, input_labels: v = null, input_boxes: b = null } = {}) { const x = await super._call(y); if (T && (x.input_points = this.reshape_input_points( T, x.original_sizes, x.reshaped_input_sizes )), v) { if (!x.input_points) throw Error("`input_points` must be provided if `input_labels` are provided."); x.input_labels = this.add_input_labels(v, x.input_points); } return b && (x.input_boxes = this.reshape_input_points( b, x.original_sizes, x.reshaped_input_sizes, !0 )), x; } /** * 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, 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, 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 {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. */ async post_process_masks(y, T, v, { mask_threshold: b = 0, binarize: x = !0, pad_size: L = null } = {}) { const K = []; L = L ?? this.pad_size; const re = [L.height, L.width]; for (let ie = 0; ie < T.length; ++ie) { const V = T[ie], U = v[ie]; let q = await (0, j.interpolate_4d)( y[ie], { mode: "bilinear", size: re } ); if (q = q.slice(null, null, [0, U[0]], [0, U[1]]), q = await (0, j.interpolate_4d)( q, { mode: "bilinear", size: V } ), x) { const A = q.data, S = new Uint8Array(A.length); for (let w = 0; w < A.length; ++w) A[w] > b && (S[w] = 1); q = new j.Tensor( "bool", S, q.dims ); } K.push(q); } return K; } /** * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. * @param {import("../../utils/image.js").RawImage} image Input original image * @param {number} target_size Target size of the resized image * @param {Object} options Options for generating crop boxes * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image. * Sets the number of layers to run, where each layer has 2**i_layer number of image crops. * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer, * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. * @param {number} [options.points_per_crop] Number of points to sample from each crop. * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is * scaled down by crop_n_points_downscale_factor**n. * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels. */ generate_crop_boxes(y, T, { crop_n_layers: v = 0, overlap_ratio: b = 0.3413333333333333, points_per_crop: x = 32, crop_n_points_downscale_factor: L = 1 } = {}) { } } } ), /***/ "./src/models/sam/processing_sam.js": ( /*!******************************************!*\ !*** ./src/models/sam/processing_sam.js ***! \******************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SamProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ); class j extends g.Processor { static image_processor_class = O.AutoImageProcessor; async _call(...N) { return await this.image_processor(...N); } post_process_masks(...N) { return this.image_processor.post_process_masks(...N); } reshape_input_points(...N) { return this.image_processor.reshape_input_points(...N); } } } ), /***/ "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js": ( /*!********************************************************************!*\ !*** ./src/models/seamless_m4t/feature_extraction_seamless_m4t.js ***! \********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SeamlessM4TFeatureExtractor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ), j = r( /*! ../../utils/audio.js */ "./src/utils/audio.js" ); class ee extends g.FeatureExtractor { constructor(y) { super(y); const T = this.config.sampling_rate, v = (0, j.mel_filter_bank)( 256, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(T / 2), // max_frequency T, // sampling_rate null, // norm "kaldi", // mel_scale !0 // triangularize_in_mel_space ); for (let b = 0; b < v.length; ++b) v[b].push(0); this.mel_filters = v, this.window = (0, j.window_function)(400, "povey", { periodic: !1 }); } /** * 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 {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(y, T) { return y = y.map((v) => v * 32768), (0, j.spectrogram)( y, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2, center: !1, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: "log", mel_floor: 1192092955078125e-22, remove_dc_offset: !0, // Custom max_num_frames: T, transpose: !0 } ); } /** * 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(y, { padding: T = !0, pad_to_multiple_of: v = 2, do_normalize_per_mel_bins: b = !0, return_attention_mask: x = !0 } = {}) { (0, g.validate_audio_inputs)(y, "SeamlessM4TFeatureExtractor"); let L = await this._extract_fbank_features(y, this.config.max_length); if (b) { const [S, w] = L.dims, P = L.data; for (let I = 0; I < w; ++I) { let le = 0; for (let se = 0; se < S; ++se) le += P[se * w + I]; const oe = le / S; let ye = 0; for (let se = 0; se < S; ++se) ye += (P[se * w + I] - oe) ** 2; ye /= S - 1; const ge = Math.sqrt(ye + 1e-7); for (let se = 0; se < S; ++se) { const be = se * w + I; P[be] = (P[be] - oe) / ge; } } } let K; if (T) { const [S, w] = L.dims, P = ( /** @type {Float32Array} */ L.data ), I = S % v; if (I > 0) { const le = new Float32Array(w * (S + I)); le.set(P), le.fill(this.config.padding_value, P.length); const oe = S + I; L = new O.Tensor( L.type, le, [oe, w] ), x && (K = new O.Tensor( "int64", new BigInt64Array(oe), [1, oe] ), K.data.fill(1n, 0, S)); } } const [re, ie] = L.dims, V = this.config.stride; if (re % V !== 0) throw new Error(`The number of frames (${re}) must be a multiple of the stride (${V}).`); const q = L.view( 1, Math.floor(re / V), ie * V ), A = { input_features: q }; if (x) { const S = q.dims[1], w = new BigInt64Array(S); if (K) { const P = K.data; for (let I = 1, le = 0; I < re; I += V, ++le) w[le] = P[I]; } else w.fill(1n); A.attention_mask = new O.Tensor( "int64", w, [1, S] ); } return A; } } } ), /***/ "./src/models/segformer/image_processing_segformer.js": ( /*!************************************************************!*\ !*** ./src/models/segformer/image_processing_segformer.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SegformerFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ SegformerImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** @type {typeof post_process_semantic_segmentation} */ post_process_semantic_segmentation(...N) { return (0, g.post_process_semantic_segmentation)(...N); } } class j extends O { } } ), /***/ "./src/models/siglip/image_processing_siglip.js": ( /*!******************************************************!*\ !*** ./src/models/siglip/image_processing_siglip.js ***! \******************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SiglipImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } } ), /***/ "./src/models/speecht5/feature_extraction_speecht5.js": ( /*!************************************************************!*\ !*** ./src/models/speecht5/feature_extraction_speecht5.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SpeechT5FeatureExtractor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); class O extends g.FeatureExtractor { } } ), /***/ "./src/models/speecht5/processing_speecht5.js": ( /*!****************************************************!*\ !*** ./src/models/speecht5/processing_speecht5.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ SpeechT5Processor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ), O = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), j = r( /*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ); class ee extends g.Processor { static tokenizer_class = O.AutoTokenizer; static feature_extractor_class = j.AutoFeatureExtractor; /** * 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(y) { return await this.feature_extractor(y); } } } ), /***/ "./src/models/swin2sr/image_processing_swin2sr.js": ( /*!********************************************************!*\ !*** ./src/models/swin2sr/image_processing_swin2sr.js ***! \********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Swin2SRImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { pad_image(ee, N, y, T = {}) { const [v, b, x] = N; return super.pad_image(ee, N, { // 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: b + (y - b % y) % y, height: v + (y - v % y) % y }, { mode: "symmetric", center: !1, constant_values: -1, ...T }); } } } ), /***/ "./src/models/vit/image_processing_vit.js": ( /*!************************************************!*\ !*** ./src/models/vit/image_processing_vit.js ***! \************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ ViTFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ ViTImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { } class j extends O { } } ), /***/ "./src/models/vitmatte/image_processing_vitmatte.js": ( /*!**********************************************************!*\ !*** ./src/models/vitmatte/image_processing_vitmatte.js ***! \**********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ VitMatteImageProcessor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.ImageProcessor { /** * Calls the feature extraction process on an array of images, preprocesses * each image, and concatenates the resulting features into a single Tensor. * @param {import("../../utils/image.js").RawImage[]} images The image(s) to extract features from. * @param {import("../../utils/image.js").RawImage[]} trimaps The trimaps(s) to extract features from. * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. */ async _call(N, y) { Array.isArray(N) || (N = [N]), Array.isArray(y) || (y = [y]); const T = await Promise.all(N.map((x) => this.preprocess(x))), v = await Promise.all(y.map((x) => this.preprocess(x, { do_normalize: !1, do_convert_rgb: !1, do_convert_grayscale: !0 }))); return { pixel_values: (0, O.stack)(T.map( // Concatenate images and trimaps (x, L) => (0, O.cat)([x.pixel_values, v[L].pixel_values], 0) ), 0), // Original sizes of images original_sizes: T.map((x) => x.original_size), // Reshaped sizes of images, before padding or cropping reshaped_input_sizes: T.map((x) => x.reshaped_input_size) }; } } } ), /***/ "./src/models/vitpose/image_processing_vitpose.js": ( /*!********************************************************!*\ !*** ./src/models/vitpose/image_processing_vitpose.js ***! \********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ VitPoseImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** * Transform the heatmaps into keypoint predictions and transform them back to the image. * NOTE: This is a naive implementation and does not include advanced post-processing techniques, * so the results may not be as accurate as the original implementation. * @param {import('../../utils/tensor.js').Tensor} outputs The model outputs. * @param {[number, number, number, number][][]} boxes List or array of bounding boxes for each image. * Each box should be a list of 4 floats representing the bounding box coordinates in COCO format (top_left_x, top_left_y, width, height). * @returns {{ * bbox: [number, number, number, number], * scores: number[], * labels: number[], * keypoints: [number, number][] * }[][]} List of keypoints predictions for each image. */ post_process_pose_estimation(ee, N, { threshold: y = null // TODO: // kernel_size = 11, // target_sizes = null, } = {}) { const T = ee.tolist(), [v, b, x, L] = ee.dims, K = []; for (let re = 0; re < v; ++re) { const ie = T[re], V = N[re], U = []; for (let q = 0; q < V.length; ++q) { const A = V[q], S = [], w = [], P = [], I = A.at(-2) / L, le = A.at(-1) / x; for (let oe = 0; oe < ie.length; ++oe) { let [ye, ge] = [0, 0], se = 0, be = -1 / 0; const pe = ie[oe]; for (let $e = 0; $e < pe.length; ++$e) { const Pe = pe[$e]; for (let Je = 0; Je < Pe.length; ++Je) { const Ue = Pe[Je]; se += Ue, be = Math.max(be, Ue), ye += (Je + 0.5) * Ue, ge += $e * Ue; } } if (y != null && be < y) continue; const Ce = [ I * ye / se, le * ge / se ]; S.push(Ce), P.push(oe), w.push(be); } U.push({ bbox: A, scores: w, labels: P, keypoints: S }); } K.push(U); } return K; } } } ), /***/ "./src/models/wav2vec2/feature_extraction_wav2vec2.js": ( /*!************************************************************!*\ !*** ./src/models/wav2vec2/feature_extraction_wav2vec2.js ***! \************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Wav2Vec2FeatureExtractor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ), O = r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); class j extends g.FeatureExtractor { /** * @param {Float32Array} input_values * @returns {Float32Array} */ _zero_mean_unit_var_norm(N) { const T = N.reduce((b, x) => b + x, 0) / N.length, v = N.reduce((b, x) => b + (x - T) ** 2, 0) / N.length; return N.map((b) => (b - T) / Math.sqrt(v + 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(N) { (0, g.validate_audio_inputs)(N, "Wav2Vec2FeatureExtractor"), N instanceof Float64Array && (N = new Float32Array(N)); let y = N; this.config.do_normalize && (y = this._zero_mean_unit_var_norm(y)); const T = [1, y.length]; return { input_values: new O.Tensor("float32", y, T), attention_mask: new O.Tensor("int64", new BigInt64Array(y.length).fill(1n), T) }; } } } ), /***/ "./src/models/wav2vec2/processing_wav2vec2.js": ( /*!****************************************************!*\ !*** ./src/models/wav2vec2/processing_wav2vec2.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Wav2Vec2Processor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), O = r( /*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ), j = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ); class ee extends j.Processor { static tokenizer_class = g.AutoTokenizer; static feature_extractor_class = O.AutoFeatureExtractor; /** * 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(y) { return await this.feature_extractor(y); } } } ), /***/ "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js": ( /*!********************************************************************!*\ !*** ./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js ***! \********************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Wav2Vec2ProcessorWithLM: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), O = r( /*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ), j = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ); class ee extends j.Processor { static tokenizer_class = g.AutoTokenizer; static feature_extractor_class = O.AutoFeatureExtractor; /** * 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(y) { return await this.feature_extractor(y); } } } ), /***/ "./src/models/wespeaker/feature_extraction_wespeaker.js": ( /*!**************************************************************!*\ !*** ./src/models/wespeaker/feature_extraction_wespeaker.js ***! \**************************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ WeSpeakerFeatureExtractor: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); var O = r( /*! ../../utils/audio.js */ "./src/utils/audio.js" ); class j extends g.FeatureExtractor { constructor(N) { super(N); const y = this.config.sampling_rate, T = (0, O.mel_filter_bank)( 256, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(y / 2), // max_frequency y, // sampling_rate null, // norm "kaldi", // mel_scale !0 // triangularize_in_mel_space ); for (let v = 0; v < T.length; ++v) T[v].push(0); this.mel_filters = T, this.window = (0, O.window_function)(400, "hamming", { periodic: !1 }), this.min_num_frames = this.config.min_num_frames; } /** * Computes the log-Mel spectrogram of the provided audio waveform. * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(N) { return N = N.map((y) => y * 32768), (0, O.spectrogram)( N, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2, center: !1, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: "log", mel_floor: 1192092955078125e-22, remove_dc_offset: !0, // Custom transpose: !0, min_num_frames: this.min_num_frames } ); } /** * 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(N) { (0, g.validate_audio_inputs)(N, "WeSpeakerFeatureExtractor"); const y = (await this._extract_fbank_features(N)).unsqueeze_(0); if (this.config.fbank_centering_span === null) { const T = ( /** @type {Float32Array} */ y.mean(1).data ), v = ( /** @type {Float32Array} */ y.data ), [b, x, L] = y.dims; for (let K = 0; K < b; ++K) { const re = K * x * L, ie = K * L; for (let V = 0; V < x; ++V) { const U = re + V * L; for (let q = 0; q < L; ++q) v[U + q] -= T[ie + q]; } } } return { input_features: y }; } } } ), /***/ "./src/models/whisper/common_whisper.js": ( /*!**********************************************!*\ !*** ./src/models/whisper/common_whisper.js ***! \**********************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ WHISPER_LANGUAGE_MAPPING: () => ( /* binding */ O ), /* harmony export */ WHISPER_TO_LANGUAGE_CODE_MAPPING: () => ( /* binding */ j ), /* harmony export */ whisper_language_to_code: () => ( /* binding */ ee ) /* harmony export */ }); const g = [ ["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"] ], O = new Map(g), j = new Map([ ...g.map(([N, y]) => [y, N]), ["burmese", "my"], ["valencian", "ca"], ["flemish", "nl"], ["haitian", "ht"], ["letzeburgesch", "lb"], ["pushto", "ps"], ["panjabi", "pa"], ["moldavian", "ro"], ["moldovan", "ro"], ["sinhalese", "si"], ["castilian", "es"] ]); function ee(N) { N = N.toLowerCase(); let y = j.get(N); if (y === void 0) if (O.has(N)) y = N; else { const v = N.length === 2 ? O.keys() : O.values(); throw new Error(`Language "${N}" is not supported. Must be one of: ${JSON.stringify(v)}`); } return y; } } ), /***/ "./src/models/whisper/feature_extraction_whisper.js": ( /*!**********************************************************!*\ !*** ./src/models/whisper/feature_extraction_whisper.js ***! \**********************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ WhisperFeatureExtractor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ); r( /*! ../../utils/tensor.js */ "./src/utils/tensor.js" ); var O = r( /*! ../../utils/audio.js */ "./src/utils/audio.js" ), j = r( /*! ../../utils/maths.js */ "./src/utils/maths.js" ); class ee extends g.FeatureExtractor { constructor(y) { super(y), this.config.mel_filters ??= (0, O.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 = (0, O.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 {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(y) { const T = await (0, O.spectrogram)( y, 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 } ), v = T.data, b = (0, j.max)( /** @type {Float32Array} */ v )[0]; for (let x = 0; x < v.length; ++x) v[x] = (Math.max(v[x], b - 8) + 4) / 4; return T; } /** * 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(y) { (0, g.validate_audio_inputs)(y, "WhisperFeatureExtractor"); let T; return y.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`." ), T = y.slice(0, this.config.n_samples)) : (T = new Float32Array(this.config.n_samples), T.set(y)), { input_features: (await this._extract_fbank_features(T)).unsqueeze_(0) }; } } } ), /***/ "./src/models/whisper/generation_whisper.js": ( /*!**************************************************!*\ !*** ./src/models/whisper/generation_whisper.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ WhisperGenerationConfig: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../generation/configuration_utils.js */ "./src/generation/configuration_utils.js" ); class O extends g.GenerationConfig { /** * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. * @type {boolean} */ return_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. * @type {boolean} */ return_token_timestamps = null; /** * The number of audio frames available in this chunk. This is only used generating word-level timestamps. * @type {number} */ num_frames = null; /** * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that * select the cross-attention heads that are highly correlated to word-level timing. * @type {[number, number][]} */ alignment_heads = null; /** * Task to use for generation, either "translate" or "transcribe". * @type {string} */ task = null; /** * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary. * @type {string} */ language = null; /** * The id of the `"<|notimestamps|>"` token. * @type {number} */ no_timestamps_token_id = null; /** * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is * provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value. * @type {number[]} */ prompt_ids = null; /** * Whether the model is multilingual or not. * @type {boolean} */ is_multilingual = null; /** * (Optional) A mapping from language tokens to their corresponding IDs. * Only required if the model is multilingual. * @type {Record|null} */ lang_to_id = null; /** * (Optional) A mapping from task tokens to their corresponding IDs. * @type {Record|null} */ task_to_id = null; /** * Used to set the maximum value of the initial timestamp. This is used to prevent the model from * predicting timestamps that are too far in the future. * @type {number} */ max_initial_timestamp_index = 1; } } ), /***/ "./src/models/whisper/processing_whisper.js": ( /*!**************************************************!*\ !*** ./src/models/whisper/processing_whisper.js ***! \**************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ WhisperProcessor: () => ( /* binding */ ee ) /* harmony export */ }); var g = r( /*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ), O = r( /*! ../../tokenizers.js */ "./src/tokenizers.js" ), j = r( /*! ../../base/processing_utils.js */ "./src/base/processing_utils.js" ); class ee extends j.Processor { static tokenizer_class = O.AutoTokenizer; static feature_extractor_class = g.AutoFeatureExtractor; /** * 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(y) { return await this.feature_extractor(y); } } } ), /***/ "./src/models/yolos/image_processing_yolos.js": ( /*!****************************************************!*\ !*** ./src/models/yolos/image_processing_yolos.js ***! \****************************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ YolosFeatureExtractor: () => ( /* binding */ j ), /* harmony export */ YolosImageProcessor: () => ( /* binding */ O ) /* harmony export */ }); var g = r( /*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ); class O extends g.ImageProcessor { /** @type {typeof post_process_object_detection} */ post_process_object_detection(...N) { return (0, g.post_process_object_detection)(...N); } } class j extends O { } } ), /***/ "./src/ops/registry.js": ( /*!*****************************!*\ !*** ./src/ops/registry.js ***! \*****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ TensorOpRegistry: () => ( /* binding */ y ) /* harmony export */ }); var g = r( /*! ../backends/onnx.js */ "./src/backends/onnx.js" ), O = r( /*! ../utils/tensor.js */ "./src/utils/tensor.js" ), j = r( /*! ../env.js */ "./src/env.js" ); const ee = j.apis.IS_BROWSER_ENV || j.apis.IS_WEBWORKER_ENV, N = async (T, v, b) => { const x = await (0, g.createInferenceSession)( new Uint8Array(T), v ); let L = Promise.resolve(); return ( /** @type {any} */ async (K) => { const re = (0, g.isONNXProxy)(), ie = Object.fromEntries(Object.entries(K).map(([U, q]) => [U, (re ? q.clone() : q).ort_tensor])), V = await (L = ee ? L.then(() => x.run(ie)) : x.run(ie)); return Array.isArray(b) ? b.map((U) => new O.Tensor(V[U])) : new O.Tensor(V[ /** @type {string} */ b ]); } ); }; class y { static session_options = { // TODO: Allow for multiple execution providers // executionProviders: ['webgpu'], }; static get nearest_interpolate_4d() { return this._nearest_interpolate_4d || (this._nearest_interpolate_4d = N( [8, 10, 18, 0, 58, 129, 1, 10, 41, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 18, 10, 4, 109, 111, 100, 101, 34, 7, 110, 101, 97, 114, 101, 115, 116, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 21], this.session_options, "y" )), this._nearest_interpolate_4d; } static get bilinear_interpolate_4d() { return this._bilinear_interpolate_4d || (this._bilinear_interpolate_4d = N( [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20], this.session_options, "y" )), this._bilinear_interpolate_4d; } static get bicubic_interpolate_4d() { return this._bicubic_interpolate_4d || (this._bicubic_interpolate_4d = N( [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20], this.session_options, "y" )), this._bicubic_interpolate_4d; } static get matmul() { return this._matmul || (this._matmul = N( [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20], this.session_options, "c" )), this._matmul; } static get stft() { return this._stft || (this._stft = N( [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17], this.session_options, "o" )), this._stft; } static get rfft() { return this._rfft || (this._rfft = N( [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20], this.session_options, "y" )), this._rfft; } static get top_k() { return this._top_k || (this._top_k = N( [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21], this.session_options, [ /* Values */ "v", /* Indices */ "i" ] )), this._top_k; } static get slice() { return this._slice || (this._slice = N( [8, 7, 18, 0, 58, 96, 10, 25, 10, 1, 120, 10, 1, 115, 10, 1, 101, 10, 1, 97, 10, 1, 116, 18, 1, 121, 34, 5, 83, 108, 105, 99, 101, 18, 1, 114, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 115, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 101, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 116, 18, 4, 10, 2, 8, 7, 98, 9, 10, 1, 121, 18, 4, 10, 2, 8, 1, 66, 2, 16, 13], this.session_options, "y" )), this._slice; } } } ), /***/ "./src/pipelines.js": ( /*!**************************!*\ !*** ./src/pipelines.js ***! \**************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AudioClassificationPipeline: () => ( /* binding */ ge ), /* harmony export */ AutomaticSpeechRecognitionPipeline: () => ( /* binding */ be ), /* harmony export */ DepthEstimationPipeline: () => ( /* binding */ Ee ), /* harmony export */ DocumentQuestionAnsweringPipeline: () => ( /* binding */ we ), /* harmony export */ FeatureExtractionPipeline: () => ( /* binding */ oe ), /* harmony export */ FillMaskPipeline: () => ( /* binding */ q ), /* harmony export */ ImageClassificationPipeline: () => ( /* binding */ Ce ), /* harmony export */ ImageFeatureExtractionPipeline: () => ( /* binding */ ye ), /* harmony export */ ImageSegmentationPipeline: () => ( /* binding */ $e ), /* harmony export */ ImageToImagePipeline: () => ( /* binding */ de ), /* harmony export */ ImageToTextPipeline: () => ( /* binding */ pe ), /* harmony export */ ObjectDetectionPipeline: () => ( /* binding */ Je ), /* harmony export */ Pipeline: () => ( /* binding */ re ), /* harmony export */ QuestionAnsweringPipeline: () => ( /* binding */ U ), /* harmony export */ SummarizationPipeline: () => ( /* binding */ S ), /* harmony export */ Text2TextGenerationPipeline: () => ( /* binding */ A ), /* harmony export */ TextClassificationPipeline: () => ( /* binding */ ie ), /* harmony export */ TextGenerationPipeline: () => ( /* binding */ I ), /* harmony export */ TextToAudioPipeline: () => ( /* binding */ X ), /* harmony export */ TokenClassificationPipeline: () => ( /* binding */ V ), /* harmony export */ TranslationPipeline: () => ( /* binding */ w ), /* harmony export */ ZeroShotAudioClassificationPipeline: () => ( /* binding */ se ), /* harmony export */ ZeroShotClassificationPipeline: () => ( /* binding */ le ), /* harmony export */ ZeroShotImageClassificationPipeline: () => ( /* binding */ Pe ), /* harmony export */ ZeroShotObjectDetectionPipeline: () => ( /* binding */ Ue ), /* harmony export */ pipeline: () => ( /* binding */ J ) /* harmony export */ }); var g = r( /*! ./tokenizers.js */ "./src/tokenizers.js" ), O = r( /*! ./models.js */ "./src/models.js" ), j = r( /*! ./models/auto/processing_auto.js */ "./src/models/auto/processing_auto.js" ); r( /*! ./base/processing_utils.js */ "./src/base/processing_utils.js" ); var ee = r( /*! ./utils/generic.js */ "./src/utils/generic.js" ), N = r( /*! ./utils/core.js */ "./src/utils/core.js" ), y = r( /*! ./utils/maths.js */ "./src/utils/maths.js" ), T = r( /*! ./utils/audio.js */ "./src/utils/audio.js" ), v = r( /*! ./utils/tensor.js */ "./src/utils/tensor.js" ), b = r( /*! ./utils/image.js */ "./src/utils/image.js" ); async function x(Ne) { return Array.isArray(Ne) || (Ne = [Ne]), await Promise.all(Ne.map((te) => b.RawImage.read(te))); } async function L(Ne, te) { return Array.isArray(Ne) || (Ne = [Ne]), await Promise.all(Ne.map((ve) => typeof ve == "string" || ve instanceof URL ? (0, T.read_audio)(ve, te) : ve instanceof Float64Array ? new Float32Array(ve) : ve)); } function K(Ne, te) { te && (Ne = Ne.map((Re) => Re | 0)); const [ve, He, je, Ve] = Ne; return { xmin: ve, ymin: He, xmax: je, ymax: Ve }; } class re extends ee.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: te, model: ve, tokenizer: He = null, processor: je = null }) { super(), this.task = te, this.model = ve, this.tokenizer = He, this.processor = je; } /** @type {DisposeType} */ async dispose() { await this.model.dispose(); } } class ie extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ re { /** * Create a new TextClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {TextClassificationPipelineCallback} */ async _call(te, { top_k: ve = 1 } = {}) { const He = this.tokenizer(te, { padding: !0, truncation: !0 }), je = await this.model(He), Ve = ( // @ts-expect-error TS2339 this.model.config.problem_type === "multi_label_classification" ? (at) => at.sigmoid() : (at) => new v.Tensor( "float32", (0, y.softmax)(at.data), at.dims ) ), Re = this.model.config.id2label, Ze = []; for (const at of je.logits) { const _t = Ve(at), lt = await (0, v.topk)(_t, ve), ct = lt[0].tolist(), ae = lt[1].tolist().map((H, me) => ({ label: Re ? Re[H] : `LABEL_${H}`, score: ct[me] })); ve === 1 ? Ze.push(...ae) : Ze.push(ae); } return Array.isArray(te) || ve === 1 ? ( /** @type {TextClassificationOutput} */ Ze ) : ( /** @type {TextClassificationOutput[]} */ Ze[0] ); } } class V extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ re { /** * Create a new TokenClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {TokenClassificationPipelineCallback} */ async _call(te, { ignore_labels: ve = ["O"] } = {}) { const He = Array.isArray(te), je = this.tokenizer(He ? te : [te], { padding: !0, truncation: !0 }), Re = (await this.model(je)).logits, Ze = this.model.config.id2label, at = []; for (let _t = 0; _t < Re.dims[0]; ++_t) { const lt = je.input_ids[_t], ct = Re[_t], F = []; for (let ae = 0; ae < ct.dims[0]; ++ae) { const H = ct[ae], me = (0, y.max)(H.data)[1], ke = Ze ? Ze[me] : `LABEL_${me}`; if (ve.includes(ke)) continue; const ze = this.tokenizer.decode([lt[ae].item()], { skip_special_tokens: !0 }); if (ze === "") continue; const Ge = (0, y.softmax)(H.data); F.push({ entity: ke, score: Ge[me], index: ae, word: ze // TODO: Add support for start and end // start: null, // end: null, }); } at.push(F); } return He ? at : at[0]; } } class U extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ re { /** * Create a new QuestionAnsweringPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {QuestionAnsweringPipelineCallback} */ async _call(te, ve, { top_k: He = 1 } = {}) { const je = this.tokenizer(te, { text_pair: ve, padding: !0, truncation: !0 }), { start_logits: Ve, end_logits: Re } = await this.model(je), Ze = je.input_ids.tolist(), at = je.attention_mask.tolist(), _t = this.tokenizer.all_special_ids, lt = []; for (let ct = 0; ct < Ve.dims[0]; ++ct) { const F = Ze[ct], ae = F.findIndex( (tt) => ( // We use == to match bigint with number // @ts-ignore tt == this.tokenizer.sep_token_id ) ); at[ct].map((tt, et) => tt == 1 && (et === 0 || et > ae && _t.findIndex((mt) => mt == F[et]) === -1)); const H = Ve[ct].tolist(), me = Re[ct].tolist(); for (let tt = 1; tt < H.length; ++tt) (at[ct] == 0 || tt <= ae || _t.findIndex((et) => et == F[tt]) !== -1) && (H[tt] = -1 / 0, me[tt] = -1 / 0); const ke = (0, y.softmax)(H).map((tt, et) => [tt, et]), ze = (0, y.softmax)(me).map((tt, et) => [tt, et]); ke[0][0] = 0, ze[0][0] = 0; const Ge = (0, N.product)(ke, ze).filter((tt) => tt[0][1] <= tt[1][1]).map((tt) => [tt[0][1], tt[1][1], tt[0][0] * tt[1][0]]).sort((tt, et) => et[2] - tt[2]); for (let tt = 0; tt < Math.min(Ge.length, He); ++tt) { const [et, mt, Nt] = Ge[tt], es = F.slice(et, mt + 1), Ts = this.tokenizer.decode(es, { skip_special_tokens: !0 }); lt.push({ answer: Ts, score: Nt }); } } return He === 1 ? lt[0] : lt; } } class q extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ re { /** * Create a new FillMaskPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {FillMaskPipelineCallback} */ async _call(te, { top_k: ve = 5 } = {}) { const He = this.tokenizer(te, { padding: !0, truncation: !0 }), { logits: je } = await this.model(He), Ve = [], Re = He.input_ids.tolist(); for (let Ze = 0; Ze < Re.length; ++Ze) { const at = Re[Ze], _t = at.findIndex( (H) => ( // We use == to match bigint with number // @ts-ignore H == this.tokenizer.mask_token_id ) ); if (_t === -1) throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`); const lt = je[Ze][_t], ct = await (0, v.topk)(new v.Tensor( "float32", (0, y.softmax)(lt.data), lt.dims ), ve), F = ct[0].tolist(), ae = ct[1].tolist(); Ve.push(ae.map((H, me) => { const ke = at.slice(); return ke[_t] = H, { score: F[me], token: Number(H), token_str: this.tokenizer.decode([H]), sequence: this.tokenizer.decode(ke, { skip_special_tokens: !0 }) }; })); } return Array.isArray(te) ? Ve : Ve[0]; } } class A extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ re { /** @type {'generated_text'} */ _key = "generated_text"; /** * Create a new Text2TextGenerationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {Text2TextGenerationPipelineCallback} */ async _call(te, ve = {}) { Array.isArray(te) || (te = [te]), this.model.config.prefix && (te = te.map((at) => this.model.config.prefix + at)); const He = this.model.config.task_specific_params; He && He[this.task] && He[this.task].prefix && (te = te.map((at) => He[this.task].prefix + at)); const je = this.tokenizer, Ve = { padding: !0, truncation: !0 }; let Re; this instanceof w && "_build_translation_inputs" in je ? Re = je._build_translation_inputs(te, Ve, ve) : Re = je(te, Ve); const Ze = await this.model.generate({ ...Re, ...ve }); return je.batch_decode( /** @type {Tensor} */ Ze, { skip_special_tokens: !0 } ).map((at) => ({ [this._key]: at })); } } class S extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ /** @type {any} */ A { /** @type {'summary_text'} */ _key = "summary_text"; /** * Create a new SummarizationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } } class w extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ /** @type {any} */ A { /** @type {'translation_text'} */ _key = "translation_text"; /** * Create a new TranslationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } } function P(Ne) { return Array.isArray(Ne) && Ne.every((te) => "role" in te && "content" in te); } class I extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ re { /** * Create a new TextGenerationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {TextGenerationPipelineCallback} */ async _call(te, ve = {}) { let He = !1, je = !1, Ve; if (typeof te == "string") Ve = te = [te]; else if (Array.isArray(te) && te.every((ae) => typeof ae == "string")) He = !0, Ve = /** @type {string[]} */ te; else { if (P(te)) te = [ /** @type {Chat} */ te ]; else if (Array.isArray(te) && te.every(P)) He = !0; else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats"); je = !0, Ve = /** @type {string[]} */ /** @type {Chat[]} */ te.map( (ae) => this.tokenizer.apply_chat_template(ae, { tokenize: !1, add_generation_prompt: !0 }) ); } const Re = ve.add_special_tokens ?? !1, Ze = je ? !1 : ve.return_full_text ?? !0; this.tokenizer.padding_side = "left"; const at = this.tokenizer(Ve, { add_special_tokens: Re, padding: !0, truncation: !0 }), _t = ( /** @type {Tensor} */ await this.model.generate({ ...at, ...ve }) ), lt = this.tokenizer.batch_decode(_t, { skip_special_tokens: !0 }); let ct; !Ze && at.input_ids.dims.at(-1) > 0 && (ct = this.tokenizer.batch_decode(at.input_ids, { skip_special_tokens: !0 }).map((ae) => ae.length)); const F = Array.from({ length: te.length }, (ae) => []); for (let ae = 0; ae < lt.length; ++ae) { const H = Math.floor(ae / _t.dims[0] * te.length); ct && (lt[ae] = lt[ae].slice(ct[H])), F[H].push({ generated_text: je ? [ .../** @type {Chat[]} */ te[H], { role: "assistant", content: lt[ae] } ] : lt[ae] }); } return !He && F.length === 1 ? F[0] : F; } } class le extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ re { /** * Create a new ZeroShotClassificationPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te), this.label2id = Object.fromEntries( Object.entries( /** @type {any} */ this.model.config.label2id ).map( ([ve, He]) => [ve.toLowerCase(), He] ) ), this.entailment_id = this.label2id.entailment, 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, 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(te, ve, { hypothesis_template: He = "This example is {}.", multi_label: je = !1 } = {}) { const Ve = Array.isArray(te); Ve || (te = [ /** @type {string} */ te ]), Array.isArray(ve) || (ve = [ve]); const Re = ve.map( (_t) => He.replace("{}", _t) ), Ze = je || ve.length === 1, at = []; for (const _t of te) { const lt = []; for (const ae of Re) { const H = this.tokenizer(_t, { text_pair: ae, padding: !0, truncation: !0 }), me = await this.model(H); Ze ? lt.push([ me.logits.data[this.contradiction_id], me.logits.data[this.entailment_id] ]) : lt.push(me.logits.data[this.entailment_id]); } const F = (Ze ? lt.map((ae) => (0, y.softmax)(ae)[1]) : (0, y.softmax)(lt)).map((ae, H) => [ae, H]).sort((ae, H) => H[0] - ae[0]); at.push({ sequence: _t, labels: F.map((ae) => ve[ae[1]]), scores: F.map((ae) => ae[0]) }); } return Ve ? at : at[0]; } } class oe extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ re { /** * Create a new FeatureExtractionPipeline. * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {FeatureExtractionPipelineCallback} */ async _call(te, { pooling: ve = ( /** @type {'none'} */ "none" ), normalize: He = !1, quantize: je = !1, precision: Ve = ( /** @type {'binary'} */ "binary" ) } = {}) { const Re = this.tokenizer(te, { padding: !0, truncation: !0 }), Ze = await this.model(Re); let at = Ze.last_hidden_state ?? Ze.logits ?? Ze.token_embeddings; if (ve !== "none") if (ve === "mean") at = (0, v.mean_pooling)(at, Re.attention_mask); else if (ve === "cls") at = at.slice(null, 0); else throw Error(`Pooling method '${ve}' not supported.`); return He && (at = at.normalize(2, -1)), je && (at = (0, v.quantize_embeddings)(at, Ve)), at; } } class ye extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ re { /** * Create a new ImageFeatureExtractionPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ImageFeatureExtractionPipelineCallback} */ async _call(te, { pool: ve = null } = {}) { const He = await x(te), { pixel_values: je } = await this.processor(He), Ve = await this.model({ pixel_values: je }); let Re; if (ve) { if (!("pooler_output" in Ve)) throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option."); Re = Ve.pooler_output; } else Re = Ve.last_hidden_state ?? Ve.logits ?? Ve.image_embeds; return Re; } } class ge extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ re { /** * Create a new AudioClassificationPipeline. * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {AudioClassificationPipelineCallback} */ async _call(te, { top_k: ve = 5 } = {}) { const He = this.processor.feature_extractor.config.sampling_rate, je = await L(te, He), Ve = this.model.config.id2label, Re = []; for (const Ze of je) { const at = await this.processor(Ze), lt = (await this.model(at)).logits[0], ct = await (0, v.topk)(new v.Tensor( "float32", (0, y.softmax)(lt.data), lt.dims ), ve), F = ct[0].tolist(), H = ct[1].tolist().map((me, ke) => ({ label: ( /** @type {string} */ Ve ? Ve[me] : `LABEL_${me}` ), score: ( /** @type {number} */ F[ke] ) })); Re.push(H); } return Array.isArray(te) ? Re : Re[0]; } } class se extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ re { /** * Create a new ZeroShotAudioClassificationPipeline. * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ZeroShotAudioClassificationPipelineCallback} */ async _call(te, ve, { hypothesis_template: He = "This is a sound of {}." } = {}) { const je = !Array.isArray(te); je && (te = [ /** @type {AudioInput} */ te ]); const Ve = ve.map( (lt) => He.replace("{}", lt) ), Re = this.tokenizer(Ve, { padding: !0, truncation: !0 }), Ze = this.processor.feature_extractor.config.sampling_rate, at = await L(te, Ze), _t = []; for (const lt of at) { const ct = await this.processor(lt), F = await this.model({ ...Re, ...ct }), ae = (0, y.softmax)(F.logits_per_audio.data); _t.push([...ae].map((H, me) => ({ score: H, label: ve[me] }))); } return je ? _t[0] : _t; } } class be extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ re { /** * Create a new AutomaticSpeechRecognitionPipeline. * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {AutomaticSpeechRecognitionPipelineCallback} */ async _call(te, ve = {}) { switch (this.model.config.model_type) { case "whisper": return this._call_whisper(te, ve); case "wav2vec2": case "wav2vec2-bert": case "unispeech": case "unispeech-sat": case "hubert": return this._call_wav2vec2(te, ve); case "moonshine": return this._call_moonshine(te, ve); default: throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`); } } /** * @type {AutomaticSpeechRecognitionPipelineCallback} * @private */ async _call_wav2vec2(te, ve) { ve.language && console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'), ve.task && console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); const He = !Array.isArray(te); He && (te = [ /** @type {AudioInput} */ te ]); const je = this.processor.feature_extractor.config.sampling_rate, Ve = await L(te, je), Re = []; for (const Ze of Ve) { const at = await this.processor(Ze), lt = (await this.model(at)).logits[0], ct = []; for (const ae of lt) ct.push((0, y.max)(ae.data)[1]); const F = this.tokenizer.decode(ct); Re.push({ text: F }); } return He ? Re[0] : Re; } /** * @type {AutomaticSpeechRecognitionPipelineCallback} * @private */ async _call_whisper(te, ve) { const He = ve.return_timestamps ?? !1, je = ve.chunk_length_s ?? 0, Ve = ve.force_full_sequences ?? !1; let Re = ve.stride_length_s ?? null; const Ze = { ...ve }; He === "word" && (Ze.return_token_timestamps = !0, Ze.return_timestamps = !1); const at = !Array.isArray(te); at && (te = [ /** @type {AudioInput} */ te ]); const _t = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions, lt = this.processor.feature_extractor.config.hop_length, ct = this.processor.feature_extractor.config.sampling_rate, F = await L(te, ct), ae = []; for (const H of F) { let me = []; if (je > 0) { if (Re === null) Re = je / 6; else if (je <= Re) throw Error("`chunk_length_s` must be larger than `stride_length_s`."); const Ge = ct * je, tt = ct * Re, et = Ge - 2 * tt; let mt = 0; for (; ; ) { const Nt = mt + Ge, es = H.subarray(mt, Nt), Ts = await this.processor(es), ms = mt === 0, Ps = Nt >= H.length; if (me.push({ stride: [ es.length, ms ? 0 : tt, Ps ? 0 : tt ], input_features: Ts.input_features, is_last: Ps }), Ps) break; mt += et; } } else me = [{ stride: [H.length, 0, 0], input_features: (await this.processor(H)).input_features, is_last: !0 }]; for (const Ge of me) { Ze.num_frames = Math.floor(Ge.stride[0] / lt); const tt = await this.model.generate({ inputs: Ge.input_features, ...Ze }); He === "word" ? (Ge.tokens = tt.sequences.tolist()[0], Ge.token_timestamps = tt.token_timestamps.tolist()[0].map( (et) => (0, y.round)(et, 2) )) : Ge.tokens = /** @type {Tensor} */ tt[0].tolist(), Ge.stride = Ge.stride.map((et) => et / ct); } const [ke, ze] = this.tokenizer._decode_asr(me, { time_precision: _t, return_timestamps: He, force_full_sequences: Ve }); ae.push({ text: ke, ...ze }); } return at ? ae[0] : ae; } /** * @type {AutomaticSpeechRecognitionPipelineCallback} * @private */ async _call_moonshine(te, ve) { const He = !Array.isArray(te); He && (te = [ /** @type {AudioInput} */ te ]); const je = this.processor.feature_extractor.config.sampling_rate, Ve = await L(te, je), Re = []; for (const Ze of Ve) { const at = await this.processor(Ze), _t = Math.floor(Ze.length / je) * 6, lt = await this.model.generate({ max_new_tokens: _t, ...ve, ...at }), ct = this.processor.batch_decode( /** @type {Tensor} */ lt, { skip_special_tokens: !0 } )[0]; Re.push({ text: ct }); } return He ? Re[0] : Re; } } class pe extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ re { /** * Create a new ImageToTextPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ImageToTextPipelineCallback} */ async _call(te, ve = {}) { const He = Array.isArray(te), je = await x(te), { pixel_values: Ve } = await this.processor(je), Re = []; for (const Ze of Ve) { Ze.dims = [1, ...Ze.dims]; const at = await this.model.generate({ inputs: Ze, ...ve }), _t = this.tokenizer.batch_decode( /** @type {Tensor} */ at, { skip_special_tokens: !0 } ).map((lt) => ({ generated_text: lt.trim() })); Re.push(_t); } return He ? Re : Re[0]; } } class Ce extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ re { /** * Create a new ImageClassificationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ImageClassificationPipelineCallback} */ async _call(te, { top_k: ve = 5 } = {}) { const He = await x(te), { pixel_values: je } = await this.processor(He), Ve = await this.model({ pixel_values: je }), Re = this.model.config.id2label, Ze = []; for (const at of Ve.logits) { const _t = await (0, v.topk)(new v.Tensor( "float32", (0, y.softmax)(at.data), at.dims ), ve), lt = _t[0].tolist(), F = _t[1].tolist().map((ae, H) => ({ label: ( /** @type {string} */ Re ? Re[ae] : `LABEL_${ae}` ), score: ( /** @type {number} */ lt[H] ) })); Ze.push(F); } return Array.isArray(te) ? Ze : Ze[0]; } } class $e extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ re { /** * Create a new ImageSegmentationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te), 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(te, { threshold: ve = 0.5, mask_threshold: He = 0.5, overlap_mask_area_threshold: je = 0.8, label_ids_to_fuse: Ve = null, target_sizes: Re = null, subtask: Ze = null } = {}) { if (Array.isArray(te) && te.length !== 1) throw Error("Image segmentation pipeline currently only supports a batch size of 1."); const _t = await x(te), lt = _t.map((ze) => [ze.height, ze.width]), { pixel_values: ct, pixel_mask: F } = await this.processor(_t), ae = await this.model({ pixel_values: ct, pixel_mask: F }); let H = null; if (Ze !== null) H = this.subtasks_mapping[Ze]; else for (let [ze, Ge] of Object.entries(this.subtasks_mapping)) if (Ge in this.processor.image_processor) { H = this.processor.image_processor[Ge].bind(this.processor.image_processor), Ze = ze; break; } const me = this.model.config.id2label, ke = []; if (Ze === "panoptic" || Ze === "instance") { const ze = H( ae, ve, He, je, Ve, Re ?? lt // TODO FIX? )[0], Ge = ze.segmentation; for (const tt of ze.segments_info) { const et = new Uint8ClampedArray(Ge.data.length); for (let Nt = 0; Nt < Ge.data.length; ++Nt) Ge.data[Nt] === tt.id && (et[Nt] = 255); const mt = new b.RawImage(et, Ge.dims[1], Ge.dims[0], 1); ke.push({ score: tt.score, label: me[tt.label_id], mask: mt }); } } else if (Ze === "semantic") { const { segmentation: ze, labels: Ge } = H(ae, Re ?? lt)[0]; for (const tt of Ge) { const et = new Uint8ClampedArray(ze.data.length); for (let Nt = 0; Nt < ze.data.length; ++Nt) ze.data[Nt] === tt && (et[Nt] = 255); const mt = new b.RawImage(et, ze.dims[1], ze.dims[0], 1); ke.push({ score: null, label: me[tt], mask: mt }); } } else throw Error(`Subtask ${Ze} not supported.`); return ke; } } class Pe extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ re { /** * Create a new ZeroShotImageClassificationPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ZeroShotImageClassificationPipelineCallback} */ async _call(te, ve, { hypothesis_template: He = "This is a photo of {}" } = {}) { const je = Array.isArray(te), Ve = await x(te), Re = ve.map( (F) => He.replace("{}", F) ), Ze = this.tokenizer(Re, { padding: this.model.config.model_type === "siglip" ? "max_length" : !0, truncation: !0 }), { pixel_values: at } = await this.processor(Ve), _t = await this.model({ ...Ze, pixel_values: at }), lt = this.model.config.model_type === "siglip" ? (F) => F.sigmoid().data : (F) => (0, y.softmax)(F.data), ct = []; for (const F of _t.logits_per_image) { const H = [...lt(F)].map((me, ke) => ({ score: me, label: ve[ke] })); H.sort((me, ke) => ke.score - me.score), ct.push(H); } return je ? ct : ct[0]; } } class Je extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ re { /** * Create a new ObjectDetectionPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ObjectDetectionPipelineCallback} */ async _call(te, { threshold: ve = 0.9, percentage: He = !1 } = {}) { const je = Array.isArray(te); if (je && te.length !== 1) throw Error("Object detection pipeline currently only supports a batch size of 1."); const Ve = await x(te), Re = He ? null : Ve.map((ae) => [ae.height, ae.width]), { pixel_values: Ze, pixel_mask: at } = await this.processor(Ve), _t = await this.model({ pixel_values: Ze, pixel_mask: at }), lt = this.processor.image_processor.post_process_object_detection(_t, ve, Re), ct = this.model.config.id2label, F = lt.map((ae) => ae.boxes.map((H, me) => ({ score: ae.scores[me], label: ct[ae.classes[me]], box: K(H, !He) }))); return je ? F : F[0]; } } class Ue extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ re { /** * Create a new ZeroShotObjectDetectionPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ZeroShotObjectDetectionPipelineCallback} */ async _call(te, ve, { threshold: He = 0.1, top_k: je = null, percentage: Ve = !1 } = {}) { const Re = Array.isArray(te), Ze = await x(te), at = this.tokenizer(ve, { padding: !0, truncation: !0 }), _t = await this.processor(Ze), lt = []; for (let ct = 0; ct < Ze.length; ++ct) { const F = Ze[ct], ae = Ve ? null : [[F.height, F.width]], H = _t.pixel_values[ct].unsqueeze_(0), me = await this.model({ ...at, pixel_values: H }); let ke; if ("post_process_grounded_object_detection" in this.processor) { const ze = this.processor.post_process_grounded_object_detection( me, at.input_ids, { // TODO: support separate threshold values box_threshold: He, text_threshold: He, target_sizes: ae } )[0]; ke = ze.boxes.map((Ge, tt) => ({ score: ze.scores[tt], label: ze.labels[tt], box: K(Ge, !Ve) })); } else { const ze = this.processor.image_processor.post_process_object_detection(me, He, ae, !0)[0]; ke = ze.boxes.map((Ge, tt) => ({ score: ze.scores[tt], label: ve[ze.classes[tt]], box: K(Ge, !Ve) })); } ke.sort((ze, Ge) => Ge.score - ze.score), je !== null && (ke = ke.slice(0, je)), lt.push(ke); } return Re ? lt : lt[0]; } } class we extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ re { /** * Create a new DocumentQuestionAnsweringPipeline. * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {DocumentQuestionAnsweringPipelineCallback} */ async _call(te, ve, He = {}) { const je = (await x(te))[0], { pixel_values: Ve } = await this.processor(je), Re = `${ve}`, Ze = this.tokenizer(Re, { add_special_tokens: !1, padding: !0, truncation: !0 }).input_ids, at = await this.model.generate({ inputs: Ve, // @ts-expect-error TS2339 max_length: this.model.config.decoder.max_position_embeddings, decoder_input_ids: Ze, ...He }), lt = this.tokenizer.batch_decode( /** @type {Tensor} */ at )[0].match(/(.*?)<\/s_answer>/); let ct = null; return lt && lt.length >= 2 && (ct = lt[1].trim()), [{ answer: ct }]; } } class X extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ re { DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"; /** * Create a new TextToAudioPipeline. * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te), this.vocoder = te.vocoder ?? null; } /** @type {TextToAudioPipelineCallback} */ async _call(te, { speaker_embeddings: ve = null } = {}) { return this.processor ? this._call_text_to_spectrogram(te, { speaker_embeddings: ve }) : this._call_text_to_waveform(te); } async _call_text_to_waveform(te) { const ve = this.tokenizer(te, { padding: !0, truncation: !0 }), { waveform: He } = await this.model(ve), je = this.model.config.sampling_rate; return new T.RawAudio( He.data, je ); } async _call_text_to_spectrogram(te, { speaker_embeddings: ve }) { if (this.vocoder || (console.log("No vocoder specified, using default HifiGan vocoder."), this.vocoder = await O.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: "fp32" })), (typeof ve == "string" || ve instanceof URL) && (ve = new Float32Array( await (await fetch(ve)).arrayBuffer() )), ve instanceof Float32Array) ve = new v.Tensor( "float32", ve, [1, ve.length] ); else if (!(ve instanceof v.Tensor)) throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`."); const { input_ids: He } = this.tokenizer(te, { padding: !0, truncation: !0 }), { waveform: je } = await this.model.generate_speech(He, ve, { vocoder: this.vocoder }), Ve = this.processor.feature_extractor.config.sampling_rate; return new T.RawAudio( je.data, Ve ); } } class de extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ re { /** * Create a new ImageToImagePipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {ImageToImagePipelineCallback} */ async _call(te) { const ve = await x(te), He = await this.processor(ve), je = await this.model(He), Ve = []; for (const Re of je.reconstruction) { const Ze = Re.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8"); Ve.push(b.RawImage.fromTensor(Ze)); } return Ve.length > 1 ? Ve : Ve[0]; } } class Ee extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ re { /** * Create a new DepthEstimationPipeline. * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. */ constructor(te) { super(te); } /** @type {DepthEstimationPipelineCallback} */ async _call(te) { const ve = await x(te), He = await this.processor(ve), { predicted_depth: je } = await this.model(He), Ve = []; for (let Re = 0; Re < ve.length; ++Re) { const Ze = je[Re], [at, _t] = Ze.dims.slice(-2), [lt, ct] = ve[Re].size, F = (await (0, v.interpolate_4d)(Ze.view(1, 1, at, _t), { size: [ct, lt], mode: "bilinear" })).view(ct, lt), ae = ( /** @type {number} */ F.min().item() ), H = ( /** @type {number} */ F.max().item() ), me = F.sub(ae).div_(H - ae).mul_(255).to("uint8").unsqueeze(0), ke = b.RawImage.fromTensor(me); Ve.push({ predicted_depth: F, depth: ke }); } return Ve.length > 1 ? Ve : Ve[0]; } } const Oe = Object.freeze({ "text-classification": { tokenizer: g.AutoTokenizer, pipeline: ie, model: O.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: g.AutoTokenizer, pipeline: V, model: O.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: g.AutoTokenizer, pipeline: U, model: O.AutoModelForQuestionAnswering, default: { // TODO: replace with original // "model": "distilbert-base-cased-distilled-squad", model: "Xenova/distilbert-base-cased-distilled-squad" }, type: "text" }, "fill-mask": { tokenizer: g.AutoTokenizer, pipeline: q, model: O.AutoModelForMaskedLM, default: { // TODO: replace with original // "model": "bert-base-uncased", model: "Xenova/bert-base-uncased" }, type: "text" }, summarization: { tokenizer: g.AutoTokenizer, pipeline: S, model: O.AutoModelForSeq2SeqLM, default: { // TODO: replace with original // "model": "sshleifer/distilbart-cnn-6-6", model: "Xenova/distilbart-cnn-6-6" }, type: "text" }, translation: { tokenizer: g.AutoTokenizer, pipeline: w, model: O.AutoModelForSeq2SeqLM, default: { // TODO: replace with original // "model": "t5-small", model: "Xenova/t5-small" }, type: "text" }, "text2text-generation": { tokenizer: g.AutoTokenizer, pipeline: A, model: O.AutoModelForSeq2SeqLM, default: { // TODO: replace with original // "model": "google/flan-t5-small", model: "Xenova/flan-t5-small" }, type: "text" }, "text-generation": { tokenizer: g.AutoTokenizer, pipeline: I, model: O.AutoModelForCausalLM, default: { // TODO: replace with original // "model": "gpt2", model: "Xenova/gpt2" }, type: "text" }, "zero-shot-classification": { tokenizer: g.AutoTokenizer, pipeline: le, model: O.AutoModelForSequenceClassification, default: { // TODO: replace with original // "model": "typeform/distilbert-base-uncased-mnli", model: "Xenova/distilbert-base-uncased-mnli" }, type: "text" }, "audio-classification": { pipeline: ge, model: O.AutoModelForAudioClassification, processor: j.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: g.AutoTokenizer, pipeline: se, model: O.AutoModel, processor: j.AutoProcessor, default: { // TODO: replace with original // "model": "laion/clap-htsat-fused", model: "Xenova/clap-htsat-unfused" }, type: "multimodal" }, "automatic-speech-recognition": { tokenizer: g.AutoTokenizer, pipeline: be, model: [O.AutoModelForSpeechSeq2Seq, O.AutoModelForCTC], processor: j.AutoProcessor, default: { // TODO: replace with original // "model": "openai/whisper-tiny.en", model: "Xenova/whisper-tiny.en" }, type: "multimodal" }, "text-to-audio": { tokenizer: g.AutoTokenizer, pipeline: X, model: [O.AutoModelForTextToWaveform, O.AutoModelForTextToSpectrogram], processor: [ j.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: g.AutoTokenizer, pipeline: pe, model: O.AutoModelForVision2Seq, processor: j.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: Ce, model: O.AutoModelForImageClassification, processor: j.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: $e, model: [O.AutoModelForImageSegmentation, O.AutoModelForSemanticSegmentation, O.AutoModelForUniversalSegmentation], processor: j.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: g.AutoTokenizer, pipeline: Pe, model: O.AutoModel, processor: j.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: Je, model: O.AutoModelForObjectDetection, processor: j.AutoProcessor, default: { // TODO: replace with original // "model": "facebook/detr-resnet-50", model: "Xenova/detr-resnet-50" }, type: "multimodal" }, "zero-shot-object-detection": { tokenizer: g.AutoTokenizer, pipeline: Ue, model: O.AutoModelForZeroShotObjectDetection, processor: j.AutoProcessor, default: { // TODO: replace with original // "model": "google/owlvit-base-patch32", model: "Xenova/owlvit-base-patch32" }, type: "multimodal" }, "document-question-answering": { tokenizer: g.AutoTokenizer, pipeline: we, model: O.AutoModelForDocumentQuestionAnswering, processor: j.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: de, model: O.AutoModelForImageToImage, processor: j.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: Ee, model: O.AutoModelForDepthEstimation, processor: j.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: g.AutoTokenizer, pipeline: oe, model: O.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: j.AutoProcessor, pipeline: ye, model: [O.AutoModelForImageFeatureExtraction, O.AutoModel], default: { // TODO: replace with original // "model": "google/vit-base-patch16-224", model: "Xenova/vit-base-patch16-224-in21k" }, type: "image" } }), Xe = 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" }); async function J(Ne, te = null, { progress_callback: ve = null, config: He = null, cache_dir: je = null, local_files_only: Ve = !1, revision: Re = "main", device: Ze = null, dtype: at = null, model_file_name: _t = null, session_options: lt = {} } = {}) { Ne = Xe[Ne] ?? Ne; const ct = Oe[Ne.split("_", 1)[0]]; if (!ct) throw Error(`Unsupported pipeline: ${Ne}. Must be one of [${Object.keys(Oe)}]`); te || (te = ct.default.model, console.log(`No model specified. Using default model: "${te}".`)); const F = { progress_callback: ve, config: He, cache_dir: je, local_files_only: Ve, revision: Re, device: Ze, dtype: at, model_file_name: _t, session_options: lt }, ae = /* @__PURE__ */ new Map([ ["tokenizer", ct.tokenizer], ["model", ct.model], ["processor", ct.processor] ]), H = await We(ae, te, F); H.task = Ne, (0, N.dispatchCallback)(ve, { status: "ready", task: Ne, model: te }); const me = ct.pipeline; return new me(H); } async function We(Ne, te, ve) { const He = /* @__PURE__ */ Object.create(null), je = []; for (const [Ve, Re] of Ne.entries()) { if (!Re) continue; let Ze; Array.isArray(Re) ? Ze = new Promise(async (at, _t) => { let lt; for (const ct of Re) { if (ct === null) { at(null); return; } try { at(await ct.from_pretrained(te, ve)); return; } catch (F) { if (F.message?.includes("Unsupported model type")) lt = F; else if (F.message?.includes("Could not locate file")) lt = F; else { _t(F); return; } } } _t(lt); }) : Ze = Re.from_pretrained(te, ve), He[Ve] = Ze, je.push(Ze); } await Promise.all(je); for (const [Ve, Re] of Object.entries(He)) He[Ve] = await Re; return He; } } ), /***/ "./src/tokenizers.js": ( /*!***************************!*\ !*** ./src/tokenizers.js ***! \***************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ AlbertTokenizer: () => ( /* binding */ Tr ), /* harmony export */ AutoTokenizer: () => ( /* binding */ as ), /* harmony export */ BartTokenizer: () => ( /* binding */ cn ), /* harmony export */ BertTokenizer: () => ( /* binding */ Kr ), /* harmony export */ BlenderbotSmallTokenizer: () => ( /* binding */ An ), /* harmony export */ BlenderbotTokenizer: () => ( /* binding */ $n ), /* harmony export */ BloomTokenizer: () => ( /* binding */ qr ), /* harmony export */ CLIPTokenizer: () => ( /* binding */ _n ), /* harmony export */ CamembertTokenizer: () => ( /* binding */ nt ), /* harmony export */ CodeGenTokenizer: () => ( /* binding */ mn ), /* harmony export */ CodeLlamaTokenizer: () => ( /* binding */ Lr ), /* harmony export */ CohereTokenizer: () => ( /* binding */ wn ), /* harmony export */ ConvBertTokenizer: () => ( /* binding */ Or ), /* harmony export */ DebertaTokenizer: () => ( /* binding */ lr ), /* harmony export */ DebertaV2Tokenizer: () => ( /* binding */ Fr ), /* harmony export */ DistilBertTokenizer: () => ( /* binding */ ir ), /* harmony export */ ElectraTokenizer: () => ( /* binding */ Ft ), /* harmony export */ EsmTokenizer: () => ( /* binding */ zr ), /* harmony export */ FalconTokenizer: () => ( /* binding */ Cn ), /* harmony export */ GPT2Tokenizer: () => ( /* binding */ Pn ), /* harmony export */ GPTNeoXTokenizer: () => ( /* binding */ kn ), /* harmony export */ GemmaTokenizer: () => ( /* binding */ to ), /* harmony export */ Grok1Tokenizer: () => ( /* binding */ Br ), /* harmony export */ HerbertTokenizer: () => ( /* binding */ Er ), /* harmony export */ LlamaTokenizer: () => ( /* binding */ pn ), /* harmony export */ M2M100Tokenizer: () => ( /* binding */ hn ), /* harmony export */ MBart50Tokenizer: () => ( /* binding */ Mr ), /* harmony export */ MBartTokenizer: () => ( /* binding */ ws ), /* harmony export */ MPNetTokenizer: () => ( /* binding */ En ), /* harmony export */ MarianTokenizer: () => ( /* binding */ Ot ), /* harmony export */ MgpstrTokenizer: () => ( /* binding */ On ), /* harmony export */ MobileBertTokenizer: () => ( /* binding */ Pr ), /* harmony export */ NllbTokenizer: () => ( /* binding */ ar ), /* harmony export */ NougatTokenizer: () => ( /* binding */ Rr ), /* harmony export */ PreTrainedTokenizer: () => ( /* binding */ Lt ), /* harmony export */ Qwen2Tokenizer: () => ( /* binding */ Sn ), /* harmony export */ RoFormerTokenizer: () => ( /* binding */ Dr ), /* harmony export */ RobertaTokenizer: () => ( /* binding */ zs ), /* harmony export */ SiglipTokenizer: () => ( /* binding */ fn ), /* harmony export */ SpeechT5Tokenizer: () => ( /* binding */ In ), /* harmony export */ SqueezeBertTokenizer: () => ( /* binding */ Hr ), /* harmony export */ T5Tokenizer: () => ( /* binding */ Zs ), /* harmony export */ TokenizerModel: () => ( /* binding */ ye ), /* harmony export */ VitsTokenizer: () => ( /* binding */ Fn ), /* harmony export */ Wav2Vec2CTCTokenizer: () => ( /* binding */ gn ), /* harmony export */ WhisperTokenizer: () => ( /* binding */ Qr ), /* harmony export */ XLMRobertaTokenizer: () => ( /* binding */ eo ), /* harmony export */ XLMTokenizer: () => ( /* binding */ vt ), /* harmony export */ is_chinese_char: () => ( /* binding */ q ) /* harmony export */ }); var g = r( /*! ./utils/generic.js */ "./src/utils/generic.js" ), O = r( /*! ./utils/core.js */ "./src/utils/core.js" ), j = r( /*! ./utils/hub.js */ "./src/utils/hub.js" ), ee = r( /*! ./utils/maths.js */ "./src/utils/maths.js" ), N = r( /*! ./utils/tensor.js */ "./src/utils/tensor.js" ), y = r( /*! ./utils/data-structures.js */ "./src/utils/data-structures.js" ), T = r( /*! @huggingface/jinja */ "./node_modules/@huggingface/jinja/dist/index.js" ), v = r( /*! ./models/whisper/common_whisper.js */ "./src/models/whisper/common_whisper.js" ); async function b(Te, M) { const Y = await Promise.all([ (0, j.getModelJSON)(Te, "tokenizer.json", !0, M), (0, j.getModelJSON)(Te, "tokenizer_config.json", !0, M) ]); return M.legacy !== null && (Y[1].legacy = M.legacy), Y; } function x(Te, M) { const Y = []; let ce = 0; for (const _e of Te.matchAll(M)) { const Fe = _e[0]; ce < _e.index && Y.push(Te.slice(ce, _e.index)), Fe.length > 0 && Y.push(Fe), ce = _e.index + Fe.length; } return ce < Te.length && Y.push(Te.slice(ce)), Y; } function L(Te, M = !0) { if (Te.Regex !== void 0) { let Y = Te.Regex.replace(/\\([#&~])/g, "$1"); for (const [ce, _e] of le) Y = Y.replaceAll(ce, _e); return new RegExp(Y, "gu"); } else if (Te.String !== void 0) { const Y = (0, O.escapeRegExp)(Te.String); return new RegExp(M ? Y : `(${Y})`, "gu"); } else return console.warn("Unknown pattern type:", Te), null; } function K(Te) { return new Map(Object.entries(Te)); } function re(Te) { const M = Te.dims; switch (M.length) { case 1: return Te.tolist(); case 2: if (M[0] !== 1) throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs."); return Te.tolist()[0]; default: throw new Error(`Expected tensor to have 1-2 dimensions, got ${M.length}.`); } } function ie(Te) { return Te.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 V(Te) { return Te.replace(new RegExp("\\p{M}", "gu"), ""); } function U(Te) { return V(Te.toLowerCase()); } function q(Te) { return Te >= 19968 && Te <= 40959 || Te >= 13312 && Te <= 19903 || Te >= 131072 && Te <= 173791 || Te >= 173824 && Te <= 177983 || Te >= 177984 && Te <= 178207 || Te >= 178208 && Te <= 183983 || Te >= 63744 && Te <= 64255 || Te >= 194560 && Te <= 195103; } function A(Te, M, Y) { const ce = []; let _e = 0; for (; _e < Te.length; ) { if (ce.push(Te[_e]), (M.get(Te[_e]) ?? Y) !== Y) { ++_e; continue; } for (; ++_e < Te.length && (M.get(Te[_e]) ?? Y) === Y; ) M.get(ce.at(-1)) !== Y && (ce[ce.length - 1] += Te[_e]); } return ce; } function S(Te) { return Te.match(/\S+/g) || []; } const w = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E", P = new RegExp(`^[${w}]+$`, "gu"), I = ".,!?…。,、।۔،", le = /* @__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]))"], // Used to override the default (invalid) regex of the bloom pretokenizer. // For more information, see https://github.com/huggingface/transformers.js/issues/94 [` ?[^(\\s|[${I}])]+`, ` ?[^\\s${I}]+`] ]); class oe { /** * 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(M) { this.content = M.content, this.id = M.id, this.single_word = M.single_word ?? !1, this.lstrip = M.lstrip ?? !1, this.rstrip = M.rstrip ?? !1, this.special = M.special ?? !1, this.normalized = M.normalized ?? null; } } class ye extends g.Callable { /** * Creates a new instance of TokenizerModel. * @param {Object} config The configuration object for the TokenizerModel. */ constructor(M) { super(), this.config = M, 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 ?? !1; } /** * 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(M, ...Y) { switch (M.type) { case "WordPiece": return new ge(M); case "Unigram": return new se(M, ...Y); case "BPE": return new Ce(M); default: if (M.vocab) return Array.isArray(M.vocab) ? new se(M, ...Y) : typeof M.vocab == "object" && M.continuing_subword_prefix && M.unk_token ? new ge(M) : new $e(M, ...Y); throw new Error(`Unknown TokenizerModel type: ${M.type}`); } } /** * Internal function to call the TokenizerModel instance. * @param {string[]} tokens The tokens to encode. * @returns {string[]} The encoded tokens. */ _call(M) { return M = this.encode(M), this.fuse_unk && (M = A(M, this.tokens_to_ids, this.unk_token_id)), M; } /** * 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(M) { 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(M) { return M.map((Y) => this.tokens_to_ids.get(Y) ?? this.unk_token_id); } /** * Converts a list of token IDs into a list of tokens. * @param {number[]|bigint[]} ids The token IDs to convert. * @returns {string[]} The converted tokens. */ convert_ids_to_tokens(M) { return M.map((Y) => this.vocab[Y] ?? this.unk_token); } } class ge extends ye { /** * @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(M) { super(M), this.tokens_to_ids = K(M.vocab), this.unk_token_id = this.tokens_to_ids.get(M.unk_token), this.unk_token = M.unk_token, this.max_input_chars_per_word = M.max_input_chars_per_word ?? 100, this.vocab = new Array(this.tokens_to_ids.size); for (const [Y, ce] of this.tokens_to_ids) this.vocab[ce] = Y; } /** * Encodes an array of tokens using WordPiece encoding. * @param {string[]} tokens The tokens to encode. * @returns {string[]} An array of encoded tokens. */ encode(M) { const Y = []; for (const ce of M) { const _e = [...ce]; if (_e.length > this.max_input_chars_per_word) { Y.push(this.unk_token); continue; } let Fe = !1, Ye = 0; const gt = []; for (; Ye < _e.length; ) { let wt = _e.length, yt = null; for (; Ye < wt; ) { let ht = _e.slice(Ye, wt).join(""); if (Ye > 0 && (ht = this.config.continuing_subword_prefix + ht), this.tokens_to_ids.has(ht)) { yt = ht; break; } --wt; } if (yt === null) { Fe = !0; break; } gt.push(yt), Ye = wt; } Fe ? Y.push(this.unk_token) : Y.push(...gt); } return Y; } } class se extends ye { /** * 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 {[string, number][]} config.vocab A 2D array representing a mapping of tokens to scores. * @param {Object} moreConfig Additional configuration object for the Unigram model. */ constructor(M, Y) { super(M); const ce = M.vocab.length; this.vocab = new Array(ce), this.scores = new Array(ce); for (let _e = 0; _e < ce; ++_e) [this.vocab[_e], this.scores[_e]] = M.vocab[_e]; this.unk_token_id = M.unk_id, this.unk_token = this.vocab[M.unk_id], this.tokens_to_ids = new Map(this.vocab.map((_e, Fe) => [_e, Fe])), this.bos_token = " ", this.bos_token_id = this.tokens_to_ids.get(this.bos_token), this.eos_token = Y.eos_token, this.eos_token_id = this.tokens_to_ids.get(this.eos_token), this.unk_token = this.vocab[this.unk_token_id], this.minScore = (0, ee.min)(this.scores)[0], this.unk_score = this.minScore - 10, this.scores[this.unk_token_id] = this.unk_score, this.trie = new y.CharTrie(), this.trie.extend(this.vocab), this.fuse_unk = !0; } /** * Populates lattice nodes. * @param {TokenLattice} lattice The token lattice to populate with nodes. */ populateNodes(M) { const Y = M.chars, ce = 1; let _e = 0; for (; _e < Y.length; ) { let Fe = !1; const Ye = Y.slice(_e).join(""), gt = this.trie.commonPrefixSearch(Ye); for (const wt of gt) { const yt = this.tokens_to_ids.get(wt), ht = this.scores[yt], ts = (0, O.len)(wt); M.insert(_e, ts, ht, yt), !Fe && ts === ce && (Fe = !0); } Fe || M.insert(_e, ce, this.unk_score, this.unk_token_id), _e += ce; } } /** * 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(M) { const Y = new y.TokenLattice(M, this.bos_token_id, this.eos_token_id); return this.populateNodes(Y), Y.tokens(); } /** * Encodes an array of tokens using Unigram encoding. * @param {string[]} tokens The tokens to encode. * @returns {string[]} An array of encoded tokens. */ encode(M) { const Y = []; for (const ce of M) { const _e = this.tokenize(ce); Y.push(..._e); } return Y; } } const be = (() => { const Te = [ ...Array.from({ length: 94 }, (_e, Fe) => Fe + 33), ...Array.from({ length: 12 }, (_e, Fe) => Fe + 161), ...Array.from({ length: 82 }, (_e, Fe) => Fe + 174) ], M = Te.slice(); let Y = 0; for (let _e = 0; _e < 256; ++_e) Te.includes(_e) || (Te.push(_e), M.push(256 + Y), Y += 1); const ce = M.map((_e) => String.fromCharCode(_e)); return Object.fromEntries(Te.map((_e, Fe) => [_e, ce[Fe]])); })(), pe = (0, O.reverseDictionary)(be); class Ce extends ye { /** * Create a BPE instance. * @param {Object} config The configuration object for BPE. * @param {Object} config.vocab A mapping of tokens to ids. * @param {string[]|[string, 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(M) { super(M), this.tokens_to_ids = K(M.vocab), this.unk_token_id = this.tokens_to_ids.get(M.unk_token), this.unk_token = M.unk_token, this.vocab = new Array(this.tokens_to_ids.size); for (const [ce, _e] of this.tokens_to_ids) this.vocab[_e] = ce; const Y = Array.isArray(M.merges[0]); this.merges = Y ? ( /** @type {[string, string][]} */ M.merges ) : ( /** @type {string[]} */ M.merges.map((ce) => ( /** @type {[string, string]} */ ce.split(" ", 2) )) ), this.bpe_ranks = new Map(this.merges.map((ce, _e) => [JSON.stringify(ce), _e])), this.end_of_word_suffix = M.end_of_word_suffix, this.continuing_subword_suffix = M.continuing_subword_suffix ?? null, this.byte_fallback = this.config.byte_fallback ?? !1, this.byte_fallback && (this.text_encoder = new TextEncoder()), this.ignore_merges = this.config.ignore_merges ?? !1, 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(M) { if (M.length === 0) return []; const Y = this.cache.get(M); if (Y !== void 0) return Y; const ce = Array.from(M); this.end_of_word_suffix && (ce[ce.length - 1] += this.end_of_word_suffix); let _e = []; if (ce.length > 1) { const Fe = new y.PriorityQueue((wt, yt) => wt.score < yt.score); let Ye = { token: ce[0], bias: 0, prev: null, next: null }, gt = Ye; for (let wt = 1; wt < ce.length; ++wt) { const yt = { bias: wt / ce.length, // Add fractional component to break ties token: ce[wt], prev: gt, next: null }; gt.next = yt, this._add_node(Fe, gt), gt = yt; } for (; !Fe.isEmpty(); ) { const wt = Fe.pop(); if (wt.deleted || !wt.next || wt.next.deleted) continue; if (wt.deleted = !0, wt.next.deleted = !0, wt.prev) { const ht = { ...wt.prev }; wt.prev.deleted = !0, wt.prev = ht, ht.prev ? ht.prev.next = ht : Ye = ht; } const yt = { token: wt.token + wt.next.token, bias: wt.bias, prev: wt.prev, next: wt.next.next }; yt.prev ? (yt.prev.next = yt, this._add_node(Fe, yt.prev)) : Ye = yt, yt.next && (yt.next.prev = yt, this._add_node(Fe, yt)); } for (let wt = Ye; wt !== null; wt = wt.next) _e.push(wt.token); } else _e = ce; if (this.continuing_subword_suffix) for (let Fe = 0; Fe < _e.length - 1; ++Fe) _e[Fe] += this.continuing_subword_suffix; return this.cache.set(M, _e), _e; } /** * Helper function to add a node to the priority queue. * @param {PriorityQueue} queue * @param {BPENode} node * @private */ _add_node(M, Y) { const ce = this.bpe_ranks.get(JSON.stringify([Y.token, Y.next.token])); ce !== void 0 && (Y.score = ce + Y.bias, M.push(Y)); } /** * 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(M) { const Y = []; for (const ce of M) { if (this.ignore_merges && this.tokens_to_ids.has(ce)) { Y.push(ce); continue; } const _e = this.bpe(ce); for (const Fe of _e) if (this.tokens_to_ids.has(Fe)) Y.push(Fe); else if (this.byte_fallback) { const Ye = Array.from(this.text_encoder.encode(Fe)).map((gt) => `<0x${gt.toString(16).toUpperCase().padStart(2, "0")}>`); Ye.every((gt) => this.tokens_to_ids.has(gt)) ? Y.push(...Ye) : Y.push(this.unk_token); } else Y.push(this.unk_token); } return Y; } } class $e extends ye { /** * 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(M, Y) { super(M), this.tokens_to_ids = K( Y.target_lang ? M.vocab[Y.target_lang] : M.vocab ), this.bos_token = Y.bos_token, this.bos_token_id = this.tokens_to_ids.get(this.bos_token), this.eos_token = Y.eos_token, this.eos_token_id = this.tokens_to_ids.get(this.eos_token), this.pad_token = Y.pad_token, this.pad_token_id = this.tokens_to_ids.get(this.pad_token), this.unk_token = Y.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 [ce, _e] of this.tokens_to_ids) this.vocab[_e] = ce; } encode(M) { return M; } } class Pe extends g.Callable { /** * @param {Object} config The configuration object for the normalizer. */ constructor(M) { super(), this.config = M; } /** * 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(M) { if (M === null) return null; switch (M.type) { case "BertNormalizer": return new We(M); case "Precompiled": return new ms(M); case "Sequence": return new J(M); case "Replace": return new Je(M); case "NFC": return new Ue(M); case "NFKC": return new we(M); case "NFKD": return new X(M); case "Strip": return new de(M); case "StripAccents": return new Ee(M); case "Lowercase": return new Oe(M); case "Prepend": return new Xe(M); default: throw new Error(`Unknown Normalizer type: ${M.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(M) { 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(M) { return this.normalize(M); } } class Je extends Pe { /** * 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(M) { const Y = L(this.config.pattern); return Y === null ? M : M.replaceAll(Y, this.config.content); } } class Ue extends Pe { /** * 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(M) { return M = M.normalize("NFC"), M; } } class we extends Pe { /** * Normalize text using NFKC normalization. * @param {string} text The text to be normalized. * @returns {string} The normalized text. */ normalize(M) { return M = M.normalize("NFKC"), M; } } class X extends Pe { /** * Normalize text using NFKD normalization. * @param {string} text The text to be normalized. * @returns {string} The normalized text. */ normalize(M) { return M = M.normalize("NFKD"), M; } } class de extends Pe { /** * Strip leading and/or trailing whitespace from the input text. * @param {string} text The input text. * @returns {string} The normalized text. */ normalize(M) { return this.config.strip_left && this.config.strip_right ? M = M.trim() : (this.config.strip_left && (M = M.trimStart()), this.config.strip_right && (M = M.trimEnd())), M; } } class Ee extends Pe { /** * Remove all accents from the text. * @param {string} text The input text. * @returns {string} The normalized text without accents. */ normalize(M) { return M = V(M), M; } } class Oe extends Pe { /** * Lowercases the input string. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(M) { return M = M.toLowerCase(), M; } } class Xe extends Pe { /** * Prepends the input string. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(M) { return M = this.config.prepend + M, M; } } class J extends Pe { /** * Create a new instance of NormalizerSequence. * @param {Object} config The configuration object. * @param {Object[]} config.normalizers An array of Normalizer configuration objects. */ constructor(M) { super(M), this.normalizers = M.normalizers.map((Y) => Pe.fromConfig(Y)); } /** * Apply a sequence of Normalizers to the input text. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(M) { return this.normalizers.reduce((Y, ce) => ce.normalize(Y), M); } } class We extends Pe { /** * 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(M) { const Y = []; for (let ce = 0; ce < M.length; ++ce) { const _e = M[ce], Fe = _e.charCodeAt(0); q(Fe) ? (Y.push(" "), Y.push(_e), Y.push(" ")) : Y.push(_e); } return Y.join(""); } /** * Strips accents from the given text. * @param {string} text The text to strip accents from. * @returns {string} The text with accents removed. */ stripAccents(M) { return M.normalize("NFD").replace(new RegExp("\\p{Mn}", "gu"), ""); } /** * 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(M) { switch (M) { case " ": case ` `: case "\r": return !1; default: return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$", "u").test(M); } } /** * Performs invalid character removal and whitespace cleanup on text. * @param {string} text The text to clean. * @returns {string} The cleaned text. * @private */ _clean_text(M) { const Y = []; for (const ce of M) { const _e = ce.charCodeAt(0); _e === 0 || _e === 65533 || this._is_control(ce) || (/^\s$/.test(ce) ? Y.push(" ") : Y.push(ce)); } return Y.join(""); } /** * Normalizes the given text based on the configuration. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(M) { return this.config.clean_text && (M = this._clean_text(M)), this.config.handle_chinese_chars && (M = this._tokenize_chinese_chars(M)), this.config.lowercase ? (M = M.toLowerCase(), this.config.strip_accents !== !1 && (M = this.stripAccents(M))) : this.config.strip_accents && (M = this.stripAccents(M)), M; } } class Ne extends g.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(M) { if (M === null) return null; switch (M.type) { case "BertPreTokenizer": return new te(M); case "Sequence": return new Ps(M); case "Whitespace": return new Is(M); case "WhitespaceSplit": return new tr(M); case "Metaspace": return new es(M); case "ByteLevel": return new ve(M); case "Split": return new He(M); case "Punctuation": return new je(M); case "Digits": return new Ve(M); case "Replace": return new xr(M); default: throw new Error(`Unknown PreTokenizer type: ${M.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(M, Y) { 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(M, Y) { return (Array.isArray(M) ? M.map((ce) => this.pre_tokenize_text(ce, Y)) : this.pre_tokenize_text(M, Y)).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(M, Y) { return this.pre_tokenize(M, Y); } } class te extends Ne { /** * 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(M) { super(), this.pattern = new RegExp(`[^\\s${w}]+|[${w}]`, "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(M, Y) { return M.trim().match(this.pattern) || []; } } class ve extends Ne { /** * Creates a new instance of the `ByteLevelPreTokenizer` class. * @param {Object} config The configuration object. */ constructor(M) { super(), this.config = M, this.add_prefix_space = this.config.add_prefix_space, this.trim_offsets = this.config.trim_offsets, this.use_regex = this.config.use_regex ?? !0, this.pattern = new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+", "gu"), this.byte_encoder = be, 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(M, Y) { return this.add_prefix_space && !M.startsWith(" ") && (M = " " + M), (this.use_regex ? M.match(this.pattern) || [] : [M]).map( (_e) => Array.from(this.text_encoder.encode(_e), (Fe) => this.byte_encoder[Fe]).join("") ); } } class He extends Ne { /** * @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(M) { super(), this.config = M, this.pattern = L(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(M, Y) { return this.pattern === null ? [] : this.config.invert ? M.match(this.pattern) || [] : this.config.behavior?.toLowerCase() === "removed" ? M.split(this.pattern).filter((ce) => ce) : x(M, this.pattern); } } class je extends Ne { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. */ constructor(M) { super(), this.config = M, this.pattern = new RegExp(`[^${w}]+|[${w}]+`, "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(M, Y) { return M.match(this.pattern) || []; } } class Ve extends Ne { /** * @param {Object} config The configuration options for the pre-tokenizer. * @param {boolean} config.individual_digits Whether to split on individual digits. */ constructor(M) { super(), this.config = M; const Y = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`; this.pattern = new RegExp(Y, "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(M, Y) { return M.match(this.pattern) || []; } } class Re extends g.Callable { /** * @param {Object} config The configuration for the post-processor. */ constructor(M) { super(), this.config = M; } /** * 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(M) { if (M === null) return null; switch (M.type) { case "TemplateProcessing": return new _t(M); case "ByteLevel": return new lt(M); case "RobertaProcessing": return new at(M); case "BertProcessing": return new Ze(M); case "Sequence": return new ct(M); default: throw new Error(`Unknown PostProcessor type: ${M.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(M, ...Y) { 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(M, ...Y) { return this.post_process(M, ...Y); } } class Ze extends Re { /** * @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(M) { super(M), this.cls = M.cls[0], this.sep = M.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(M, Y = null, { add_special_tokens: ce = !0 } = {}) { ce && (M = (0, O.mergeArrays)([this.cls], M, [this.sep])); let _e = new Array(M.length).fill(0); if (Y !== null) { const Fe = ce && this instanceof at ? [this.sep] : [], Ye = ce ? [this.sep] : []; M = (0, O.mergeArrays)(M, Fe, Y, Ye), _e = (0, O.mergeArrays)(_e, new Array(Y.length + Fe.length + Ye.length).fill(1)); } return { tokens: M, token_type_ids: _e }; } } class at extends Ze { } class _t extends Re { /** * 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(M) { super(M), this.single = M.single, this.pair = M.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(M, Y = null, { add_special_tokens: ce = !0 } = {}) { const _e = Y === null ? this.single : this.pair; let Fe = [], Ye = []; for (const gt of _e) "SpecialToken" in gt ? ce && (Fe.push(gt.SpecialToken.id), Ye.push(gt.SpecialToken.type_id)) : "Sequence" in gt && (gt.Sequence.id === "A" ? (Fe = (0, O.mergeArrays)(Fe, M), Ye = (0, O.mergeArrays)(Ye, new Array(M.length).fill(gt.Sequence.type_id))) : gt.Sequence.id === "B" && (Fe = (0, O.mergeArrays)(Fe, Y), Ye = (0, O.mergeArrays)(Ye, new Array(Y.length).fill(gt.Sequence.type_id)))); return { tokens: Fe, token_type_ids: Ye }; } } class lt extends Re { /** * 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(M, Y = null) { return Y && (M = (0, O.mergeArrays)(M, Y)), { tokens: M }; } } class ct extends Re { /** * Creates a new instance of PostProcessorSequence. * @param {Object} config The configuration object. * @param {Object[]} config.processors The list of post-processors to apply. */ constructor(M) { super(M), this.processors = M.processors.map((Y) => Re.fromConfig(Y)); } /** * 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(M, Y = null, ce = {}) { let _e; for (const Fe of this.processors) if (Fe instanceof lt) M = Fe.post_process(M).tokens, Y && (Y = Fe.post_process(Y).tokens); else { const Ye = Fe.post_process(M, Y, ce); M = Ye.tokens, _e = Ye.token_type_ids; } return { tokens: M, token_type_ids: _e }; } } class F extends g.Callable { /** * Creates an instance of `Decoder`. * * @param {Object} config The configuration object. */ constructor(M) { super(), this.config = M, this.added_tokens = [], this.end_of_word_suffix = null, this.trim_offsets = M.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(M) { if (M === null) return null; switch (M.type) { case "WordPiece": return new ze(M); case "Metaspace": return new Ts(M); case "ByteLevel": return new Ge(M); case "Replace": return new ae(M); case "ByteFallback": return new H(M); case "Fuse": return new me(M); case "Strip": return new ke(M); case "Sequence": return new et(M); case "CTC": return new tt(M); case "BPEDecoder": return new mt(M); default: throw new Error(`Unknown Decoder type: ${M.type}`); } } /** * Calls the `decode` method. * * @param {string[]} tokens The list of tokens. * @returns {string} The decoded string. */ _call(M) { return this.decode(M); } /** * Decodes a list of tokens. * @param {string[]} tokens The list of tokens. * @returns {string} The decoded string. */ decode(M) { return this.decode_chain(M).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(M) { throw Error("`decode_chain` should be implemented in subclass."); } } class ae extends F { /** @type {Decoder['decode_chain']} */ decode_chain(M) { const Y = L(this.config.pattern); return Y === null ? M : M.map((ce) => ce.replaceAll(Y, this.config.content)); } } class H extends F { constructor(M) { super(M), this.text_decoder = new TextDecoder(); } /** @type {Decoder['decode_chain']} */ decode_chain(M) { const Y = []; let ce = []; for (const _e of M) { let Fe = null; if (_e.length === 6 && _e.startsWith("<0x") && _e.endsWith(">")) { const Ye = parseInt(_e.slice(3, 5), 16); isNaN(Ye) || (Fe = Ye); } if (Fe !== null) ce.push(Fe); else { if (ce.length > 0) { const Ye = this.text_decoder.decode(Uint8Array.from(ce)); Y.push(Ye), ce = []; } Y.push(_e); } } if (ce.length > 0) { const _e = this.text_decoder.decode(Uint8Array.from(ce)); Y.push(_e), ce = []; } return Y; } } class me extends F { /** @type {Decoder['decode_chain']} */ decode_chain(M) { return [M.join("")]; } } class ke extends F { constructor(M) { super(M), this.content = this.config.content, this.start = this.config.start, this.stop = this.config.stop; } /** @type {Decoder['decode_chain']} */ decode_chain(M) { return M.map((Y) => { let ce = 0; for (let Fe = 0; Fe < this.start && Y[Fe] === this.content; ++Fe) { ce = Fe + 1; continue; } let _e = Y.length; for (let Fe = 0; Fe < this.stop; ++Fe) { const Ye = Y.length - Fe - 1; if (Y[Ye] === this.content) { _e = Ye; continue; } else break; } return Y.slice(ce, _e); }); } } class ze extends F { /** * 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(M) { super(M), this.cleanup = M.cleanup; } /** @type {Decoder['decode_chain']} */ decode_chain(M) { return M.map((Y, ce) => (ce !== 0 && (Y.startsWith(this.config.prefix) ? Y = Y.replace(this.config.prefix, "") : Y = " " + Y), this.cleanup && (Y = ie(Y)), Y)); } } class Ge extends F { /** * Create a `ByteLevelDecoder` object. * @param {Object} config Configuration object. */ constructor(M) { super(M), this.byte_decoder = pe, this.text_decoder = new TextDecoder("utf-8", { fatal: !1, ignoreBOM: !0 }), 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(M) { const Y = M.join(""), ce = new Uint8Array([...Y].map((Fe) => this.byte_decoder[Fe])); return this.text_decoder.decode(ce); } /** @type {Decoder['decode_chain']} */ decode_chain(M) { const Y = []; let ce = []; for (const _e of M) this.added_tokens.find((Fe) => Fe.content === _e) !== void 0 ? (ce.length > 0 && (Y.push(this.convert_tokens_to_string(ce)), ce = []), Y.push(_e)) : ce.push(_e); return ce.length > 0 && Y.push(this.convert_tokens_to_string(ce)), Y; } } class tt extends F { constructor(M) { super(M), 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(M) { if (M.length === 0) return ""; const Y = [M[0]]; for (let Fe = 1; Fe < M.length; ++Fe) M[Fe] !== Y.at(-1) && Y.push(M[Fe]); let _e = Y.filter((Fe) => Fe !== this.pad_token).join(""); return this.cleanup && (_e = ie(_e).replaceAll(this.word_delimiter_token, " ").trim()), _e; } /** @type {Decoder['decode_chain']} */ decode_chain(M) { return [this.convert_tokens_to_string(M)]; } } class et extends F { /** * Creates a new instance of DecoderSequence. * @param {Object} config The configuration object. * @param {Object[]} config.decoders The list of decoders to apply. */ constructor(M) { super(M), this.decoders = M.decoders.map((Y) => F.fromConfig(Y)); } /** @type {Decoder['decode_chain']} */ decode_chain(M) { return this.decoders.reduce((Y, ce) => ce.decode_chain(Y), M); } } class mt extends F { constructor(M) { super(M), this.suffix = this.config.suffix; } /** @type {Decoder['decode_chain']} */ decode_chain(M) { return M.map((Y, ce) => Y.replaceAll(this.suffix, ce === M.length - 1 ? "" : " ")); } } class Nt extends F { /** @type {Decoder['decode_chain']} */ decode_chain(M) { let Y = ""; for (let ce = 1; ce < M.length; ce += 2) Y += M[ce]; return [Y]; } } class es extends Ne { /** * @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(M) { super(), this.addPrefixSpace = M.add_prefix_space, this.replacement = M.replacement, this.strRep = M.str_rep || this.replacement, this.prepend_scheme = M.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(M, { section_index: Y = void 0 } = {}) { let ce = M.replaceAll(" ", this.strRep); return ( // 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 && !ce.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && Y === 0) && (ce = this.strRep + ce), [ce] ); } } class Ts extends F { /** * 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(M) { super(M), this.addPrefixSpace = M.add_prefix_space, this.replacement = M.replacement; } /** @type {Decoder['decode_chain']} */ decode_chain(M) { const Y = []; for (let ce = 0; ce < M.length; ++ce) { let _e = M[ce].replaceAll(this.replacement, " "); this.addPrefixSpace && ce == 0 && _e.startsWith(" ") && (_e = _e.substring(1)), Y.push(_e); } return Y; } } class ms extends Pe { /** * Create a new instance of Precompiled normalizer. * @param {Object} config The configuration object. * @param {any} config.precompiled_charsmap Precompiled chars mapping. */ constructor(M) { super(M), this.charsmap = M.precompiled_charsmap; } /** * Normalizes the given text by applying the precompiled charsmap. * @param {string} text The text to normalize. * @returns {string} The normalized text. */ normalize(M) { return M = M.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ""), M = M.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, " "), M.includes("~") ? M = M.split("~").map((ce) => ce.normalize("NFKC")).join("~") : M = M.normalize("NFKC"), M; } } class Ps extends Ne { /** * 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(M) { super(), this.tokenizers = M.pretokenizers.map((Y) => Ne.fromConfig(Y)); } /** * 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(M, Y) { return this.tokenizers.reduce((ce, _e) => _e.pre_tokenize(ce, Y), [M]); } } class Is extends Ne { /** * Creates an instance of WhitespacePreTokenizer. * @param {Object} config The configuration object for the pre-tokenizer. */ constructor(M) { 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(M, Y) { return M.match(/\w+|[^\w\s]+/g) || []; } } class tr extends Ne { /** * Creates an instance of WhitespaceSplit. * @param {Object} config The configuration object for the pre-tokenizer. */ constructor(M) { 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(M, Y) { return S(M); } } class xr extends Ne { /** * @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(M) { super(), this.config = M, this.pattern = L(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(M, Y) { return this.pattern === null ? [M] : [M.replaceAll(this.pattern, this.config.content)]; } } const Gr = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token" // additional_special_tokens (TODO) ]; function Vs(Te, M, Y, ce) { for (const _e of Object.keys(Te)) { const Fe = M - Te[_e].length, Ye = Y(_e), gt = new Array(Fe).fill(Ye); Te[_e] = ce === "right" ? (0, O.mergeArrays)(Te[_e], gt) : (0, O.mergeArrays)(gt, Te[_e]); } } function yr(Te, M) { for (const Y of Object.keys(Te)) Te[Y].length = M; } class Lt extends g.Callable { return_token_type_ids = !1; padding_side = "right"; /** * Create a new PreTrainedTokenizer instance. * @param {Object} tokenizerJSON The JSON of the tokenizer. * @param {Object} tokenizerConfig The config of the tokenizer. */ constructor(M, Y) { super(), this._tokenizer_config = Y, this.normalizer = Pe.fromConfig(M.normalizer), this.pre_tokenizer = Ne.fromConfig(M.pre_tokenizer), this.model = ye.fromConfig(M.model, Y), this.post_processor = Re.fromConfig(M.post_processor), this.decoder = F.fromConfig(M.decoder), this.special_tokens = [], this.all_special_ids = [], this.added_tokens = []; for (const ce of M.added_tokens) { const _e = new oe(ce); this.added_tokens.push(_e), this.model.tokens_to_ids.set(_e.content, _e.id), this.model.vocab[_e.id] = _e.content, _e.special && (this.special_tokens.push(_e.content), this.all_special_ids.push(_e.id)); } if (this.additional_special_tokens = Y.additional_special_tokens ?? [], this.special_tokens.push(...this.additional_special_tokens), this.special_tokens = [...new Set(this.special_tokens)], 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.slice().sort((ce, _e) => _e.content.length - ce.content.length).map((ce) => `${ce.lstrip ? "\\s*" : ""}(${(0, O.escapeRegExp)(ce.content)})${ce.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.bos_token = this.getToken("bos_token"), this.bos_token_id = this.model.tokens_to_ids.get(this.bos_token), this.eos_token = this.getToken("eos_token"), this.eos_token_id = this.model.tokens_to_ids.get(this.eos_token), this.model_max_length = Y.model_max_length, this.remove_space = Y.remove_space, this.clean_up_tokenization_spaces = Y.clean_up_tokenization_spaces ?? !0, this.do_lowercase_and_remove_accent = Y.do_lowercase_and_remove_accent ?? !1, Y.padding_side && (this.padding_side = Y.padding_side), this.legacy = !1, this.chat_template = Y.chat_template ?? null, Array.isArray(this.chat_template)) { const ce = /* @__PURE__ */ Object.create(null); for (const { name: _e, template: Fe } of this.chat_template) { if (typeof _e != "string" || typeof Fe != "string") throw new Error('Chat template must be a list of objects with "name" and "template" properties'); ce[_e] = Fe; } this.chat_template = ce; } 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". * @private */ getToken(...M) { for (const Y of M) { const ce = this._tokenizer_config[Y]; if (ce) if (typeof ce == "object") { if (ce.__type === "AddedToken") return ce.content; throw Error(`Unknown token: ${ce}`); } else return ce; } 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(M, { progress_callback: Y = null, config: ce = null, cache_dir: _e = null, local_files_only: Fe = !1, revision: Ye = "main", legacy: gt = null } = {}) { const wt = await b(M, { progress_callback: Y, config: ce, cache_dir: _e, local_files_only: Fe, revision: Ye, legacy: gt }); return new this(...wt); } /** * @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(M, { text_pair: Y = null, add_special_tokens: ce = !0, padding: _e = !1, truncation: Fe = null, max_length: Ye = null, return_tensor: gt = !0, // Different to HF return_token_type_ids: wt = null } = {}) { const yt = Array.isArray(M); let ht; if (yt) { if (M.length === 0) throw Error("text array must be non-empty"); if (Y !== null) { if (Array.isArray(Y)) { if (M.length !== Y.length) throw Error("text and text_pair must have the same length"); } else throw Error("text_pair must also be an array"); ht = M.map( (Xt, bs) => this._encode_plus(Xt, { text_pair: Y[bs], add_special_tokens: ce, return_token_type_ids: wt }) ); } else ht = M.map((Xt) => this._encode_plus(Xt, { add_special_tokens: ce, return_token_type_ids: wt })); } else { if (M == null) throw Error("text may not be null or undefined"); if (Array.isArray(Y)) throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array)."); ht = [this._encode_plus(M, { text_pair: Y, add_special_tokens: ce, return_token_type_ids: wt })]; } if (Ye === null ? _e === "max_length" ? Ye = this.model_max_length : Ye = (0, ee.max)(ht.map((Xt) => Xt.input_ids.length))[0] : Fe || 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."), Ye = Math.min(Ye, this.model_max_length ?? 1 / 0), _e || Fe) for (let Xt = 0; Xt < ht.length; ++Xt) ht[Xt].input_ids.length !== Ye && (ht[Xt].input_ids.length > Ye ? Fe && yr(ht[Xt], Ye) : _e && Vs( ht[Xt], Ye, (bs) => bs === "input_ids" ? this.pad_token_id : 0, this.padding_side )); const ts = {}; if (gt) { if (!(_e && Fe) && ht.some((bs) => { for (const Ks of Object.keys(bs)) if (bs[Ks].length !== ht[0][Ks]?.length) return !0; return !1; })) 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 Xt = [ht.length, ht[0].input_ids.length]; for (const bs of Object.keys(ht[0])) ts[bs] = new N.Tensor( "int64", BigInt64Array.from(ht.flatMap((Ks) => Ks[bs]).map(BigInt)), Xt ); } else { for (const Xt of Object.keys(ht[0])) ts[Xt] = ht.map((bs) => bs[Xt]); if (!yt) for (const Xt of Object.keys(ts)) ts[Xt] = ts[Xt][0]; } return ( /** @type {BatchEncoding} */ ts ); } /** * 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(M) { return M === null ? null : (this.added_tokens_regex ? M.split(this.added_tokens_regex).filter((_e) => _e) : [M]).map((_e, Fe) => { if (this.added_tokens.find((gt) => gt.content === _e) !== void 0) return _e; { if (this.remove_space === !0 && (_e = _e.trim().split(/\s+/).join(" ")), this.do_lowercase_and_remove_accent && (_e = U(_e)), this.normalizer !== null && (_e = this.normalizer(_e)), _e.length === 0) return []; const gt = this.pre_tokenizer !== null ? this.pre_tokenizer(_e, { section_index: Fe }) : [_e]; return this.model(gt); } }).flat(); } /** * Encodes a single text or a pair of texts using the model's tokenizer. * * @param {string} text The text to encode. * @param {Object} options An optional object containing the following properties: * @param {string} [options.text_pair=null] The optional second text to encode. * @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(M, { text_pair: Y = null, add_special_tokens: ce = !0, return_token_type_ids: _e = null } = {}) { const { tokens: Fe, token_type_ids: Ye } = this._tokenize_helper(M, { pair: Y, add_special_tokens: ce }), gt = this.model.convert_tokens_to_ids(Fe), wt = { input_ids: gt, attention_mask: new Array(gt.length).fill(1) }; return (_e ?? this.return_token_type_ids) && Ye && (wt.token_type_ids = Ye), wt; } /** * Internal helper function to tokenize a text, and optionally a pair of texts. * @param {string} text The text to tokenize. * @param {Object} options An optional object containing the following properties: * @param {string} [options.pair=null] The optional second text to tokenize. * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs. */ _tokenize_helper(M, { pair: Y = null, add_special_tokens: ce = !1 } = {}) { const _e = this._encode_text(M), Fe = this._encode_text(Y); return this.post_processor ? this.post_processor(_e, Fe, { add_special_tokens: ce }) : { tokens: (0, O.mergeArrays)(_e ?? [], Fe ?? []) }; } /** * Converts a string into a sequence of tokens. * @param {string} text The sequence to be encoded. * @param {Object} options An optional object containing the following properties: * @param {string} [options.pair] A second sequence to be encoded with the first. * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. * @returns {string[]} The list of tokens. */ tokenize(M, { pair: Y = null, add_special_tokens: ce = !1 } = {}) { return this._tokenize_helper(M, { pair: Y, add_special_tokens: ce }).tokens; } /** * Encodes a single text or a pair of texts using the model's tokenizer. * * @param {string} text The text to encode. * @param {Object} options An optional object containing the following properties: * @param {string} [options.text_pair=null] The optional second text to encode. * @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(M, { text_pair: Y = null, add_special_tokens: ce = !0, return_token_type_ids: _e = null } = {}) { return this._encode_plus(M, { text_pair: Y, add_special_tokens: ce, return_token_type_ids: _e }).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(M, Y = {}) { return M instanceof N.Tensor && (M = M.tolist()), M.map((ce) => this.decode(ce, Y)); } /** * Decodes a sequence of token IDs back to a string. * * @param {number[]|bigint[]|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(M, Y = {}) { if (M instanceof N.Tensor && (M = re(M)), !Array.isArray(M) || M.length === 0 || !(0, O.isIntegralNumber)(M[0])) throw Error("token_ids must be a non-empty array of integers."); return this.decode_single(M, Y); } /** * Decode a single list of token ids to a string. * @param {number[]|bigint[]} 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(M, { skip_special_tokens: Y = !1, clean_up_tokenization_spaces: ce = null }) { let _e = this.model.convert_ids_to_tokens(M); Y && (_e = _e.filter((Ye) => !this.special_tokens.includes(Ye))); let Fe = this.decoder ? this.decoder(_e) : _e.join(" "); return this.decoder && this.decoder.end_of_word_suffix && (Fe = Fe.replaceAll(this.decoder.end_of_word_suffix, " "), Y && (Fe = Fe.trim())), (ce ?? this.clean_up_tokenization_spaces) && (Fe = ie(Fe)), Fe; } /** * Retrieve the chat template string used for tokenizing chat messages. This template is used * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat * template for better generation tracking. * * @param {Object} options An optional object containing the following properties: * @param {string} [options.chat_template=null] * A Jinja template or the name of a template to use for this conversion. * It is usually not necessary to pass anything to this argument, * as the model's template will be used by default. * @param {Object[]} [options.tools=null] * A list of tools (callable functions) that will be accessible to the model. If the template does not * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, * giving the name, description and argument types for the tool. See our * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) * for more information. * @returns {string} The chat template string. */ get_chat_template({ chat_template: M = null, tools: Y = null } = {}) { if (this.chat_template && typeof this.chat_template == "object") { const ce = this.chat_template; if (M !== null && Object.hasOwn(ce, M)) M = ce[M]; else if (M === null) if (Y !== null && "tool_use" in ce) M = ce.tool_use; else if ("default" in ce) M = ce.default; else 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(ce).sort()}.` ); } else if (M === null) if (this.chat_template) M = this.chat_template; else throw Error( "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating" ); return M; } /** * 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. * * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. * * **Example:** Applying a chat template to a conversation. * * ```javascript * import { AutoTokenizer } from "@huggingface/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, * representing the chat history so far. * @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 chat template will be used instead. * @param {Object[]} [options.tools=null] * A list of tools (callable functions) that will be accessible to the model. If the template does not * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, * giving the name, description and argument types for the tool. See our * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) * for more information. * @param {Record[]} [options.documents=null] * A list of dicts representing documents that will be accessible to the model if it is performing RAG * (retrieval-augmented generation). If the template does not support RAG, this argument will have no * effect. We recommend that each document should be a dict containing "title" and "text" keys. Please * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG) * for examples of passing documents with chat templates. * @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 {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false. * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer. * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output. */ apply_chat_template(M, { tools: Y = null, documents: ce = null, chat_template: _e = null, add_generation_prompt: Fe = !1, tokenize: Ye = !0, padding: gt = !1, truncation: wt = !1, max_length: yt = null, return_tensor: ht = !0, return_dict: ts = !1, tokenizer_kwargs: Xt = {}, ...bs } = {}) { if (_e = this.get_chat_template({ chat_template: _e, tools: Y }), typeof _e != "string") throw Error(`chat_template must be a string, but got ${typeof _e}`); let Ks = this._compiled_template_cache.get(_e); Ks === void 0 && (Ks = new T.Template(_e), this._compiled_template_cache.set(_e, Ks)); const jt = /* @__PURE__ */ Object.create(null); for (const Hs of Gr) { const er = this.getToken(Hs); er && (jt[Hs] = er); } const rs = Ks.render({ messages: M, add_generation_prompt: Fe, tools: Y, documents: ce, ...jt, ...bs }); if (Ye) { const Hs = this._call(rs, { add_special_tokens: !1, padding: gt, truncation: wt, max_length: yt, return_tensor: ht, ...Xt }); return ts ? Hs : Hs.input_ids; } return rs; } } class Kr extends Lt { return_token_type_ids = !0; } class Tr extends Lt { return_token_type_ids = !0; } class Pr extends Lt { return_token_type_ids = !0; } class Hr extends Lt { return_token_type_ids = !0; } class lr extends Lt { return_token_type_ids = !0; } class Fr extends Lt { return_token_type_ids = !0; } class Er extends Lt { return_token_type_ids = !0; } class Or extends Lt { return_token_type_ids = !0; } class Dr extends Lt { return_token_type_ids = !0; } class ir extends Lt { } class nt extends Lt { } class vt extends Lt { return_token_type_ids = !0; constructor(M, Y) { super(M, Y), console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); } } class Ft extends Lt { return_token_type_ids = !0; } class Zs extends Lt { } class Pn extends Lt { } class cn extends Lt { } class ws extends Lt { constructor(M, Y) { super(M, Y), this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/, this.language_codes = this.special_tokens.filter((ce) => this.languageRegex.test(ce)), this.lang_to_token = (ce) => ce; } /** * 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(M, Y, ce) { return pr(this, M, Y, ce); } } class Mr extends ws { } class zs extends Lt { } class qr extends Lt { } const ss = "▁"; class pn extends Lt { padding_side = "left"; constructor(M, Y) { super(M, Y), this.legacy = Y.legacy ?? !0, this.legacy || (this.normalizer = null, this.pre_tokenizer = new es({ replacement: ss, add_prefix_space: !0, 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(M) { if (M === null) return null; if (this.legacy || M.length === 0) return super._encode_text(M); let Y = super._encode_text(ss + M.replaceAll(ss, " ")); return Y.length > 1 && Y[0] === ss && this.special_tokens.includes(Y[1]) && (Y = Y.slice(1)), Y; } } class Lr extends Lt { } class eo extends Lt { } class En extends Lt { } class Cn extends Lt { } class kn extends Lt { } class zr extends Lt { } class Sn extends Lt { } class to extends Lt { } class Br extends Lt { } function pr(Te, M, Y, ce) { if (!("language_codes" in Te) || !Array.isArray(Te.language_codes)) throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids."); if (!("languageRegex" in Te) || !(Te.languageRegex instanceof RegExp)) throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression."); if (!("lang_to_token" in Te) || typeof Te.lang_to_token != "function") throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function."); const _e = ce.src_lang, Fe = ce.tgt_lang; if (!Te.language_codes.includes(Fe)) throw new Error(`Target language code "${Fe}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`); if (_e !== void 0) { if (!Te.language_codes.includes(_e)) throw new Error(`Source language code "${_e}" is not valid. Must be one of: {${Te.language_codes.join(", ")}}`); for (const Ye of Te.post_processor.config.single) if ("SpecialToken" in Ye && Te.languageRegex.test(Ye.SpecialToken.id)) { Ye.SpecialToken.id = Te.lang_to_token(_e); break; } } return ce.forced_bos_token_id = Te.model.convert_tokens_to_ids([Te.lang_to_token(Fe)])[0], Te._call(M, Y); } class ar extends Lt { constructor(M, Y) { super(M, Y), this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/, this.language_codes = this.special_tokens.filter((ce) => this.languageRegex.test(ce)), this.lang_to_token = (ce) => ce; } /** * 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(M, Y, ce) { return pr(this, M, Y, ce); } } class hn extends Lt { constructor(M, Y) { super(M, Y), this.languageRegex = /^__[a-z]{2,3}__$/, this.language_codes = this.special_tokens.filter((ce) => this.languageRegex.test(ce)).map((ce) => ce.slice(2, -2)), this.lang_to_token = (ce) => `__${ce}__`; } /** * 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(M, Y, ce) { return pr(this, M, Y, ce); } } class Qr extends Lt { get timestamp_begin() { return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; } /** * Decodes automatic speech recognition (ASR) sequences. * @param {Array<{tokens: bigint[], 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(M, { return_timestamps: Y = !1, return_language: ce = !1, time_precision: _e = null, force_full_sequences: Fe = !0 } = {}) { if (_e === null) throw Error("Must specify time_precision"); let Ye = null; const gt = Y === "word"; function wt() { return { language: Ye, timestamp: [null, null], text: "" }; } const yt = []; let ht = wt(), ts = 0; const Xt = this.timestamp_begin, Ks = Xt + 1500; let jt = [], rs = [], Hs = !1, er = null; const De = new Set(this.all_special_ids); for (const Es of M) { const qs = Es.tokens, At = gt ? Es.token_timestamps : null; let nr = null, hr = Xt; if ("stride" in Es) { const [Mt, Wt, Fs] = Es.stride; if (ts -= Wt, er = Mt - Fs, Wt && (hr = Wt / _e + Xt), Fs) for (let ks = qs.length - 1; ks >= 0; --ks) { const Us = Number(qs[ks]); if (Us >= Xt) { if (nr !== null && (Us - Xt) * _e < er) break; nr = Us; } } } let ds = [], Cs = []; for (let Mt = 0; Mt < qs.length; ++Mt) { const Wt = Number(qs[Mt]); if (De.has(Wt)) { const Fs = this.decode([Wt]), ks = v.WHISPER_LANGUAGE_MAPPING.get(Fs.slice(2, -2)); if (ks !== void 0) { if (Ye !== null && ks !== Ye && !Y) { jt.push(ds); const Us = this.findLongestCommonSequence(jt)[0], Pt = this.decode(Us); ht.text = Pt, yt.push(ht), jt = [], ds = [], ht = wt(); } Ye = ht.language = ks; } } else if (Wt >= Xt && Wt <= Ks) { const Fs = (Wt - Xt) * _e + ts, ks = (0, ee.round)(Fs, 2); if (nr !== null && Wt >= nr) Hs = !0; else if (Hs || jt.length > 0 && Wt < hr) Hs = !1; else if (ht.timestamp[0] === null) ht.timestamp[0] = ks; else if (ks !== ht.timestamp[0]) { ht.timestamp[1] = ks, jt.push(ds), gt && rs.push(Cs); const [Us, Pt] = this.findLongestCommonSequence( jt, rs ), Xr = this.decode(Us); ht.text = Xr, gt && (ht.words = this.collateWordTimestamps( Us, Pt, Ye )), yt.push(ht), jt = [], ds = [], rs = [], Cs = [], ht = wt(); } } else if (ds.push(Wt), gt) { let Fs = (0, ee.round)(At[Mt] + ts, 2), ks; if (Mt + 1 < At.length) { ks = (0, ee.round)(At[Mt + 1] + ts, 2); const Us = this.decode([Wt]); P.test(Us) && (ks = (0, ee.round)(Math.min(Fs + _e, ks), 2)); } else ks = null; Cs.push([Fs, ks]); } } if ("stride" in Es) { const [Mt, Wt, Fs] = Es.stride; ts += Mt - Fs; } ds.length > 0 ? (jt.push(ds), gt && rs.push(Cs)) : jt.every((Mt) => Mt.length === 0) && (ht = wt(), jt = [], ds = [], rs = [], Cs = []); } if (jt.length > 0) { if (Fe && Y) 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 [Es, qs] = this.findLongestCommonSequence(jt, rs), At = this.decode(Es); ht.text = At, gt && (ht.words = this.collateWordTimestamps( Es, qs, Ye )), yt.push(ht); } let Xs = /* @__PURE__ */ Object.create(null); const Cr = yt.map((Es) => Es.text).join(""); if (Y || ce) { for (let Es = 0; Es < yt.length; ++Es) { const qs = yt[Es]; Y || delete qs.timestamp, ce || delete qs.language; } if (gt) { const Es = []; for (const qs of yt) for (const At of qs.words) Es.push(At); Xs = { chunks: Es }; } else Xs = { chunks: yt }; } return [Cr, Xs]; } /** * 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(M, Y = null) { let ce = M[0], _e = ce.length, Fe = []; const Ye = Array.isArray(Y) && Y.length > 0; let gt = Ye ? [] : null, wt = Ye ? Y[0] : null; for (let yt = 1; yt < M.length; ++yt) { const ht = M[yt]; let ts = 0, Xt = [_e, _e, 0, 0]; const bs = ht.length; for (let Xs = 1; Xs < _e + bs; ++Xs) { const Cr = Math.max(0, _e - Xs), Es = Math.min(_e, _e + bs - Xs), qs = ce.slice(Cr, Es), At = Math.max(0, Xs - _e), nr = Math.min(bs, Xs), hr = ht.slice(At, nr); if (qs.length !== hr.length) throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); let ds; Ye ? ds = qs.filter((Wt, Fs) => Wt === hr[Fs] && wt[Cr + Fs] <= Y[yt][At + Fs]).length : ds = qs.filter((Wt, Fs) => Wt === hr[Fs]).length; const Cs = Xs / 1e4, Mt = ds / Xs + Cs; ds > 1 && Mt > ts && (ts = Mt, Xt = [Cr, Es, At, nr]); } const [Ks, jt, rs, Hs] = Xt, er = Math.floor((jt + Ks) / 2), De = Math.floor((Hs + rs) / 2); Fe.push(...ce.slice(0, er)), ce = ht.slice(De), _e = ce.length, Ye && (gt.push(...wt.slice(0, er)), wt = Y[yt].slice(De)); } return Fe.push(...ce), Ye ? (gt.push(...wt), [Fe, gt]) : [Fe, []]; } /** @private */ collateWordTimestamps(M, Y, ce) { const [_e, Fe, Ye] = this.combineTokensIntoWords(M, ce), gt = []; for (let wt = 0; wt < _e.length; ++wt) { const yt = Ye[wt]; gt.push({ text: _e[wt], timestamp: [ Y[yt.at(0)][0], Y[yt.at(-1)][1] ] }); } return gt; } /** * 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(M, Y, ce = `"'“¡¿([{-`, _e = `"'.。,,!!??::”)]}、`) { Y = Y ?? "english"; let Fe, Ye, gt; return ["chinese", "japanese", "thai", "lao", "myanmar"].includes(Y) ? [Fe, Ye, gt] = this.splitTokensOnUnicode(M) : [Fe, Ye, gt] = this.splitTokensOnSpaces(M), this.mergePunctuations(Fe, Ye, gt, ce, _e); } /** @type {PreTrainedTokenizer['decode']} */ decode(M, Y) { let ce; return Y?.decode_with_timestamps ? (M instanceof N.Tensor && (M = re(M)), ce = this.decodeWithTimestamps(M, Y)) : ce = super.decode(M, Y), ce; } /** * @param {number[]|bigint[]} token_ids List of token IDs to decode. * @param {Object} decode_args Optional arguments for decoding * @private */ decodeWithTimestamps(M, Y) { const ce = Y?.time_precision ?? 0.02, _e = Array.from(this.all_special_ids).at(-1) + 1; let Fe = [[]]; for (let Ye of M) if (Ye = Number(Ye), Ye >= _e) { const gt = ((Ye - _e) * ce).toFixed(2); Fe.push(`<|${gt}|>`), Fe.push([]); } else Fe[Fe.length - 1].push(Ye); return Fe = Fe.map( (Ye) => typeof Ye == "string" ? Ye : super.decode(Ye, Y) ), Fe.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(M) { const Y = this.decode(M, { // @ts-ignore decode_with_timestamps: !0 }), ce = "�", _e = [], Fe = [], Ye = []; let gt = [], wt = [], yt = 0; for (let ht = 0; ht < M.length; ++ht) { const ts = M[ht]; gt.push(ts), wt.push(ht); const Xt = this.decode(gt, { // @ts-ignore decode_with_timestamps: !0 }); (!Xt.includes(ce) || Y[yt + Xt.indexOf(ce)] === ce) && (_e.push(Xt), Fe.push(gt), Ye.push(wt), gt = [], wt = [], yt += Xt.length); } return [_e, Fe, Ye]; } /** * Combine tokens into words by splitting at whitespace and punctuation tokens. * @param {number[]} tokens * @private */ splitTokensOnSpaces(M) { const [Y, ce, _e] = this.splitTokensOnUnicode(M), Fe = [], Ye = [], gt = [], wt = new RegExp(`^[${w}]$`, "gu"); for (let yt = 0; yt < Y.length; ++yt) { const ht = Y[yt], ts = ce[yt], Xt = _e[yt], bs = ts[0] >= this.model.tokens_to_ids.get("<|endoftext|>"), Ks = ht.startsWith(" "), jt = ht.trim(), rs = wt.test(jt); if (bs || Ks || rs || Fe.length === 0) Fe.push(ht), Ye.push(ts), gt.push(Xt); else { const Hs = Fe.length - 1; Fe[Hs] += ht, Ye[Hs].push(...ts), gt[Hs].push(...Xt); } } return [Fe, Ye, gt]; } /** * Merges punctuation tokens with neighboring words. * @param {string[]} words * @param {number[][]} tokens * @param {number[][]} indices * @param {string} prepended * @param {string} appended * @private */ mergePunctuations(M, Y, ce, _e, Fe) { const Ye = structuredClone(M), gt = structuredClone(Y), wt = structuredClone(ce); let yt = Ye.length - 2, ht = Ye.length - 1; for (; yt >= 0; ) Ye[yt].startsWith(" ") && _e.includes(Ye[yt].trim()) ? (Ye[ht] = Ye[yt] + Ye[ht], gt[ht] = (0, O.mergeArrays)(gt[yt], gt[ht]), wt[ht] = (0, O.mergeArrays)(wt[yt], wt[ht]), Ye[yt] = "", gt[yt] = [], wt[yt] = []) : ht = yt, --yt; for (yt = 0, ht = 1; ht < Ye.length; ) !Ye[yt].endsWith(" ") && Fe.includes(Ye[ht]) ? (Ye[yt] += Ye[ht], gt[yt] = (0, O.mergeArrays)(gt[yt], gt[ht]), wt[yt] = (0, O.mergeArrays)(wt[yt], wt[ht]), Ye[ht] = "", gt[ht] = [], wt[ht] = []) : yt = ht, ++ht; return [ Ye.filter((ts) => ts), gt.filter((ts) => ts.length > 0), wt.filter((ts) => ts.length > 0) ]; } } class mn extends Lt { } class _n extends Lt { } class fn extends Lt { } class Ot extends Lt { /** * Create a new MarianTokenizer instance. * @param {Object} tokenizerJSON The JSON of the tokenizer. * @param {Object} tokenizerConfig The config of the tokenizer. */ constructor(M, Y) { super(M, Y), this.languageRegex = /^(>>\w+<<)\s*/g, this.supported_language_codes = this.model.vocab.filter( (ce) => this.languageRegex.test(ce) ), 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(M) { if (M === null) return null; const [Y, ...ce] = M.trim().split(this.languageRegex); if (ce.length === 0) return super._encode_text(Y); if (ce.length === 2) { const [_e, Fe] = ce; return this.supported_language_codes.includes(_e) || console.warn(`Unsupported language code "${_e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`), (0, O.mergeArrays)([_e], super._encode_text(Fe)); } } } class gn extends Lt { } class $n extends Lt { } class An extends Lt { } class In extends Lt { } class Rr extends Lt { } class Fn extends Lt { constructor(M, Y) { super(M, Y), this.decoder = new Nt({}); } } class wn extends Lt { } class On extends Lt { } class as { static TOKENIZER_CLASS_MAPPING = { T5Tokenizer: Zs, DistilBertTokenizer: ir, CamembertTokenizer: nt, DebertaTokenizer: lr, DebertaV2Tokenizer: Fr, BertTokenizer: Kr, HerbertTokenizer: Er, ConvBertTokenizer: Or, RoFormerTokenizer: Dr, XLMTokenizer: vt, ElectraTokenizer: Ft, MobileBertTokenizer: Pr, SqueezeBertTokenizer: Hr, AlbertTokenizer: Tr, GPT2Tokenizer: Pn, BartTokenizer: cn, MBartTokenizer: ws, MBart50Tokenizer: Mr, RobertaTokenizer: zs, WhisperTokenizer: Qr, CodeGenTokenizer: mn, CLIPTokenizer: _n, SiglipTokenizer: fn, MarianTokenizer: Ot, BloomTokenizer: qr, NllbTokenizer: ar, M2M100Tokenizer: hn, LlamaTokenizer: pn, CodeLlamaTokenizer: Lr, XLMRobertaTokenizer: eo, MPNetTokenizer: En, FalconTokenizer: Cn, GPTNeoXTokenizer: kn, EsmTokenizer: zr, Wav2Vec2CTCTokenizer: gn, BlenderbotTokenizer: $n, BlenderbotSmallTokenizer: An, SpeechT5Tokenizer: In, NougatTokenizer: Rr, VitsTokenizer: Fn, Qwen2Tokenizer: Sn, GemmaTokenizer: to, Grok1Tokenizer: Br, CohereTokenizer: wn, MgpstrTokenizer: On, // Base case: PreTrainedTokenizer: Lt }; /** * 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(M, { progress_callback: Y = null, config: ce = null, cache_dir: _e = null, local_files_only: Fe = !1, revision: Ye = "main", legacy: gt = null } = {}) { const [wt, yt] = await b(M, { progress_callback: Y, config: ce, cache_dir: _e, local_files_only: Fe, revision: Ye, legacy: gt }), ht = yt.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer"; let ts = this.TOKENIZER_CLASS_MAPPING[ht]; return ts || (console.warn(`Unknown tokenizer class "${ht}", attempting to construct from base class.`), ts = Lt), new ts(wt, yt); } } } ), /***/ "./src/utils/audio.js": ( /*!****************************!*\ !*** ./src/utils/audio.js ***! \****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ RawAudio: () => ( /* binding */ ge ), /* harmony export */ hamming: () => ( /* binding */ x ), /* harmony export */ hanning: () => ( /* binding */ b ), /* harmony export */ mel_filter_bank: () => ( /* binding */ q ), /* harmony export */ read_audio: () => ( /* binding */ T ), /* harmony export */ spectrogram: () => ( /* binding */ I ), /* harmony export */ window_function: () => ( /* binding */ le ) /* harmony export */ }); var g = r( /*! ./hub.js */ "./src/utils/hub.js" ), O = r( /*! ./maths.js */ "./src/utils/maths.js" ), j = r( /*! ./core.js */ "./src/utils/core.js" ), ee = r( /*! ../env.js */ "./src/env.js" ), N = r( /*! fs */ "?7a2c" ), y = r( /*! ./tensor.js */ "./src/utils/tensor.js" ); async function T(se, be) { if (typeof AudioContext > "u") 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 pe = await (await (0, g.getFile)(se)).arrayBuffer(), Ce = new AudioContext({ sampleRate: be }); typeof be > "u" && console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`); const $e = await Ce.decodeAudioData(pe); let Pe; if ($e.numberOfChannels === 2) { const Je = Math.sqrt(2), Ue = $e.getChannelData(0), we = $e.getChannelData(1); Pe = new Float32Array(Ue.length); for (let X = 0; X < $e.length; ++X) Pe[X] = Je * (Ue[X] + we[X]) / 2; } else Pe = $e.getChannelData(0); return Pe; } function v(se, be) { if (se < 1) return new Float64Array(); if (se === 1) return new Float64Array([1]); const pe = 1 - be, Ce = 2 * Math.PI / (se - 1), $e = new Float64Array(se); for (let Pe = 0; Pe < se; ++Pe) $e[Pe] = be - pe * Math.cos(Pe * Ce); return $e; } function b(se) { return v(se, 0.5); } function x(se) { return v(se, 0.54); } const L = { htk: (se) => 2595 * Math.log10(1 + se / 700), kaldi: (se) => 1127 * Math.log(1 + se / 700), slaney: (se, be = 1e3, pe = 15, Ce = 27 / Math.log(6.4)) => se >= be ? pe + Math.log(se / be) * Ce : 3 * se / 200 }; function K(se, be = "htk") { const pe = L[be]; if (!pe) throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); return typeof se == "number" ? pe(se) : se.map((Ce) => pe(Ce)); } const re = { htk: (se) => 700 * (10 ** (se / 2595) - 1), kaldi: (se) => 700 * (Math.exp(se / 1127) - 1), slaney: (se, be = 1e3, pe = 15, Ce = Math.log(6.4) / 27) => se >= pe ? be * Math.exp(Ce * (se - pe)) : 200 * se / 3 }; function ie(se, be = "htk") { const pe = re[be]; if (!pe) throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); return typeof se == "number" ? pe(se) : se.map((Ce) => pe(Ce)); } function V(se, be) { const pe = Float64Array.from( { length: be.length - 1 }, (Je, Ue) => be[Ue + 1] - be[Ue] ), Ce = Array.from({ length: se.length }, () => new Array(be.length)); for (let Je = 0; Je < se.length; ++Je) { const Ue = Ce[Je]; for (let we = 0; we < be.length; ++we) Ue[we] = be[we] - se[Je]; } const $e = be.length - 2, Pe = Array.from({ length: $e }, () => new Array(se.length)); for (let Je = 0; Je < se.length; ++Je) { const Ue = Ce[Je]; for (let we = 0; we < $e; ++we) { const X = -Ue[we] / pe[we], de = Ue[we + 2] / pe[we + 1]; Pe[we][Je] = Math.max(0, Math.min(X, de)); } } return Pe; } function U(se, be, pe) { const Ce = (be - se) / (pe - 1); return Float64Array.from({ length: pe }, ($e, Pe) => se + Ce * Pe); } function q(se, be, pe, Ce, $e, Pe = null, Je = "htk", Ue = !1) { if (Pe !== null && Pe !== "slaney") throw new Error('norm must be one of null or "slaney"'); const we = K(pe, Je), X = K(Ce, Je), de = U(we, X, be + 2); let Ee = ie(de, Je), Oe; if (Ue) { const J = $e / (se * 2); Oe = K(Float64Array.from({ length: se }, (We, Ne) => Ne * J), Je), Ee = de; } else Oe = U(0, Math.floor($e / 2), se); const Xe = V(Oe, Ee); if (Pe !== null && Pe === "slaney") for (let J = 0; J < be; ++J) { const We = Xe[J], Ne = 2 / (Ee[J + 2] - Ee[J]); for (let te = 0; te < se; ++te) We[te] *= Ne; } return Xe; } function A(se, be, pe) { const Ce = new se.constructor(se.length + be + pe), $e = se.length - 1; for (let Pe = 0; Pe < se.length; ++Pe) Ce[be + Pe] = se[Pe]; for (let Pe = 1; Pe <= be; ++Pe) Ce[be - Pe] = se[(0, j.calculateReflectOffset)(Pe, $e)]; for (let Pe = 1; Pe <= pe; ++Pe) Ce[$e + be + Pe] = se[(0, j.calculateReflectOffset)($e - Pe, $e)]; return Ce; } function S(se, be, pe, Ce, $e) { if (pe <= 0) throw new Error("reference must be greater than zero"); if (Ce <= 0) throw new Error("min_value must be greater than zero"); pe = Math.max(Ce, pe); const Pe = Math.log10(pe); for (let Je = 0; Je < se.length; ++Je) se[Je] = be * Math.log10(Math.max(Ce, se[Je]) - Pe); if ($e !== null) { if ($e <= 0) throw new Error("db_range must be greater than zero"); const Je = (0, O.max)(se)[0] - $e; for (let Ue = 0; Ue < se.length; ++Ue) se[Ue] = Math.max(se[Ue], Je); } return se; } function w(se, be = 1, pe = 1e-5, Ce = null) { return S(se, 20, be, pe, Ce); } function P(se, be = 1, pe = 1e-10, Ce = null) { return S(se, 10, be, pe, Ce); } async function I(se, be, pe, Ce, { fft_length: $e = null, power: Pe = 1, center: Je = !0, pad_mode: Ue = "reflect", onesided: we = !0, preemphasis: X = null, mel_filters: de = null, mel_floor: Ee = 1e-10, log_mel: Oe = null, reference: Xe = 1, min_value: J = 1e-10, db_range: We = null, remove_dc_offset: Ne = null, // Custom parameters for efficiency reasons min_num_frames: te = null, max_num_frames: ve = null, do_pad: He = !0, transpose: je = !1 } = {}) { const Ve = be.length; if ($e === null && ($e = pe), pe > $e) throw Error(`frame_length (${pe}) may not be larger than fft_length (${$e})`); if (Ve !== pe) throw new Error(`Length of the window (${Ve}) must equal frame_length (${pe})`); if (Ce <= 0) throw new Error("hop_length must be greater than zero"); if (Pe === null && de !== 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 (Je) { if (Ue !== "reflect") throw new Error(`pad_mode="${Ue}" not implemented yet.`); const ze = Math.floor(($e - 1) / 2) + 1; se = A(se, ze, ze); } let Re = Math.floor(1 + Math.floor((se.length - pe) / Ce)); te !== null && Re < te && (Re = te); const Ze = we ? Math.floor($e / 2) + 1 : $e; let at = Re, _t = Re; ve !== null && (ve > Re ? He && (_t = ve) : _t = at = ve); const lt = new O.FFT($e), ct = new Float64Array($e), F = new Float64Array(lt.outputBufferSize), ae = new Float32Array(Ze * _t); for (let ze = 0; ze < at; ++ze) { const Ge = ze * Ce, tt = Math.min(se.length - Ge, pe); tt !== pe && ct.fill(0, 0, pe); for (let et = 0; et < tt; ++et) ct[et] = se[Ge + et]; if (Ne) { let et = 0; for (let Nt = 0; Nt < tt; ++Nt) et += ct[Nt]; const mt = et / tt; for (let Nt = 0; Nt < tt; ++Nt) ct[Nt] -= mt; } if (X !== null) { for (let et = tt - 1; et >= 1; --et) ct[et] -= X * ct[et - 1]; ct[0] *= 1 - X; } for (let et = 0; et < be.length; ++et) ct[et] *= be[et]; lt.realTransform(F, ct); for (let et = 0; et < Ze; ++et) { const mt = et << 1; ae[et * _t + ze] = F[mt] ** 2 + F[mt + 1] ** 2; } } if (Pe !== null && Pe !== 2) { const ze = 2 / Pe; for (let Ge = 0; Ge < ae.length; ++Ge) ae[Ge] **= ze; } const H = de.length; let me = await (0, y.matmul)( // TODO: Make `mel_filters` a Tensor during initialization new y.Tensor("float32", de.flat(), [H, Ze]), new y.Tensor("float32", ae, [Ze, _t]) ); je && (me = me.transpose(1, 0)); const ke = ( /** @type {Float32Array} */ me.data ); for (let ze = 0; ze < ke.length; ++ze) ke[ze] = Math.max(Ee, ke[ze]); if (Pe !== null && Oe !== null) { const ze = Math.min(ke.length, at * H); switch (Oe) { case "log": for (let Ge = 0; Ge < ze; ++Ge) ke[Ge] = Math.log(ke[Ge]); break; case "log10": for (let Ge = 0; Ge < ze; ++Ge) ke[Ge] = Math.log10(ke[Ge]); break; case "dB": if (Pe === 1) w(ke, Xe, J, We); else if (Pe === 2) P(ke, Xe, J, We); else throw new Error(`Cannot use log_mel option '${Oe}' with power ${Pe}`); break; default: throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${Oe}'`); } } return me; } function le(se, be, { periodic: pe = !0, frame_length: Ce = null, center: $e = !0 } = {}) { const Pe = pe ? se + 1 : se; let Je; switch (be) { case "boxcar": Je = new Float64Array(Pe).fill(1); break; case "hann": case "hann_window": Je = b(Pe); break; case "hamming": Je = x(Pe); break; case "povey": Je = b(Pe).map((Ue) => Math.pow(Ue, 0.85)); break; default: throw new Error(`Unknown window type ${be}.`); } if (pe && (Je = Je.subarray(0, se)), Ce === null) return Je; if (se > Ce) throw new Error(`Length of the window (${se}) may not be larger than frame_length (${Ce})`); return Je; } function oe(se, be) { let pe = 44; const Ce = new ArrayBuffer(pe + se.length * 4), $e = new DataView(Ce); ye($e, 0, "RIFF"), $e.setUint32(4, 36 + se.length * 4, !0), ye($e, 8, "WAVE"), ye($e, 12, "fmt "), $e.setUint32(16, 16, !0), $e.setUint16(20, 3, !0), $e.setUint16(22, 1, !0), $e.setUint32(24, be, !0), $e.setUint32(28, be * 4, !0), $e.setUint16(32, 4, !0), $e.setUint16(34, 32, !0), ye($e, 36, "data"), $e.setUint32(40, se.length * 4, !0); for (let Pe = 0; Pe < se.length; ++Pe, pe += 4) $e.setFloat32(pe, se[Pe], !0); return Ce; } function ye(se, be, pe) { for (let Ce = 0; Ce < pe.length; ++Ce) se.setUint8(be + Ce, pe.charCodeAt(Ce)); } class ge { /** * Create a new `RawAudio` object. * @param {Float32Array} audio Audio data * @param {number} sampling_rate Sampling rate of the audio data */ constructor(be, pe) { this.audio = be, this.sampling_rate = pe; } /** * Convert the audio to a wav file buffer. * @returns {ArrayBuffer} The WAV file. */ toWav() { return oe(this.audio, this.sampling_rate); } /** * Convert the audio to a blob. * @returns {Blob} */ toBlob() { const be = this.toWav(); return new Blob([be], { type: "audio/wav" }); } /** * Save the audio to a wav file. * @param {string} path */ async save(be) { let pe; if (ee.apis.IS_BROWSER_ENV) { if (ee.apis.IS_WEBWORKER_ENV) throw new Error("Unable to save a file from a Web Worker."); pe = j.saveBlob; } else if (ee.apis.IS_FS_AVAILABLE) pe = async (Ce, $e) => { let Pe = await $e.arrayBuffer(); N.writeFileSync(Ce, Buffer.from(Pe)); }; else throw new Error("Unable to save because filesystem is disabled in this environment."); await pe(be, this.toBlob()); } } } ), /***/ "./src/utils/constants.js": ( /*!********************************!*\ !*** ./src/utils/constants.js ***! \********************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ CHAT_TEMPLATE_NAME: () => ( /* binding */ y ), /* harmony export */ CONFIG_NAME: () => ( /* binding */ O ), /* harmony export */ FEATURE_EXTRACTOR_NAME: () => ( /* binding */ j ), /* harmony export */ GENERATION_CONFIG_NAME: () => ( /* binding */ T ), /* harmony export */ GITHUB_ISSUE_URL: () => ( /* binding */ g ), /* harmony export */ IMAGE_PROCESSOR_NAME: () => ( /* binding */ ee ), /* harmony export */ PROCESSOR_NAME: () => ( /* binding */ N ) /* harmony export */ }); const g = "https://github.com/huggingface/transformers.js/issues/new/choose", O = "config.json", j = "preprocessor_config.json", ee = j, N = "processor_config.json", y = "chat_template.json", T = "generation_config.json"; } ), /***/ "./src/utils/core.js": ( /*!***************************!*\ !*** ./src/utils/core.js ***! \***************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ calculateDimensions: () => ( /* binding */ T ), /* harmony export */ calculateReflectOffset: () => ( /* binding */ L ), /* harmony export */ count: () => ( /* binding */ V ), /* harmony export */ dispatchCallback: () => ( /* binding */ g ), /* harmony export */ escapeRegExp: () => ( /* binding */ j ), /* harmony export */ isIntegralNumber: () => ( /* binding */ N ), /* harmony export */ isNullishDimension: () => ( /* binding */ y ), /* harmony export */ isTypedArray: () => ( /* binding */ ee ), /* harmony export */ len: () => ( /* binding */ ie ), /* harmony export */ mergeArrays: () => ( /* binding */ b ), /* harmony export */ pick: () => ( /* binding */ re ), /* harmony export */ pop: () => ( /* binding */ v ), /* harmony export */ product: () => ( /* binding */ x ), /* harmony export */ reverseDictionary: () => ( /* binding */ O ), /* harmony export */ saveBlob: () => ( /* binding */ K ) /* harmony export */ }); function g(U, q) { U && U(q); } function O(U) { return Object.fromEntries(Object.entries(U).map(([q, A]) => [A, q])); } function j(U) { return U.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function ee(U) { return U?.prototype?.__proto__?.constructor?.name === "TypedArray"; } function N(U) { return Number.isInteger(U) || typeof U == "bigint"; } function y(U) { return U == null || U === -1; } function T(U) { const q = []; let A = U; for (; Array.isArray(A); ) q.push(A.length), A = A[0]; return q; } function v(U, q, A = void 0) { const S = U[q]; if (S !== void 0) return delete U[q], S; if (A === void 0) throw Error(`Key ${q} does not exist in object.`); return A; } function b(...U) { return Array.prototype.concat.apply([], U); } function x(...U) { return U.reduce((q, A) => q.flatMap((S) => A.map((w) => [S, w]))); } function L(U, q) { return Math.abs((U + q) % (2 * q) - q); } function K(U, q) { const A = URL.createObjectURL(q), S = document.createElement("a"); S.href = A, S.download = U, S.click(), S.remove(), URL.revokeObjectURL(A); } function re(U, q) { return Object.assign( {}, ...q.map((A) => { if (U[A] !== void 0) return { [A]: U[A] }; }) ); } function ie(U) { let q = 0; for (const A of U) ++q; return q; } function V(U, q) { let A = 0; for (const S of U) S === q && ++A; return A; } } ), /***/ "./src/utils/data-structures.js": ( /*!**************************************!*\ !*** ./src/utils/data-structures.js ***! \**************************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ CharTrie: () => ( /* binding */ O ), /* harmony export */ PriorityQueue: () => ( /* binding */ g ), /* harmony export */ TokenLattice: () => ( /* binding */ ee ) /* harmony export */ }); class g { /** * Create a new PriorityQueue. * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap. */ constructor(T = (b, x) => b > x, v = 1 / 0) { this._heap = [], this._comparator = T, this._maxSize = v; } /** * 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(...T) { return this.extend(T); } /** * 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(T) { for (const v of T) if (this.size < this._maxSize) this._heap.push(v), this._siftUp(); else { const b = this._smallest(); this._comparator(v, this._heap[b]) && (this._heap[b] = v, this._siftUpFrom(b)); } 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 T = this.peek(), v = this.size - 1; return v > 0 && this._swap(0, v), this._heap.pop(), this._siftDown(), T; } /** * Replace the element with the highest priority in the queue with a new value. * @param {*} value The new value. * @returns {*} The replaced value. */ replace(T) { const v = this.peek(); return this._heap[0] = T, this._siftDown(), v; } /** * 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(T) { return (T + 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(T) { return (T << 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(T) { return T + 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(T, v) { return this._comparator(this._heap[T], this._heap[v]); } /** * 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(T, v) { const b = this._heap[T]; this._heap[T] = this._heap[v], this._heap[v] = b; } /** * Maintain the heap property by updating positions in the heap, * starting at the last element and moving up the heap. * @private */ _siftUp() { this._siftUpFrom(this.size - 1); } /** * Helper function to sift up from a given node. * @param {number} node The index of the node to start sifting up from. */ _siftUpFrom(T) { for (; T > 0 && this._greater(T, this._parent(T)); ) this._swap(T, this._parent(T)), T = this._parent(T); } /** * Maintain the heap property by updating positions in the heap, * starting at the first element and moving down the heap. * @private */ _siftDown() { let T = 0; for (; this._left(T) < this.size && this._greater(this._left(T), T) || this._right(T) < this.size && this._greater(this._right(T), T); ) { const v = this._right(T) < this.size && this._greater(this._right(T), this._left(T)) ? this._right(T) : this._left(T); this._swap(T, v), T = v; } } /** * Get the index of the smallest element in the heap. Since we use an array-based heap, * the index can be computed without needing to traverse the heap. * @private */ _smallest() { return 2 ** Math.floor(Math.log2(this.size)) - 1; } } class O { constructor() { this.root = j.default(); } /** * Adds one or more `texts` to the trie. * @param {string[]} texts The strings to add to the trie. */ extend(T) { for (const v of T) this.push(v); } /** * Adds text to the trie. * @param {string} text The string to add to the trie. */ push(T) { let v = this.root; for (const b of T) { let x = v.children.get(b); x === void 0 && (x = j.default(), v.children.set(b, x)), v = x; } v.isLeaf = !0; } /** * 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(T) { let v = this.root; if (v === void 0) return; let b = ""; for (const x of T) { if (b += x, v = v.children.get(x), v === void 0) return; v.isLeaf && (yield b); } } } class j { /** * 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(T, v) { this.isLeaf = T, this.children = v; } /** * 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 j(!1, /* @__PURE__ */ new Map()); } } class ee { /** * 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(T, v, b) { this.chars = Array.from(T), this.len = this.chars.length, this.bosTokenId = v, this.eosTokenId = b, this.nodes = [], this.beginNodes = Array.from({ length: this.len + 1 }, () => []), this.endNodes = Array.from({ length: this.len + 1 }, () => []); const x = new N(this.bosTokenId, 0, 0, 0, 0), L = new N(this.eosTokenId, 1, this.len, 0, 0); this.nodes.push(x.clone()), this.nodes.push(L.clone()), this.beginNodes[this.len].push(L), this.endNodes[0].push(x); } /** * 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(T, v, b, x) { const L = this.nodes.length, K = new N(x, L, T, v, b); this.beginNodes[T].push(K), this.endNodes[T + v].push(K), this.nodes.push(K); } /** * Implements the Viterbi algorithm to compute the most likely sequence of tokens. * * @returns {TokenLatticeNode[]} The most likely sequence of tokens. */ viterbi() { const T = this.len; let v = 0; for (; v <= T; ) { if (this.beginNodes[v].length == 0) return []; for (let re of this.beginNodes[v]) { re.prev = null; let ie = 0, V = null; for (let U of this.endNodes[v]) { const q = U.backtraceScore + re.score; (V === null || q > ie) && (V = U.clone(), ie = q); } if (V !== null) re.prev = V, re.backtraceScore = ie; else return []; } ++v; } const b = [], L = this.beginNodes[T][0].prev; if (L === null) return []; let K = L.clone(); for (; K.prev !== null; ) b.push(K.clone()), K = K.clone().prev.clone(); return b.reverse(), b; } /** * @param {TokenLatticeNode} node * @returns {string} The array of nodes representing the most likely sequence of tokens. */ piece(T) { return this.chars.slice(T.pos, T.pos + T.length).join(""); } /** * @returns {string[]} The most likely sequence of tokens. */ tokens() { return this.viterbi().map((v) => this.piece(v)); } /** * @returns {number[]} The most likely sequence of token ids. */ tokenIds() { return this.viterbi().map((v) => v.tokenId); } } class N { /** * 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(T, v, b, x, L) { this.tokenId = T, this.nodeId = v, this.pos = b, this.length = x, this.score = L, this.prev = null, this.backtraceScore = 0; } /** * Returns a clone of this node. * @returns {TokenLatticeNode} A clone of this node. */ clone() { const T = new N(this.tokenId, this.nodeId, this.pos, this.length, this.score); return T.prev = this.prev, T.backtraceScore = this.backtraceScore, T; } } } ), /***/ "./src/utils/devices.js": ( /*!******************************!*\ !*** ./src/utils/devices.js ***! \******************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DEVICE_TYPES: () => ( /* binding */ g ) /* harmony export */ }); const g = Object.freeze({ auto: "auto", // Auto-detect based on device and environment gpu: "gpu", // Auto-detect GPU cpu: "cpu", // CPU wasm: "wasm", // WebAssembly webgpu: "webgpu", // WebGPU cuda: "cuda", // CUDA dml: "dml", // DirectML webnn: "webnn", // WebNN (default) "webnn-npu": "webnn-npu", // WebNN NPU "webnn-gpu": "webnn-gpu", // WebNN GPU "webnn-cpu": "webnn-cpu" // WebNN CPU }); } ), /***/ "./src/utils/dtypes.js": ( /*!*****************************!*\ !*** ./src/utils/dtypes.js ***! \*****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ DATA_TYPES: () => ( /* binding */ ee ), /* harmony export */ DEFAULT_DEVICE_DTYPE_MAPPING: () => ( /* binding */ N ), /* harmony export */ DEFAULT_DTYPE_SUFFIX_MAPPING: () => ( /* binding */ y ), /* harmony export */ isWebGpuFp16Supported: () => ( /* binding */ j ) /* harmony export */ }); var g = r( /*! ../env.js */ "./src/env.js" ), O = r( /*! ./devices.js */ "./src/utils/devices.js" ); const j = /* @__PURE__ */ function() { let T; return async function() { if (T === void 0) if (!g.apis.IS_WEBGPU_AVAILABLE) T = !1; else try { T = (await navigator.gpu.requestAdapter()).features.has("shader-f16"); } catch { T = !1; } return T; }; }(), ee = Object.freeze({ auto: "auto", // Auto-detect based on environment fp32: "fp32", fp16: "fp16", q8: "q8", int8: "int8", uint8: "uint8", q4: "q4", bnb4: "bnb4", q4f16: "q4f16" // fp16 model with int4 block weight quantization }), N = Object.freeze({ // NOTE: If not specified, will default to fp32 [O.DEVICE_TYPES.wasm]: ee.q8 }), y = Object.freeze({ [ee.fp32]: "", [ee.fp16]: "_fp16", [ee.int8]: "_int8", [ee.uint8]: "_uint8", [ee.q8]: "_quantized", [ee.q4]: "_q4", [ee.q4f16]: "_q4f16", [ee.bnb4]: "_bnb4" }); } ), /***/ "./src/utils/generic.js": ( /*!******************************!*\ !*** ./src/utils/generic.js ***! \******************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Callable: () => ( /* binding */ g ) /* harmony export */ }); const g = ( /** @type {any} */ class { /** * Creates a new instance of the Callable class. */ constructor() { let O = function(...j) { return O._call(...j); }; return Object.setPrototypeOf(O, 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(...O) { throw Error("Must implement _call method in subclass"); } } ); } ), /***/ "./src/utils/hub.js": ( /*!**************************!*\ !*** ./src/utils/hub.js ***! \**************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ getFile: () => ( /* binding */ v ), /* harmony export */ getModelFile: () => ( /* binding */ re ), /* harmony export */ getModelJSON: () => ( /* binding */ ie ) /* harmony export */ }); var g = r( /*! fs */ "?7a2c" ), O = r( /*! path */ "?a42a" ), j = r( /*! ../env.js */ "./src/env.js" ), ee = r( /*! ./core.js */ "./src/utils/core.js" ); const N = { 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" }; class y { /** * Creates a new `FileResponse` object. * @param {string|URL} filePath */ constructor(A) { if (this.filePath = A, this.headers = new Headers(), this.exists = g.existsSync(A), this.exists) { this.status = 200, this.statusText = "OK"; let S = g.statSync(A); this.headers.set("content-length", S.size.toString()), this.updateContentType(); let w = this; this.body = new ReadableStream({ start(P) { w.arrayBuffer().then((I) => { P.enqueue(new Uint8Array(I)), P.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 A = this.filePath.toString().split(".").pop().toLowerCase(); this.headers.set("content-type", N[A] ?? "application/octet-stream"); } /** * Clone the current FileResponse object. * @returns {FileResponse} A new FileResponse object with the same properties as the current object. */ clone() { let A = new y(this.filePath); return A.exists = this.exists, A.status = this.status, A.statusText = this.statusText, A.headers = new Headers(this.headers), A; } /** * 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() { return ( /** @type {ArrayBuffer} */ (await g.promises.readFile(this.filePath)).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 A = await g.promises.readFile(this.filePath); return new Blob([A], { 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() { return await g.promises.readFile(this.filePath, "utf8"); } /** * 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()); } } function T(q, A = null, S = null) { let w; try { w = new URL(q); } catch { return !1; } return !(A && !A.includes(w.protocol) || S && !S.includes(w.hostname)); } async function v(q) { if (j.env.useFS && !T(q, ["http:", "https:", "blob:"])) return new y(q); if (typeof process < "u" && process?.release?.name === "node") { const A = !!process.env?.TESTING_REMOTELY, S = j.env.version, w = new Headers(); if (w.set("User-Agent", `transformers.js/${S}; is_ci/${A};`), T(q, ["http:", "https:"], ["huggingface.co", "hf.co"])) { const I = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; I && w.set("Authorization", `Bearer ${I}`); } return fetch(q, { headers: w }); } else return fetch(q); } const b = { // 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" }; function x(q, A, S) { if (!S) return null; const w = b[q] ?? `Error (${q}) occurred while trying to load file`; throw Error(`${w}: "${A}".`); } class L { /** * Instantiate a `FileCache` object. * @param {string} path */ constructor(A) { this.path = A; } /** * Checks whether the given request is in the cache. * @param {string} request * @returns {Promise} */ async match(A) { let S = O.join(this.path, A), w = new y(S); if (w.exists) return w; } /** * Adds the given response to the cache. * @param {string} request * @param {Response|FileResponse} response * @returns {Promise} */ async put(A, S) { const w = Buffer.from(await S.arrayBuffer()); let P = O.join(this.path, A); try { await g.promises.mkdir(O.dirname(P), { recursive: !0 }), await g.promises.writeFile(P, w); } catch (I) { console.warn("An error occurred while writing the file to cache:", I); } } // 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>; } async function K(q, ...A) { for (let S of A) try { let w = await q.match(S); if (w) return w; } catch { continue; } } async function re(q, A, S = !0, w = {}) { if (!j.env.allowLocalModels) { if (w.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`)."); if (!j.env.allowRemoteModels) throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`."); } (0, ee.dispatchCallback)(w.progress_callback, { status: "initiate", name: q, file: A }); let P; if (!P && j.env.useBrowserCache) { if (typeof caches > "u") throw Error("Browser cache is not available in this environment."); try { P = await caches.open("transformers-cache"); } catch (Je) { console.warn("An error occurred while opening the browser cache:", Je); } } if (!P && j.env.useFSCache && (P = new L(w.cache_dir ?? j.env.cacheDir)), !P && j.env.useCustomCache) { if (!j.env.customCache) throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined."); if (!j.env.customCache.match || !j.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" ); P = j.env.customCache; } const I = w.revision ?? "main"; let le = U(q, A), oe = U(j.env.localModelPath, le), ye = U( j.env.remoteHost, j.env.remotePathTemplate.replaceAll("{model}", q).replaceAll("{revision}", encodeURIComponent(I)), A ), ge = I === "main" ? le : U(q, I, A), se, be = P instanceof L ? ge : ye, pe = !1, Ce; P && (Ce = await K(P, oe, be)); const $e = Ce !== void 0; if (Ce === void 0) { if (j.env.allowLocalModels) if (T(le, ["http:", "https:"])) { if (w.local_files_only) throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${le}.`); if (!j.env.allowRemoteModels) throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${le}.`); } else try { Ce = await v(oe), se = oe; } catch (Ue) { console.warn(`Unable to load from local path "${oe}": "${Ue}"`); } if (Ce === void 0 || Ce.status === 404) { if (w.local_files_only || !j.env.allowRemoteModels) { if (S) throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${oe}".`); return null; } if (Ce = await v(ye), Ce.status !== 200) return x(Ce.status, ye, S); se = be; } pe = P && typeof Response < "u" && Ce instanceof Response && Ce.status === 200; } (0, ee.dispatchCallback)(w.progress_callback, { status: "download", name: q, file: A }); let Pe; return w.progress_callback ? $e && typeof navigator < "u" && /firefox/i.test(navigator.userAgent) ? (Pe = new Uint8Array(await Ce.arrayBuffer()), (0, ee.dispatchCallback)(w.progress_callback, { status: "progress", name: q, file: A, progress: 100, loaded: Pe.length, total: Pe.length })) : Pe = await V(Ce, (Je) => { (0, ee.dispatchCallback)(w.progress_callback, { status: "progress", name: q, file: A, ...Je }); }) : Pe = new Uint8Array(await Ce.arrayBuffer()), // Only cache web responses // i.e., do not cache FileResponses (prevents duplication) pe && se && // Check again whether request is in cache. If not, we add the response to the cache await P.match(se) === void 0 && await P.put(se, new Response(Pe, { headers: Ce.headers })).catch((Je) => { console.warn(`Unable to add response to browser cache: ${Je}.`); }), (0, ee.dispatchCallback)(w.progress_callback, { status: "done", name: q, file: A }), Pe; } async function ie(q, A, S = !0, w = {}) { let P = await re(q, A, S, w); if (P === null) return {}; let le = new TextDecoder("utf-8").decode(P); return JSON.parse(le); } async function V(q, A) { const S = q.headers.get("Content-Length"); S === null && console.warn("Unable to determine content-length from response headers. Will expand buffer when needed."); let w = parseInt(S ?? "0"), P = new Uint8Array(w), I = 0; const le = q.body.getReader(); async function oe() { const { done: ye, value: ge } = await le.read(); if (ye) return; let se = I + ge.length; if (se > w) { w = se; let pe = new Uint8Array(w); pe.set(P), P = pe; } P.set(ge, I), I = se; const be = I / w * 100; return A({ progress: be, loaded: I, total: w }), oe(); } return await oe(), P; } function U(...q) { return q = q.map((A, S) => (S && (A = A.replace(new RegExp("^/"), "")), S !== q.length - 1 && (A = A.replace(new RegExp("/$"), "")), A)), q.join("/"); } } ), /***/ "./src/utils/image.js": ( /*!****************************!*\ !*** ./src/utils/image.js ***! \****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ RawImage: () => ( /* binding */ K ), /* harmony export */ load_image: () => ( /* binding */ re ) /* harmony export */ }); var g = r( /*! ./core.js */ "./src/utils/core.js" ), O = r( /*! ./hub.js */ "./src/utils/hub.js" ), j = r( /*! ../env.js */ "./src/env.js" ), ee = r( /*! ./tensor.js */ "./src/utils/tensor.js" ), N = r( /*! sharp */ "?2b25" ); let y, T, v; const b = j.apis.IS_BROWSER_ENV || j.apis.IS_WEBWORKER_ENV; if (b) y = (ie, V) => { if (!self.OffscreenCanvas) throw new Error("OffscreenCanvas not supported by this browser."); return new self.OffscreenCanvas(ie, V); }, v = self.createImageBitmap, T = self.ImageData; else if (N) v = async (ie) => { const U = (await ie.metadata()).channels, { data: q, info: A } = await ie.rotate().raw().toBuffer({ resolveWithObject: !0 }), S = new K(new Uint8ClampedArray(q), A.width, A.height, A.channels); return U !== void 0 && U !== A.channels && S.convert(U), S; }; else throw new Error("Unable to load image processing library."); const x = { 0: "nearest", 1: "lanczos", 2: "bilinear", 3: "bicubic", 4: "box", 5: "hamming" }, L = /* @__PURE__ */ new Map([ ["png", "image/png"], ["jpg", "image/jpeg"], ["jpeg", "image/jpeg"], ["gif", "image/gif"] ]); class K { /** * 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(V, U, q, A) { this.data = V, this.width = U, this.height = q, this.channels = A; } /** * 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(V) { if (V instanceof K) return V; if (typeof V == "string" || V instanceof URL) return await this.fromURL(V); throw new Error(`Unsupported input type: ${typeof V}`); } /** * Read an image from a canvas. * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from. * @returns {RawImage} The image object. */ static fromCanvas(V) { if (!b) throw new Error("fromCanvas() is only supported in browser environments."); const q = V.getContext("2d").getImageData(0, 0, V.width, V.height).data; return new K(q, V.width, V.height, 4); } /** * 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(V) { const U = await (0, O.getFile)(V); if (U.status !== 200) throw new Error(`Unable to read image from "${V}" (${U.status} ${U.statusText})`); const q = await U.blob(); return this.fromBlob(q); } /** * 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(V) { if (b) { const U = await v(V), q = y(U.width, U.height).getContext("2d"); return q.drawImage(U, 0, 0), new this(q.getImageData(0, 0, U.width, U.height).data, U.width, U.height, 4); } else { const U = N(await V.arrayBuffer()); return await v(U); } } /** * Helper method to create a new Image from a tensor * @param {Tensor} tensor */ static fromTensor(V, U = "CHW") { if (V.dims.length !== 3) throw new Error(`Tensor should have 3 dimensions, but has ${V.dims.length} dimensions.`); if (U === "CHW") V = V.transpose(1, 2, 0); else if (U !== "HWC") throw new Error(`Unsupported channel format: ${U}`); if (!(V.data instanceof Uint8ClampedArray || V.data instanceof Uint8Array)) throw new Error(`Unsupported tensor type: ${V.type}`); switch (V.dims[2]) { case 1: case 2: case 3: case 4: return new K(V.data, V.dims[1], V.dims[0], V.dims[2]); default: throw new Error(`Unsupported number of channels: ${V.dims[2]}`); } } /** * Convert the image to grayscale format. * @returns {RawImage} `this` to support chaining. */ grayscale() { if (this.channels === 1) return this; const V = new Uint8ClampedArray(this.width * this.height * 1); switch (this.channels) { case 3: // rgb to grayscale case 4: for (let U = 0, q = 0; U < this.data.length; U += this.channels) { const A = this.data[U], S = this.data[U + 1], w = this.data[U + 2]; V[q++] = Math.round(0.2989 * A + 0.587 * S + 0.114 * w); } break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(V, this.width, this.height, 1); } /** * Convert the image to RGB format. * @returns {RawImage} `this` to support chaining. */ rgb() { if (this.channels === 3) return this; const V = new Uint8ClampedArray(this.width * this.height * 3); switch (this.channels) { case 1: for (let U = 0, q = 0; U < this.data.length; ++U) V[q++] = this.data[U], V[q++] = this.data[U], V[q++] = this.data[U]; break; case 4: for (let U = 0, q = 0; U < this.data.length; U += 4) V[q++] = this.data[U], V[q++] = this.data[U + 1], V[q++] = this.data[U + 2]; break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(V, this.width, this.height, 3); } /** * Convert the image to RGBA format. * @returns {RawImage} `this` to support chaining. */ rgba() { if (this.channels === 4) return this; const V = new Uint8ClampedArray(this.width * this.height * 4); switch (this.channels) { case 1: for (let U = 0, q = 0; U < this.data.length; ++U) V[q++] = this.data[U], V[q++] = this.data[U], V[q++] = this.data[U], V[q++] = 255; break; case 3: for (let U = 0, q = 0; U < this.data.length; U += 3) V[q++] = this.data[U], V[q++] = this.data[U + 1], V[q++] = this.data[U + 2], V[q++] = 255; break; default: throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } return this._update(V, this.width, this.height, 4); } /** * Apply an alpha mask to the image. Operates in place. * @param {RawImage} mask The mask to apply. It should have a single channel. * @returns {RawImage} The masked image. * @throws {Error} If the mask is not the same size as the image. * @throws {Error} If the image does not have 4 channels. * @throws {Error} If the mask is not a single channel. */ putAlpha(V) { if (V.width !== this.width || V.height !== this.height) throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${V.width}x${V.height}`); if (V.channels !== 1) throw new Error(`Expected mask to have 1 channel, but got ${V.channels}`); const U = this.data, q = V.data, A = this.width * this.height; if (this.channels === 3) { const S = new Uint8ClampedArray(A * 4); for (let w = 0, P = 0, I = 0; w < A; ++w) S[I++] = U[P++], S[I++] = U[P++], S[I++] = U[P++], S[I++] = q[w]; return this._update(S, this.width, this.height, 4); } else if (this.channels === 4) { for (let S = 0; S < A; ++S) U[4 * S + 3] = q[S]; return this; } throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`); } /** * 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. `null` or `-1` will preserve the aspect ratio. * @param {number} height The height of the new image. `null` or `-1` will preserve the aspect ratio. * @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(V, U, { resample: q = 2 } = {}) { if (this.width === V && this.height === U) return this; let A = x[q] ?? q; const S = (0, g.isNullishDimension)(V), w = (0, g.isNullishDimension)(U); if (S && w) return this; if (S ? V = U / this.height * this.width : w && (U = V / this.width * this.height), b) { const P = this.channels, I = this.toCanvas(), le = y(V, U).getContext("2d"); return le.drawImage(I, 0, 0, V, U), new K(le.getImageData(0, 0, V, U).data, V, U, 4).convert(P); } else { let P = this.toSharp(); switch (A) { case "box": case "hamming": (A === "box" || A === "hamming") && (console.warn(`Resampling method ${A} is not yet supported. Using bilinear instead.`), A = "bilinear"); case "nearest": case "bilinear": case "bicubic": P = P.affine([V / this.width, 0, 0, U / this.height], { interpolator: A }); break; case "lanczos": P = P.resize({ width: V, height: U, fit: "fill", kernel: "lanczos3" // PIL Lanczos uses a kernel size of 3 }); break; default: throw new Error(`Resampling method ${A} is not supported.`); } return await v(P); } } async pad([V, U, q, A]) { if (V = Math.max(V, 0), U = Math.max(U, 0), q = Math.max(q, 0), A = Math.max(A, 0), V === 0 && U === 0 && q === 0 && A === 0) return this; if (b) { const S = this.channels, w = this.toCanvas(), P = this.width + V + U, I = this.height + q + A, le = y(P, I).getContext("2d"); return le.drawImage( w, 0, 0, this.width, this.height, V, q, this.width, this.height ), new K( le.getImageData(0, 0, P, I).data, P, I, 4 ).convert(S); } else { const S = this.toSharp().extend({ left: V, right: U, top: q, bottom: A }); return await v(S); } } async crop([V, U, q, A]) { if (V = Math.max(V, 0), U = Math.max(U, 0), q = Math.min(q, this.width - 1), A = Math.min(A, this.height - 1), V === 0 && U === 0 && q === this.width - 1 && A === this.height - 1) return this; const S = q - V + 1, w = A - U + 1; if (b) { const P = this.channels, I = this.toCanvas(), le = y(S, w).getContext("2d"); return le.drawImage( I, V, U, S, w, 0, 0, S, w ), new K(le.getImageData(0, 0, S, w).data, S, w, 4).convert(P); } else { const P = this.toSharp().extract({ left: V, top: U, width: S, height: w }); return await v(P); } } async center_crop(V, U) { if (this.width === V && this.height === U) return this; const q = (this.width - V) / 2, A = (this.height - U) / 2; if (b) { const S = this.channels, w = this.toCanvas(), P = y(V, U).getContext("2d"); let I = 0, le = 0, oe = 0, ye = 0; return q >= 0 ? I = q : oe = -q, A >= 0 ? le = A : ye = -A, P.drawImage( w, I, le, V, U, oe, ye, V, U ), new K(P.getImageData(0, 0, V, U).data, V, U, 4).convert(S); } else { let S = this.toSharp(); if (q >= 0 && A >= 0) S = S.extract({ left: Math.floor(q), top: Math.floor(A), width: V, height: U }); else if (q <= 0 && A <= 0) { const w = Math.floor(-A), P = Math.floor(-q); S = S.extend({ top: w, left: P, // Ensures the resulting image has the desired dimensions right: V - this.width - P, bottom: U - this.height - w }); } else { let w = [0, 0], P = 0; A < 0 ? (w[0] = Math.floor(-A), w[1] = U - this.height - w[0]) : P = Math.floor(A); let I = [0, 0], le = 0; q < 0 ? (I[0] = Math.floor(-q), I[1] = V - this.width - I[0]) : le = Math.floor(q), S = S.extend({ top: w[0], bottom: w[1], left: I[0], right: I[1] }).extract({ left: le, top: P, width: V, height: U }); } return await v(S); } } async toBlob(V = "image/png", U = 1) { if (!b) throw new Error("toBlob() is only supported in browser environments."); return await this.toCanvas().convertToBlob({ type: V, quality: U }); } toTensor(V = "CHW") { let U = new ee.Tensor( "uint8", new Uint8Array(this.data), [this.height, this.width, this.channels] ); if (V !== "HWC") if (V === "CHW") U = U.permute(2, 0, 1); else throw new Error(`Unsupported channel format: ${V}`); return U; } toCanvas() { if (!b) throw new Error("toCanvas() is only supported in browser environments."); const V = this.clone().rgba(), U = y(V.width, V.height), q = new T(V.data, V.width, V.height); return U.getContext("2d").putImageData(q, 0, 0), U; } /** * Split this image into individual bands. This method returns an array of individual image bands from an image. * For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). * * Inspired by PIL's `Image.split()` [function](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.split). * @returns {RawImage[]} An array containing bands. */ split() { const { data: V, width: U, height: q, channels: A } = this, S = ( /** @type {any} */ V.constructor ), w = V.length / A, P = Array.from( { length: A }, () => new S(w) ); for (let I = 0; I < w; ++I) { const le = A * I; for (let oe = 0; oe < A; ++oe) P[oe][I] = V[le + oe]; } return P.map((I) => new K(I, U, q, 1)); } /** * 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(V, U, q, A = null) { return this.data = V, this.width = U, this.height = q, A !== null && (this.channels = A), this; } /** * Clone the image * @returns {RawImage} The cloned image */ clone() { return new K(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(V) { if (this.channels === V) return this; switch (V) { 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(V) { if (b) { if (j.apis.IS_WEBWORKER_ENV) throw new Error("Unable to save an image from a Web Worker."); const U = V.split(".").pop().toLowerCase(), q = L.get(U) ?? "image/png", A = await this.toBlob(q); (0, g.saveBlob)(V, A); } else { if (j.apis.IS_FS_AVAILABLE) return await this.toSharp().toFile(V); throw new Error("Unable to save the image because filesystem is disabled in this environment."); } } toSharp() { if (b) throw new Error("toSharp() is only supported in server-side environments."); return N(this.data, { raw: { width: this.width, height: this.height, channels: this.channels } }); } } const re = K.read.bind(K); } ), /***/ "./src/utils/maths.js": ( /*!****************************!*\ !*** ./src/utils/maths.js ***! \****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ FFT: () => ( /* binding */ re ), /* harmony export */ bankers_round: () => ( /* binding */ U ), /* harmony export */ cos_sim: () => ( /* binding */ y ), /* harmony export */ dot: () => ( /* binding */ N ), /* harmony export */ dynamic_time_warping: () => ( /* binding */ q ), /* harmony export */ interpolate_data: () => ( /* binding */ g ), /* harmony export */ log_softmax: () => ( /* binding */ ee ), /* harmony export */ magnitude: () => ( /* binding */ T ), /* harmony export */ max: () => ( /* binding */ b ), /* harmony export */ medianFilter: () => ( /* binding */ ie ), /* harmony export */ min: () => ( /* binding */ v ), /* harmony export */ permute_data: () => ( /* binding */ O ), /* harmony export */ round: () => ( /* binding */ V ), /* harmony export */ softmax: () => ( /* binding */ j ) /* harmony export */ }); function g(A, [S, w, P], [I, le], oe = "bilinear", ye = !1) { const ge = le / P, se = I / w, be = new A.constructor(I * le * S), pe = w * P, Ce = I * le; for (let $e = 0; $e < I; ++$e) for (let Pe = 0; Pe < le; ++Pe) { const Je = $e * le + Pe, Ue = (Pe + 0.5) / ge - 0.5, we = ($e + 0.5) / se - 0.5; let X = Math.floor(Ue), de = Math.floor(we); const Ee = Math.min(X + 1, P - 1), Oe = Math.min(de + 1, w - 1); X = Math.max(X, 0), de = Math.max(de, 0); const Xe = Ue - X, J = we - de, We = (1 - Xe) * (1 - J), Ne = Xe * (1 - J), te = (1 - Xe) * J, ve = Xe * J, He = de * P, je = Oe * P, Ve = He + X, Re = He + Ee, Ze = je + X, at = je + Ee; for (let _t = 0; _t < S; ++_t) { const lt = _t * pe; be[_t * Ce + Je] = We * A[lt + Ve] + Ne * A[lt + Re] + te * A[lt + Ze] + ve * A[lt + at]; } } return be; } function O(A, S, w) { const P = new Array(w.length), I = new Array(w.length); for (let ye = w.length - 1, ge = 1; ye >= 0; --ye) I[ye] = ge, P[ye] = S[w[ye]], ge *= P[ye]; const le = w.map((ye, ge) => I[w.indexOf(ge)]), oe = new A.constructor(A.length); for (let ye = 0; ye < A.length; ++ye) { let ge = 0; for (let se = S.length - 1, be = ye; se >= 0; --se) ge += be % S[se] * le[se], be = Math.floor(be / S[se]); oe[ge] = A[ye]; } return [oe, P]; } function j(A) { const S = b(A)[0], w = A.map((le) => Math.exp(le - S)), P = w.reduce((le, oe) => le + oe, 0); return w.map((le) => le / P); } function ee(A) { const S = b(A)[0]; let w = 0; for (let le = 0; le < A.length; ++le) w += Math.exp(A[le] - S); const P = Math.log(w); return A.map((le) => le - S - P); } function N(A, S) { let w = 0; for (let P = 0; P < A.length; ++P) w += A[P] * S[P]; return w; } function y(A, S) { const w = N(A, S), P = T(A), I = T(S); return w / (P * I); } function T(A) { return Math.sqrt(A.reduce((S, w) => S + w * w, 0)); } function v(A) { if (A.length === 0) throw Error("Array must not be empty"); let S = A[0], w = 0; for (let P = 1; P < A.length; ++P) A[P] < S && (S = A[P], w = P); return ( /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ [S, w] ); } function b(A) { if (A.length === 0) throw Error("Array must not be empty"); let S = A[0], w = 0; for (let P = 1; P < A.length; ++P) A[P] > S && (S = A[P], w = P); return ( /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ [S, w] ); } function x(A) { return A > 0 && (A & A - 1) === 0; } class L { /** * @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(S) { if (this.size = S | 0, this.size <= 1 || !x(this.size)) throw new Error("FFT size must be a power of two larger than 1"); this._csize = S << 1, this.table = new Float64Array(this.size * 2); for (let P = 0; P < this.table.length; P += 2) { const I = Math.PI * P / this.size; this.table[P] = Math.cos(I), this.table[P + 1] = -Math.sin(I); } let w = 0; for (let P = 1; this.size > P; P <<= 1) ++w; this._width = w % 2 === 0 ? w - 1 : w, this._bitrev = new Int32Array(1 << this._width); for (let P = 0; P < this._bitrev.length; ++P) { this._bitrev[P] = 0; for (let I = 0; I < this._width; I += 2) { const le = this._width - I - 2; this._bitrev[P] |= (P >>> I & 3) << le; } } } /** * 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(S, w) { const P = w || new Array(S.length >>> 1); for (let I = 0; I < S.length; I += 2) P[I >>> 1] = S[I]; return P; } /** * 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(S, w) { const P = w || this.createComplexArray(); for (let I = 0; I < P.length; I += 2) P[I] = S[I >>> 1], P[I + 1] = 0; return P; } /** * 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(S, w) { if (S === w) throw new Error("Input and output buffers must be different"); this._transform4( S, w, 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(S, w) { if (S === w) throw new Error("Input and output buffers must be different"); this._realTransform4( S, w, 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(S, w) { if (S === w) throw new Error("Input and output buffers must be different"); this._transform4( S, w, -1 /* DONE */ ); for (let P = 0; P < S.length; ++P) S[P] /= 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(S, w, P) { const I = this._csize; let oe = 1 << this._width, ye = I / oe << 1, ge, se; const be = this._bitrev; if (ye === 4) for (ge = 0, se = 0; ge < I; ge += ye, ++se) { const Ce = be[se]; this._singleTransform2(w, S, ge, Ce, oe); } else for (ge = 0, se = 0; ge < I; ge += ye, ++se) { const Ce = be[se]; this._singleTransform4(w, S, ge, Ce, oe, P); } const pe = this.table; for (oe >>= 2; oe >= 2; oe >>= 2) { ye = I / oe << 1; const Ce = ye >>> 2; for (ge = 0; ge < I; ge += ye) { const $e = ge + Ce - 1; for (let Pe = ge, Je = 0; Pe < $e; Pe += 2, Je += oe) { const Ue = Pe, we = Ue + Ce, X = we + Ce, de = X + Ce, Ee = S[Ue], Oe = S[Ue + 1], Xe = S[we], J = S[we + 1], We = S[X], Ne = S[X + 1], te = S[de], ve = S[de + 1], He = pe[Je], je = P * pe[Je + 1], Ve = Xe * He - J * je, Re = Xe * je + J * He, Ze = pe[2 * Je], at = P * pe[2 * Je + 1], _t = We * Ze - Ne * at, lt = We * at + Ne * Ze, ct = pe[3 * Je], F = P * pe[3 * Je + 1], ae = te * ct - ve * F, H = te * F + ve * ct, me = Ee + _t, ke = Oe + lt, ze = Ee - _t, Ge = Oe - lt, tt = Ve + ae, et = Re + H, mt = P * (Ve - ae), Nt = P * (Re - H); S[Ue] = me + tt, S[Ue + 1] = ke + et, S[we] = ze + Nt, S[we + 1] = Ge - mt, S[X] = me - tt, S[X + 1] = ke - et, S[de] = ze - Nt, S[de + 1] = Ge + mt; } } } } /** * 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(S, w, P, I, le) { const oe = S[I], ye = S[I + 1], ge = S[I + le], se = S[I + le + 1]; w[P] = oe + ge, w[P + 1] = ye + se, w[P + 2] = oe - ge, w[P + 3] = ye - se; } /** * 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(S, w, P, I, le, oe) { const ye = le * 2, ge = le * 3, se = S[I], be = S[I + 1], pe = S[I + le], Ce = S[I + le + 1], $e = S[I + ye], Pe = S[I + ye + 1], Je = S[I + ge], Ue = S[I + ge + 1], we = se + $e, X = be + Pe, de = se - $e, Ee = be - Pe, Oe = pe + Je, Xe = Ce + Ue, J = oe * (pe - Je), We = oe * (Ce - Ue); w[P] = we + Oe, w[P + 1] = X + Xe, w[P + 2] = de + We, w[P + 3] = Ee - J, w[P + 4] = we - Oe, w[P + 5] = X - Xe, w[P + 6] = de - We, w[P + 7] = Ee + J; } /** * 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(S, w, P) { const I = this._csize; let oe = 1 << this._width, ye = I / oe << 1, ge, se; const be = this._bitrev; if (ye === 4) for (ge = 0, se = 0; ge < I; ge += ye, ++se) { const $e = be[se]; this._singleRealTransform2(w, S, ge, $e >>> 1, oe >>> 1); } else for (ge = 0, se = 0; ge < I; ge += ye, ++se) { const $e = be[se]; this._singleRealTransform4(w, S, ge, $e >>> 1, oe >>> 1, P); } const pe = this.table; for (oe >>= 2; oe >= 2; oe >>= 2) { ye = I / oe << 1; const $e = ye >>> 1, Pe = $e >>> 1, Je = Pe >>> 1; for (ge = 0; ge < I; ge += ye) for (let Ue = 0, we = 0; Ue <= Je; Ue += 2, we += oe) { const X = ge + Ue, de = X + Pe, Ee = de + Pe, Oe = Ee + Pe, Xe = S[X], J = S[X + 1], We = S[de], Ne = S[de + 1], te = S[Ee], ve = S[Ee + 1], He = S[Oe], je = S[Oe + 1], Ve = Xe, Re = J, Ze = pe[we], at = P * pe[we + 1], _t = We * Ze - Ne * at, lt = We * at + Ne * Ze, ct = pe[2 * we], F = P * pe[2 * we + 1], ae = te * ct - ve * F, H = te * F + ve * ct, me = pe[3 * we], ke = P * pe[3 * we + 1], ze = He * me - je * ke, Ge = He * ke + je * me, tt = Ve + ae, et = Re + H, mt = Ve - ae, Nt = Re - H, es = _t + ze, Ts = lt + Ge, ms = P * (_t - ze), Ps = P * (lt - Ge); if (S[X] = tt + es, S[X + 1] = et + Ts, S[de] = mt + Ps, S[de + 1] = Nt - ms, Ue === 0) { S[Ee] = tt - es, S[Ee + 1] = et - Ts; continue; } if (Ue === Je) continue; const Is = ge + Pe - Ue, tr = ge + $e - Ue; S[Is] = mt - P * Ps, S[Is + 1] = -Nt - P * ms, S[tr] = tt - P * es, S[tr + 1] = -et + P * Ts; } } const Ce = I >>> 1; for (let $e = 2; $e < Ce; $e += 2) S[I - $e] = S[$e], S[I - $e + 1] = -S[$e + 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(S, w, P, I, le) { const oe = S[I], ye = S[I + le]; w[P] = oe + ye, w[P + 1] = 0, w[P + 2] = oe - ye, w[P + 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(S, w, P, I, le, oe) { const ye = le * 2, ge = le * 3, se = S[I], be = S[I + le], pe = S[I + ye], Ce = S[I + ge], $e = se + pe, Pe = se - pe, Je = be + Ce, Ue = oe * (be - Ce); w[P] = $e + Je, w[P + 1] = 0, w[P + 2] = Pe, w[P + 3] = -Ue, w[P + 4] = $e - Je, w[P + 5] = 0, w[P + 6] = Pe, w[P + 7] = Ue; } } class K { /** * Constructs a new NP2FFT object. * @param {number} fft_length The length of the FFT */ constructor(S) { const w = 2 * (S - 1), P = 2 * (2 * S - 1), I = 2 ** Math.ceil(Math.log2(P)); this.bufferSize = I, this._a = w; const le = new Float64Array(P), oe = new Float64Array(I); this._chirpBuffer = new Float64Array(I), this._buffer1 = new Float64Array(I), this._buffer2 = new Float64Array(I), this._outBuffer1 = new Float64Array(I), this._outBuffer2 = new Float64Array(I); const ye = -2 * Math.PI / S, ge = Math.cos(ye), se = Math.sin(ye); for (let be = 0; be < P >> 1; ++be) { const pe = (be + 1 - S) ** 2 / 2, Ce = Math.sqrt(ge ** 2 + se ** 2) ** pe, $e = pe * Math.atan2(se, ge), Pe = 2 * be; le[Pe] = Ce * Math.cos($e), le[Pe + 1] = Ce * Math.sin($e), oe[Pe] = le[Pe], oe[Pe + 1] = -le[Pe + 1]; } this._slicedChirpBuffer = le.subarray(w, P), this._f = new L(I >> 1), this._f.transform(this._chirpBuffer, oe); } _transform(S, w, P) { const I = this._buffer1, le = this._buffer2, oe = this._outBuffer1, ye = this._outBuffer2, ge = this._chirpBuffer, se = this._slicedChirpBuffer, be = this._a; if (P) for (let pe = 0; pe < se.length; pe += 2) { const Ce = pe + 1, $e = pe >> 1, Pe = w[$e]; I[pe] = Pe * se[pe], I[Ce] = Pe * se[Ce]; } else for (let pe = 0; pe < se.length; pe += 2) { const Ce = pe + 1; I[pe] = w[pe] * se[pe] - w[Ce] * se[Ce], I[Ce] = w[pe] * se[Ce] + w[Ce] * se[pe]; } this._f.transform(oe, I); for (let pe = 0; pe < ge.length; pe += 2) { const Ce = pe + 1; le[pe] = oe[pe] * ge[pe] - oe[Ce] * ge[Ce], le[Ce] = oe[pe] * ge[Ce] + oe[Ce] * ge[pe]; } this._f.inverseTransform(ye, le); for (let pe = 0; pe < ye.length; pe += 2) { const Ce = ye[pe + be], $e = ye[pe + be + 1], Pe = se[pe], Je = se[pe + 1]; S[pe] = Ce * Pe - $e * Je, S[pe + 1] = Ce * Je + $e * Pe; } } transform(S, w) { this._transform(S, w, !1); } realTransform(S, w) { this._transform(S, w, !0); } } class re { constructor(S) { this.fft_length = S, this.isPowerOfTwo = x(S), this.isPowerOfTwo ? (this.fft = new L(S), this.outputBufferSize = 2 * S) : (this.fft = new K(S), this.outputBufferSize = this.fft.bufferSize); } realTransform(S, w) { this.fft.realTransform(S, w); } transform(S, w) { this.fft.transform(S, w); } } function ie(A, S) { if (S % 2 === 0 || S <= 0) throw new Error("Window size must be a positive odd number"); const w = new A.constructor(A.length), P = new A.constructor(S), I = Math.floor(S / 2); for (let le = 0; le < A.length; ++le) { let oe = 0; for (let ye = -I; ye <= I; ++ye) { let ge = le + ye; ge < 0 ? ge = Math.abs(ge) : ge >= A.length && (ge = 2 * (A.length - 1) - ge), P[oe++] = A[ge]; } P.sort(), w[le] = P[I]; } return w; } function V(A, S) { const w = Math.pow(10, S); return Math.round(A * w) / w; } function U(A) { const S = Math.round(A); return Math.abs(A) % 1 === 0.5 ? S % 2 === 0 ? S : S - 1 : S; } function q(A) { const S = A.length, w = A[0].length, P = [S + 1, w + 1], I = Array.from( { length: P[0] }, () => Array(P[1]).fill(1 / 0) ); I[0][0] = 0; const le = Array.from( { length: P[0] }, () => Array(P[1]).fill(-1) ); for (let be = 1; be < P[1]; ++be) for (let pe = 1; pe < P[0]; ++pe) { const Ce = I[pe - 1][be - 1], $e = I[pe - 1][be], Pe = I[pe][be - 1]; let Je, Ue; Ce < $e && Ce < Pe ? (Je = Ce, Ue = 0) : $e < Ce && $e < Pe ? (Je = $e, Ue = 1) : (Je = Pe, Ue = 2), I[pe][be] = A[pe - 1][be - 1] + Je, le[pe][be] = Ue; } for (let be = 0; be < P[1]; ++be) le[0][be] = 2; for (let be = 0; be < P[0]; ++be) le[be][0] = 1; let oe = S, ye = w, ge = [], se = []; for (; oe > 0 || ye > 0; ) switch (ge.push(oe - 1), se.push(ye - 1), le[oe][ye]) { case 0: --oe, --ye; break; case 1: --oe; break; case 2: --ye; break; default: throw new Error( `Internal error in dynamic time warping. Unexpected trace[${oe}, ${ye}]. Please file a bug report.` ); } return ge.reverse(), se.reverse(), [ge, se]; } } ), /***/ "./src/utils/tensor.js": ( /*!*****************************!*\ !*** ./src/utils/tensor.js ***! \*****************************/ /***/ (Ie, $, r) => { r.r($), r.d($, { /* harmony export */ Tensor: () => ( /* binding */ N ), /* harmony export */ cat: () => ( /* binding */ w ), /* harmony export */ full: () => ( /* binding */ se ), /* harmony export */ full_like: () => ( /* binding */ be ), /* harmony export */ interpolate: () => ( /* binding */ v ), /* harmony export */ interpolate_4d: () => ( /* binding */ b ), /* harmony export */ layer_norm: () => ( /* binding */ U ), /* harmony export */ matmul: () => ( /* binding */ x ), /* harmony export */ mean: () => ( /* binding */ oe ), /* harmony export */ mean_pooling: () => ( /* binding */ V ), /* harmony export */ ones: () => ( /* binding */ pe ), /* harmony export */ ones_like: () => ( /* binding */ Ce ), /* harmony export */ permute: () => ( /* binding */ T ), /* harmony export */ quantize_embeddings: () => ( /* binding */ Ue ), /* harmony export */ rand: () => ( /* binding */ Je ), /* harmony export */ rfft: () => ( /* binding */ L ), /* harmony export */ slice: () => ( /* binding */ ie ), /* harmony export */ stack: () => ( /* binding */ P ), /* harmony export */ std_mean: () => ( /* binding */ le ), /* harmony export */ topk: () => ( /* binding */ K ), /* harmony export */ zeros: () => ( /* binding */ $e ), /* harmony export */ zeros_like: () => ( /* binding */ Pe ) /* harmony export */ }); var g = r( /*! ./maths.js */ "./src/utils/maths.js" ), O = r( /*! ../backends/onnx.js */ "./src/backends/onnx.js" ), j = r( /*! ../ops/registry.js */ "./src/ops/registry.js" ); const ee = Object.freeze({ float32: Float32Array, float16: Uint16Array, float64: Float64Array, string: Array, // string[] int8: Int8Array, uint8: Uint8Array, int16: Int16Array, uint16: Uint16Array, int32: Int32Array, uint32: Uint32Array, int64: BigInt64Array, uint64: BigUint64Array, bool: Uint8Array, uint4: Uint8Array, int4: Int8Array }); class N { /** @type {number[]} Dimensions of the tensor. */ get dims() { return this.ort_tensor.dims; } set dims(X) { this.ort_tensor.dims = X; } /** @type {DataType} Type of the tensor. */ get type() { return this.ort_tensor.type; } /** @type {DataArray} The data stored in the tensor. */ get data() { return this.ort_tensor.data; } /** @type {number} The number of elements in the tensor. */ get size() { return this.ort_tensor.size; } /** @type {string} The location of the tensor data. */ get location() { return this.ort_tensor.location; } ort_tensor; /** * Create a new Tensor or copy an existing Tensor. * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args */ constructor(...X) { return (0, O.isONNXTensor)(X[0]) ? this.ort_tensor = /** @type {ONNXTensor} */ X[0] : this.ort_tensor = new O.Tensor( /** @type {DataType} */ X[0], /** @type {Exclude} */ X[1], X[2] ), new Proxy(this, { get: (de, Ee) => { if (typeof Ee == "string") { let Oe = Number(Ee); if (Number.isInteger(Oe)) return de._getitem(Oe); } return de[Ee]; }, set: (de, Ee, Oe) => de[Ee] = Oe }); } dispose() { this.ort_tensor.dispose(); } /** * 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 [X, ...de] = this.dims; if (de.length > 0) { const Ee = de.reduce((Oe, Xe) => Oe * Xe); for (let Oe = 0; Oe < X; ++Oe) yield this._subarray(Oe, Ee, de); } 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(X) { const [de, ...Ee] = this.dims; if (X = S(X, de), Ee.length > 0) { const Oe = Ee.reduce((Xe, J) => Xe * J); return this._subarray(X, Oe, Ee); } else return new N(this.type, [this.data[X]], Ee); } /** * @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(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) if (de[Ee] == X) return Ee; return -1; } /** * @param {number} index * @param {number} iterSize * @param {any} iterDims * @returns {Tensor} */ _subarray(X, de, Ee) { const Oe = X * de, Xe = (X + 1) * de, J = "subarray" in this.data ? this.data.subarray(Oe, Xe) : this.data.slice(Oe, Xe); return new N(this.type, J, Ee); } /** * 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() { const X = this.data; if (X.length !== 1) throw new Error(`a Tensor with ${X.length} elements cannot be converted to Scalar`); return X[0]; } /** * Convert tensor data to a n-dimensional JS list * @returns {Array} */ tolist() { return y(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_() { const X = this.data; for (let de = 0; de < X.length; ++de) X[de] = 1 / (1 + Math.exp(-X[de])); return this; } /** * Return a new Tensor with a callback function applied to each element. * @param {Function} callback - The function to apply to each element. It should take three arguments: * the current element, its index, and the tensor's data array. * @returns {Tensor} A new Tensor with the callback function applied to each element. */ map(X) { return this.clone().map_(X); } /** * Apply a callback function to each element of the tensor in place. * @param {Function} callback - The function to apply to each element. It should take three arguments: * the current element, its index, and the tensor's data array. * @returns {Tensor} Returns `this`. */ map_(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] = X(de[Ee], Ee, de); 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(X) { return this.clone().mul_(X); } /** * Multiply the tensor by a constant in place. * @param {number} val The value to multiply by. * @returns {Tensor} Returns `this`. */ mul_(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] *= X; return this; } /** * Return a new Tensor with every element divided by a constant. * @param {number} val The value to divide by. * @returns {Tensor} The new tensor. */ div(X) { return this.clone().div_(X); } /** * Divide the tensor by a constant in place. * @param {number} val The value to divide by. * @returns {Tensor} Returns `this`. */ div_(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] /= X; 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(X) { return this.clone().add_(X); } /** * Add the tensor by a constant in place. * @param {number} val The value to add by. * @returns {Tensor} Returns `this`. */ add_(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] += X; return this; } /** * Return a new Tensor with every element subtracted by a constant. * @param {number} val The value to subtract by. * @returns {Tensor} The new tensor. */ sub(X) { return this.clone().sub_(X); } /** * Subtract the tensor by a constant in place. * @param {number} val The value to subtract by. * @returns {Tensor} Returns `this`. */ sub_(X) { const de = this.data; for (let Ee = 0; Ee < de.length; ++Ee) de[Ee] -= X; return this; } /** * Creates a deep copy of the current Tensor. * @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original. */ clone() { return new N(this.type, this.data.slice(), this.dims.slice()); } /** * Performs a slice operation on the Tensor along specified dimensions. * * Consider a Tensor that has a dimension of [4, 7]: * ``` * [ 1, 2, 3, 4, 5, 6, 7] * [ 8, 9, 10, 11, 12, 13, 14] * [15, 16, 17, 18, 19, 20, 21] * [22, 23, 24, 25, 26, 27, 28] * ``` * We can slice against the two dims of row and column, for instance in this * case we can start at the second element, and return to the second last, * like this: * ``` * tensor.slice([1, -1], [1, -1]); * ``` * which would return: * ``` * [ 9, 10, 11, 12, 13 ] * [ 16, 17, 18, 19, 20 ] * ``` * * @param {...(number|number[]|null)} slices The slice specifications for each dimension. * - If a number is given, then a single element is selected. * - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected. * - If null is given, then the entire dimension is selected. * @returns {Tensor} A new Tensor containing the selected elements. * @throws {Error} If the slice input is invalid. */ slice(...X) { const de = [], Ee = []; for (let te = 0; te < this.dims.length; ++te) { let ve = X[te]; if (ve == null) Ee.push([0, this.dims[te]]), de.push(this.dims[te]); else if (typeof ve == "number") ve = S(ve, this.dims[te], te), Ee.push([ve, ve + 1]); else if (Array.isArray(ve) && ve.length === 2) { let [He, je] = ve; if (He = He === null ? 0 : S(He, this.dims[te], te, !1), je = je === null ? this.dims[te] : S(je, this.dims[te], te, !1), He > je) throw new Error(`Invalid slice: ${ve}`); const Ve = [ Math.max(He, 0), Math.min(je, this.dims[te]) ]; Ee.push(Ve), de.push(Ve[1] - Ve[0]); } else throw new Error(`Invalid slice: ${ve}`); } const Oe = Ee.map(([te, ve]) => ve - te), Xe = Oe.reduce((te, ve) => te * ve), J = this.data, We = new J.constructor(Xe), Ne = this.stride(); for (let te = 0; te < Xe; ++te) { let ve = 0; for (let He = Oe.length - 1, je = te; He >= 0; --He) { const Ve = Oe[He]; ve += (je % Ve + Ee[He][0]) * Ne[He], je = Math.floor(je / Ve); } We[te] = J[ve]; } return new N(this.type, We, de); } /** * Return a permuted version of this Tensor, according to the provided dimensions. * @param {...number} dims Dimensions to permute. * @returns {Tensor} The permuted tensor. */ permute(...X) { return T(this, X); } // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute() transpose(...X) { return this.permute(...X); } /** * 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(X = null, de = !1) { return this.norm(1, X, de); } /** * 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(X = "fro", de = null, Ee = !1) { if (X === "fro") X = 2; else if (typeof X == "string") throw Error(`Unsupported norm: ${X}`); const Oe = this.data, Xe = (te, ve) => te + ve ** X; if (de === null) { const te = Oe.reduce(Xe, 0) ** (1 / X); return new N(this.type, [te], []); } const [J, We, Ne] = I(Xe, this, de, Ee); if (X !== 1) for (let te = 0; te < We.length; ++te) We[te] = We[te] ** (1 / X); return new N(J, We, Ne); } /** * 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_(X = 2, de = 1) { de = S(de, this.dims.length); const Ee = this.norm(X, de, !0), Oe = this.data, Xe = Ee.data; for (let J = 0; J < Oe.length; ++J) { let We = 0; for (let Ne = this.dims.length - 1, te = J, ve = 1; Ne >= 0; --Ne) { const He = this.dims[Ne]; if (Ne !== de) { const je = te % He; We += je * ve, ve *= this.dims[Ne]; } te = Math.floor(te / He); } Oe[J] /= Xe[We]; } 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(X = 2, de = 1) { return this.clone().normalize_(X, de); } /** * 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 ye(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|number[]} [dim=null] If given, the input will be squeezed only in the specified dimensions. * @returns {Tensor} The squeezed tensor */ squeeze(X = null) { return new N( this.type, this.data, q(this.dims, X) ); } /** * In-place version of @see {@link Tensor.squeeze} */ squeeze_(X = null) { return this.dims = q(this.dims, X), 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 {Tensor} The unsqueezed tensor */ unsqueeze(X = null) { return new N( this.type, this.data, A(this.dims, X) ); } /** * In-place version of @see {@link Tensor.unsqueeze} */ unsqueeze_(X = null) { return this.dims = A(this.dims, X), this; } /** * In-place version of @see {@link Tensor.flatten} */ flatten_(X = 0, de = -1) { de = (de + this.dims.length) % this.dims.length; let Ee = this.dims.slice(0, X), Oe = this.dims.slice(X, de + 1), Xe = this.dims.slice(de + 1); return this.dims = [...Ee, Oe.reduce((J, We) => J * We, 1), ...Xe], 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 {Tensor} The flattened tensor. */ flatten(X = 0, de = -1) { return this.clone().flatten_(X, de); } /** * 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(...X) { let de = -1; for (let Oe = 0; Oe < X.length; ++Oe) if (X[Oe] === -1) { if (de !== -1) throw new Error("Only one dimension can be inferred"); de = Oe; } const Ee = this.data; if (de !== -1) { const Oe = X.reduce((Xe, J, We) => We !== de ? Xe * J : Xe, 1); X[de] = Ee.length / Oe; } return new N(this.type, Ee, X); } neg_() { const X = this.data; for (let de = 0; de < X.length; ++de) X[de] = -X[de]; return this; } neg() { return this.clone().neg_(); } /** * Computes input > val element-wise. * @param {number} val The value to compare with. * @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere. */ gt(X) { const de = new Uint8Array(this.data.length), Ee = this.data; for (let Oe = 0; Oe < Ee.length; ++Oe) de[Oe] = Ee[Oe] > X ? 1 : 0; return new N("bool", de, this.dims); } /** * Computes input < val element-wise. * @param {number} val The value to compare with. * @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere. */ lt(X) { const de = new Uint8Array(this.data.length), Ee = this.data; for (let Oe = 0; Oe < Ee.length; ++Oe) de[Oe] = Ee[Oe] < X ? 1 : 0; return new N("bool", de, this.dims); } /** * In-place version of @see {@link Tensor.clamp} */ clamp_(X, de) { const Ee = this.data; for (let Oe = 0; Oe < Ee.length; ++Oe) Ee[Oe] = Math.min(Math.max(Ee[Oe], X), de); 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 {Tensor} the output tensor. */ clamp(X, de) { return this.clone().clamp_(X, de); } /** * In-place version of @see {@link Tensor.round} */ round_() { const X = this.data; for (let de = 0; de < X.length; ++de) X[de] = Math.round(X[de]); return this; } /** * Rounds elements of input to the nearest integer. * @returns {Tensor} the output tensor. */ round() { return this.clone().round_(); } mean(X = null, de = !1) { return oe(this, X, de); } min(X = null, de = !1) { if (X === null) { const J = (0, g.min)(this.data)[0]; return new N(this.type, [J], [ /* scalar */ ]); } const [Ee, Oe, Xe] = I((J, We) => Math.min(J, We), this, X, de, 1 / 0); return new N(Ee, Oe, Xe); } max(X = null, de = !1) { if (X === null) { const J = (0, g.max)(this.data)[0]; return new N(this.type, [J], [ /* scalar */ ]); } const [Ee, Oe, Xe] = I((J, We) => Math.max(J, We), this, X, de, -1 / 0); return new N(Ee, Oe, Xe); } argmin(X = null, de = !1) { if (X !== null) throw new Error("`dim !== null` not yet implemented."); const Ee = (0, g.min)(this.data)[1]; return new N("int64", [BigInt(Ee)], []); } argmax(X = null, de = !1) { if (X !== null) throw new Error("`dim !== null` not yet implemented."); const Ee = (0, g.max)(this.data)[1]; return new N("int64", [BigInt(Ee)], []); } /** * Performs Tensor dtype conversion. * @param {DataType} type The desired data type. * @returns {Tensor} The converted tensor. */ to(X) { if (this.type === X) return this; if (!ee.hasOwnProperty(X)) throw new Error(`Unsupported type: ${X}`); let de; const Ee = ["int64", "uint64"].includes(this.type), Oe = ["int64", "uint64"].includes(X); return Ee && !Oe ? de = Number : !Ee && Oe && (de = BigInt), new N(X, ee[X].from(this.data, de), this.dims); } } function y(we, X) { const de = we.length, Ee = X.reduce((Xe, J) => Xe * J); if (de !== Ee) throw Error(`cannot reshape array of size ${de} into shape (${X})`); let Oe = we; for (let Xe = X.length - 1; Xe >= 0; Xe--) Oe = Oe.reduce((J, We) => { let Ne = J[J.length - 1]; return Ne.length < X[Xe] ? Ne.push(We) : J.push([We]), J; }, [[]]); return Oe[0]; } function T(we, X) { const [de, Ee] = (0, g.permute_data)(we.data, we.dims, X); return new N(we.type, de, Ee); } function v(we, [X, de], Ee = "bilinear", Oe = !1) { const Xe = we.dims.at(-3) ?? 1, J = we.dims.at(-2), We = we.dims.at(-1); let Ne = (0, g.interpolate_data)( /** @type {import('./maths.js').TypedArray}*/ we.data, [Xe, J, We], [X, de], Ee, Oe ); return new N(we.type, Ne, [Xe, X, de]); } async function b(we, { size: X = null, mode: de = "bilinear" } = {}) { if (we.dims.length !== 4) throw new Error("`interpolate_4d` currently only supports 4D input."); if (!X) throw new Error("`interpolate_4d` requires a `size` argument."); let Ee; if (X.length === 2) Ee = [...we.dims.slice(0, 2), ...X]; else if (X.length === 3) Ee = [we.dims[0], ...X]; else if (X.length === 4) Ee = X; else throw new Error("`size` must be of length 2, 3, or 4."); let Oe; if (de === "nearest") Oe = await j.TensorOpRegistry.nearest_interpolate_4d; else if (de === "bilinear") Oe = await j.TensorOpRegistry.bilinear_interpolate_4d; else if (de === "bicubic") Oe = await j.TensorOpRegistry.bicubic_interpolate_4d; else throw new Error(`Unsupported mode: ${de}`); const Xe = new N("int64", new BigInt64Array(Ee.map(BigInt)), [Ee.length]); return await Oe({ x: we, s: Xe }); } async function x(we, X) { return await (await j.TensorOpRegistry.matmul)({ a: we, b: X }); } async function L(we, X) { return await (await j.TensorOpRegistry.rfft)({ x: we, a: X }); } async function K(we, X) { const de = await j.TensorOpRegistry.top_k; return X == null ? X = we.dims.at(-1) : X = Math.min(X, we.dims.at(-1)), await de({ x: we, k: new N( "int64", [BigInt(X)], [1] ) }); } const re = (we) => new N("int64", we, [we.length]); async function ie(we, X, de, Ee, Oe) { return await (await j.TensorOpRegistry.slice)({ x: we, s: re(X), e: re(de), a: re(Ee), t: re(Oe ?? new Array(Ee.length).fill(1)) }); } function V(we, X) { const de = we.data, Ee = X.data, Oe = [we.dims[0], we.dims[2]], Xe = new de.constructor(Oe[0] * Oe[1]), [J, We, Ne] = we.dims; let te = 0; for (let ve = 0; ve < J; ++ve) { const He = ve * Ne * We; for (let je = 0; je < Ne; ++je) { let Ve = 0, Re = 0; const Ze = ve * We, at = He + je; for (let lt = 0; lt < We; ++lt) { const ct = Number(Ee[Ze + lt]); Re += ct, Ve += de[at + lt * Ne] * ct; } const _t = Ve / Re; Xe[te++] = _t; } } return new N( we.type, Xe, Oe ); } function U(we, X, { eps: de = 1e-5 } = {}) { if (we.dims.length !== 2) throw new Error("`layer_norm` currently only supports 2D input."); const [Ee, Oe] = we.dims; if (X.length !== 1 && X[0] !== Oe) throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`."); const [Xe, J] = le(we, 1, 0, !0), We = ( /** @type {Float32Array} */ Xe.data ), Ne = ( /** @type {Float32Array} */ J.data ), te = ( /** @type {Float32Array} */ we.data ), ve = new te.constructor(te.length); for (let He = 0; He < Ee; ++He) { const je = He * Oe; for (let Ve = 0; Ve < Oe; ++Ve) { const Re = je + Ve; ve[Re] = (te[Re] - Ne[He]) / (We[He] + de); } } return new N(we.type, ve, we.dims); } function q(we, X) { return we = we.slice(), X === null ? we = we.filter((de) => de !== 1) : typeof X == "number" ? we[X] === 1 && we.splice(X, 1) : Array.isArray(X) && (we = we.filter((de, Ee) => de !== 1 || !X.includes(Ee))), we; } function A(we, X) { return X = S(X, we.length + 1), we = we.slice(), we.splice(X, 0, 1), we; } function S(we, X, de = null, Ee = !0) { if (Ee && (we < -X || we >= X)) throw new Error(`IndexError: index ${we} is out of bounds for dimension${de === null ? "" : " " + de} with size ${X}`); return we < 0 && (we = (we % X + X) % X), we; } function w(we, X = 0) { X = S(X, we[0].dims.length); const de = we[0].dims.slice(); de[X] = we.reduce((J, We) => J + We.dims[X], 0); const Ee = de.reduce((J, We) => J * We, 1), Oe = new we[0].data.constructor(Ee), Xe = we[0].type; if (X === 0) { let J = 0; for (const We of we) { const Ne = We.data; Oe.set(Ne, J), J += Ne.length; } } else { let J = 0; for (let We = 0; We < we.length; ++We) { const { data: Ne, dims: te } = we[We]; for (let ve = 0; ve < Ne.length; ++ve) { let He = 0; for (let je = te.length - 1, Ve = ve, Re = 1; je >= 0; --je) { const Ze = te[je]; let at = Ve % Ze; je === X && (at += J), He += at * Re, Re *= de[je], Ve = Math.floor(Ve / Ze); } Oe[He] = Ne[ve]; } J += te[X]; } } return new N(Xe, Oe, de); } function P(we, X = 0) { return w(we.map((de) => de.unsqueeze(X)), X); } function I(we, X, de = null, Ee = !1, Oe = null) { const Xe = X.data, J = X.dims; de = S(de, J.length); const We = J.slice(); We[de] = 1; const Ne = new Xe.constructor(Xe.length / J[de]); Oe !== null && Ne.fill(Oe); for (let te = 0; te < Xe.length; ++te) { let ve = 0; for (let He = J.length - 1, je = te, Ve = 1; He >= 0; --He) { const Re = J[He]; if (He !== de) { const Ze = je % Re; ve += Ze * Ve, Ve *= We[He]; } je = Math.floor(je / Re); } Ne[ve] = we(Ne[ve], Xe[te], te, ve); } return Ee || We.splice(de, 1), [X.type, Ne, We]; } function le(we, X = null, de = 1, Ee = !1) { const Oe = ( /** @type {Float32Array} */ we.data ), Xe = we.dims; if (X === null) { const Ve = Oe.reduce((_t, lt) => _t + lt, 0) / Oe.length, Re = Math.sqrt(Oe.reduce((_t, lt) => _t + (lt - Ve) ** 2, 0) / (Oe.length - de)), Ze = new N(we.type, [Ve], [ /* scalar */ ]); return [new N(we.type, [Re], [ /* scalar */ ]), Ze]; } X = S(X, Xe.length); const J = oe(we, X, Ee), We = J.data, [Ne, te, ve] = I((je, Ve, Re, Ze) => je + (Ve - We[Ze]) ** 2, we, X, Ee); for (let je = 0; je < te.length; ++je) te[je] = Math.sqrt(te[je] / (Xe[X] - de)); return [new N(Ne, te, ve), J]; } function oe(we, X = null, de = !1) { const Ee = we.dims, Oe = ( /** @type {Float32Array} */ we.data ); if (X === null) { const Ne = Oe.reduce((te, ve) => te + ve, 0); return new N(we.type, [Ne / Oe.length], [ /* scalar */ ]); } X = S(X, Ee.length); const [Xe, J, We] = I((Ne, te) => Ne + te, we, X, de); if (Ee[X] !== 1) for (let Ne = 0; Ne < J.length; ++Ne) J[Ne] /= Ee[X]; return new N(Xe, J, We); } function ye(we) { const X = new Array(we.length); for (let de = we.length - 1, Ee = 1; de >= 0; --de) X[de] = Ee, Ee *= we[de]; return X; } function ge(we, X, de, Ee) { const Oe = we.reduce((Xe, J) => Xe * J, 1); return new N( de, new Ee(Oe).fill(X), we ); } function se(we, X) { let de, Ee; if (typeof X == "number") de = "float32", Ee = Float32Array; else if (typeof X == "bigint") de = "int64", Ee = BigInt64Array; else if (typeof X == "boolean") de = "bool", Ee = Uint8Array; else throw new Error(`Unsupported data type: ${typeof X}`); return ge(we, X, de, Ee); } function be(we, X) { return se(we.dims, X); } function pe(we) { return ge(we, 1n, "int64", BigInt64Array); } function Ce(we) { return pe(we.dims); } function $e(we) { return ge(we, 0n, "int64", BigInt64Array); } function Pe(we) { return $e(we.dims); } function Je(we) { const X = we.reduce((de, Ee) => de * Ee, 1); return new N( "float32", Float32Array.from({ length: X }, () => Math.random()), we ); } function Ue(we, X) { if (we.dims.length !== 2) throw new Error("The tensor must have 2 dimensions"); if (we.dims.at(-1) % 8 !== 0) throw new Error("The last dimension of the tensor must be a multiple of 8"); if (!["binary", "ubinary"].includes(X)) throw new Error("The precision must be either 'binary' or 'ubinary'"); const de = X === "binary", Ee = de ? "int8" : "uint8", Oe = de ? Int8Array : Uint8Array, Xe = we.data, J = new Oe(Xe.length / 8); for (let We = 0; We < Xe.length; ++We) { const Ne = Xe[We] > 0 ? 1 : 0, te = Math.floor(We / 8), ve = We % 8; J[te] |= Ne << 7 - ve, de && ve === 0 && (J[te] -= 128); } return new N(Ee, J, [we.dims[0], we.dims[1] / 8]); } } ) /******/ }, Qm = {}; function ps(Ie) { var $ = Qm[Ie]; if ($ !== void 0) return $.exports; var r = Qm[Ie] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; return Xm[Ie](r, r.exports, ps), r.exports; } ps.m = Xm; (() => { var Ie = Object.getPrototypeOf ? (r) => Object.getPrototypeOf(r) : (r) => r.__proto__, $; ps.t = function(r, g) { if (g & 1 && (r = this(r)), g & 8 || typeof r == "object" && r && (g & 4 && r.__esModule || g & 16 && typeof r.then == "function")) return r; var O = /* @__PURE__ */ Object.create(null); ps.r(O); var j = {}; $ = $ || [null, Ie({}), Ie([]), Ie(Ie)]; for (var ee = g & 2 && r; typeof ee == "object" && !~$.indexOf(ee); ee = Ie(ee)) Object.getOwnPropertyNames(ee).forEach((N) => j[N] = () => r[N]); return j.default = () => r, ps.d(O, j), O; }; })(); ps.d = (Ie, $) => { for (var r in $) ps.o($, r) && !ps.o(Ie, r) && Object.defineProperty(Ie, r, { enumerable: !0, get: $[r] }); }; ps.o = (Ie, $) => Object.prototype.hasOwnProperty.call(Ie, $); ps.r = (Ie) => { typeof Symbol < "u" && Symbol.toStringTag && Object.defineProperty(Ie, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(Ie, "__esModule", { value: !0 }); }; (() => { var Ie; if (typeof import.meta.url == "string" && (Ie = import.meta.url), !Ie) throw new Error("Automatic publicPath is not supported in this browser"); Ie = Ie.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"), ps.p = Ie; })(); ps.b = new URL(import.meta.url); var d = {}; (() => { /*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/ ps.r(d), ps.d(d, { /* harmony export */ ASTFeatureExtractor: () => ( /* reexport safe */ v.ASTFeatureExtractor ), /* harmony export */ ASTForAudioClassification: () => ( /* reexport safe */ r.ASTForAudioClassification ), /* harmony export */ ASTModel: () => ( /* reexport safe */ r.ASTModel ), /* harmony export */ ASTPreTrainedModel: () => ( /* reexport safe */ r.ASTPreTrainedModel ), /* harmony export */ AlbertForMaskedLM: () => ( /* reexport safe */ r.AlbertForMaskedLM ), /* harmony export */ AlbertForQuestionAnswering: () => ( /* reexport safe */ r.AlbertForQuestionAnswering ), /* harmony export */ AlbertForSequenceClassification: () => ( /* reexport safe */ r.AlbertForSequenceClassification ), /* harmony export */ AlbertModel: () => ( /* reexport safe */ r.AlbertModel ), /* harmony export */ AlbertPreTrainedModel: () => ( /* reexport safe */ r.AlbertPreTrainedModel ), /* harmony export */ AlbertTokenizer: () => ( /* reexport safe */ g.AlbertTokenizer ), /* harmony export */ AudioClassificationPipeline: () => ( /* reexport safe */ $.AudioClassificationPipeline ), /* harmony export */ AutoConfig: () => ( /* reexport safe */ O.AutoConfig ), /* harmony export */ AutoFeatureExtractor: () => ( /* reexport safe */ b.AutoFeatureExtractor ), /* harmony export */ AutoImageProcessor: () => ( /* reexport safe */ K.AutoImageProcessor ), /* harmony export */ AutoModel: () => ( /* reexport safe */ r.AutoModel ), /* harmony export */ AutoModelForAudioClassification: () => ( /* reexport safe */ r.AutoModelForAudioClassification ), /* harmony export */ AutoModelForAudioFrameClassification: () => ( /* reexport safe */ r.AutoModelForAudioFrameClassification ), /* harmony export */ AutoModelForCTC: () => ( /* reexport safe */ r.AutoModelForCTC ), /* harmony export */ AutoModelForCausalLM: () => ( /* reexport safe */ r.AutoModelForCausalLM ), /* harmony export */ AutoModelForDepthEstimation: () => ( /* reexport safe */ r.AutoModelForDepthEstimation ), /* harmony export */ AutoModelForDocumentQuestionAnswering: () => ( /* reexport safe */ r.AutoModelForDocumentQuestionAnswering ), /* harmony export */ AutoModelForImageClassification: () => ( /* reexport safe */ r.AutoModelForImageClassification ), /* harmony export */ AutoModelForImageFeatureExtraction: () => ( /* reexport safe */ r.AutoModelForImageFeatureExtraction ), /* harmony export */ AutoModelForImageMatting: () => ( /* reexport safe */ r.AutoModelForImageMatting ), /* harmony export */ AutoModelForImageSegmentation: () => ( /* reexport safe */ r.AutoModelForImageSegmentation ), /* harmony export */ AutoModelForImageToImage: () => ( /* reexport safe */ r.AutoModelForImageToImage ), /* harmony export */ AutoModelForMaskGeneration: () => ( /* reexport safe */ r.AutoModelForMaskGeneration ), /* harmony export */ AutoModelForMaskedLM: () => ( /* reexport safe */ r.AutoModelForMaskedLM ), /* harmony export */ AutoModelForNormalEstimation: () => ( /* reexport safe */ r.AutoModelForNormalEstimation ), /* harmony export */ AutoModelForObjectDetection: () => ( /* reexport safe */ r.AutoModelForObjectDetection ), /* harmony export */ AutoModelForPoseEstimation: () => ( /* reexport safe */ r.AutoModelForPoseEstimation ), /* harmony export */ AutoModelForQuestionAnswering: () => ( /* reexport safe */ r.AutoModelForQuestionAnswering ), /* harmony export */ AutoModelForSemanticSegmentation: () => ( /* reexport safe */ r.AutoModelForSemanticSegmentation ), /* harmony export */ AutoModelForSeq2SeqLM: () => ( /* reexport safe */ r.AutoModelForSeq2SeqLM ), /* harmony export */ AutoModelForSequenceClassification: () => ( /* reexport safe */ r.AutoModelForSequenceClassification ), /* harmony export */ AutoModelForSpeechSeq2Seq: () => ( /* reexport safe */ r.AutoModelForSpeechSeq2Seq ), /* harmony export */ AutoModelForTextToSpectrogram: () => ( /* reexport safe */ r.AutoModelForTextToSpectrogram ), /* harmony export */ AutoModelForTextToWaveform: () => ( /* reexport safe */ r.AutoModelForTextToWaveform ), /* harmony export */ AutoModelForTokenClassification: () => ( /* reexport safe */ r.AutoModelForTokenClassification ), /* harmony export */ AutoModelForUniversalSegmentation: () => ( /* reexport safe */ r.AutoModelForUniversalSegmentation ), /* harmony export */ AutoModelForVision2Seq: () => ( /* reexport safe */ r.AutoModelForVision2Seq ), /* harmony export */ AutoModelForXVector: () => ( /* reexport safe */ r.AutoModelForXVector ), /* harmony export */ AutoModelForZeroShotObjectDetection: () => ( /* reexport safe */ r.AutoModelForZeroShotObjectDetection ), /* harmony export */ AutoProcessor: () => ( /* reexport safe */ V.AutoProcessor ), /* harmony export */ AutoTokenizer: () => ( /* reexport safe */ g.AutoTokenizer ), /* harmony export */ AutomaticSpeechRecognitionPipeline: () => ( /* reexport safe */ $.AutomaticSpeechRecognitionPipeline ), /* harmony export */ BartForConditionalGeneration: () => ( /* reexport safe */ r.BartForConditionalGeneration ), /* harmony export */ BartForSequenceClassification: () => ( /* reexport safe */ r.BartForSequenceClassification ), /* harmony export */ BartModel: () => ( /* reexport safe */ r.BartModel ), /* harmony export */ BartPretrainedModel: () => ( /* reexport safe */ r.BartPretrainedModel ), /* harmony export */ BartTokenizer: () => ( /* reexport safe */ g.BartTokenizer ), /* harmony export */ BaseModelOutput: () => ( /* reexport safe */ r.BaseModelOutput ), /* harmony export */ BaseStreamer: () => ( /* reexport safe */ U.BaseStreamer ), /* harmony export */ BeitFeatureExtractor: () => ( /* reexport safe */ L.BeitFeatureExtractor ), /* harmony export */ BeitForImageClassification: () => ( /* reexport safe */ r.BeitForImageClassification ), /* harmony export */ BeitModel: () => ( /* reexport safe */ r.BeitModel ), /* harmony export */ BeitPreTrainedModel: () => ( /* reexport safe */ r.BeitPreTrainedModel ), /* harmony export */ BertForMaskedLM: () => ( /* reexport safe */ r.BertForMaskedLM ), /* harmony export */ BertForQuestionAnswering: () => ( /* reexport safe */ r.BertForQuestionAnswering ), /* harmony export */ BertForSequenceClassification: () => ( /* reexport safe */ r.BertForSequenceClassification ), /* harmony export */ BertForTokenClassification: () => ( /* reexport safe */ r.BertForTokenClassification ), /* harmony export */ BertModel: () => ( /* reexport safe */ r.BertModel ), /* harmony export */ BertPreTrainedModel: () => ( /* reexport safe */ r.BertPreTrainedModel ), /* harmony export */ BertTokenizer: () => ( /* reexport safe */ g.BertTokenizer ), /* harmony export */ BitImageProcessor: () => ( /* reexport safe */ L.BitImageProcessor ), /* harmony export */ BlenderbotForConditionalGeneration: () => ( /* reexport safe */ r.BlenderbotForConditionalGeneration ), /* harmony export */ BlenderbotModel: () => ( /* reexport safe */ r.BlenderbotModel ), /* harmony export */ BlenderbotPreTrainedModel: () => ( /* reexport safe */ r.BlenderbotPreTrainedModel ), /* harmony export */ BlenderbotSmallForConditionalGeneration: () => ( /* reexport safe */ r.BlenderbotSmallForConditionalGeneration ), /* harmony export */ BlenderbotSmallModel: () => ( /* reexport safe */ r.BlenderbotSmallModel ), /* harmony export */ BlenderbotSmallPreTrainedModel: () => ( /* reexport safe */ r.BlenderbotSmallPreTrainedModel ), /* harmony export */ BlenderbotSmallTokenizer: () => ( /* reexport safe */ g.BlenderbotSmallTokenizer ), /* harmony export */ BlenderbotTokenizer: () => ( /* reexport safe */ g.BlenderbotTokenizer ), /* harmony export */ BloomForCausalLM: () => ( /* reexport safe */ r.BloomForCausalLM ), /* harmony export */ BloomModel: () => ( /* reexport safe */ r.BloomModel ), /* harmony export */ BloomPreTrainedModel: () => ( /* reexport safe */ r.BloomPreTrainedModel ), /* harmony export */ BloomTokenizer: () => ( /* reexport safe */ g.BloomTokenizer ), /* harmony export */ CLIPFeatureExtractor: () => ( /* reexport safe */ L.CLIPFeatureExtractor ), /* harmony export */ CLIPImageProcessor: () => ( /* reexport safe */ L.CLIPImageProcessor ), /* harmony export */ CLIPModel: () => ( /* reexport safe */ r.CLIPModel ), /* harmony export */ CLIPPreTrainedModel: () => ( /* reexport safe */ r.CLIPPreTrainedModel ), /* harmony export */ CLIPSegForImageSegmentation: () => ( /* reexport safe */ r.CLIPSegForImageSegmentation ), /* harmony export */ CLIPSegModel: () => ( /* reexport safe */ r.CLIPSegModel ), /* harmony export */ CLIPSegPreTrainedModel: () => ( /* reexport safe */ r.CLIPSegPreTrainedModel ), /* harmony export */ CLIPTextModel: () => ( /* reexport safe */ r.CLIPTextModel ), /* harmony export */ CLIPTextModelWithProjection: () => ( /* reexport safe */ r.CLIPTextModelWithProjection ), /* harmony export */ CLIPTokenizer: () => ( /* reexport safe */ g.CLIPTokenizer ), /* harmony export */ CLIPVisionModel: () => ( /* reexport safe */ r.CLIPVisionModel ), /* harmony export */ CLIPVisionModelWithProjection: () => ( /* reexport safe */ r.CLIPVisionModelWithProjection ), /* harmony export */ CamembertForMaskedLM: () => ( /* reexport safe */ r.CamembertForMaskedLM ), /* harmony export */ CamembertForQuestionAnswering: () => ( /* reexport safe */ r.CamembertForQuestionAnswering ), /* harmony export */ CamembertForSequenceClassification: () => ( /* reexport safe */ r.CamembertForSequenceClassification ), /* harmony export */ CamembertForTokenClassification: () => ( /* reexport safe */ r.CamembertForTokenClassification ), /* harmony export */ CamembertModel: () => ( /* reexport safe */ r.CamembertModel ), /* harmony export */ CamembertPreTrainedModel: () => ( /* reexport safe */ r.CamembertPreTrainedModel ), /* harmony export */ CamembertTokenizer: () => ( /* reexport safe */ g.CamembertTokenizer ), /* harmony export */ CausalLMOutput: () => ( /* reexport safe */ r.CausalLMOutput ), /* harmony export */ CausalLMOutputWithPast: () => ( /* reexport safe */ r.CausalLMOutputWithPast ), /* harmony export */ ChineseCLIPFeatureExtractor: () => ( /* reexport safe */ L.ChineseCLIPFeatureExtractor ), /* harmony export */ ChineseCLIPModel: () => ( /* reexport safe */ r.ChineseCLIPModel ), /* harmony export */ ChineseCLIPPreTrainedModel: () => ( /* reexport safe */ r.ChineseCLIPPreTrainedModel ), /* harmony export */ ClapAudioModelWithProjection: () => ( /* reexport safe */ r.ClapAudioModelWithProjection ), /* harmony export */ ClapFeatureExtractor: () => ( /* reexport safe */ v.ClapFeatureExtractor ), /* harmony export */ ClapModel: () => ( /* reexport safe */ r.ClapModel ), /* harmony export */ ClapPreTrainedModel: () => ( /* reexport safe */ r.ClapPreTrainedModel ), /* harmony export */ ClapTextModelWithProjection: () => ( /* reexport safe */ r.ClapTextModelWithProjection ), /* harmony export */ ClassifierFreeGuidanceLogitsProcessor: () => ( /* reexport safe */ A.ClassifierFreeGuidanceLogitsProcessor ), /* harmony export */ CodeGenForCausalLM: () => ( /* reexport safe */ r.CodeGenForCausalLM ), /* harmony export */ CodeGenModel: () => ( /* reexport safe */ r.CodeGenModel ), /* harmony export */ CodeGenPreTrainedModel: () => ( /* reexport safe */ r.CodeGenPreTrainedModel ), /* harmony export */ CodeGenTokenizer: () => ( /* reexport safe */ g.CodeGenTokenizer ), /* harmony export */ CodeLlamaTokenizer: () => ( /* reexport safe */ g.CodeLlamaTokenizer ), /* harmony export */ CohereForCausalLM: () => ( /* reexport safe */ r.CohereForCausalLM ), /* harmony export */ CohereModel: () => ( /* reexport safe */ r.CohereModel ), /* harmony export */ CoherePreTrainedModel: () => ( /* reexport safe */ r.CoherePreTrainedModel ), /* harmony export */ CohereTokenizer: () => ( /* reexport safe */ g.CohereTokenizer ), /* harmony export */ ConvBertForMaskedLM: () => ( /* reexport safe */ r.ConvBertForMaskedLM ), /* harmony export */ ConvBertForQuestionAnswering: () => ( /* reexport safe */ r.ConvBertForQuestionAnswering ), /* harmony export */ ConvBertForSequenceClassification: () => ( /* reexport safe */ r.ConvBertForSequenceClassification ), /* harmony export */ ConvBertForTokenClassification: () => ( /* reexport safe */ r.ConvBertForTokenClassification ), /* harmony export */ ConvBertModel: () => ( /* reexport safe */ r.ConvBertModel ), /* harmony export */ ConvBertPreTrainedModel: () => ( /* reexport safe */ r.ConvBertPreTrainedModel ), /* harmony export */ ConvBertTokenizer: () => ( /* reexport safe */ g.ConvBertTokenizer ), /* harmony export */ ConvNextFeatureExtractor: () => ( /* reexport safe */ L.ConvNextFeatureExtractor ), /* harmony export */ ConvNextForImageClassification: () => ( /* reexport safe */ r.ConvNextForImageClassification ), /* harmony export */ ConvNextImageProcessor: () => ( /* reexport safe */ L.ConvNextImageProcessor ), /* harmony export */ ConvNextModel: () => ( /* reexport safe */ r.ConvNextModel ), /* harmony export */ ConvNextPreTrainedModel: () => ( /* reexport safe */ r.ConvNextPreTrainedModel ), /* harmony export */ ConvNextV2ForImageClassification: () => ( /* reexport safe */ r.ConvNextV2ForImageClassification ), /* harmony export */ ConvNextV2Model: () => ( /* reexport safe */ r.ConvNextV2Model ), /* harmony export */ ConvNextV2PreTrainedModel: () => ( /* reexport safe */ r.ConvNextV2PreTrainedModel ), /* harmony export */ DPTFeatureExtractor: () => ( /* reexport safe */ L.DPTFeatureExtractor ), /* harmony export */ DPTForDepthEstimation: () => ( /* reexport safe */ r.DPTForDepthEstimation ), /* harmony export */ DPTImageProcessor: () => ( /* reexport safe */ L.DPTImageProcessor ), /* harmony export */ DPTModel: () => ( /* reexport safe */ r.DPTModel ), /* harmony export */ DPTPreTrainedModel: () => ( /* reexport safe */ r.DPTPreTrainedModel ), /* harmony export */ DebertaForMaskedLM: () => ( /* reexport safe */ r.DebertaForMaskedLM ), /* harmony export */ DebertaForQuestionAnswering: () => ( /* reexport safe */ r.DebertaForQuestionAnswering ), /* harmony export */ DebertaForSequenceClassification: () => ( /* reexport safe */ r.DebertaForSequenceClassification ), /* harmony export */ DebertaForTokenClassification: () => ( /* reexport safe */ r.DebertaForTokenClassification ), /* harmony export */ DebertaModel: () => ( /* reexport safe */ r.DebertaModel ), /* harmony export */ DebertaPreTrainedModel: () => ( /* reexport safe */ r.DebertaPreTrainedModel ), /* harmony export */ DebertaTokenizer: () => ( /* reexport safe */ g.DebertaTokenizer ), /* harmony export */ DebertaV2ForMaskedLM: () => ( /* reexport safe */ r.DebertaV2ForMaskedLM ), /* harmony export */ DebertaV2ForQuestionAnswering: () => ( /* reexport safe */ r.DebertaV2ForQuestionAnswering ), /* harmony export */ DebertaV2ForSequenceClassification: () => ( /* reexport safe */ r.DebertaV2ForSequenceClassification ), /* harmony export */ DebertaV2ForTokenClassification: () => ( /* reexport safe */ r.DebertaV2ForTokenClassification ), /* harmony export */ DebertaV2Model: () => ( /* reexport safe */ r.DebertaV2Model ), /* harmony export */ DebertaV2PreTrainedModel: () => ( /* reexport safe */ r.DebertaV2PreTrainedModel ), /* harmony export */ DebertaV2Tokenizer: () => ( /* reexport safe */ g.DebertaV2Tokenizer ), /* harmony export */ DecisionTransformerModel: () => ( /* reexport safe */ r.DecisionTransformerModel ), /* harmony export */ DecisionTransformerPreTrainedModel: () => ( /* reexport safe */ r.DecisionTransformerPreTrainedModel ), /* harmony export */ DeiTFeatureExtractor: () => ( /* reexport safe */ L.DeiTFeatureExtractor ), /* harmony export */ DeiTForImageClassification: () => ( /* reexport safe */ r.DeiTForImageClassification ), /* harmony export */ DeiTImageProcessor: () => ( /* reexport safe */ L.DeiTImageProcessor ), /* harmony export */ DeiTModel: () => ( /* reexport safe */ r.DeiTModel ), /* harmony export */ DeiTPreTrainedModel: () => ( /* reexport safe */ r.DeiTPreTrainedModel ), /* harmony export */ DepthAnythingForDepthEstimation: () => ( /* reexport safe */ r.DepthAnythingForDepthEstimation ), /* harmony export */ DepthAnythingPreTrainedModel: () => ( /* reexport safe */ r.DepthAnythingPreTrainedModel ), /* harmony export */ DepthEstimationPipeline: () => ( /* reexport safe */ $.DepthEstimationPipeline ), /* harmony export */ DepthProForDepthEstimation: () => ( /* reexport safe */ r.DepthProForDepthEstimation ), /* harmony export */ DepthProPreTrainedModel: () => ( /* reexport safe */ r.DepthProPreTrainedModel ), /* harmony export */ DetrFeatureExtractor: () => ( /* reexport safe */ L.DetrFeatureExtractor ), /* harmony export */ DetrForObjectDetection: () => ( /* reexport safe */ r.DetrForObjectDetection ), /* harmony export */ DetrForSegmentation: () => ( /* reexport safe */ r.DetrForSegmentation ), /* harmony export */ DetrImageProcessor: () => ( /* reexport safe */ L.DetrImageProcessor ), /* harmony export */ DetrModel: () => ( /* reexport safe */ r.DetrModel ), /* harmony export */ DetrObjectDetectionOutput: () => ( /* reexport safe */ r.DetrObjectDetectionOutput ), /* harmony export */ DetrPreTrainedModel: () => ( /* reexport safe */ r.DetrPreTrainedModel ), /* harmony export */ DetrSegmentationOutput: () => ( /* reexport safe */ r.DetrSegmentationOutput ), /* harmony export */ Dinov2ForImageClassification: () => ( /* reexport safe */ r.Dinov2ForImageClassification ), /* harmony export */ Dinov2Model: () => ( /* reexport safe */ r.Dinov2Model ), /* harmony export */ Dinov2PreTrainedModel: () => ( /* reexport safe */ r.Dinov2PreTrainedModel ), /* harmony export */ Dinov2WithRegistersForImageClassification: () => ( /* reexport safe */ r.Dinov2WithRegistersForImageClassification ), /* harmony export */ Dinov2WithRegistersModel: () => ( /* reexport safe */ r.Dinov2WithRegistersModel ), /* harmony export */ Dinov2WithRegistersPreTrainedModel: () => ( /* reexport safe */ r.Dinov2WithRegistersPreTrainedModel ), /* harmony export */ DistilBertForMaskedLM: () => ( /* reexport safe */ r.DistilBertForMaskedLM ), /* harmony export */ DistilBertForQuestionAnswering: () => ( /* reexport safe */ r.DistilBertForQuestionAnswering ), /* harmony export */ DistilBertForSequenceClassification: () => ( /* reexport safe */ r.DistilBertForSequenceClassification ), /* harmony export */ DistilBertForTokenClassification: () => ( /* reexport safe */ r.DistilBertForTokenClassification ), /* harmony export */ DistilBertModel: () => ( /* reexport safe */ r.DistilBertModel ), /* harmony export */ DistilBertPreTrainedModel: () => ( /* reexport safe */ r.DistilBertPreTrainedModel ), /* harmony export */ DistilBertTokenizer: () => ( /* reexport safe */ g.DistilBertTokenizer ), /* harmony export */ DocumentQuestionAnsweringPipeline: () => ( /* reexport safe */ $.DocumentQuestionAnsweringPipeline ), /* harmony export */ DonutFeatureExtractor: () => ( /* reexport safe */ L.DonutFeatureExtractor ), /* harmony export */ DonutImageProcessor: () => ( /* reexport safe */ L.DonutImageProcessor ), /* harmony export */ DonutSwinModel: () => ( /* reexport safe */ r.DonutSwinModel ), /* harmony export */ DonutSwinPreTrainedModel: () => ( /* reexport safe */ r.DonutSwinPreTrainedModel ), /* harmony export */ EfficientNetForImageClassification: () => ( /* reexport safe */ r.EfficientNetForImageClassification ), /* harmony export */ EfficientNetImageProcessor: () => ( /* reexport safe */ L.EfficientNetImageProcessor ), /* harmony export */ EfficientNetModel: () => ( /* reexport safe */ r.EfficientNetModel ), /* harmony export */ EfficientNetPreTrainedModel: () => ( /* reexport safe */ r.EfficientNetPreTrainedModel ), /* harmony export */ ElectraForMaskedLM: () => ( /* reexport safe */ r.ElectraForMaskedLM ), /* harmony export */ ElectraForQuestionAnswering: () => ( /* reexport safe */ r.ElectraForQuestionAnswering ), /* harmony export */ ElectraForSequenceClassification: () => ( /* reexport safe */ r.ElectraForSequenceClassification ), /* harmony export */ ElectraForTokenClassification: () => ( /* reexport safe */ r.ElectraForTokenClassification ), /* harmony export */ ElectraModel: () => ( /* reexport safe */ r.ElectraModel ), /* harmony export */ ElectraPreTrainedModel: () => ( /* reexport safe */ r.ElectraPreTrainedModel ), /* harmony export */ ElectraTokenizer: () => ( /* reexport safe */ g.ElectraTokenizer ), /* harmony export */ EosTokenCriteria: () => ( /* reexport safe */ q.EosTokenCriteria ), /* harmony export */ EsmForMaskedLM: () => ( /* reexport safe */ r.EsmForMaskedLM ), /* harmony export */ EsmForSequenceClassification: () => ( /* reexport safe */ r.EsmForSequenceClassification ), /* harmony export */ EsmForTokenClassification: () => ( /* reexport safe */ r.EsmForTokenClassification ), /* harmony export */ EsmModel: () => ( /* reexport safe */ r.EsmModel ), /* harmony export */ EsmPreTrainedModel: () => ( /* reexport safe */ r.EsmPreTrainedModel ), /* harmony export */ EsmTokenizer: () => ( /* reexport safe */ g.EsmTokenizer ), /* harmony export */ ExaoneForCausalLM: () => ( /* reexport safe */ r.ExaoneForCausalLM ), /* harmony export */ ExaoneModel: () => ( /* reexport safe */ r.ExaoneModel ), /* harmony export */ ExaonePreTrainedModel: () => ( /* reexport safe */ r.ExaonePreTrainedModel ), /* harmony export */ FFT: () => ( /* reexport safe */ y.FFT ), /* harmony export */ FalconForCausalLM: () => ( /* reexport safe */ r.FalconForCausalLM ), /* harmony export */ FalconModel: () => ( /* reexport safe */ r.FalconModel ), /* harmony export */ FalconPreTrainedModel: () => ( /* reexport safe */ r.FalconPreTrainedModel ), /* harmony export */ FalconTokenizer: () => ( /* reexport safe */ g.FalconTokenizer ), /* harmony export */ FastViTForImageClassification: () => ( /* reexport safe */ r.FastViTForImageClassification ), /* harmony export */ FastViTModel: () => ( /* reexport safe */ r.FastViTModel ), /* harmony export */ FastViTPreTrainedModel: () => ( /* reexport safe */ r.FastViTPreTrainedModel ), /* harmony export */ FeatureExtractionPipeline: () => ( /* reexport safe */ $.FeatureExtractionPipeline ), /* harmony export */ FeatureExtractor: () => ( /* reexport safe */ T.FeatureExtractor ), /* harmony export */ FillMaskPipeline: () => ( /* reexport safe */ $.FillMaskPipeline ), /* harmony export */ Florence2ForConditionalGeneration: () => ( /* reexport safe */ r.Florence2ForConditionalGeneration ), /* harmony export */ Florence2PreTrainedModel: () => ( /* reexport safe */ r.Florence2PreTrainedModel ), /* harmony export */ Florence2Processor: () => ( /* reexport safe */ ie.Florence2Processor ), /* harmony export */ ForcedBOSTokenLogitsProcessor: () => ( /* reexport safe */ A.ForcedBOSTokenLogitsProcessor ), /* harmony export */ ForcedEOSTokenLogitsProcessor: () => ( /* reexport safe */ A.ForcedEOSTokenLogitsProcessor ), /* harmony export */ GLPNFeatureExtractor: () => ( /* reexport safe */ L.GLPNFeatureExtractor ), /* harmony export */ GLPNForDepthEstimation: () => ( /* reexport safe */ r.GLPNForDepthEstimation ), /* harmony export */ GLPNModel: () => ( /* reexport safe */ r.GLPNModel ), /* harmony export */ GLPNPreTrainedModel: () => ( /* reexport safe */ r.GLPNPreTrainedModel ), /* harmony export */ GPT2LMHeadModel: () => ( /* reexport safe */ r.GPT2LMHeadModel ), /* harmony export */ GPT2Model: () => ( /* reexport safe */ r.GPT2Model ), /* harmony export */ GPT2PreTrainedModel: () => ( /* reexport safe */ r.GPT2PreTrainedModel ), /* harmony export */ GPT2Tokenizer: () => ( /* reexport safe */ g.GPT2Tokenizer ), /* harmony export */ GPTBigCodeForCausalLM: () => ( /* reexport safe */ r.GPTBigCodeForCausalLM ), /* harmony export */ GPTBigCodeModel: () => ( /* reexport safe */ r.GPTBigCodeModel ), /* harmony export */ GPTBigCodePreTrainedModel: () => ( /* reexport safe */ r.GPTBigCodePreTrainedModel ), /* harmony export */ GPTJForCausalLM: () => ( /* reexport safe */ r.GPTJForCausalLM ), /* harmony export */ GPTJModel: () => ( /* reexport safe */ r.GPTJModel ), /* harmony export */ GPTJPreTrainedModel: () => ( /* reexport safe */ r.GPTJPreTrainedModel ), /* harmony export */ GPTNeoForCausalLM: () => ( /* reexport safe */ r.GPTNeoForCausalLM ), /* harmony export */ GPTNeoModel: () => ( /* reexport safe */ r.GPTNeoModel ), /* harmony export */ GPTNeoPreTrainedModel: () => ( /* reexport safe */ r.GPTNeoPreTrainedModel ), /* harmony export */ GPTNeoXForCausalLM: () => ( /* reexport safe */ r.GPTNeoXForCausalLM ), /* harmony export */ GPTNeoXModel: () => ( /* reexport safe */ r.GPTNeoXModel ), /* harmony export */ GPTNeoXPreTrainedModel: () => ( /* reexport safe */ r.GPTNeoXPreTrainedModel ), /* harmony export */ GPTNeoXTokenizer: () => ( /* reexport safe */ g.GPTNeoXTokenizer ), /* harmony export */ Gemma2ForCausalLM: () => ( /* reexport safe */ r.Gemma2ForCausalLM ), /* harmony export */ Gemma2Model: () => ( /* reexport safe */ r.Gemma2Model ), /* harmony export */ Gemma2PreTrainedModel: () => ( /* reexport safe */ r.Gemma2PreTrainedModel ), /* harmony export */ GemmaForCausalLM: () => ( /* reexport safe */ r.GemmaForCausalLM ), /* harmony export */ GemmaModel: () => ( /* reexport safe */ r.GemmaModel ), /* harmony export */ GemmaPreTrainedModel: () => ( /* reexport safe */ r.GemmaPreTrainedModel ), /* harmony export */ GemmaTokenizer: () => ( /* reexport safe */ g.GemmaTokenizer ), /* harmony export */ GlmForCausalLM: () => ( /* reexport safe */ r.GlmForCausalLM ), /* harmony export */ GlmModel: () => ( /* reexport safe */ r.GlmModel ), /* harmony export */ GlmPreTrainedModel: () => ( /* reexport safe */ r.GlmPreTrainedModel ), /* harmony export */ GraniteForCausalLM: () => ( /* reexport safe */ r.GraniteForCausalLM ), /* harmony export */ GraniteModel: () => ( /* reexport safe */ r.GraniteModel ), /* harmony export */ GranitePreTrainedModel: () => ( /* reexport safe */ r.GranitePreTrainedModel ), /* harmony export */ Grok1Tokenizer: () => ( /* reexport safe */ g.Grok1Tokenizer ), /* harmony export */ GroundingDinoForObjectDetection: () => ( /* reexport safe */ r.GroundingDinoForObjectDetection ), /* harmony export */ GroundingDinoImageProcessor: () => ( /* reexport safe */ L.GroundingDinoImageProcessor ), /* harmony export */ GroundingDinoPreTrainedModel: () => ( /* reexport safe */ r.GroundingDinoPreTrainedModel ), /* harmony export */ GroundingDinoProcessor: () => ( /* reexport safe */ ie.GroundingDinoProcessor ), /* harmony export */ GroupViTModel: () => ( /* reexport safe */ r.GroupViTModel ), /* harmony export */ GroupViTPreTrainedModel: () => ( /* reexport safe */ r.GroupViTPreTrainedModel ), /* harmony export */ HeliumForCausalLM: () => ( /* reexport safe */ r.HeliumForCausalLM ), /* harmony export */ HeliumModel: () => ( /* reexport safe */ r.HeliumModel ), /* harmony export */ HeliumPreTrainedModel: () => ( /* reexport safe */ r.HeliumPreTrainedModel ), /* harmony export */ HerbertTokenizer: () => ( /* reexport safe */ g.HerbertTokenizer ), /* harmony export */ HieraForImageClassification: () => ( /* reexport safe */ r.HieraForImageClassification ), /* harmony export */ HieraModel: () => ( /* reexport safe */ r.HieraModel ), /* harmony export */ HieraPreTrainedModel: () => ( /* reexport safe */ r.HieraPreTrainedModel ), /* harmony export */ HubertForCTC: () => ( /* reexport safe */ r.HubertForCTC ), /* harmony export */ HubertForSequenceClassification: () => ( /* reexport safe */ r.HubertForSequenceClassification ), /* harmony export */ HubertModel: () => ( /* reexport safe */ r.HubertModel ), /* harmony export */ HubertPreTrainedModel: () => ( /* reexport safe */ r.HubertPreTrainedModel ), /* harmony export */ IJepaForImageClassification: () => ( /* reexport safe */ r.IJepaForImageClassification ), /* harmony export */ IJepaModel: () => ( /* reexport safe */ r.IJepaModel ), /* harmony export */ IJepaPreTrainedModel: () => ( /* reexport safe */ r.IJepaPreTrainedModel ), /* harmony export */ Idefics3ForConditionalGeneration: () => ( /* reexport safe */ r.Idefics3ForConditionalGeneration ), /* harmony export */ Idefics3ImageProcessor: () => ( /* reexport safe */ L.Idefics3ImageProcessor ), /* harmony export */ Idefics3PreTrainedModel: () => ( /* reexport safe */ r.Idefics3PreTrainedModel ), /* harmony export */ Idefics3Processor: () => ( /* reexport safe */ ie.Idefics3Processor ), /* harmony export */ ImageClassificationPipeline: () => ( /* reexport safe */ $.ImageClassificationPipeline ), /* harmony export */ ImageFeatureExtractionPipeline: () => ( /* reexport safe */ $.ImageFeatureExtractionPipeline ), /* harmony export */ ImageFeatureExtractor: () => ( /* reexport safe */ v.ImageFeatureExtractor ), /* harmony export */ ImageMattingOutput: () => ( /* reexport safe */ r.ImageMattingOutput ), /* harmony export */ ImageProcessor: () => ( /* reexport safe */ x.ImageProcessor ), /* harmony export */ ImageSegmentationPipeline: () => ( /* reexport safe */ $.ImageSegmentationPipeline ), /* harmony export */ ImageToImagePipeline: () => ( /* reexport safe */ $.ImageToImagePipeline ), /* harmony export */ ImageToTextPipeline: () => ( /* reexport safe */ $.ImageToTextPipeline ), /* harmony export */ InterruptableStoppingCriteria: () => ( /* reexport safe */ q.InterruptableStoppingCriteria ), /* harmony export */ JAISLMHeadModel: () => ( /* reexport safe */ r.JAISLMHeadModel ), /* harmony export */ JAISModel: () => ( /* reexport safe */ r.JAISModel ), /* harmony export */ JAISPreTrainedModel: () => ( /* reexport safe */ r.JAISPreTrainedModel ), /* harmony export */ JinaCLIPImageProcessor: () => ( /* reexport safe */ L.JinaCLIPImageProcessor ), /* harmony export */ JinaCLIPModel: () => ( /* reexport safe */ r.JinaCLIPModel ), /* harmony export */ JinaCLIPPreTrainedModel: () => ( /* reexport safe */ r.JinaCLIPPreTrainedModel ), /* harmony export */ JinaCLIPProcessor: () => ( /* reexport safe */ ie.JinaCLIPProcessor ), /* harmony export */ JinaCLIPTextModel: () => ( /* reexport safe */ r.JinaCLIPTextModel ), /* harmony export */ JinaCLIPVisionModel: () => ( /* reexport safe */ r.JinaCLIPVisionModel ), /* harmony export */ LlamaForCausalLM: () => ( /* reexport safe */ r.LlamaForCausalLM ), /* harmony export */ LlamaModel: () => ( /* reexport safe */ r.LlamaModel ), /* harmony export */ LlamaPreTrainedModel: () => ( /* reexport safe */ r.LlamaPreTrainedModel ), /* harmony export */ LlamaTokenizer: () => ( /* reexport safe */ g.LlamaTokenizer ), /* harmony export */ LlavaForConditionalGeneration: () => ( /* reexport safe */ r.LlavaForConditionalGeneration ), /* harmony export */ LlavaOnevisionForConditionalGeneration: () => ( /* reexport safe */ r.LlavaOnevisionForConditionalGeneration ), /* harmony export */ LlavaOnevisionImageProcessor: () => ( /* reexport safe */ L.LlavaOnevisionImageProcessor ), /* harmony export */ LlavaPreTrainedModel: () => ( /* reexport safe */ r.LlavaPreTrainedModel ), /* harmony export */ LogitsProcessor: () => ( /* reexport safe */ A.LogitsProcessor ), /* harmony export */ LogitsProcessorList: () => ( /* reexport safe */ A.LogitsProcessorList ), /* harmony export */ LogitsWarper: () => ( /* reexport safe */ A.LogitsWarper ), /* harmony export */ LongT5ForConditionalGeneration: () => ( /* reexport safe */ r.LongT5ForConditionalGeneration ), /* harmony export */ LongT5Model: () => ( /* reexport safe */ r.LongT5Model ), /* harmony export */ LongT5PreTrainedModel: () => ( /* reexport safe */ r.LongT5PreTrainedModel ), /* harmony export */ M2M100ForConditionalGeneration: () => ( /* reexport safe */ r.M2M100ForConditionalGeneration ), /* harmony export */ M2M100Model: () => ( /* reexport safe */ r.M2M100Model ), /* harmony export */ M2M100PreTrainedModel: () => ( /* reexport safe */ r.M2M100PreTrainedModel ), /* harmony export */ M2M100Tokenizer: () => ( /* reexport safe */ g.M2M100Tokenizer ), /* harmony export */ MBart50Tokenizer: () => ( /* reexport safe */ g.MBart50Tokenizer ), /* harmony export */ MBartForCausalLM: () => ( /* reexport safe */ r.MBartForCausalLM ), /* harmony export */ MBartForConditionalGeneration: () => ( /* reexport safe */ r.MBartForConditionalGeneration ), /* harmony export */ MBartForSequenceClassification: () => ( /* reexport safe */ r.MBartForSequenceClassification ), /* harmony export */ MBartModel: () => ( /* reexport safe */ r.MBartModel ), /* harmony export */ MBartPreTrainedModel: () => ( /* reexport safe */ r.MBartPreTrainedModel ), /* harmony export */ MBartTokenizer: () => ( /* reexport safe */ g.MBartTokenizer ), /* harmony export */ MPNetForMaskedLM: () => ( /* reexport safe */ r.MPNetForMaskedLM ), /* harmony export */ MPNetForQuestionAnswering: () => ( /* reexport safe */ r.MPNetForQuestionAnswering ), /* harmony export */ MPNetForSequenceClassification: () => ( /* reexport safe */ r.MPNetForSequenceClassification ), /* harmony export */ MPNetForTokenClassification: () => ( /* reexport safe */ r.MPNetForTokenClassification ), /* harmony export */ MPNetModel: () => ( /* reexport safe */ r.MPNetModel ), /* harmony export */ MPNetPreTrainedModel: () => ( /* reexport safe */ r.MPNetPreTrainedModel ), /* harmony export */ MPNetTokenizer: () => ( /* reexport safe */ g.MPNetTokenizer ), /* harmony export */ MT5ForConditionalGeneration: () => ( /* reexport safe */ r.MT5ForConditionalGeneration ), /* harmony export */ MT5Model: () => ( /* reexport safe */ r.MT5Model ), /* harmony export */ MT5PreTrainedModel: () => ( /* reexport safe */ r.MT5PreTrainedModel ), /* harmony export */ MarianMTModel: () => ( /* reexport safe */ r.MarianMTModel ), /* harmony export */ MarianModel: () => ( /* reexport safe */ r.MarianModel ), /* harmony export */ MarianPreTrainedModel: () => ( /* reexport safe */ r.MarianPreTrainedModel ), /* harmony export */ MarianTokenizer: () => ( /* reexport safe */ g.MarianTokenizer ), /* harmony export */ Mask2FormerImageProcessor: () => ( /* reexport safe */ L.Mask2FormerImageProcessor ), /* harmony export */ MaskFormerFeatureExtractor: () => ( /* reexport safe */ L.MaskFormerFeatureExtractor ), /* harmony export */ MaskFormerForInstanceSegmentation: () => ( /* reexport safe */ r.MaskFormerForInstanceSegmentation ), /* harmony export */ MaskFormerImageProcessor: () => ( /* reexport safe */ L.MaskFormerImageProcessor ), /* harmony export */ MaskFormerModel: () => ( /* reexport safe */ r.MaskFormerModel ), /* harmony export */ MaskFormerPreTrainedModel: () => ( /* reexport safe */ r.MaskFormerPreTrainedModel ), /* harmony export */ MaskedLMOutput: () => ( /* reexport safe */ r.MaskedLMOutput ), /* harmony export */ MaxLengthCriteria: () => ( /* reexport safe */ q.MaxLengthCriteria ), /* harmony export */ MgpstrForSceneTextRecognition: () => ( /* reexport safe */ r.MgpstrForSceneTextRecognition ), /* harmony export */ MgpstrModelOutput: () => ( /* reexport safe */ r.MgpstrModelOutput ), /* harmony export */ MgpstrPreTrainedModel: () => ( /* reexport safe */ r.MgpstrPreTrainedModel ), /* harmony export */ MgpstrProcessor: () => ( /* reexport safe */ ie.MgpstrProcessor ), /* harmony export */ MgpstrTokenizer: () => ( /* reexport safe */ g.MgpstrTokenizer ), /* harmony export */ MinLengthLogitsProcessor: () => ( /* reexport safe */ A.MinLengthLogitsProcessor ), /* harmony export */ MinNewTokensLengthLogitsProcessor: () => ( /* reexport safe */ A.MinNewTokensLengthLogitsProcessor ), /* harmony export */ MistralForCausalLM: () => ( /* reexport safe */ r.MistralForCausalLM ), /* harmony export */ MistralModel: () => ( /* reexport safe */ r.MistralModel ), /* harmony export */ MistralPreTrainedModel: () => ( /* reexport safe */ r.MistralPreTrainedModel ), /* harmony export */ MobileBertForMaskedLM: () => ( /* reexport safe */ r.MobileBertForMaskedLM ), /* harmony export */ MobileBertForQuestionAnswering: () => ( /* reexport safe */ r.MobileBertForQuestionAnswering ), /* harmony export */ MobileBertForSequenceClassification: () => ( /* reexport safe */ r.MobileBertForSequenceClassification ), /* harmony export */ MobileBertModel: () => ( /* reexport safe */ r.MobileBertModel ), /* harmony export */ MobileBertPreTrainedModel: () => ( /* reexport safe */ r.MobileBertPreTrainedModel ), /* harmony export */ MobileBertTokenizer: () => ( /* reexport safe */ g.MobileBertTokenizer ), /* harmony export */ MobileLLMForCausalLM: () => ( /* reexport safe */ r.MobileLLMForCausalLM ), /* harmony export */ MobileLLMModel: () => ( /* reexport safe */ r.MobileLLMModel ), /* harmony export */ MobileLLMPreTrainedModel: () => ( /* reexport safe */ r.MobileLLMPreTrainedModel ), /* harmony export */ MobileNetV1FeatureExtractor: () => ( /* reexport safe */ L.MobileNetV1FeatureExtractor ), /* harmony export */ MobileNetV1ForImageClassification: () => ( /* reexport safe */ r.MobileNetV1ForImageClassification ), /* harmony export */ MobileNetV1ImageProcessor: () => ( /* reexport safe */ L.MobileNetV1ImageProcessor ), /* harmony export */ MobileNetV1Model: () => ( /* reexport safe */ r.MobileNetV1Model ), /* harmony export */ MobileNetV1PreTrainedModel: () => ( /* reexport safe */ r.MobileNetV1PreTrainedModel ), /* harmony export */ MobileNetV2FeatureExtractor: () => ( /* reexport safe */ L.MobileNetV2FeatureExtractor ), /* harmony export */ MobileNetV2ForImageClassification: () => ( /* reexport safe */ r.MobileNetV2ForImageClassification ), /* harmony export */ MobileNetV2ImageProcessor: () => ( /* reexport safe */ L.MobileNetV2ImageProcessor ), /* harmony export */ MobileNetV2Model: () => ( /* reexport safe */ r.MobileNetV2Model ), /* harmony export */ MobileNetV2PreTrainedModel: () => ( /* reexport safe */ r.MobileNetV2PreTrainedModel ), /* harmony export */ MobileNetV3FeatureExtractor: () => ( /* reexport safe */ L.MobileNetV3FeatureExtractor ), /* harmony export */ MobileNetV3ForImageClassification: () => ( /* reexport safe */ r.MobileNetV3ForImageClassification ), /* harmony export */ MobileNetV3ImageProcessor: () => ( /* reexport safe */ L.MobileNetV3ImageProcessor ), /* harmony export */ MobileNetV3Model: () => ( /* reexport safe */ r.MobileNetV3Model ), /* harmony export */ MobileNetV3PreTrainedModel: () => ( /* reexport safe */ r.MobileNetV3PreTrainedModel ), /* harmony export */ MobileNetV4FeatureExtractor: () => ( /* reexport safe */ L.MobileNetV4FeatureExtractor ), /* harmony export */ MobileNetV4ForImageClassification: () => ( /* reexport safe */ r.MobileNetV4ForImageClassification ), /* harmony export */ MobileNetV4ImageProcessor: () => ( /* reexport safe */ L.MobileNetV4ImageProcessor ), /* harmony export */ MobileNetV4Model: () => ( /* reexport safe */ r.MobileNetV4Model ), /* harmony export */ MobileNetV4PreTrainedModel: () => ( /* reexport safe */ r.MobileNetV4PreTrainedModel ), /* harmony export */ MobileViTFeatureExtractor: () => ( /* reexport safe */ L.MobileViTFeatureExtractor ), /* harmony export */ MobileViTForImageClassification: () => ( /* reexport safe */ r.MobileViTForImageClassification ), /* harmony export */ MobileViTImageProcessor: () => ( /* reexport safe */ L.MobileViTImageProcessor ), /* harmony export */ MobileViTModel: () => ( /* reexport safe */ r.MobileViTModel ), /* harmony export */ MobileViTPreTrainedModel: () => ( /* reexport safe */ r.MobileViTPreTrainedModel ), /* harmony export */ MobileViTV2ForImageClassification: () => ( /* reexport safe */ r.MobileViTV2ForImageClassification ), /* harmony export */ MobileViTV2Model: () => ( /* reexport safe */ r.MobileViTV2Model ), /* harmony export */ MobileViTV2PreTrainedModel: () => ( /* reexport safe */ r.MobileViTV2PreTrainedModel ), /* harmony export */ ModelOutput: () => ( /* reexport safe */ r.ModelOutput ), /* harmony export */ ModernBertForMaskedLM: () => ( /* reexport safe */ r.ModernBertForMaskedLM ), /* harmony export */ ModernBertForSequenceClassification: () => ( /* reexport safe */ r.ModernBertForSequenceClassification ), /* harmony export */ ModernBertForTokenClassification: () => ( /* reexport safe */ r.ModernBertForTokenClassification ), /* harmony export */ ModernBertModel: () => ( /* reexport safe */ r.ModernBertModel ), /* harmony export */ ModernBertPreTrainedModel: () => ( /* reexport safe */ r.ModernBertPreTrainedModel ), /* harmony export */ Moondream1ForConditionalGeneration: () => ( /* reexport safe */ r.Moondream1ForConditionalGeneration ), /* harmony export */ MoonshineFeatureExtractor: () => ( /* reexport safe */ v.MoonshineFeatureExtractor ), /* harmony export */ MoonshineForConditionalGeneration: () => ( /* reexport safe */ r.MoonshineForConditionalGeneration ), /* harmony export */ MoonshineModel: () => ( /* reexport safe */ r.MoonshineModel ), /* harmony export */ MoonshinePreTrainedModel: () => ( /* reexport safe */ r.MoonshinePreTrainedModel ), /* harmony export */ MoonshineProcessor: () => ( /* reexport safe */ ie.MoonshineProcessor ), /* harmony export */ MptForCausalLM: () => ( /* reexport safe */ r.MptForCausalLM ), /* harmony export */ MptModel: () => ( /* reexport safe */ r.MptModel ), /* harmony export */ MptPreTrainedModel: () => ( /* reexport safe */ r.MptPreTrainedModel ), /* harmony export */ MultiModalityCausalLM: () => ( /* reexport safe */ r.MultiModalityCausalLM ), /* harmony export */ MultiModalityPreTrainedModel: () => ( /* reexport safe */ r.MultiModalityPreTrainedModel ), /* harmony export */ MusicgenForCausalLM: () => ( /* reexport safe */ r.MusicgenForCausalLM ), /* harmony export */ MusicgenForConditionalGeneration: () => ( /* reexport safe */ r.MusicgenForConditionalGeneration ), /* harmony export */ MusicgenModel: () => ( /* reexport safe */ r.MusicgenModel ), /* harmony export */ MusicgenPreTrainedModel: () => ( /* reexport safe */ r.MusicgenPreTrainedModel ), /* harmony export */ NllbTokenizer: () => ( /* reexport safe */ g.NllbTokenizer ), /* harmony export */ NoBadWordsLogitsProcessor: () => ( /* reexport safe */ A.NoBadWordsLogitsProcessor ), /* harmony export */ NoRepeatNGramLogitsProcessor: () => ( /* reexport safe */ A.NoRepeatNGramLogitsProcessor ), /* harmony export */ NomicBertModel: () => ( /* reexport safe */ r.NomicBertModel ), /* harmony export */ NomicBertPreTrainedModel: () => ( /* reexport safe */ r.NomicBertPreTrainedModel ), /* harmony export */ NougatImageProcessor: () => ( /* reexport safe */ L.NougatImageProcessor ), /* harmony export */ NougatTokenizer: () => ( /* reexport safe */ g.NougatTokenizer ), /* harmony export */ OPTForCausalLM: () => ( /* reexport safe */ r.OPTForCausalLM ), /* harmony export */ OPTModel: () => ( /* reexport safe */ r.OPTModel ), /* harmony export */ OPTPreTrainedModel: () => ( /* reexport safe */ r.OPTPreTrainedModel ), /* harmony export */ ObjectDetectionPipeline: () => ( /* reexport safe */ $.ObjectDetectionPipeline ), /* harmony export */ Olmo2ForCausalLM: () => ( /* reexport safe */ r.Olmo2ForCausalLM ), /* harmony export */ Olmo2Model: () => ( /* reexport safe */ r.Olmo2Model ), /* harmony export */ Olmo2PreTrainedModel: () => ( /* reexport safe */ r.Olmo2PreTrainedModel ), /* harmony export */ OlmoForCausalLM: () => ( /* reexport safe */ r.OlmoForCausalLM ), /* harmony export */ OlmoModel: () => ( /* reexport safe */ r.OlmoModel ), /* harmony export */ OlmoPreTrainedModel: () => ( /* reexport safe */ r.OlmoPreTrainedModel ), /* harmony export */ OpenELMForCausalLM: () => ( /* reexport safe */ r.OpenELMForCausalLM ), /* harmony export */ OpenELMModel: () => ( /* reexport safe */ r.OpenELMModel ), /* harmony export */ OpenELMPreTrainedModel: () => ( /* reexport safe */ r.OpenELMPreTrainedModel ), /* harmony export */ OwlViTFeatureExtractor: () => ( /* reexport safe */ L.OwlViTFeatureExtractor ), /* harmony export */ OwlViTForObjectDetection: () => ( /* reexport safe */ r.OwlViTForObjectDetection ), /* harmony export */ OwlViTImageProcessor: () => ( /* reexport safe */ L.OwlViTImageProcessor ), /* harmony export */ OwlViTModel: () => ( /* reexport safe */ r.OwlViTModel ), /* harmony export */ OwlViTPreTrainedModel: () => ( /* reexport safe */ r.OwlViTPreTrainedModel ), /* harmony export */ OwlViTProcessor: () => ( /* reexport safe */ ie.OwlViTProcessor ), /* harmony export */ Owlv2ForObjectDetection: () => ( /* reexport safe */ r.Owlv2ForObjectDetection ), /* harmony export */ Owlv2ImageProcessor: () => ( /* reexport safe */ L.Owlv2ImageProcessor ), /* harmony export */ Owlv2Model: () => ( /* reexport safe */ r.Owlv2Model ), /* harmony export */ Owlv2PreTrainedModel: () => ( /* reexport safe */ r.Owlv2PreTrainedModel ), /* harmony export */ PaliGemmaForConditionalGeneration: () => ( /* reexport safe */ r.PaliGemmaForConditionalGeneration ), /* harmony export */ PaliGemmaPreTrainedModel: () => ( /* reexport safe */ r.PaliGemmaPreTrainedModel ), /* harmony export */ PaliGemmaProcessor: () => ( /* reexport safe */ ie.PaliGemmaProcessor ), /* harmony export */ PatchTSMixerForPrediction: () => ( /* reexport safe */ r.PatchTSMixerForPrediction ), /* harmony export */ PatchTSMixerModel: () => ( /* reexport safe */ r.PatchTSMixerModel ), /* harmony export */ PatchTSMixerPreTrainedModel: () => ( /* reexport safe */ r.PatchTSMixerPreTrainedModel ), /* harmony export */ PatchTSTForPrediction: () => ( /* reexport safe */ r.PatchTSTForPrediction ), /* harmony export */ PatchTSTModel: () => ( /* reexport safe */ r.PatchTSTModel ), /* harmony export */ PatchTSTPreTrainedModel: () => ( /* reexport safe */ r.PatchTSTPreTrainedModel ), /* harmony export */ Phi3ForCausalLM: () => ( /* reexport safe */ r.Phi3ForCausalLM ), /* harmony export */ Phi3Model: () => ( /* reexport safe */ r.Phi3Model ), /* harmony export */ Phi3PreTrainedModel: () => ( /* reexport safe */ r.Phi3PreTrainedModel ), /* harmony export */ Phi3VForCausalLM: () => ( /* reexport safe */ r.Phi3VForCausalLM ), /* harmony export */ Phi3VImageProcessor: () => ( /* reexport safe */ L.Phi3VImageProcessor ), /* harmony export */ Phi3VPreTrainedModel: () => ( /* reexport safe */ r.Phi3VPreTrainedModel ), /* harmony export */ Phi3VProcessor: () => ( /* reexport safe */ ie.Phi3VProcessor ), /* harmony export */ PhiForCausalLM: () => ( /* reexport safe */ r.PhiForCausalLM ), /* harmony export */ PhiModel: () => ( /* reexport safe */ r.PhiModel ), /* harmony export */ PhiPreTrainedModel: () => ( /* reexport safe */ r.PhiPreTrainedModel ), /* harmony export */ Pipeline: () => ( /* reexport safe */ $.Pipeline ), /* harmony export */ PreTrainedModel: () => ( /* reexport safe */ r.PreTrainedModel ), /* harmony export */ PreTrainedTokenizer: () => ( /* reexport safe */ g.PreTrainedTokenizer ), /* harmony export */ PretrainedConfig: () => ( /* reexport safe */ O.PretrainedConfig ), /* harmony export */ PretrainedMixin: () => ( /* reexport safe */ r.PretrainedMixin ), /* harmony export */ Processor: () => ( /* reexport safe */ re.Processor ), /* harmony export */ PvtForImageClassification: () => ( /* reexport safe */ r.PvtForImageClassification ), /* harmony export */ PvtImageProcessor: () => ( /* reexport safe */ L.PvtImageProcessor ), /* harmony export */ PvtModel: () => ( /* reexport safe */ r.PvtModel ), /* harmony export */ PvtPreTrainedModel: () => ( /* reexport safe */ r.PvtPreTrainedModel ), /* harmony export */ PyAnnoteFeatureExtractor: () => ( /* reexport safe */ v.PyAnnoteFeatureExtractor ), /* harmony export */ PyAnnoteForAudioFrameClassification: () => ( /* reexport safe */ r.PyAnnoteForAudioFrameClassification ), /* harmony export */ PyAnnoteModel: () => ( /* reexport safe */ r.PyAnnoteModel ), /* harmony export */ PyAnnotePreTrainedModel: () => ( /* reexport safe */ r.PyAnnotePreTrainedModel ), /* harmony export */ PyAnnoteProcessor: () => ( /* reexport safe */ ie.PyAnnoteProcessor ), /* harmony export */ QuestionAnsweringModelOutput: () => ( /* reexport safe */ r.QuestionAnsweringModelOutput ), /* harmony export */ QuestionAnsweringPipeline: () => ( /* reexport safe */ $.QuestionAnsweringPipeline ), /* harmony export */ Qwen2ForCausalLM: () => ( /* reexport safe */ r.Qwen2ForCausalLM ), /* harmony export */ Qwen2Model: () => ( /* reexport safe */ r.Qwen2Model ), /* harmony export */ Qwen2PreTrainedModel: () => ( /* reexport safe */ r.Qwen2PreTrainedModel ), /* harmony export */ Qwen2Tokenizer: () => ( /* reexport safe */ g.Qwen2Tokenizer ), /* harmony export */ Qwen2VLForConditionalGeneration: () => ( /* reexport safe */ r.Qwen2VLForConditionalGeneration ), /* harmony export */ Qwen2VLImageProcessor: () => ( /* reexport safe */ L.Qwen2VLImageProcessor ), /* harmony export */ Qwen2VLPreTrainedModel: () => ( /* reexport safe */ r.Qwen2VLPreTrainedModel ), /* harmony export */ Qwen2VLProcessor: () => ( /* reexport safe */ ie.Qwen2VLProcessor ), /* harmony export */ RTDetrForObjectDetection: () => ( /* reexport safe */ r.RTDetrForObjectDetection ), /* harmony export */ RTDetrImageProcessor: () => ( /* reexport safe */ L.RTDetrImageProcessor ), /* harmony export */ RTDetrModel: () => ( /* reexport safe */ r.RTDetrModel ), /* harmony export */ RTDetrObjectDetectionOutput: () => ( /* reexport safe */ r.RTDetrObjectDetectionOutput ), /* harmony export */ RTDetrPreTrainedModel: () => ( /* reexport safe */ r.RTDetrPreTrainedModel ), /* harmony export */ RawAudio: () => ( /* reexport safe */ j.RawAudio ), /* harmony export */ RawImage: () => ( /* reexport safe */ ee.RawImage ), /* harmony export */ RepetitionPenaltyLogitsProcessor: () => ( /* reexport safe */ A.RepetitionPenaltyLogitsProcessor ), /* harmony export */ ResNetForImageClassification: () => ( /* reexport safe */ r.ResNetForImageClassification ), /* harmony export */ ResNetModel: () => ( /* reexport safe */ r.ResNetModel ), /* harmony export */ ResNetPreTrainedModel: () => ( /* reexport safe */ r.ResNetPreTrainedModel ), /* harmony export */ RoFormerForMaskedLM: () => ( /* reexport safe */ r.RoFormerForMaskedLM ), /* harmony export */ RoFormerForQuestionAnswering: () => ( /* reexport safe */ r.RoFormerForQuestionAnswering ), /* harmony export */ RoFormerForSequenceClassification: () => ( /* reexport safe */ r.RoFormerForSequenceClassification ), /* harmony export */ RoFormerForTokenClassification: () => ( /* reexport safe */ r.RoFormerForTokenClassification ), /* harmony export */ RoFormerModel: () => ( /* reexport safe */ r.RoFormerModel ), /* harmony export */ RoFormerPreTrainedModel: () => ( /* reexport safe */ r.RoFormerPreTrainedModel ), /* harmony export */ RoFormerTokenizer: () => ( /* reexport safe */ g.RoFormerTokenizer ), /* harmony export */ RobertaForMaskedLM: () => ( /* reexport safe */ r.RobertaForMaskedLM ), /* harmony export */ RobertaForQuestionAnswering: () => ( /* reexport safe */ r.RobertaForQuestionAnswering ), /* harmony export */ RobertaForSequenceClassification: () => ( /* reexport safe */ r.RobertaForSequenceClassification ), /* harmony export */ RobertaForTokenClassification: () => ( /* reexport safe */ r.RobertaForTokenClassification ), /* harmony export */ RobertaModel: () => ( /* reexport safe */ r.RobertaModel ), /* harmony export */ RobertaPreTrainedModel: () => ( /* reexport safe */ r.RobertaPreTrainedModel ), /* harmony export */ RobertaTokenizer: () => ( /* reexport safe */ g.RobertaTokenizer ), /* harmony export */ SamImageProcessor: () => ( /* reexport safe */ L.SamImageProcessor ), /* harmony export */ SamImageSegmentationOutput: () => ( /* reexport safe */ r.SamImageSegmentationOutput ), /* harmony export */ SamModel: () => ( /* reexport safe */ r.SamModel ), /* harmony export */ SamPreTrainedModel: () => ( /* reexport safe */ r.SamPreTrainedModel ), /* harmony export */ SamProcessor: () => ( /* reexport safe */ ie.SamProcessor ), /* harmony export */ SapiensForDepthEstimation: () => ( /* reexport safe */ r.SapiensForDepthEstimation ), /* harmony export */ SapiensForNormalEstimation: () => ( /* reexport safe */ r.SapiensForNormalEstimation ), /* harmony export */ SapiensForSemanticSegmentation: () => ( /* reexport safe */ r.SapiensForSemanticSegmentation ), /* harmony export */ SapiensPreTrainedModel: () => ( /* reexport safe */ r.SapiensPreTrainedModel ), /* harmony export */ SeamlessM4TFeatureExtractor: () => ( /* reexport safe */ v.SeamlessM4TFeatureExtractor ), /* harmony export */ SegformerFeatureExtractor: () => ( /* reexport safe */ L.SegformerFeatureExtractor ), /* harmony export */ SegformerForImageClassification: () => ( /* reexport safe */ r.SegformerForImageClassification ), /* harmony export */ SegformerForSemanticSegmentation: () => ( /* reexport safe */ r.SegformerForSemanticSegmentation ), /* harmony export */ SegformerImageProcessor: () => ( /* reexport safe */ L.SegformerImageProcessor ), /* harmony export */ SegformerModel: () => ( /* reexport safe */ r.SegformerModel ), /* harmony export */ SegformerPreTrainedModel: () => ( /* reexport safe */ r.SegformerPreTrainedModel ), /* harmony export */ Seq2SeqLMOutput: () => ( /* reexport safe */ r.Seq2SeqLMOutput ), /* harmony export */ SequenceClassifierOutput: () => ( /* reexport safe */ r.SequenceClassifierOutput ), /* harmony export */ SiglipImageProcessor: () => ( /* reexport safe */ L.SiglipImageProcessor ), /* harmony export */ SiglipModel: () => ( /* reexport safe */ r.SiglipModel ), /* harmony export */ SiglipPreTrainedModel: () => ( /* reexport safe */ r.SiglipPreTrainedModel ), /* harmony export */ SiglipTextModel: () => ( /* reexport safe */ r.SiglipTextModel ), /* harmony export */ SiglipTokenizer: () => ( /* reexport safe */ g.SiglipTokenizer ), /* harmony export */ SiglipVisionModel: () => ( /* reexport safe */ r.SiglipVisionModel ), /* harmony export */ SpeechT5FeatureExtractor: () => ( /* reexport safe */ v.SpeechT5FeatureExtractor ), /* harmony export */ SpeechT5ForSpeechToText: () => ( /* reexport safe */ r.SpeechT5ForSpeechToText ), /* harmony export */ SpeechT5ForTextToSpeech: () => ( /* reexport safe */ r.SpeechT5ForTextToSpeech ), /* harmony export */ SpeechT5HifiGan: () => ( /* reexport safe */ r.SpeechT5HifiGan ), /* harmony export */ SpeechT5Model: () => ( /* reexport safe */ r.SpeechT5Model ), /* harmony export */ SpeechT5PreTrainedModel: () => ( /* reexport safe */ r.SpeechT5PreTrainedModel ), /* harmony export */ SpeechT5Processor: () => ( /* reexport safe */ ie.SpeechT5Processor ), /* harmony export */ SpeechT5Tokenizer: () => ( /* reexport safe */ g.SpeechT5Tokenizer ), /* harmony export */ SqueezeBertForMaskedLM: () => ( /* reexport safe */ r.SqueezeBertForMaskedLM ), /* harmony export */ SqueezeBertForQuestionAnswering: () => ( /* reexport safe */ r.SqueezeBertForQuestionAnswering ), /* harmony export */ SqueezeBertForSequenceClassification: () => ( /* reexport safe */ r.SqueezeBertForSequenceClassification ), /* harmony export */ SqueezeBertModel: () => ( /* reexport safe */ r.SqueezeBertModel ), /* harmony export */ SqueezeBertPreTrainedModel: () => ( /* reexport safe */ r.SqueezeBertPreTrainedModel ), /* harmony export */ SqueezeBertTokenizer: () => ( /* reexport safe */ g.SqueezeBertTokenizer ), /* harmony export */ StableLmForCausalLM: () => ( /* reexport safe */ r.StableLmForCausalLM ), /* harmony export */ StableLmModel: () => ( /* reexport safe */ r.StableLmModel ), /* harmony export */ StableLmPreTrainedModel: () => ( /* reexport safe */ r.StableLmPreTrainedModel ), /* harmony export */ Starcoder2ForCausalLM: () => ( /* reexport safe */ r.Starcoder2ForCausalLM ), /* harmony export */ Starcoder2Model: () => ( /* reexport safe */ r.Starcoder2Model ), /* harmony export */ Starcoder2PreTrainedModel: () => ( /* reexport safe */ r.Starcoder2PreTrainedModel ), /* harmony export */ StoppingCriteria: () => ( /* reexport safe */ q.StoppingCriteria ), /* harmony export */ StoppingCriteriaList: () => ( /* reexport safe */ q.StoppingCriteriaList ), /* harmony export */ StyleTextToSpeech2Model: () => ( /* reexport safe */ r.StyleTextToSpeech2Model ), /* harmony export */ StyleTextToSpeech2PreTrainedModel: () => ( /* reexport safe */ r.StyleTextToSpeech2PreTrainedModel ), /* harmony export */ SummarizationPipeline: () => ( /* reexport safe */ $.SummarizationPipeline ), /* harmony export */ SuppressTokensAtBeginLogitsProcessor: () => ( /* reexport safe */ A.SuppressTokensAtBeginLogitsProcessor ), /* harmony export */ Swin2SRForImageSuperResolution: () => ( /* reexport safe */ r.Swin2SRForImageSuperResolution ), /* harmony export */ Swin2SRImageProcessor: () => ( /* reexport safe */ L.Swin2SRImageProcessor ), /* harmony export */ Swin2SRModel: () => ( /* reexport safe */ r.Swin2SRModel ), /* harmony export */ Swin2SRPreTrainedModel: () => ( /* reexport safe */ r.Swin2SRPreTrainedModel ), /* harmony export */ SwinForImageClassification: () => ( /* reexport safe */ r.SwinForImageClassification ), /* harmony export */ SwinModel: () => ( /* reexport safe */ r.SwinModel ), /* harmony export */ SwinPreTrainedModel: () => ( /* reexport safe */ r.SwinPreTrainedModel ), /* harmony export */ T5ForConditionalGeneration: () => ( /* reexport safe */ r.T5ForConditionalGeneration ), /* harmony export */ T5Model: () => ( /* reexport safe */ r.T5Model ), /* harmony export */ T5PreTrainedModel: () => ( /* reexport safe */ r.T5PreTrainedModel ), /* harmony export */ T5Tokenizer: () => ( /* reexport safe */ g.T5Tokenizer ), /* harmony export */ TableTransformerForObjectDetection: () => ( /* reexport safe */ r.TableTransformerForObjectDetection ), /* harmony export */ TableTransformerModel: () => ( /* reexport safe */ r.TableTransformerModel ), /* harmony export */ TableTransformerObjectDetectionOutput: () => ( /* reexport safe */ r.TableTransformerObjectDetectionOutput ), /* harmony export */ TableTransformerPreTrainedModel: () => ( /* reexport safe */ r.TableTransformerPreTrainedModel ), /* harmony export */ TemperatureLogitsWarper: () => ( /* reexport safe */ A.TemperatureLogitsWarper ), /* harmony export */ Tensor: () => ( /* reexport safe */ N.Tensor ), /* harmony export */ Text2TextGenerationPipeline: () => ( /* reexport safe */ $.Text2TextGenerationPipeline ), /* harmony export */ TextClassificationPipeline: () => ( /* reexport safe */ $.TextClassificationPipeline ), /* harmony export */ TextGenerationPipeline: () => ( /* reexport safe */ $.TextGenerationPipeline ), /* harmony export */ TextStreamer: () => ( /* reexport safe */ U.TextStreamer ), /* harmony export */ TextToAudioPipeline: () => ( /* reexport safe */ $.TextToAudioPipeline ), /* harmony export */ TokenClassificationPipeline: () => ( /* reexport safe */ $.TokenClassificationPipeline ), /* harmony export */ TokenClassifierOutput: () => ( /* reexport safe */ r.TokenClassifierOutput ), /* harmony export */ TokenizerModel: () => ( /* reexport safe */ g.TokenizerModel ), /* harmony export */ TopKLogitsWarper: () => ( /* reexport safe */ A.TopKLogitsWarper ), /* harmony export */ TopPLogitsWarper: () => ( /* reexport safe */ A.TopPLogitsWarper ), /* harmony export */ TrOCRForCausalLM: () => ( /* reexport safe */ r.TrOCRForCausalLM ), /* harmony export */ TrOCRPreTrainedModel: () => ( /* reexport safe */ r.TrOCRPreTrainedModel ), /* harmony export */ TranslationPipeline: () => ( /* reexport safe */ $.TranslationPipeline ), /* harmony export */ UniSpeechForCTC: () => ( /* reexport safe */ r.UniSpeechForCTC ), /* harmony export */ UniSpeechForSequenceClassification: () => ( /* reexport safe */ r.UniSpeechForSequenceClassification ), /* harmony export */ UniSpeechModel: () => ( /* reexport safe */ r.UniSpeechModel ), /* harmony export */ UniSpeechPreTrainedModel: () => ( /* reexport safe */ r.UniSpeechPreTrainedModel ), /* harmony export */ UniSpeechSatForAudioFrameClassification: () => ( /* reexport safe */ r.UniSpeechSatForAudioFrameClassification ), /* harmony export */ UniSpeechSatForCTC: () => ( /* reexport safe */ r.UniSpeechSatForCTC ), /* harmony export */ UniSpeechSatForSequenceClassification: () => ( /* reexport safe */ r.UniSpeechSatForSequenceClassification ), /* harmony export */ UniSpeechSatModel: () => ( /* reexport safe */ r.UniSpeechSatModel ), /* harmony export */ UniSpeechSatPreTrainedModel: () => ( /* reexport safe */ r.UniSpeechSatPreTrainedModel ), /* harmony export */ VLChatProcessor: () => ( /* reexport safe */ ie.VLChatProcessor ), /* harmony export */ VLMImageProcessor: () => ( /* reexport safe */ L.VLMImageProcessor ), /* harmony export */ ViTFeatureExtractor: () => ( /* reexport safe */ L.ViTFeatureExtractor ), /* harmony export */ ViTForImageClassification: () => ( /* reexport safe */ r.ViTForImageClassification ), /* harmony export */ ViTImageProcessor: () => ( /* reexport safe */ L.ViTImageProcessor ), /* harmony export */ ViTMAEModel: () => ( /* reexport safe */ r.ViTMAEModel ), /* harmony export */ ViTMAEPreTrainedModel: () => ( /* reexport safe */ r.ViTMAEPreTrainedModel ), /* harmony export */ ViTMSNForImageClassification: () => ( /* reexport safe */ r.ViTMSNForImageClassification ), /* harmony export */ ViTMSNModel: () => ( /* reexport safe */ r.ViTMSNModel ), /* harmony export */ ViTMSNPreTrainedModel: () => ( /* reexport safe */ r.ViTMSNPreTrainedModel ), /* harmony export */ ViTModel: () => ( /* reexport safe */ r.ViTModel ), /* harmony export */ ViTPreTrainedModel: () => ( /* reexport safe */ r.ViTPreTrainedModel ), /* harmony export */ VisionEncoderDecoderModel: () => ( /* reexport safe */ r.VisionEncoderDecoderModel ), /* harmony export */ VitMatteForImageMatting: () => ( /* reexport safe */ r.VitMatteForImageMatting ), /* harmony export */ VitMatteImageProcessor: () => ( /* reexport safe */ L.VitMatteImageProcessor ), /* harmony export */ VitMattePreTrainedModel: () => ( /* reexport safe */ r.VitMattePreTrainedModel ), /* harmony export */ VitPoseForPoseEstimation: () => ( /* reexport safe */ r.VitPoseForPoseEstimation ), /* harmony export */ VitPoseImageProcessor: () => ( /* reexport safe */ L.VitPoseImageProcessor ), /* harmony export */ VitPosePreTrainedModel: () => ( /* reexport safe */ r.VitPosePreTrainedModel ), /* harmony export */ VitsModel: () => ( /* reexport safe */ r.VitsModel ), /* harmony export */ VitsModelOutput: () => ( /* reexport safe */ r.VitsModelOutput ), /* harmony export */ VitsPreTrainedModel: () => ( /* reexport safe */ r.VitsPreTrainedModel ), /* harmony export */ VitsTokenizer: () => ( /* reexport safe */ g.VitsTokenizer ), /* harmony export */ Wav2Vec2BertForCTC: () => ( /* reexport safe */ r.Wav2Vec2BertForCTC ), /* harmony export */ Wav2Vec2BertForSequenceClassification: () => ( /* reexport safe */ r.Wav2Vec2BertForSequenceClassification ), /* harmony export */ Wav2Vec2BertModel: () => ( /* reexport safe */ r.Wav2Vec2BertModel ), /* harmony export */ Wav2Vec2BertPreTrainedModel: () => ( /* reexport safe */ r.Wav2Vec2BertPreTrainedModel ), /* harmony export */ Wav2Vec2CTCTokenizer: () => ( /* reexport safe */ g.Wav2Vec2CTCTokenizer ), /* harmony export */ Wav2Vec2FeatureExtractor: () => ( /* reexport safe */ v.Wav2Vec2FeatureExtractor ), /* harmony export */ Wav2Vec2ForAudioFrameClassification: () => ( /* reexport safe */ r.Wav2Vec2ForAudioFrameClassification ), /* harmony export */ Wav2Vec2ForCTC: () => ( /* reexport safe */ r.Wav2Vec2ForCTC ), /* harmony export */ Wav2Vec2ForSequenceClassification: () => ( /* reexport safe */ r.Wav2Vec2ForSequenceClassification ), /* harmony export */ Wav2Vec2Model: () => ( /* reexport safe */ r.Wav2Vec2Model ), /* harmony export */ Wav2Vec2PreTrainedModel: () => ( /* reexport safe */ r.Wav2Vec2PreTrainedModel ), /* harmony export */ Wav2Vec2Processor: () => ( /* reexport safe */ ie.Wav2Vec2Processor ), /* harmony export */ Wav2Vec2ProcessorWithLM: () => ( /* reexport safe */ ie.Wav2Vec2ProcessorWithLM ), /* harmony export */ WavLMForAudioFrameClassification: () => ( /* reexport safe */ r.WavLMForAudioFrameClassification ), /* harmony export */ WavLMForCTC: () => ( /* reexport safe */ r.WavLMForCTC ), /* harmony export */ WavLMForSequenceClassification: () => ( /* reexport safe */ r.WavLMForSequenceClassification ), /* harmony export */ WavLMForXVector: () => ( /* reexport safe */ r.WavLMForXVector ), /* harmony export */ WavLMModel: () => ( /* reexport safe */ r.WavLMModel ), /* harmony export */ WavLMPreTrainedModel: () => ( /* reexport safe */ r.WavLMPreTrainedModel ), /* harmony export */ WeSpeakerFeatureExtractor: () => ( /* reexport safe */ v.WeSpeakerFeatureExtractor ), /* harmony export */ WeSpeakerResNetModel: () => ( /* reexport safe */ r.WeSpeakerResNetModel ), /* harmony export */ WeSpeakerResNetPreTrainedModel: () => ( /* reexport safe */ r.WeSpeakerResNetPreTrainedModel ), /* harmony export */ WhisperFeatureExtractor: () => ( /* reexport safe */ v.WhisperFeatureExtractor ), /* harmony export */ WhisperForConditionalGeneration: () => ( /* reexport safe */ r.WhisperForConditionalGeneration ), /* harmony export */ WhisperModel: () => ( /* reexport safe */ r.WhisperModel ), /* harmony export */ WhisperPreTrainedModel: () => ( /* reexport safe */ r.WhisperPreTrainedModel ), /* harmony export */ WhisperProcessor: () => ( /* reexport safe */ ie.WhisperProcessor ), /* harmony export */ WhisperTextStreamer: () => ( /* reexport safe */ U.WhisperTextStreamer ), /* harmony export */ WhisperTimeStampLogitsProcessor: () => ( /* reexport safe */ A.WhisperTimeStampLogitsProcessor ), /* harmony export */ WhisperTokenizer: () => ( /* reexport safe */ g.WhisperTokenizer ), /* harmony export */ XLMForQuestionAnswering: () => ( /* reexport safe */ r.XLMForQuestionAnswering ), /* harmony export */ XLMForSequenceClassification: () => ( /* reexport safe */ r.XLMForSequenceClassification ), /* harmony export */ XLMForTokenClassification: () => ( /* reexport safe */ r.XLMForTokenClassification ), /* harmony export */ XLMModel: () => ( /* reexport safe */ r.XLMModel ), /* harmony export */ XLMPreTrainedModel: () => ( /* reexport safe */ r.XLMPreTrainedModel ), /* harmony export */ XLMRobertaForMaskedLM: () => ( /* reexport safe */ r.XLMRobertaForMaskedLM ), /* harmony export */ XLMRobertaForQuestionAnswering: () => ( /* reexport safe */ r.XLMRobertaForQuestionAnswering ), /* harmony export */ XLMRobertaForSequenceClassification: () => ( /* reexport safe */ r.XLMRobertaForSequenceClassification ), /* harmony export */ XLMRobertaForTokenClassification: () => ( /* reexport safe */ r.XLMRobertaForTokenClassification ), /* harmony export */ XLMRobertaModel: () => ( /* reexport safe */ r.XLMRobertaModel ), /* harmony export */ XLMRobertaPreTrainedModel: () => ( /* reexport safe */ r.XLMRobertaPreTrainedModel ), /* harmony export */ XLMRobertaTokenizer: () => ( /* reexport safe */ g.XLMRobertaTokenizer ), /* harmony export */ XLMTokenizer: () => ( /* reexport safe */ g.XLMTokenizer ), /* harmony export */ XLMWithLMHeadModel: () => ( /* reexport safe */ r.XLMWithLMHeadModel ), /* harmony export */ XVectorOutput: () => ( /* reexport safe */ r.XVectorOutput ), /* harmony export */ YolosFeatureExtractor: () => ( /* reexport safe */ L.YolosFeatureExtractor ), /* harmony export */ YolosForObjectDetection: () => ( /* reexport safe */ r.YolosForObjectDetection ), /* harmony export */ YolosImageProcessor: () => ( /* reexport safe */ L.YolosImageProcessor ), /* harmony export */ YolosModel: () => ( /* reexport safe */ r.YolosModel ), /* harmony export */ YolosObjectDetectionOutput: () => ( /* reexport safe */ r.YolosObjectDetectionOutput ), /* harmony export */ YolosPreTrainedModel: () => ( /* reexport safe */ r.YolosPreTrainedModel ), /* harmony export */ ZeroShotAudioClassificationPipeline: () => ( /* reexport safe */ $.ZeroShotAudioClassificationPipeline ), /* harmony export */ ZeroShotClassificationPipeline: () => ( /* reexport safe */ $.ZeroShotClassificationPipeline ), /* harmony export */ ZeroShotImageClassificationPipeline: () => ( /* reexport safe */ $.ZeroShotImageClassificationPipeline ), /* harmony export */ ZeroShotObjectDetectionPipeline: () => ( /* reexport safe */ $.ZeroShotObjectDetectionPipeline ), /* harmony export */ bankers_round: () => ( /* reexport safe */ y.bankers_round ), /* harmony export */ cat: () => ( /* reexport safe */ N.cat ), /* harmony export */ cos_sim: () => ( /* reexport safe */ y.cos_sim ), /* harmony export */ dot: () => ( /* reexport safe */ y.dot ), /* harmony export */ dynamic_time_warping: () => ( /* reexport safe */ y.dynamic_time_warping ), /* harmony export */ env: () => ( /* reexport safe */ Ie.env ), /* harmony export */ full: () => ( /* reexport safe */ N.full ), /* harmony export */ full_like: () => ( /* reexport safe */ N.full_like ), /* harmony export */ getKeyValueShapes: () => ( /* reexport safe */ O.getKeyValueShapes ), /* harmony export */ hamming: () => ( /* reexport safe */ j.hamming ), /* harmony export */ hanning: () => ( /* reexport safe */ j.hanning ), /* harmony export */ interpolate: () => ( /* reexport safe */ N.interpolate ), /* harmony export */ interpolate_4d: () => ( /* reexport safe */ N.interpolate_4d ), /* harmony export */ interpolate_data: () => ( /* reexport safe */ y.interpolate_data ), /* harmony export */ is_chinese_char: () => ( /* reexport safe */ g.is_chinese_char ), /* harmony export */ layer_norm: () => ( /* reexport safe */ N.layer_norm ), /* harmony export */ load_image: () => ( /* reexport safe */ ee.load_image ), /* harmony export */ log_softmax: () => ( /* reexport safe */ y.log_softmax ), /* harmony export */ magnitude: () => ( /* reexport safe */ y.magnitude ), /* harmony export */ matmul: () => ( /* reexport safe */ N.matmul ), /* harmony export */ max: () => ( /* reexport safe */ y.max ), /* harmony export */ mean: () => ( /* reexport safe */ N.mean ), /* harmony export */ mean_pooling: () => ( /* reexport safe */ N.mean_pooling ), /* harmony export */ medianFilter: () => ( /* reexport safe */ y.medianFilter ), /* harmony export */ mel_filter_bank: () => ( /* reexport safe */ j.mel_filter_bank ), /* harmony export */ min: () => ( /* reexport safe */ y.min ), /* harmony export */ ones: () => ( /* reexport safe */ N.ones ), /* harmony export */ ones_like: () => ( /* reexport safe */ N.ones_like ), /* harmony export */ permute: () => ( /* reexport safe */ N.permute ), /* harmony export */ permute_data: () => ( /* reexport safe */ y.permute_data ), /* harmony export */ pipeline: () => ( /* reexport safe */ $.pipeline ), /* harmony export */ quantize_embeddings: () => ( /* reexport safe */ N.quantize_embeddings ), /* harmony export */ rand: () => ( /* reexport safe */ N.rand ), /* harmony export */ read_audio: () => ( /* reexport safe */ j.read_audio ), /* harmony export */ rfft: () => ( /* reexport safe */ N.rfft ), /* harmony export */ round: () => ( /* reexport safe */ y.round ), /* harmony export */ slice: () => ( /* reexport safe */ N.slice ), /* harmony export */ softmax: () => ( /* reexport safe */ y.softmax ), /* harmony export */ spectrogram: () => ( /* reexport safe */ j.spectrogram ), /* harmony export */ stack: () => ( /* reexport safe */ N.stack ), /* harmony export */ std_mean: () => ( /* reexport safe */ N.std_mean ), /* harmony export */ topk: () => ( /* reexport safe */ N.topk ), /* harmony export */ window_function: () => ( /* reexport safe */ j.window_function ), /* harmony export */ zeros: () => ( /* reexport safe */ N.zeros ), /* harmony export */ zeros_like: () => ( /* reexport safe */ N.zeros_like ) /* harmony export */ }); var Ie = ps( /*! ./env.js */ "./src/env.js" ), $ = ps( /*! ./pipelines.js */ "./src/pipelines.js" ), r = ps( /*! ./models.js */ "./src/models.js" ), g = ps( /*! ./tokenizers.js */ "./src/tokenizers.js" ), O = ps( /*! ./configs.js */ "./src/configs.js" ), j = ps( /*! ./utils/audio.js */ "./src/utils/audio.js" ), ee = ps( /*! ./utils/image.js */ "./src/utils/image.js" ), N = ps( /*! ./utils/tensor.js */ "./src/utils/tensor.js" ), y = ps( /*! ./utils/maths.js */ "./src/utils/maths.js" ), T = ps( /*! ./base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js" ), v = ps( /*! ./models/feature_extractors.js */ "./src/models/feature_extractors.js" ), b = ps( /*! ./models/auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js" ), x = ps( /*! ./base/image_processors_utils.js */ "./src/base/image_processors_utils.js" ), L = ps( /*! ./models/image_processors.js */ "./src/models/image_processors.js" ), K = ps( /*! ./models/auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js" ), re = ps( /*! ./base/processing_utils.js */ "./src/base/processing_utils.js" ), ie = ps( /*! ./models/processors.js */ "./src/models/processors.js" ), V = ps( /*! ./models/auto/processing_auto.js */ "./src/models/auto/processing_auto.js" ), U = ps( /*! ./generation/streamers.js */ "./src/generation/streamers.js" ), q = ps( /*! ./generation/stopping_criteria.js */ "./src/generation/stopping_criteria.js" ), A = ps( /*! ./generation/logits_process.js */ "./src/generation/logits_process.js" ); })(); d.ASTFeatureExtractor; d.ASTForAudioClassification; d.ASTModel; d.ASTPreTrainedModel; d.AlbertForMaskedLM; d.AlbertForQuestionAnswering; d.AlbertForSequenceClassification; d.AlbertModel; d.AlbertPreTrainedModel; d.AlbertTokenizer; d.AudioClassificationPipeline; d.AutoConfig; d.AutoFeatureExtractor; d.AutoImageProcessor; d.AutoModel; d.AutoModelForAudioClassification; d.AutoModelForAudioFrameClassification; d.AutoModelForCTC; d.AutoModelForCausalLM; d.AutoModelForDepthEstimation; d.AutoModelForDocumentQuestionAnswering; d.AutoModelForImageClassification; d.AutoModelForImageFeatureExtraction; d.AutoModelForImageMatting; d.AutoModelForImageSegmentation; d.AutoModelForImageToImage; d.AutoModelForMaskGeneration; d.AutoModelForMaskedLM; d.AutoModelForNormalEstimation; d.AutoModelForObjectDetection; d.AutoModelForPoseEstimation; d.AutoModelForQuestionAnswering; d.AutoModelForSemanticSegmentation; d.AutoModelForSeq2SeqLM; d.AutoModelForSequenceClassification; d.AutoModelForSpeechSeq2Seq; d.AutoModelForTextToSpectrogram; d.AutoModelForTextToWaveform; d.AutoModelForTokenClassification; d.AutoModelForUniversalSegmentation; d.AutoModelForVision2Seq; d.AutoModelForXVector; d.AutoModelForZeroShotObjectDetection; d.AutoProcessor; d.AutoTokenizer; d.AutomaticSpeechRecognitionPipeline; d.BartForConditionalGeneration; d.BartForSequenceClassification; d.BartModel; d.BartPretrainedModel; d.BartTokenizer; d.BaseModelOutput; d.BaseStreamer; d.BeitFeatureExtractor; d.BeitForImageClassification; d.BeitModel; d.BeitPreTrainedModel; d.BertForMaskedLM; d.BertForQuestionAnswering; d.BertForSequenceClassification; d.BertForTokenClassification; d.BertModel; d.BertPreTrainedModel; d.BertTokenizer; d.BitImageProcessor; d.BlenderbotForConditionalGeneration; d.BlenderbotModel; d.BlenderbotPreTrainedModel; d.BlenderbotSmallForConditionalGeneration; d.BlenderbotSmallModel; d.BlenderbotSmallPreTrainedModel; d.BlenderbotSmallTokenizer; d.BlenderbotTokenizer; d.BloomForCausalLM; d.BloomModel; d.BloomPreTrainedModel; d.BloomTokenizer; d.CLIPFeatureExtractor; d.CLIPImageProcessor; d.CLIPModel; d.CLIPPreTrainedModel; d.CLIPSegForImageSegmentation; d.CLIPSegModel; d.CLIPSegPreTrainedModel; d.CLIPTextModel; d.CLIPTextModelWithProjection; d.CLIPTokenizer; d.CLIPVisionModel; d.CLIPVisionModelWithProjection; d.CamembertForMaskedLM; d.CamembertForQuestionAnswering; d.CamembertForSequenceClassification; d.CamembertForTokenClassification; d.CamembertModel; d.CamembertPreTrainedModel; d.CamembertTokenizer; d.CausalLMOutput; d.CausalLMOutputWithPast; d.ChineseCLIPFeatureExtractor; d.ChineseCLIPModel; d.ChineseCLIPPreTrainedModel; d.ClapAudioModelWithProjection; d.ClapFeatureExtractor; d.ClapModel; d.ClapPreTrainedModel; d.ClapTextModelWithProjection; d.ClassifierFreeGuidanceLogitsProcessor; d.CodeGenForCausalLM; d.CodeGenModel; d.CodeGenPreTrainedModel; d.CodeGenTokenizer; d.CodeLlamaTokenizer; d.CohereForCausalLM; d.CohereModel; d.CoherePreTrainedModel; d.CohereTokenizer; d.ConvBertForMaskedLM; d.ConvBertForQuestionAnswering; d.ConvBertForSequenceClassification; d.ConvBertForTokenClassification; d.ConvBertModel; d.ConvBertPreTrainedModel; d.ConvBertTokenizer; d.ConvNextFeatureExtractor; d.ConvNextForImageClassification; d.ConvNextImageProcessor; d.ConvNextModel; d.ConvNextPreTrainedModel; d.ConvNextV2ForImageClassification; d.ConvNextV2Model; d.ConvNextV2PreTrainedModel; d.DPTFeatureExtractor; d.DPTForDepthEstimation; d.DPTImageProcessor; d.DPTModel; d.DPTPreTrainedModel; d.DebertaForMaskedLM; d.DebertaForQuestionAnswering; d.DebertaForSequenceClassification; d.DebertaForTokenClassification; d.DebertaModel; d.DebertaPreTrainedModel; d.DebertaTokenizer; d.DebertaV2ForMaskedLM; d.DebertaV2ForQuestionAnswering; d.DebertaV2ForSequenceClassification; d.DebertaV2ForTokenClassification; d.DebertaV2Model; d.DebertaV2PreTrainedModel; d.DebertaV2Tokenizer; d.DecisionTransformerModel; d.DecisionTransformerPreTrainedModel; d.DeiTFeatureExtractor; d.DeiTForImageClassification; d.DeiTImageProcessor; d.DeiTModel; d.DeiTPreTrainedModel; d.DepthAnythingForDepthEstimation; d.DepthAnythingPreTrainedModel; d.DepthEstimationPipeline; d.DepthProForDepthEstimation; d.DepthProPreTrainedModel; d.DetrFeatureExtractor; d.DetrForObjectDetection; d.DetrForSegmentation; d.DetrImageProcessor; d.DetrModel; d.DetrObjectDetectionOutput; d.DetrPreTrainedModel; d.DetrSegmentationOutput; d.Dinov2ForImageClassification; d.Dinov2Model; d.Dinov2PreTrainedModel; d.Dinov2WithRegistersForImageClassification; d.Dinov2WithRegistersModel; d.Dinov2WithRegistersPreTrainedModel; d.DistilBertForMaskedLM; d.DistilBertForQuestionAnswering; d.DistilBertForSequenceClassification; d.DistilBertForTokenClassification; d.DistilBertModel; d.DistilBertPreTrainedModel; d.DistilBertTokenizer; d.DocumentQuestionAnsweringPipeline; d.DonutFeatureExtractor; d.DonutImageProcessor; d.DonutSwinModel; d.DonutSwinPreTrainedModel; d.EfficientNetForImageClassification; d.EfficientNetImageProcessor; d.EfficientNetModel; d.EfficientNetPreTrainedModel; d.ElectraForMaskedLM; d.ElectraForQuestionAnswering; d.ElectraForSequenceClassification; d.ElectraForTokenClassification; d.ElectraModel; d.ElectraPreTrainedModel; d.ElectraTokenizer; d.EosTokenCriteria; d.EsmForMaskedLM; d.EsmForSequenceClassification; d.EsmForTokenClassification; d.EsmModel; d.EsmPreTrainedModel; d.EsmTokenizer; d.ExaoneForCausalLM; d.ExaoneModel; d.ExaonePreTrainedModel; d.FFT; d.FalconForCausalLM; d.FalconModel; d.FalconPreTrainedModel; d.FalconTokenizer; d.FastViTForImageClassification; d.FastViTModel; d.FastViTPreTrainedModel; d.FeatureExtractionPipeline; d.FeatureExtractor; d.FillMaskPipeline; d.Florence2ForConditionalGeneration; d.Florence2PreTrainedModel; d.Florence2Processor; d.ForcedBOSTokenLogitsProcessor; d.ForcedEOSTokenLogitsProcessor; d.GLPNFeatureExtractor; d.GLPNForDepthEstimation; d.GLPNModel; d.GLPNPreTrainedModel; d.GPT2LMHeadModel; d.GPT2Model; d.GPT2PreTrainedModel; d.GPT2Tokenizer; d.GPTBigCodeForCausalLM; d.GPTBigCodeModel; d.GPTBigCodePreTrainedModel; d.GPTJForCausalLM; d.GPTJModel; d.GPTJPreTrainedModel; d.GPTNeoForCausalLM; d.GPTNeoModel; d.GPTNeoPreTrainedModel; d.GPTNeoXForCausalLM; d.GPTNeoXModel; d.GPTNeoXPreTrainedModel; d.GPTNeoXTokenizer; d.Gemma2ForCausalLM; d.Gemma2Model; d.Gemma2PreTrainedModel; d.GemmaForCausalLM; d.GemmaModel; d.GemmaPreTrainedModel; d.GemmaTokenizer; d.GlmForCausalLM; d.GlmModel; d.GlmPreTrainedModel; d.GraniteForCausalLM; d.GraniteModel; d.GranitePreTrainedModel; d.Grok1Tokenizer; d.GroundingDinoForObjectDetection; d.GroundingDinoImageProcessor; d.GroundingDinoPreTrainedModel; d.GroundingDinoProcessor; d.GroupViTModel; d.GroupViTPreTrainedModel; d.HeliumForCausalLM; d.HeliumModel; d.HeliumPreTrainedModel; d.HerbertTokenizer; d.HieraForImageClassification; d.HieraModel; d.HieraPreTrainedModel; d.HubertForCTC; d.HubertForSequenceClassification; d.HubertModel; d.HubertPreTrainedModel; d.IJepaForImageClassification; d.IJepaModel; d.IJepaPreTrainedModel; d.Idefics3ForConditionalGeneration; d.Idefics3ImageProcessor; d.Idefics3PreTrainedModel; d.Idefics3Processor; d.ImageClassificationPipeline; d.ImageFeatureExtractionPipeline; d.ImageFeatureExtractor; d.ImageMattingOutput; d.ImageProcessor; d.ImageSegmentationPipeline; d.ImageToImagePipeline; d.ImageToTextPipeline; d.InterruptableStoppingCriteria; d.JAISLMHeadModel; d.JAISModel; d.JAISPreTrainedModel; d.JinaCLIPImageProcessor; d.JinaCLIPModel; d.JinaCLIPPreTrainedModel; d.JinaCLIPProcessor; d.JinaCLIPTextModel; d.JinaCLIPVisionModel; d.LlamaForCausalLM; d.LlamaModel; d.LlamaPreTrainedModel; d.LlamaTokenizer; d.LlavaForConditionalGeneration; d.LlavaOnevisionForConditionalGeneration; d.LlavaOnevisionImageProcessor; d.LlavaPreTrainedModel; d.LogitsProcessor; d.LogitsProcessorList; d.LogitsWarper; d.LongT5ForConditionalGeneration; d.LongT5Model; d.LongT5PreTrainedModel; d.M2M100ForConditionalGeneration; d.M2M100Model; d.M2M100PreTrainedModel; d.M2M100Tokenizer; d.MBart50Tokenizer; d.MBartForCausalLM; d.MBartForConditionalGeneration; d.MBartForSequenceClassification; d.MBartModel; d.MBartPreTrainedModel; d.MBartTokenizer; d.MPNetForMaskedLM; d.MPNetForQuestionAnswering; d.MPNetForSequenceClassification; d.MPNetForTokenClassification; d.MPNetModel; d.MPNetPreTrainedModel; d.MPNetTokenizer; d.MT5ForConditionalGeneration; d.MT5Model; d.MT5PreTrainedModel; d.MarianMTModel; d.MarianModel; d.MarianPreTrainedModel; d.MarianTokenizer; d.Mask2FormerImageProcessor; d.MaskFormerFeatureExtractor; d.MaskFormerForInstanceSegmentation; d.MaskFormerImageProcessor; d.MaskFormerModel; d.MaskFormerPreTrainedModel; d.MaskedLMOutput; d.MaxLengthCriteria; d.MgpstrForSceneTextRecognition; d.MgpstrModelOutput; d.MgpstrPreTrainedModel; d.MgpstrProcessor; d.MgpstrTokenizer; d.MinLengthLogitsProcessor; d.MinNewTokensLengthLogitsProcessor; d.MistralForCausalLM; d.MistralModel; d.MistralPreTrainedModel; d.MobileBertForMaskedLM; d.MobileBertForQuestionAnswering; d.MobileBertForSequenceClassification; d.MobileBertModel; d.MobileBertPreTrainedModel; d.MobileBertTokenizer; d.MobileLLMForCausalLM; d.MobileLLMModel; d.MobileLLMPreTrainedModel; d.MobileNetV1FeatureExtractor; d.MobileNetV1ForImageClassification; d.MobileNetV1ImageProcessor; d.MobileNetV1Model; d.MobileNetV1PreTrainedModel; d.MobileNetV2FeatureExtractor; d.MobileNetV2ForImageClassification; d.MobileNetV2ImageProcessor; d.MobileNetV2Model; d.MobileNetV2PreTrainedModel; d.MobileNetV3FeatureExtractor; d.MobileNetV3ForImageClassification; d.MobileNetV3ImageProcessor; d.MobileNetV3Model; d.MobileNetV3PreTrainedModel; d.MobileNetV4FeatureExtractor; d.MobileNetV4ForImageClassification; d.MobileNetV4ImageProcessor; d.MobileNetV4Model; d.MobileNetV4PreTrainedModel; d.MobileViTFeatureExtractor; d.MobileViTForImageClassification; d.MobileViTImageProcessor; d.MobileViTModel; d.MobileViTPreTrainedModel; d.MobileViTV2ForImageClassification; d.MobileViTV2Model; d.MobileViTV2PreTrainedModel; d.ModelOutput; d.ModernBertForMaskedLM; d.ModernBertForSequenceClassification; d.ModernBertForTokenClassification; d.ModernBertModel; d.ModernBertPreTrainedModel; d.Moondream1ForConditionalGeneration; d.MoonshineFeatureExtractor; d.MoonshineForConditionalGeneration; d.MoonshineModel; d.MoonshinePreTrainedModel; d.MoonshineProcessor; d.MptForCausalLM; d.MptModel; d.MptPreTrainedModel; d.MultiModalityCausalLM; d.MultiModalityPreTrainedModel; d.MusicgenForCausalLM; d.MusicgenForConditionalGeneration; d.MusicgenModel; d.MusicgenPreTrainedModel; d.NllbTokenizer; d.NoBadWordsLogitsProcessor; d.NoRepeatNGramLogitsProcessor; d.NomicBertModel; d.NomicBertPreTrainedModel; d.NougatImageProcessor; d.NougatTokenizer; d.OPTForCausalLM; d.OPTModel; d.OPTPreTrainedModel; d.ObjectDetectionPipeline; d.Olmo2ForCausalLM; d.Olmo2Model; d.Olmo2PreTrainedModel; d.OlmoForCausalLM; d.OlmoModel; d.OlmoPreTrainedModel; d.OpenELMForCausalLM; d.OpenELMModel; d.OpenELMPreTrainedModel; d.OwlViTFeatureExtractor; d.OwlViTForObjectDetection; d.OwlViTImageProcessor; d.OwlViTModel; d.OwlViTPreTrainedModel; d.OwlViTProcessor; d.Owlv2ForObjectDetection; d.Owlv2ImageProcessor; d.Owlv2Model; d.Owlv2PreTrainedModel; d.PaliGemmaForConditionalGeneration; d.PaliGemmaPreTrainedModel; d.PaliGemmaProcessor; d.PatchTSMixerForPrediction; d.PatchTSMixerModel; d.PatchTSMixerPreTrainedModel; d.PatchTSTForPrediction; d.PatchTSTModel; d.PatchTSTPreTrainedModel; d.Phi3ForCausalLM; d.Phi3Model; d.Phi3PreTrainedModel; d.Phi3VForCausalLM; d.Phi3VImageProcessor; d.Phi3VPreTrainedModel; d.Phi3VProcessor; d.PhiForCausalLM; d.PhiModel; d.PhiPreTrainedModel; d.Pipeline; d.PreTrainedModel; d.PreTrainedTokenizer; d.PretrainedConfig; d.PretrainedMixin; d.Processor; d.PvtForImageClassification; d.PvtImageProcessor; d.PvtModel; d.PvtPreTrainedModel; d.PyAnnoteFeatureExtractor; d.PyAnnoteForAudioFrameClassification; d.PyAnnoteModel; d.PyAnnotePreTrainedModel; d.PyAnnoteProcessor; d.QuestionAnsweringModelOutput; d.QuestionAnsweringPipeline; d.Qwen2ForCausalLM; d.Qwen2Model; d.Qwen2PreTrainedModel; d.Qwen2Tokenizer; d.Qwen2VLForConditionalGeneration; d.Qwen2VLImageProcessor; d.Qwen2VLPreTrainedModel; d.Qwen2VLProcessor; d.RTDetrForObjectDetection; d.RTDetrImageProcessor; d.RTDetrModel; d.RTDetrObjectDetectionOutput; d.RTDetrPreTrainedModel; d.RawAudio; d.RawImage; d.RepetitionPenaltyLogitsProcessor; d.ResNetForImageClassification; d.ResNetModel; d.ResNetPreTrainedModel; d.RoFormerForMaskedLM; d.RoFormerForQuestionAnswering; d.RoFormerForSequenceClassification; d.RoFormerForTokenClassification; d.RoFormerModel; d.RoFormerPreTrainedModel; d.RoFormerTokenizer; d.RobertaForMaskedLM; d.RobertaForQuestionAnswering; d.RobertaForSequenceClassification; d.RobertaForTokenClassification; d.RobertaModel; d.RobertaPreTrainedModel; d.RobertaTokenizer; d.SamImageProcessor; d.SamImageSegmentationOutput; d.SamModel; d.SamPreTrainedModel; d.SamProcessor; d.SapiensForDepthEstimation; d.SapiensForNormalEstimation; d.SapiensForSemanticSegmentation; d.SapiensPreTrainedModel; d.SeamlessM4TFeatureExtractor; d.SegformerFeatureExtractor; d.SegformerForImageClassification; d.SegformerForSemanticSegmentation; d.SegformerImageProcessor; d.SegformerModel; d.SegformerPreTrainedModel; d.Seq2SeqLMOutput; d.SequenceClassifierOutput; d.SiglipImageProcessor; d.SiglipModel; d.SiglipPreTrainedModel; d.SiglipTextModel; d.SiglipTokenizer; d.SiglipVisionModel; d.SpeechT5FeatureExtractor; d.SpeechT5ForSpeechToText; d.SpeechT5ForTextToSpeech; d.SpeechT5HifiGan; d.SpeechT5Model; d.SpeechT5PreTrainedModel; d.SpeechT5Processor; d.SpeechT5Tokenizer; d.SqueezeBertForMaskedLM; d.SqueezeBertForQuestionAnswering; d.SqueezeBertForSequenceClassification; d.SqueezeBertModel; d.SqueezeBertPreTrainedModel; d.SqueezeBertTokenizer; d.StableLmForCausalLM; d.StableLmModel; d.StableLmPreTrainedModel; d.Starcoder2ForCausalLM; d.Starcoder2Model; d.Starcoder2PreTrainedModel; d.StoppingCriteria; d.StoppingCriteriaList; d.StyleTextToSpeech2Model; d.StyleTextToSpeech2PreTrainedModel; d.SummarizationPipeline; d.SuppressTokensAtBeginLogitsProcessor; d.Swin2SRForImageSuperResolution; d.Swin2SRImageProcessor; d.Swin2SRModel; d.Swin2SRPreTrainedModel; d.SwinForImageClassification; d.SwinModel; d.SwinPreTrainedModel; d.T5ForConditionalGeneration; d.T5Model; d.T5PreTrainedModel; d.T5Tokenizer; d.TableTransformerForObjectDetection; d.TableTransformerModel; d.TableTransformerObjectDetectionOutput; d.TableTransformerPreTrainedModel; d.TemperatureLogitsWarper; d.Tensor; d.Text2TextGenerationPipeline; d.TextClassificationPipeline; d.TextGenerationPipeline; d.TextStreamer; d.TextToAudioPipeline; d.TokenClassificationPipeline; d.TokenClassifierOutput; d.TokenizerModel; d.TopKLogitsWarper; d.TopPLogitsWarper; d.TrOCRForCausalLM; d.TrOCRPreTrainedModel; d.TranslationPipeline; d.UniSpeechForCTC; d.UniSpeechForSequenceClassification; d.UniSpeechModel; d.UniSpeechPreTrainedModel; d.UniSpeechSatForAudioFrameClassification; d.UniSpeechSatForCTC; d.UniSpeechSatForSequenceClassification; d.UniSpeechSatModel; d.UniSpeechSatPreTrainedModel; d.VLChatProcessor; d.VLMImageProcessor; d.ViTFeatureExtractor; d.ViTForImageClassification; d.ViTImageProcessor; d.ViTMAEModel; d.ViTMAEPreTrainedModel; d.ViTMSNForImageClassification; d.ViTMSNModel; d.ViTMSNPreTrainedModel; d.ViTModel; d.ViTPreTrainedModel; d.VisionEncoderDecoderModel; d.VitMatteForImageMatting; d.VitMatteImageProcessor; d.VitMattePreTrainedModel; d.VitPoseForPoseEstimation; d.VitPoseImageProcessor; d.VitPosePreTrainedModel; d.VitsModel; d.VitsModelOutput; d.VitsPreTrainedModel; d.VitsTokenizer; d.Wav2Vec2BertForCTC; d.Wav2Vec2BertForSequenceClassification; d.Wav2Vec2BertModel; d.Wav2Vec2BertPreTrainedModel; d.Wav2Vec2CTCTokenizer; d.Wav2Vec2FeatureExtractor; d.Wav2Vec2ForAudioFrameClassification; d.Wav2Vec2ForCTC; d.Wav2Vec2ForSequenceClassification; d.Wav2Vec2Model; d.Wav2Vec2PreTrainedModel; d.Wav2Vec2Processor; d.Wav2Vec2ProcessorWithLM; d.WavLMForAudioFrameClassification; d.WavLMForCTC; d.WavLMForSequenceClassification; d.WavLMForXVector; d.WavLMModel; d.WavLMPreTrainedModel; d.WeSpeakerFeatureExtractor; d.WeSpeakerResNetModel; d.WeSpeakerResNetPreTrainedModel; d.WhisperFeatureExtractor; d.WhisperForConditionalGeneration; d.WhisperModel; d.WhisperPreTrainedModel; d.WhisperProcessor; d.WhisperTextStreamer; d.WhisperTimeStampLogitsProcessor; d.WhisperTokenizer; d.XLMForQuestionAnswering; d.XLMForSequenceClassification; d.XLMForTokenClassification; d.XLMModel; d.XLMPreTrainedModel; d.XLMRobertaForMaskedLM; d.XLMRobertaForQuestionAnswering; d.XLMRobertaForSequenceClassification; d.XLMRobertaForTokenClassification; d.XLMRobertaModel; d.XLMRobertaPreTrainedModel; d.XLMRobertaTokenizer; d.XLMTokenizer; d.XLMWithLMHeadModel; d.XVectorOutput; d.YolosFeatureExtractor; d.YolosForObjectDetection; d.YolosImageProcessor; d.YolosModel; d.YolosObjectDetectionOutput; d.YolosPreTrainedModel; d.ZeroShotAudioClassificationPipeline; d.ZeroShotClassificationPipeline; d.ZeroShotImageClassificationPipeline; d.ZeroShotObjectDetectionPipeline; d.bankers_round; d.cat; d.cos_sim; d.dot; d.dynamic_time_warping; d.env; d.full; d.full_like; d.getKeyValueShapes; d.hamming; d.hanning; d.interpolate; d.interpolate_4d; d.interpolate_data; d.is_chinese_char; d.layer_norm; d.load_image; d.log_softmax; d.magnitude; d.matmul; d.max; d.mean; d.mean_pooling; d.medianFilter; d.mel_filter_bank; d.min; d.ones; d.ones_like; d.permute; d.permute_data; var vf = d.pipeline; d.quantize_embeddings; d.rand; d.read_audio; d.rfft; d.round; d.slice; d.softmax; d.spectrogram; d.stack; d.std_mean; d.topk; d.window_function; d.zeros; d.zeros_like; class xf { #t = null; #s = null; #e = null; constructor({ task: $ = "text-classification", model: r = "Cohee/distilbert-base-uncased-go-emotions-onnx" } = {}) { this.#t = $, this.#s = r; } destroy() { this.#e = null; } async loadPipeline() { return this.#e || (this.#e = await vf(this.#t, this.#s)), Promise.resolve(this.#e); } async generate($) { return this.loadPipeline().then(async (r) => r($)).then((r) => r[0]); } } let Op = null; self.onmessage = ({ data: { type: Ie, data: $ } }) => { switch (Ie) { case "constructor": Op = new xf($ || {}); break; case "destroy": Op.destroy(); break; case "loadPipeline": Op.loadPipeline(...$ || []).then(() => self.postMessage(null)); break; case "generate": Op.generate(...$ || []).then(self.postMessage); break; default: throw new Error("Unknown type " + Ie); } };