diff --git "a/assets/worker-Dx_8b-Xw.js" "b/assets/worker-Dx_8b-Xw.js" new file mode 100644--- /dev/null +++ "b/assets/worker-Dx_8b-Xw.js" @@ -0,0 +1,2593 @@ +var Fm=Object.defineProperty;var Om=(wn,ns,js)=>ns in wn?Fm(wn,ns,{enumerable:!0,configurable:!0,writable:!0,value:js}):wn[ns]=js;var xe=(wn,ns,js)=>Om(wn,typeof ns!="symbol"?ns+"":ns,js);(function(){"use strict";var wn={},ns={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":($t,me,l)=>{$t.exports=l.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":($t,me,l)=>{l.r(me),l.d(me,{Environment:()=>Xe,Interpreter:()=>lt,Template:()=>vt,parse:()=>Ee,tokenize:()=>P});var x=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",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",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"}),X=Object.freeze({set:x.Set,for:x.For,in:x.In,is:x.Is,if:x.If,else:x.Else,endif:x.EndIf,elif:x.ElseIf,endfor:x.EndFor,and:x.And,or:x.Or,not:x.Not,"not in":x.NotIn,macro:x.Macro,endmacro:x.EndMacro,true:x.BooleanLiteral,false:x.BooleanLiteral,True:x.BooleanLiteral,False:x.BooleanLiteral}),ye=class{constructor(M,W){this.value=M,this.type=W}};function ve(M){return/\w/.test(M)}function Te(M){return/[0-9]/.test(M)}var B=[["{%",x.OpenStatement],["%}",x.CloseStatement],["{{",x.OpenExpression],["}}",x.CloseExpression],["(",x.OpenParen],[")",x.CloseParen],["{",x.OpenCurlyBracket],["}",x.CloseCurlyBracket],["[",x.OpenSquareBracket],["]",x.CloseSquareBracket],[",",x.Comma],[".",x.Dot],[":",x.Colon],["|",x.Pipe],["<=",x.ComparisonBinaryOperator],[">=",x.ComparisonBinaryOperator],["==",x.ComparisonBinaryOperator],["!=",x.ComparisonBinaryOperator],["<",x.ComparisonBinaryOperator],[">",x.ComparisonBinaryOperator],["+",x.AdditiveBinaryOperator],["-",x.AdditiveBinaryOperator],["*",x.MultiplicativeBinaryOperator],["/",x.MultiplicativeBinaryOperator],["%",x.MultiplicativeBinaryOperator],["=",x.Equals]],E=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function N(M,W={}){return M.endsWith(` +`)&&(M=M.slice(0,-1)),M=M.replace(/{#.*?#}/gs,"{##}"),W.lstrip_blocks&&(M=M.replace(/^[ \t]*({[#%])/gm,"$1")),W.trim_blocks&&(M=M.replace(/([#%]})\n/g,"$1")),M.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(M,W={}){var et,At,mt;const S=[],Q=N(M,W);let he=0;const Ye=Se=>{let C="";for(;Se(Q[he]);){if(Q[he]==="\\"){if(++he,he>=Q.length)throw new SyntaxError("Unexpected end of input");const K=Q[he++],we=E.get(K);if(we===void 0)throw new SyntaxError(`Unexpected escaped character: ${K}`);C+=we;continue}if(C+=Q[he++],he>=Q.length)throw new SyntaxError("Unexpected end of input")}return C};e:for(;he0){S.push(new ye(K,x.Text));continue}}Ye(K=>/\s/.test(K));const C=Q[he];if(C==="-"||C==="+"){const K=(At=S.at(-1))==null?void 0:At.type;if(K===x.Text||K===void 0)throw new SyntaxError(`Unexpected character: ${C}`);switch(K){case x.Identifier:case x.NumericLiteral:case x.BooleanLiteral:case x.StringLiteral:case x.CloseParen:case x.CloseSquareBracket:break;default:{++he;const we=Ye(Te);S.push(new ye(`${C}${we}`,we.length>0?x.NumericLiteral:x.UnaryOperator));continue}}}for(const[K,we]of B)if(Q.slice(he,he+K.length)===K){S.push(new ye(K,we)),he+=K.length;continue e}if(C==="'"||C==='"'){++he;const K=Ye(we=>we!==C);S.push(new ye(K,x.StringLiteral)),++he;continue}if(Te(C)){const K=Ye(Te);S.push(new ye(K,x.NumericLiteral));continue}if(ve(C)){const K=Ye(ve),we=Object.hasOwn(X,K)?X[K]:x.Identifier;we===x.In&&((mt=S.at(-1))==null?void 0:mt.type)===x.Not?(S.pop(),S.push(new ye("not in",x.NotIn))):S.push(new ye(K,we));continue}throw new SyntaxError(`Unexpected character: ${C}`)}return S}var te=class{constructor(){xe(this,"type","Statement")}},J=class extends te{constructor(W){super();xe(this,"type","Program");this.body=W}},se=class extends te{constructor(W,S,Q){super();xe(this,"type","If");this.test=W,this.body=S,this.alternate=Q}},ae=class extends te{constructor(W,S,Q,he){super();xe(this,"type","For");this.loopvar=W,this.iterable=S,this.body=Q,this.defaultBlock=he}},D=class extends te{constructor(W,S){super();xe(this,"type","Set");this.assignee=W,this.value=S}},ee=class extends te{constructor(W,S,Q){super();xe(this,"type","Macro");this.name=W,this.args=S,this.body=Q}},G=class extends te{constructor(){super(...arguments);xe(this,"type","Expression")}},ie=class extends G{constructor(W,S,Q){super();xe(this,"type","MemberExpression");this.object=W,this.property=S,this.computed=Q}},fe=class extends G{constructor(W,S){super();xe(this,"type","CallExpression");this.callee=W,this.args=S}},L=class extends G{constructor(W){super();xe(this,"type","Identifier");this.value=W}},O=class extends G{constructor(W){super();xe(this,"type","Literal");this.value=W}},j=class extends O{constructor(){super(...arguments);xe(this,"type","NumericLiteral")}},A=class extends O{constructor(){super(...arguments);xe(this,"type","StringLiteral")}},ge=class extends O{constructor(){super(...arguments);xe(this,"type","BooleanLiteral")}},be=class extends O{constructor(){super(...arguments);xe(this,"type","ArrayLiteral")}},Ce=class extends O{constructor(){super(...arguments);xe(this,"type","TupleLiteral")}},ke=class extends O{constructor(){super(...arguments);xe(this,"type","ObjectLiteral")}},De=class extends G{constructor(W,S,Q){super();xe(this,"type","BinaryExpression");this.operator=W,this.left=S,this.right=Q}},Je=class extends G{constructor(W,S){super();xe(this,"type","FilterExpression");this.operand=W,this.filter=S}},Ue=class extends G{constructor(W,S){super();xe(this,"type","SelectExpression");this.iterable=W,this.test=S}},bt=class extends G{constructor(W,S,Q){super();xe(this,"type","TestExpression");this.operand=W,this.negate=S,this.test=Q}},_e=class extends G{constructor(W,S){super();xe(this,"type","UnaryExpression");this.operator=W,this.argument=S}},V=class extends G{constructor(W=void 0,S=void 0,Q=void 0){super();xe(this,"type","SliceExpression");this.start=W,this.stop=S,this.step=Q}},pe=class extends G{constructor(W,S){super();xe(this,"type","KeywordArgumentExpression");this.key=W,this.value=S}};function Ee(M){const W=new J([]);let S=0;function Q(Ze,Et){const Bt=M[S++];if(!Bt||Bt.type!==Ze)throw new Error(`Parser Error: ${Et}. ${Bt.type} !== ${Ze}.`);return Bt}function he(){switch(M[S].type){case x.Text:return At();case x.OpenStatement:return mt();case x.OpenExpression:return Se();default:throw new SyntaxError(`Unexpected token type: ${M[S].type}`)}}function Ye(...Ze){return S+Ze.length<=M.length&&Ze.some((Et,Bt)=>Et!==M[S+Bt].type)}function et(...Ze){return S+Ze.length<=M.length&&Ze.every((Et,Bt)=>Et===M[S+Bt].type)}function At(){return new A(Q(x.Text,"Expected text token").value)}function mt(){Q(x.OpenStatement,"Expected opening statement token");let Ze;switch(M[S].type){case x.Set:++S,Ze=C(),Q(x.CloseStatement,"Expected closing statement token");break;case x.If:++S,Ze=K(),Q(x.OpenStatement,"Expected {% token"),Q(x.EndIf,"Expected endif token"),Q(x.CloseStatement,"Expected %} token");break;case x.Macro:++S,Ze=we(),Q(x.OpenStatement,"Expected {% token"),Q(x.EndMacro,"Expected endmacro token"),Q(x.CloseStatement,"Expected %} token");break;case x.For:++S,Ze=Ae(),Q(x.OpenStatement,"Expected {% token"),Q(x.EndFor,"Expected endfor token"),Q(x.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${M[S].type}`)}return Ze}function Se(){Q(x.OpenExpression,"Expected opening expression token");const Ze=Ne();return Q(x.CloseExpression,"Expected closing expression token"),Ze}function C(){const Ze=Ne();if(et(x.Equals)){++S;const Et=C();return new D(Ze,Et)}return Ze}function K(){var qr,Un,Fn,Lr,Zr,Nr,Sn,Pr;const Ze=Ne();Q(x.CloseStatement,"Expected closing statement token");const Et=[],Bt=[];for(;!(((qr=M[S])==null?void 0:qr.type)===x.OpenStatement&&(((Un=M[S+1])==null?void 0:Un.type)===x.ElseIf||((Fn=M[S+1])==null?void 0:Fn.type)===x.Else||((Lr=M[S+1])==null?void 0:Lr.type)===x.EndIf));)Et.push(he());if(((Zr=M[S])==null?void 0:Zr.type)===x.OpenStatement&&((Nr=M[S+1])==null?void 0:Nr.type)!==x.EndIf)if(++S,et(x.ElseIf))Q(x.ElseIf,"Expected elseif token"),Bt.push(K());else for(Q(x.Else,"Expected else token"),Q(x.CloseStatement,"Expected closing statement token");!(((Sn=M[S])==null?void 0:Sn.type)===x.OpenStatement&&((Pr=M[S+1])==null?void 0:Pr.type)===x.EndIf);)Bt.push(he());return new se(Ze,Et,Bt)}function we(){const Ze=Cr();if(Ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Et=Nt();Q(x.CloseStatement,"Expected closing statement token");const Bt=[];for(;Ye(x.OpenStatement,x.EndMacro);)Bt.push(he());return new ee(Ze,Et,Bt)}function Be(Ze=!1){const Et=Ze?Cr:Ne,Bt=[Et()],qr=et(x.Comma);for(;qr&&(++S,Bt.push(Et()),!!et(x.Comma)););return qr?new Ce(Bt):Bt[0]}function Ae(){const Ze=Be(!0);if(!(Ze instanceof L||Ze instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ze.type} instead`);Q(x.In,"Expected `in` keyword following loop variable");const Et=Ne();Q(x.CloseStatement,"Expected closing statement token");const Bt=[];for(;Ye(x.OpenStatement,x.EndFor)&&Ye(x.OpenStatement,x.Else);)Bt.push(he());const qr=[];if(et(x.OpenStatement,x.Else))for(++S,++S,Q(x.CloseStatement,"Expected closing statement token");Ye(x.OpenStatement,x.EndFor);)qr.push(he());return new ae(Ze,Et,Bt,qr)}function Ne(){return ut()}function ut(){const Ze=nt();if(et(x.If)){++S;const Et=nt();if(et(x.Else)){++S;const Bt=nt();return new se(Et,[Ze],[Bt])}else return new Ue(Ze,Et)}return Ze}function nt(){let Ze=Mt();for(;et(x.Or);){const Et=M[S];++S;const Bt=Mt();Ze=new De(Et,Ze,Bt)}return Ze}function Mt(){let Ze=ht();for(;et(x.And);){const Et=M[S];++S;const Bt=ht();Ze=new De(Et,Ze,Bt)}return Ze}function ht(){let Ze;for(;et(x.Not);){const Et=M[S];++S;const Bt=ht();Ze=new _e(Et,Bt)}return Ze??Tt()}function Tt(){let Ze=Rt();for(;et(x.ComparisonBinaryOperator)||et(x.In)||et(x.NotIn);){const Et=M[S];++S;const Bt=Rt();Ze=new De(Et,Ze,Bt)}return Ze}function Rt(){let Ze=Wt();for(;et(x.AdditiveBinaryOperator);){const Et=M[S];++S;const Bt=Wt();Ze=new De(Et,Ze,Bt)}return Ze}function Qe(){const Ze=er();return et(x.OpenParen)?Vt(Ze):Ze}function Vt(Ze){let Et=new fe(Ze,Nt());return et(x.OpenParen)&&(Et=Vt(Et)),Et}function Nt(){Q(x.OpenParen,"Expected opening parenthesis for arguments list");const Ze=Ht();return Q(x.CloseParen,"Expected closing parenthesis for arguments list"),Ze}function Ht(){const Ze=[];for(;!et(x.CloseParen);){let Et=Ne();if(et(x.Equals)){if(++S,!(Et instanceof L))throw new SyntaxError("Expected identifier for keyword argument");const Bt=Ne();Et=new pe(Et,Bt)}Ze.push(Et),et(x.Comma)&&++S}return Ze}function Xt(){const Ze=[];let Et=!1;for(;!et(x.CloseSquareBracket);)et(x.Colon)?(Ze.push(void 0),++S,Et=!0):(Ze.push(Ne()),et(x.Colon)&&(++S,Et=!0));if(Ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Et){if(Ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new V(...Ze)}return Ze[0]}function er(){let Ze=Cr();for(;et(x.Dot)||et(x.OpenSquareBracket);){const Et=M[S];++S;let Bt;const qr=Et.type!==x.Dot;if(qr)Bt=Xt(),Q(x.CloseSquareBracket,"Expected closing square bracket");else if(Bt=Cr(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ze=new ie(Ze,Bt,qr)}return Ze}function Wt(){let Ze=Tr();for(;et(x.MultiplicativeBinaryOperator);){const Et=M[S];++S;const Bt=Tr();Ze=new De(Et,Ze,Bt)}return Ze}function Tr(){let Ze=Ur();for(;et(x.Is);){++S;const Et=et(x.Not);Et&&++S;let Bt=Cr();if(Bt instanceof ge&&(Bt=new L(Bt.value.toString())),!(Bt instanceof L))throw new SyntaxError("Expected identifier for the test");Ze=new bt(Ze,Et,Bt)}return Ze}function Ur(){let Ze=Qe();for(;et(x.Pipe);){++S;let Et=Cr();if(!(Et instanceof L))throw new SyntaxError("Expected identifier for the filter");et(x.OpenParen)&&(Et=Vt(Et)),Ze=new Je(Ze,Et)}return Ze}function Cr(){const Ze=M[S];switch(Ze.type){case x.NumericLiteral:return++S,new j(Number(Ze.value));case x.StringLiteral:return++S,new A(Ze.value);case x.BooleanLiteral:return++S,new ge(Ze.value.toLowerCase()==="true");case x.Identifier:return++S,new L(Ze.value);case x.OpenParen:{++S;const Et=Be();if(M[S].type!==x.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${M[S].type} instead`);return++S,Et}case x.OpenSquareBracket:{++S;const Et=[];for(;!et(x.CloseSquareBracket);)Et.push(Ne()),et(x.Comma)&&++S;return++S,new be(Et)}case x.OpenCurlyBracket:{++S;const Et=new Map;for(;!et(x.CloseCurlyBracket);){const Bt=Ne();Q(x.Colon,"Expected colon between key and value in object literal");const qr=Ne();Et.set(Bt,qr),et(x.Comma)&&++S}return++S,new ke(Et)}default:throw new SyntaxError(`Unexpected token: ${Ze.type}`)}}for(;S=0?(W=(W??(W=0))<0?Math.max(M.length+W,0):Math.min(W,M.length),S=(S??(S=M.length))<0?Math.max(M.length+S,0):Math.min(S,M.length)):(W=(W??(W=M.length-1))<0?Math.max(M.length+W,-1):Math.min(W,M.length-1),S=(S??(S=-1))<-1?Math.max(M.length+S,-1):Math.min(S,M.length-1));const Ye=[];for(let et=W;he*etW.toUpperCase())}var rt=class{constructor(M=void 0){xe(this,"type","RuntimeValue");xe(this,"value");xe(this,"builtins",new Map);this.value=M}__bool__(){return new st(!!this.value)}},ot=class extends rt{constructor(){super(...arguments);xe(this,"type","NumericValue")}},Re=class extends rt{constructor(){super(...arguments);xe(this,"type","StringValue");xe(this,"builtins",new Map([["upper",new je(()=>new Re(this.value.toUpperCase()))],["lower",new je(()=>new Re(this.value.toLowerCase()))],["strip",new je(()=>new Re(this.value.trim()))],["title",new je(()=>new Re(ct(this.value)))],["length",new ot(this.value.length)]]))}},st=class extends rt{constructor(){super(...arguments);xe(this,"type","BooleanValue")}},xt=class extends rt{constructor(){super(...arguments);xe(this,"type","ObjectValue");xe(this,"builtins",new Map([["get",new je(([W,S])=>{if(!(W instanceof Re))throw new Error(`Object key must be a string: got ${W.type}`);return this.value.get(W.value)??S??new qe})],["items",new je(()=>new ne(Array.from(this.value.entries()).map(([W,S])=>new ne([new Re(W),S]))))]]))}__bool__(){return new st(this.value.size>0)}},ze=class extends xt{constructor(){super(...arguments);xe(this,"type","KeywordArgumentsValue")}},ne=class extends rt{constructor(){super(...arguments);xe(this,"type","ArrayValue");xe(this,"builtins",new Map([["length",new ot(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},$e=class extends ne{constructor(){super(...arguments);xe(this,"type","TupleValue")}},je=class extends rt{constructor(){super(...arguments);xe(this,"type","FunctionValue")}},qe=class extends rt{constructor(){super(...arguments);xe(this,"type","NullValue")}},Ve=class extends rt{constructor(){super(...arguments);xe(this,"type","UndefinedValue")}},Xe=class{constructor(M){xe(this,"variables",new Map([["namespace",new je(M=>{if(M.length===0)return new xt(new Map);if(M.length!==1||!(M[0]instanceof xt))throw new Error("`namespace` expects either zero arguments or a single object argument");return M[0]})]]));xe(this,"tests",new Map([["boolean",M=>M.type==="BooleanValue"],["callable",M=>M instanceof je],["odd",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${M.type}`);return M.value%2!==0}],["even",M=>{if(M.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${M.type}`);return M.value%2===0}],["false",M=>M.type==="BooleanValue"&&!M.value],["true",M=>M.type==="BooleanValue"&&M.value],["string",M=>M.type==="StringValue"],["number",M=>M.type==="NumericValue"],["integer",M=>M.type==="NumericValue"&&Number.isInteger(M.value)],["iterable",M=>M instanceof ne||M instanceof Re],["lower",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toLowerCase()}],["upper",M=>{const W=M.value;return M.type==="StringValue"&&W===W.toUpperCase()}],["none",M=>M.type==="NullValue"],["defined",M=>M.type!=="UndefinedValue"],["undefined",M=>M.type==="UndefinedValue"],["equalto",(M,W)=>M.value===W.value],["eq",(M,W)=>M.value===W.value]]));this.parent=M}set(M,W){return this.declareVariable(M,ft(W))}declareVariable(M,W){if(this.variables.has(M))throw new SyntaxError(`Variable already declared: ${M}`);return this.variables.set(M,W),W}setVariable(M,W){return this.variables.set(M,W),W}resolve(M){if(this.variables.has(M))return this;if(this.parent)return this.parent.resolve(M);throw new Error(`Unknown variable: ${M}`)}lookupVariable(M){try{return this.resolve(M).variables.get(M)??new Ve}catch{return new Ve}}},lt=class{constructor(M){xe(this,"global");this.global=M??new Xe}run(M){return this.evaluate(M,this.global)}evaluateBinaryExpression(M,W){const S=this.evaluate(M.left,W);switch(M.operator.value){case"and":return S.__bool__().value?this.evaluate(M.right,W):S;case"or":return S.__bool__().value?S:this.evaluate(M.right,W)}const Q=this.evaluate(M.right,W);switch(M.operator.value){case"==":return new st(S.value==Q.value);case"!=":return new st(S.value!=Q.value)}if(S instanceof Ve||Q instanceof Ve)throw new Error("Cannot perform operation on undefined values");if(S instanceof qe||Q instanceof qe)throw new Error("Cannot perform operation on null values");if(S instanceof ot&&Q instanceof ot)switch(M.operator.value){case"+":return new ot(S.value+Q.value);case"-":return new ot(S.value-Q.value);case"*":return new ot(S.value*Q.value);case"/":return new ot(S.value/Q.value);case"%":return new ot(S.value%Q.value);case"<":return new st(S.value":return new st(S.value>Q.value);case">=":return new st(S.value>=Q.value);case"<=":return new st(S.value<=Q.value)}else if(S instanceof ne&&Q instanceof ne)switch(M.operator.value){case"+":return new ne(S.value.concat(Q.value))}else if(Q instanceof ne){const he=Q.value.find(Ye=>Ye.value===S.value)!==void 0;switch(M.operator.value){case"in":return new st(he);case"not in":return new st(!he)}}if(S instanceof Re||Q instanceof Re)switch(M.operator.value){case"+":return new Re(S.value.toString()+Q.value.toString())}if(S instanceof Re&&Q instanceof Re)switch(M.operator.value){case"in":return new st(Q.value.includes(S.value));case"not in":return new st(!Q.value.includes(S.value))}if(S instanceof Re&&Q instanceof xt)switch(M.operator.value){case"in":return new st(Q.value.has(S.value));case"not in":return new st(!Q.value.has(S.value))}throw new SyntaxError(`Unknown operator "${M.operator.value}" between ${S.type} and ${Q.type}`)}evaluateArguments(M,W){const S=[],Q=new Map;for(const he of M)if(he.type==="KeywordArgumentExpression"){const Ye=he;Q.set(Ye.key.value,this.evaluate(Ye.value,W))}else{if(Q.size>0)throw new Error("Positional arguments must come before keyword arguments");S.push(this.evaluate(he,W))}return[S,Q]}evaluateFilterExpression(M,W){const S=this.evaluate(M.operand,W);if(M.filter.type==="Identifier"){const Q=M.filter;if(Q.value==="tojson")return new Re(gt(S));if(S instanceof ne)switch(Q.value){case"list":return S;case"first":return S.value[0];case"last":return S.value[S.value.length-1];case"length":return new ot(S.value.length);case"reverse":return new ne(S.value.reverse());case"sort":return new ne(S.value.sort((he,Ye)=>{if(he.type!==Ye.type)throw new Error(`Cannot compare different types: ${he.type} and ${Ye.type}`);switch(he.type){case"NumericValue":return he.value-Ye.value;case"StringValue":return he.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Q.value}`)}else if(S instanceof Re)switch(Q.value){case"length":return new ot(S.value.length);case"upper":return new Re(S.value.toUpperCase());case"lower":return new Re(S.value.toLowerCase());case"title":return new Re(ct(S.value));case"capitalize":return new Re(S.value.charAt(0).toUpperCase()+S.value.slice(1));case"trim":return new Re(S.value.trim());case"indent":return new Re(S.value.split(` +`).map((he,Ye)=>Ye===0||he.length===0?he:" "+he).join(` +`));case"string":return S;default:throw new Error(`Unknown StringValue filter: ${Q.value}`)}else if(S instanceof ot)switch(Q.value){case"abs":return new ot(Math.abs(S.value));default:throw new Error(`Unknown NumericValue filter: ${Q.value}`)}else if(S instanceof xt)switch(Q.value){case"items":return new ne(Array.from(S.value.entries()).map(([he,Ye])=>new ne([new Re(he),Ye])));case"length":return new ot(S.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Q.value}`)}throw new Error(`Cannot apply filter "${Q.value}" to type: ${S.type}`)}else if(M.filter.type==="CallExpression"){const Q=M.filter;if(Q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Q.callee.type}`);const he=Q.callee.value;if(he==="tojson"){const[,Ye]=this.evaluateArguments(Q.args,W),et=Ye.get("indent")??new qe;if(!(et instanceof ot||et instanceof qe))throw new Error("If set, indent must be a number");return new Re(gt(S,et.value))}if(S instanceof ne){switch(he){case"selectattr":{if(S.value.some(C=>!(C instanceof xt)))throw new Error("`selectattr` can only be applied to array of objects");if(Q.args.some(C=>C.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ye,et,At]=Q.args.map(C=>this.evaluate(C,W));let mt;if(et){const C=W.tests.get(et.value);if(!C)throw new Error(`Unknown test: ${et.value}`);mt=C}else mt=(...C)=>C[0].__bool__().value;const Se=S.value.filter(C=>{const K=C.value.get(Ye.value);return K?mt(K,At):!1});return new ne(Se)}case"map":{const[,Ye]=this.evaluateArguments(Q.args,W);if(Ye.has("attribute")){const et=Ye.get("attribute");if(!(et instanceof Re))throw new Error("attribute must be a string");const At=Ye.get("default"),mt=S.value.map(Se=>{if(!(Se instanceof xt))throw new Error("items in map must be an object");return Se.value.get(et.value)??At??new Ve});return new ne(mt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if(S instanceof Re){switch(he){case"indent":{const[Ye,et]=this.evaluateArguments(Q.args,W),At=Ye.at(0)??et.get("width")??new ot(4);if(!(At instanceof ot))throw new Error("width must be a number");const mt=Ye.at(1)??et.get("first")??new st(!1),Se=Ye.at(2)??et.get("blank")??new st(!1),C=S.value.split(` +`),K=" ".repeat(At.value),we=C.map((Be,Ae)=>!mt.value&&Ae===0||!Se.value&&Be.length===0?Be:K+Be);return new Re(we.join(` +`))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${M.filter.type}`)}evaluateTestExpression(M,W){const S=this.evaluate(M.operand,W),Q=W.tests.get(M.test.value);if(!Q)throw new Error(`Unknown test: ${M.test.value}`);const he=Q(S);return new st(M.negate?!he:he)}evaluateUnaryExpression(M,W){const S=this.evaluate(M.argument,W);switch(M.operator.value){case"not":return new st(!S.value);default:throw new SyntaxError(`Unknown operator: ${M.operator.value}`)}}evalProgram(M,W){return this.evaluateBlock(M.body,W)}evaluateBlock(M,W){let S="";for(const Q of M){const he=this.evaluate(Q,W);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&(S+=he.value)}return new Re(S)}evaluateIdentifier(M,W){return W.lookupVariable(M.value)}evaluateCallExpression(M,W){const[S,Q]=this.evaluateArguments(M.args,W);Q.size>0&&S.push(new ze(Q));const he=this.evaluate(M.callee,W);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value(S,W)}evaluateSliceExpression(M,W,S){if(!(M instanceof ne||M instanceof Re))throw new Error("Slice object must be an array or string");const Q=this.evaluate(W.start,S),he=this.evaluate(W.stop,S),Ye=this.evaluate(W.step,S);if(!(Q instanceof ot||Q instanceof Ve))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof ot||he instanceof Ve))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof ot||Ye instanceof Ve))throw new Error("Slice step must be numeric or undefined");return M instanceof ne?new ne(Ke(M.value,Q.value,he.value,Ye.value)):new Re(Ke(Array.from(M.value),Q.value,he.value,Ye.value).join(""))}evaluateMemberExpression(M,W){const S=this.evaluate(M.object,W);let Q;if(M.computed){if(M.property.type==="SliceExpression")return this.evaluateSliceExpression(S,M.property,W);Q=this.evaluate(M.property,W)}else Q=new Re(M.property.value);let he;if(S instanceof xt){if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=S.value.get(Q.value)??S.builtins.get(Q.value)}else if(S instanceof ne||S instanceof Re)if(Q instanceof ot)he=S.value.at(Q.value),S instanceof Re&&(he=new Re(S.value.at(Q.value)));else if(Q instanceof Re)he=S.builtins.get(Q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Q.type}`);else{if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=S.builtins.get(Q.value)}return he instanceof rt?he:new Ve}evaluateSet(M,W){const S=this.evaluate(M.value,W);if(M.assignee.type==="Identifier"){const Q=M.assignee.value;W.setVariable(Q,S)}else if(M.assignee.type==="MemberExpression"){const Q=M.assignee,he=this.evaluate(Q.object,W);if(!(he instanceof xt))throw new Error("Cannot assign to member of non-object");if(Q.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Q.property.value,S)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(M.assignee)}`);return new qe}evaluateIf(M,W){const S=this.evaluate(M.test,W);return this.evaluateBlock(S.__bool__().value?M.body:M.alternate,W)}evaluateFor(M,W){const S=new Xe(W);let Q,he;if(M.iterable.type==="SelectExpression"){const Se=M.iterable;he=this.evaluate(Se.iterable,S),Q=Se.test}else he=this.evaluate(M.iterable,S);if(!(he instanceof ne))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Ye=[],et=[];for(let Se=0;SeBe.setVariable(M.loopvar.value,K);else if(M.loopvar.type==="TupleLiteral"){const Be=M.loopvar;if(K.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${K.type}`);const Ae=K;if(Be.value.length!==Ae.value.length)throw new Error(`Too ${Be.value.length>Ae.value.length?"few":"many"} items to unpack`);we=Ne=>{for(let ut=0;ut0?Ye[Se-1]:new Ve],["nextitem",Se{var et;const he=new Xe(Q);S=S.slice();let Ye;((et=S.at(-1))==null?void 0:et.type)==="KeywordArgumentsValue"&&(Ye=S.pop());for(let At=0;Atthis.evaluate(S,W)));case"TupleLiteral":return new $e(M.value.map(S=>this.evaluate(S,W)));case"ObjectLiteral":{const S=new Map;for(const[Q,he]of M.value){const Ye=this.evaluate(Q,W);if(!(Ye instanceof Re))throw new Error(`Object keys must be strings: got ${Ye.type}`);S.set(Ye.value,this.evaluate(he,W))}return new xt(S)}case"Identifier":return this.evaluateIdentifier(M,W);case"CallExpression":return this.evaluateCallExpression(M,W);case"MemberExpression":return this.evaluateMemberExpression(M,W);case"UnaryExpression":return this.evaluateUnaryExpression(M,W);case"BinaryExpression":return this.evaluateBinaryExpression(M,W);case"FilterExpression":return this.evaluateFilterExpression(M,W);case"TestExpression":return this.evaluateTestExpression(M,W);default:throw new SyntaxError(`Unknown node type: ${M.type}`)}}};function ft(M){switch(typeof M){case"number":return new ot(M);case"string":return new Re(M);case"boolean":return new st(M);case"undefined":return new Ve;case"object":return M===null?new qe:Array.isArray(M)?new ne(M.map(ft)):new xt(new Map(Object.entries(M).map(([W,S])=>[W,ft(S)])));case"function":return new je((W,S)=>{const Q=M(...W.map(he=>he.value))??null;return ft(Q)});default:throw new Error(`Cannot convert to runtime value: ${M}`)}}function gt(M,W,S){const Q=S??0;switch(M.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(M.value);case"ArrayValue":case"ObjectValue":{const he=W?" ".repeat(W):"",Ye=` +`+he.repeat(Q),et=Ye+he;if(M.type==="ArrayValue"){const At=M.value.map(mt=>gt(mt,W,Q+1));return W?`[${et}${At.join(`,${et}`)}${Ye}]`:`[${At.join(", ")}]`}else{const At=Array.from(M.value.entries()).map(([mt,Se])=>{const C=`"${mt}": ${gt(Se,W,Q+1)}`;return W?`${et}${C}`:C});return W?`{${At.join(",")}${Ye}}`:`{${At.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${M.type}`)}}var vt=class{constructor(M){xe(this,"parsed");const W=P(M,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ee(W)}render(M){const W=new Xe;W.set("false",!1),W.set("true",!0),W.set("raise_exception",he=>{throw new Error(he)}),W.set("range",re);for(const[he,Ye]of Object.entries(M))W.set(he,Ye);return new lt(W).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":($t,me,l)=>{l.r(me),l.d(me,{registerBackend:()=>ye,resolveBackendAndExecutionProviders:()=>Te});const x=new Map,X=[],ye=(B,E,N)=>{if(E&&typeof E.init=="function"&&typeof E.createInferenceSessionHandler=="function"){const P=x.get(B);if(P===void 0)x.set(B,{backend:E,priority:N});else{if(P.priority>N)return;if(P.priority===N&&P.backend!==E)throw new Error(`cannot register backend "${B}" using priority ${N}`)}if(N>=0){const te=X.indexOf(B);te!==-1&&X.splice(te,1);for(let J=0;J{const E=x.get(B);if(!E)return"backend not found.";if(E.initialized)return E.backend;if(E.aborted)return E.error;{const N=!!E.initPromise;try{return N||(E.initPromise=E.backend.init(B)),await E.initPromise,E.initialized=!0,E.backend}catch(P){return N||(E.error=`${P}`,E.aborted=!0),E.error}finally{delete E.initPromise}}},Te=async B=>{const E=B.executionProviders||[],N=E.map(D=>typeof D=="string"?D:D.name),P=N.length===0?X:N;let te;const J=[],se=new Set;for(const D of P){const ee=await ve(D);typeof ee=="string"?J.push({name:D,err:ee}):(te||(te=ee),te===ee&&se.add(D))}if(!te)throw new Error(`no available backend found. ERR: ${J.map(D=>`[${D.name}] ${D.err}`).join(", ")}`);for(const{name:D,err:ee}of J)N.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${ee}`);const ae=E.filter(D=>se.has(typeof D=="string"?D:D.name));return[te,new Proxy(B,{get:(D,ee)=>ee==="executionProviders"?ae:Reflect.get(D,ee)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":($t,me,l)=>{l.r(me),l.d(me,{registerBackend:()=>x.registerBackend});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":($t,me,l)=>{l.r(me),l.d(me,{env:()=>ye});var x=l("./node_modules/onnxruntime-common/dist/esm/version.js");let X="warning";const ye={wasm:{},webgl:{},webgpu:{},versions:{common:x.version},set logLevel(ve){if(ve!==void 0){if(typeof ve!="string"||["verbose","info","warning","error","fatal"].indexOf(ve)===-1)throw new Error(`Unsupported logging level: ${ve}`);X=ve}},get logLevel(){return X}};Object.defineProperty(ye,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":($t,me,l)=>{l.r(me),l.d(me,{env:()=>X});var x=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const X=x.env},"./node_modules/onnxruntime-common/dist/esm/index.js":($t,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>ye.InferenceSession,TRACE:()=>Te.TRACE,TRACE_FUNC_BEGIN:()=>Te.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Te.TRACE_FUNC_END,Tensor:()=>ve.Tensor,TrainingSession:()=>B.TrainingSession,env:()=>X.env,registerBackend:()=>x.registerBackend});var x=l("./node_modules/onnxruntime-common/dist/esm/backend.js"),X=l("./node_modules/onnxruntime-common/dist/esm/env.js"),ye=l("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ve=l("./node_modules/onnxruntime-common/dist/esm/tensor.js");l("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),l("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Te=l("./node_modules/onnxruntime-common/dist/esm/trace.js");l("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),l("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var B=l("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":($t,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),X=l("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ye=l("./node_modules/onnxruntime-common/dist/esm/trace.js");class ve{constructor(B){this.handler=B}async run(B,E,N){(0,ye.TRACE_FUNC_BEGIN)();const P={};let te={};if(typeof B!="object"||B===null||B instanceof X.Tensor||Array.isArray(B))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let J=!0;if(typeof E=="object"){if(E===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(E instanceof X.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(E)){if(E.length===0)throw new TypeError("'fetches' cannot be an empty array.");J=!1;for(const D of E){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);P[D]=null}if(typeof N=="object"&&N!==null)te=N;else if(typeof N<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const ee=Object.getOwnPropertyNames(E);for(const G of this.outputNames)if(ee.indexOf(G)!==-1){const ie=E[G];(ie===null||ie instanceof X.Tensor)&&(D=!0,J=!1,P[G]=ie)}if(D){if(typeof N=="object"&&N!==null)te=N;else if(typeof N<"u")throw new TypeError("'options' must be an object.")}else te=E}}else if(typeof E<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of this.inputNames)if(typeof B[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(J)for(const D of this.outputNames)P[D]=null;const se=await this.handler.run(B,P,te),ae={};for(const D in se)if(Object.hasOwnProperty.call(se,D)){const ee=se[D];ee instanceof X.Tensor?ae[D]=ee:ae[D]=new X.Tensor(ee.type,ee.data,ee.dims)}return(0,ye.TRACE_FUNC_END)(),ae}async release(){return this.handler.dispose()}static async create(B,E,N,P){(0,ye.TRACE_FUNC_BEGIN)();let te,J={};if(typeof B=="string"){if(te=B,typeof E=="object"&&E!==null)J=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else if(B instanceof Uint8Array){if(te=B,typeof E=="object"&&E!==null)J=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else if(B instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&B instanceof SharedArrayBuffer){const ee=B;let G=0,ie=B.byteLength;if(typeof E=="object"&&E!==null)J=E;else if(typeof E=="number"){if(G=E,!Number.isSafeInteger(G))throw new RangeError("'byteOffset' must be an integer.");if(G<0||G>=ee.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ee.byteLength}).`);if(ie=B.byteLength-G,typeof N=="number"){if(ie=N,!Number.isSafeInteger(ie))throw new RangeError("'byteLength' must be an integer.");if(ie<=0||G+ie>ee.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ee.byteLength-G}].`);if(typeof P=="object"&&P!==null)J=P;else if(typeof P<"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 E<"u")throw new TypeError("'options' must be an object.");te=new Uint8Array(ee,G,ie)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[se,ae]=await(0,x.resolveBackendAndExecutionProviders)(J),D=await se.createInferenceSessionHandler(te,ae);return(0,ye.TRACE_FUNC_END)(),new ve(D)}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":($t,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>X});var x=l("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const X=x.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":($t,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":($t,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":($t,me,l)=>{l.r(me),l.d(me,{tensorToDataURL:()=>x,tensorToImageData:()=>X});const x=(ye,ve)=>{const Te=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Te.width=ye.dims[3],Te.height=ye.dims[2];const B=Te.getContext("2d");if(B!=null){let E,N;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(E=ye.dims[2],N=ye.dims[3]):(E=ye.dims[3],N=ye.dims[2]);const P=(ve==null?void 0:ve.format)!==void 0?ve.format:"RGB",te=ve==null?void 0:ve.norm;let J,se;te===void 0||te.mean===void 0?J=[255,255,255,255]:typeof te.mean=="number"?J=[te.mean,te.mean,te.mean,te.mean]:(J=[te.mean[0],te.mean[1],te.mean[2],0],te.mean[3]!==void 0&&(J[3]=te.mean[3])),te===void 0||te.bias===void 0?se=[0,0,0,0]:typeof te.bias=="number"?se=[te.bias,te.bias,te.bias,te.bias]:(se=[te.bias[0],te.bias[1],te.bias[2],0],te.bias[3]!==void 0&&(se[3]=te.bias[3]));const ae=N*E;let D=0,ee=ae,G=ae*2,ie=-1;P==="RGBA"?(D=0,ee=ae,G=ae*2,ie=ae*3):P==="RGB"?(D=0,ee=ae,G=ae*2):P==="RBG"&&(D=0,G=ae,ee=ae*2);for(let fe=0;fe{const Te=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let B;if(Te!=null){let E,N,P;(ve==null?void 0:ve.tensorLayout)!==void 0&&ve.tensorLayout==="NHWC"?(E=ye.dims[2],N=ye.dims[1],P=ye.dims[3]):(E=ye.dims[3],N=ye.dims[2],P=ye.dims[1]);const te=ve!==void 0&&ve.format!==void 0?ve.format:"RGB",J=ve==null?void 0:ve.norm;let se,ae;J===void 0||J.mean===void 0?se=[255,255,255,255]:typeof J.mean=="number"?se=[J.mean,J.mean,J.mean,J.mean]:(se=[J.mean[0],J.mean[1],J.mean[2],255],J.mean[3]!==void 0&&(se[3]=J.mean[3])),J===void 0||J.bias===void 0?ae=[0,0,0,0]:typeof J.bias=="number"?ae=[J.bias,J.bias,J.bias,J.bias]:(ae=[J.bias[0],J.bias[1],J.bias[2],0],J.bias[3]!==void 0&&(ae[3]=J.bias[3]));const D=N*E;if(ve!==void 0&&(ve.format!==void 0&&P===4&&ve.format!=="RGBA"||P===3&&ve.format!=="RGB"&&ve.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const ee=4;let G=0,ie=1,fe=2,L=3,O=0,j=D,A=D*2,ge=-1;te==="RGBA"?(O=0,j=D,A=D*2,ge=D*3):te==="RGB"?(O=0,j=D,A=D*2):te==="RBG"&&(O=0,A=D,j=D*2),B=Te.createImageData(E,N);for(let be=0;be{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":($t,me,l)=>{l.r(me),l.d(me,{bufferToTensor:()=>X,tensorFromGpuBuffer:()=>Te,tensorFromImage:()=>ye,tensorFromPinnedBuffer:()=>B,tensorFromTexture:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const X=(E,N)=>{if(E===void 0)throw new Error("Image buffer must be defined");if(N.height===void 0||N.width===void 0)throw new Error("Image height and width must be defined");if(N.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:te}=N,J=N.norm??{mean:255,bias:0};let se,ae;typeof J.mean=="number"?se=[J.mean,J.mean,J.mean,J.mean]:se=[J.mean[0],J.mean[1],J.mean[2],J.mean[3]??255],typeof J.bias=="number"?ae=[J.bias,J.bias,J.bias,J.bias]:ae=[J.bias[0],J.bias[1],J.bias[2],J.bias[3]??0];const D=N.format!==void 0?N.format:"RGBA",ee=N.tensorFormat!==void 0&&N.tensorFormat!==void 0?N.tensorFormat:"RGB",G=P*te,ie=ee==="RGBA"?new Float32Array(G*4):new Float32Array(G*3);let fe=4,L=0,O=1,j=2,A=3,ge=0,be=G,Ce=G*2,ke=-1;D==="RGB"&&(fe=3,L=0,O=1,j=2,A=-1),ee==="RGBA"?ke=G*3:ee==="RBG"?(ge=0,Ce=G,be=G*2):ee==="BGR"&&(Ce=0,be=G,ge=G*2);for(let Je=0;Je{const P=typeof HTMLImageElement<"u"&&E instanceof HTMLImageElement,te=typeof ImageData<"u"&&E instanceof ImageData,J=typeof ImageBitmap<"u"&&E instanceof ImageBitmap,se=typeof E=="string";let ae,D=N??{};const ee=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},G=ie=>ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(P){const ie=ee();ie.width=E.width,ie.height=E.height;const fe=G(ie);if(fe!=null){let L=E.height,O=E.width;if(N!==void 0&&N.resizedHeight!==void 0&&N.resizedWidth!==void 0&&(L=N.resizedHeight,O=N.resizedWidth),N!==void 0){if(D=N,N.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=L,D.width=O}else D.tensorFormat="RGBA",D.height=L,D.width=O;fe.drawImage(E,0,0),ae=fe.getImageData(0,0,O,L).data}else throw new Error("Can not access image data")}else if(te){let ie,fe;if(N!==void 0&&N.resizedWidth!==void 0&&N.resizedHeight!==void 0?(ie=N.resizedHeight,fe=N.resizedWidth):(ie=E.height,fe=E.width),N!==void 0&&(D=N),D.format="RGBA",D.height=ie,D.width=fe,N!==void 0){const L=ee();L.width=fe,L.height=ie;const O=G(L);if(O!=null)O.putImageData(E,0,0),ae=O.getImageData(0,0,fe,ie).data;else throw new Error("Can not access image data")}else ae=E.data}else if(J){if(N===void 0)throw new Error("Please provide image config with format for Imagebitmap");const ie=ee();ie.width=E.width,ie.height=E.height;const fe=G(ie);if(fe!=null){const L=E.height,O=E.width;return fe.drawImage(E,0,0,O,L),ae=fe.getImageData(0,0,O,L).data,D.height=L,D.width=O,X(ae,D)}else throw new Error("Can not access image data")}else{if(se)return new Promise((ie,fe)=>{const L=ee(),O=G(L);if(!E||!O)return fe();const j=new Image;j.crossOrigin="Anonymous",j.src=E,j.onload=()=>{L.width=j.width,L.height=j.height,O.drawImage(j,0,0,L.width,L.height);const A=O.getImageData(0,0,L.width,L.height);D.height=L.height,D.width=L.width,ie(X(A.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ae!==void 0)return X(ae,D);throw new Error("Input data provided is not supported - aborted tensor creation")},ve=(E,N)=>{const{width:P,height:te,download:J,dispose:se}=N,ae=[1,te,P,4];return new x.Tensor({location:"texture",type:"float32",texture:E,dims:ae,download:J,dispose:se})},Te=(E,N)=>{const{dataType:P,dims:te,download:J,dispose:se}=N;return new x.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:E,dims:te,download:J,dispose:se})},B=(E,N,P)=>new x.Tensor({location:"cpu-pinned",type:E,data:N,dims:P??[N.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":($t,me,l)=>{l.r(me)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":($t,me,l)=>{l.r(me),l.d(me,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>X,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>x,checkTypedArray:()=>ve});const x=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),X=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ye=!1;const ve=()=>{if(!ye){ye=!0;const Te=typeof BigInt64Array<"u"&&BigInt64Array.from,B=typeof BigUint64Array<"u"&&BigUint64Array.from,E=typeof Float16Array<"u"&&Float16Array.from;Te&&(x.set("int64",BigInt64Array),X.set(BigInt64Array,"int64")),B&&(x.set("uint64",BigUint64Array),X.set(BigUint64Array,"uint64")),E?(x.set("float16",Float16Array),X.set(Float16Array,"float16")):x.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":($t,me,l)=>{l.r(me),l.d(me,{Tensor:()=>Te});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),X=l("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ye=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ve=l("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Te{constructor(E,N,P){(0,ye.checkTypedArray)();let te,J;if(typeof E=="object"&&"location"in E)switch(this.dataLocation=E.location,te=E.type,J=E.dims,E.location){case"cpu-pinned":{const ae=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(te);if(!ae)throw new TypeError(`unsupported type "${te}" to create tensor from pinned buffer`);if(!(E.data instanceof ae))throw new TypeError(`buffer should be of type ${ae.name}`);this.cpuData=E.data;break}case"texture":{if(te!=="float32")throw new TypeError(`unsupported type "${te}" to create tensor from texture`);this.gpuTextureData=E.texture,this.downloader=E.download,this.disposer=E.dispose;break}case"gpu-buffer":{if(te!=="float32"&&te!=="float16"&&te!=="int32"&&te!=="int64"&&te!=="uint32"&&te!=="uint8"&&te!=="bool")throw new TypeError(`unsupported type "${te}" to create tensor from gpu buffer`);this.gpuBufferData=E.gpuBuffer,this.downloader=E.download,this.disposer=E.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ae,D;if(typeof E=="string")if(te=E,D=P,E==="string"){if(!Array.isArray(N))throw new TypeError("A string tensor's data must be a string array.");ae=N}else{const ee=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(E);if(ee===void 0)throw new TypeError(`Unsupported tensor type: ${E}.`);if(Array.isArray(N)){if(E==="float16"&&ee===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");E==="uint64"||E==="int64"?ae=ee.from(N,BigInt):ae=ee.from(N)}else if(N instanceof ee)ae=N;else throw new TypeError(`A ${te} tensor's data must be type of ${ee}`)}else if(D=N,Array.isArray(E)){if(E.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const ee=typeof E[0];if(ee==="string")te="string",ae=E;else if(ee==="boolean")te="bool",ae=Uint8Array.from(E);else throw new TypeError(`Invalid element type of data array: ${ee}.`)}else{const ee=ye.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(E.constructor);if(ee===void 0)throw new TypeError(`Unsupported type for tensor data: ${E.constructor}.`);te=ee,ae=E}if(D===void 0)D=[ae.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");J=D,this.cpuData=ae,this.dataLocation="cpu"}const se=(0,ve.calculateSize)(J);if(this.cpuData&&se!==this.cpuData.length)throw new Error(`Tensor's size(${se}) does not match data length(${this.cpuData.length}).`);this.type=te,this.dims=J,this.size=se}static async fromImage(E,N){return(0,X.tensorFromImage)(E,N)}static fromTexture(E,N){return(0,X.tensorFromTexture)(E,N)}static fromGpuBuffer(E,N){return(0,X.tensorFromGpuBuffer)(E,N)}static fromPinnedBuffer(E,N,P){return(0,X.tensorFromPinnedBuffer)(E,N,P)}toDataURL(E){return(0,x.tensorToDataURL)(this,E)}toImageData(E){return(0,x.tensorToImageData)(this,E)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(E){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const N=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=N,E&&this.disposer&&(this.disposer(),this.disposer=void 0),N}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.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(0,ve.tensorReshape)(this,E)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":($t,me,l)=>{l.r(me),l.d(me,{calculateSize:()=>X,tensorReshape:()=>ye});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const X=ve=>{let Te=1;for(let B=0;B{switch(ve.location){case"cpu":return new x.Tensor(ve.type,ve.data,Te);case"cpu-pinned":return new x.Tensor({location:"cpu-pinned",data:ve.data,type:ve.type,dims:Te});case"texture":return new x.Tensor({location:"texture",texture:ve.texture,type:ve.type,dims:Te});case"gpu-buffer":return new x.Tensor({location:"gpu-buffer",gpuBuffer:ve.gpuBuffer,type:ve.type,dims:Te});default:throw new Error(`tensorReshape: tensor location ${ve.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":($t,me,l)=>{l.r(me),l.d(me,{Tensor:()=>X});var x=l("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const X=x.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":($t,me,l)=>{l.r(me),l.d(me,{TRACE:()=>X,TRACE_FUNC_BEGIN:()=>ve,TRACE_FUNC_END:()=>Te});var x=l("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const X=(B,E)=>{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||console.timeStamp(`${B}::ORT::${E}`)},ye=(B,E)=>{var te;const N=((te=new Error().stack)==null?void 0:te.split(/\r\n|\r|\n/g))||[];let P=!1;for(let J=0;J{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||ye("BEGIN",B)},Te=B=>{(typeof x.env.trace>"u"?!x.env.wasm.trace:!x.env.trace)||ye("END",B)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":($t,me,l)=>{l.r(me),l.d(me,{TrainingSession:()=>ve});var x=l("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),X=l("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class ve{constructor(B,E,N){this.handler=B,this.hasOptimizerModel=E,this.hasEvalModel=N}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(B,E){const N=B.evalModel||"",P=B.optimizerModel||"",te=E||{},[J,se]=await(0,x.resolveBackendAndExecutionProviders)(te);if(J.createTrainingSessionHandler){const ae=await J.createTrainingSessionHandler(B.checkpointState,B.trainModel,N,P,se);return new ve(ae,!!B.optimizerModel,!!B.evalModel)}else throw new Error(ye)}typeNarrowingForRunStep(B,E,N,P,te){const J={};let se={};if(typeof N!="object"||N===null||N instanceof X.Tensor||Array.isArray(N))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ae=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof X.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");ae=!1;for(const D of P){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(E.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);J[D]=null}if(typeof te=="object"&&te!==null)se=te;else if(typeof te<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const ee=Object.getOwnPropertyNames(P);for(const G of E)if(ee.indexOf(G)!==-1){const ie=P[G];(ie===null||ie instanceof X.Tensor)&&(D=!0,ae=!1,J[G]=ie)}if(D){if(typeof te=="object"&&te!==null)se=te;else if(typeof te<"u")throw new TypeError("'options' must be an object.")}else se=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of B)if(typeof N[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ae)for(const D of E)J[D]=null;return[J,se]}convertHandlerReturnTypeToMapOfTensors(B){const E={};for(const N in B)if(Object.hasOwnProperty.call(B,N)){const P=B[N];P instanceof X.Tensor?E[N]=P:E[N]=new X.Tensor(P.type,P.data,P.dims)}return E}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(B,E,N){const[P,te]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,B,E,N),J=await this.handler.runTrainStep(B,P,te);return this.convertHandlerReturnTypeToMapOfTensors(J)}async runOptimizerStep(B){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(B||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(B,E,N){if(this.hasEvalModel){const[P,te]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,B,E,N),J=await this.handler.runEvalStep(B,P,te);return this.convertHandlerReturnTypeToMapOfTensors(J)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(B=!0){return this.handler.getParametersSize(B)}async loadParametersBuffer(B,E=!0){const N=await this.getParametersSize(E);if(B.length!==4*N)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(B,E)}async getContiguousParameters(B=!0){return this.handler.getContiguousParameters(B)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":($t,me,l)=>{l.r(me),l.d(me,{TrainingSession:()=>X});var x=l("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const X=x.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":($t,me,l)=>{l.r(me),l.d(me,{version:()=>x});const x="1.18.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":($t,me,l)=>{l.r(me),l.d(me,{InferenceSession:()=>gt,TRACE:()=>$e,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>Ve,Tensor:()=>ze,TrainingSession:()=>At,default:()=>mf,env:()=>A,registerBackend:()=>se});/*! + * ONNX Runtime Web v1.19.0-dev.20240804-ee2fe87e2d + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var x=Object.defineProperty,X=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,Te=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),B=(e,t)=>()=>(e&&(t=e(e=0)),t),E=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})},N=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ye(t))!ve.call(e,s)&&s!==r&&x(e,s,{get:()=>t[s],enumerable:!(n=X(t,s))||n.enumerable});return e},P=e=>N(x({},"__esModule",{value:!0}),e),te,J,se,ae,D,ee=B(()=>{te=new Map,J=[],se=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=te.get(e);if(n===void 0)te.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=J.indexOf(e);s!==-1&&J.splice(s,1);for(let a=0;a{let t=te.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},D=async e=>{let t=e.executionProviders||[],r=t.map(c=>typeof c=="string"?c:c.name),n=r.length===0?J:r,s,a=[],i=new Set;for(let c of n){let h=await ae(c);typeof h=="string"?a.push({name:c,err:h}):(s||(s=h),s===h&&i.add(c))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(c=>`[${c.name}] ${c.err}`).join(", ")}`);for(let{name:c,err:h}of a)r.includes(c)&&console.warn(`removing requested execution provider "${c}" from session options because it is not available: ${h}`);let d=t.filter(c=>i.has(typeof c=="string"?c:c.name));return[s,new Proxy(e,{get:(c,h)=>h==="executionProviders"?d:Reflect.get(c,h)})]}}),G=B(()=>{ee()}),ie,fe=B(()=>{ie="1.19.0-dev.20240730-530a2d7b41"}),L,O,j=B(()=>{fe(),L="warning",O={wasm:{},webgl:{},webgpu:{},versions:{common:ie},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}`);L=e}},get logLevel(){return L}},Object.defineProperty(O,"logLevel",{enumerable:!0})}),A,ge=B(()=>{j(),A=O}),be,Ce,ke=B(()=>{be=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,c,h;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let w=a*s,y=0,u=w,k=w*2,T=-1;i==="RGBA"?(y=0,u=w,k=w*2,T=w*3):i==="RGB"?(y=0,u=w,k=w*2):i==="RBG"&&(y=0,k=w,u=w*2);for(let I=0;I{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",c=t==null?void 0:t.norm,h,w;c===void 0||c.mean===void 0?h=[255,255,255,255]:typeof c.mean=="number"?h=[c.mean,c.mean,c.mean,c.mean]:(h=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(h[3]=c.mean[3])),c===void 0||c.bias===void 0?w=[0,0,0,0]:typeof c.bias=="number"?w=[c.bias,c.bias,c.bias,c.bias]:(w=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(w[3]=c.bias[3]));let y=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,k=0,T=1,I=2,U=3,q=0,R=y,ce=y*2,Z=-1;d==="RGBA"?(q=0,R=y,ce=y*2,Z=y*3):d==="RGB"?(q=0,R=y,ce=y*2):d==="RBG"&&(q=0,ce=y,R=y*2),n=r.createImageData(s,a);for(let oe=0;oe{xt(),De=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,w=c==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),y=4,u=0,k=1,T=2,I=3,U=0,q=h,R=h*2,ce=-1;d==="RGB"&&(y=3,u=0,k=1,T=2,I=-1),c==="RGBA"?ce=h*3:c==="RBG"?(U=0,R=h,q=h*2):c==="BGR"&&(R=0,q=h,U=h*2);for(let Z=0;Z{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,d=t??{},c=()=>{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=w=>w instanceof HTMLCanvasElement||w instanceof OffscreenCanvas?w.getContext("2d"):null;if(r){let w=c();w.width=e.width,w.height=e.height;let y=h(w);if(y!=null){let u=e.height,k=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,k=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=k}else d.tensorFormat="RGBA",d.height=u,d.width=k;y.drawImage(e,0,0),i=y.getImageData(0,0,k,u).data}else throw new Error("Can not access image data")}else if(n){let w,y;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(w=t.resizedHeight,y=t.resizedWidth):(w=e.height,y=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=w,d.width=y,t!==void 0){let u=c();u.width=y,u.height=w;let k=h(u);if(k!=null)k.putImageData(e,0,0),i=k.getImageData(0,0,y,w).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let w=c();w.width=e.width,w.height=e.height;let y=h(w);if(y!=null){let u=e.height,k=e.width;return y.drawImage(e,0,0,k,u),i=y.getImageData(0,0,k,u).data,d.height=u,d.width=k,De(i,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,y)=>{let u=c(),k=h(u);if(!e||!k)return y();let T=new Image;T.crossOrigin="Anonymous",T.src=e,T.onload=()=>{u.width=T.width,u.height=T.height,k.drawImage(T,0,0,u.width,u.height);let I=k.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,w(De(I.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return De(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Ue=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new st({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},bt=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new st({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},_e=(e,t,r)=>new st({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),pe,Ee,re,Ke,ct=B(()=>{pe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Ee=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),re=!1,Ke=()=>{if(!re){re=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(pe.set("int64",BigInt64Array),Ee.set(BigInt64Array,"int64")),t&&(pe.set("uint64",BigUint64Array),Ee.set(BigUint64Array,"uint64")),r?(pe.set("float16",Float16Array),Ee.set(Float16Array,"float16")):pe.set("float16",Uint16Array)}}}),rt,ot,Re=B(()=>{xt(),rt=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new st(e.type,e.data,t);case"cpu-pinned":return new st({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new st({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new st({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),st,xt=B(()=>{ke(),V(),ct(),Re(),st=class{constructor(e,t,r){Ke();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=pe.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,d;if(typeof e=="string")if(n=e,d=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let c=pe.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&c===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?i=c.from(t,BigInt):i=c.from(t)}else if(t instanceof c)i=t;else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else{let c=Ee.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(d===void 0)d=[i.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");s=d,this.cpuData=i,this.dataLocation="cpu"}let a=rt(s);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Je(e,t)}static fromTexture(e,t){return Ue(e,t)}static fromGpuBuffer(e,t){return bt(e,t)}static fromPinnedBuffer(e,t,r){return _e(e,t,r)}toDataURL(e){return be(this,e)}toImageData(e){return Ce(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!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.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 ot(this,e)}}}),ze,ne=B(()=>{xt(),ze=st}),$e,je,qe,Ve,Xe=B(()=>{j(),$e=(e,t)=>{(typeof O.trace>"u"?!O.wasm.trace:!O.trace)||console.timeStamp(`${e}::ORT::${t}`)},je=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof O.trace>"u"?!O.wasm.trace:!O.trace)||je("BEGIN",e)},Ve=e=>{(typeof O.trace>"u"?!O.wasm.trace:!O.trace)||je("END",e)}}),lt,ft=B(()=>{ee(),ne(),Xe(),lt=class Kh{constructor(t){this.handler=t}async run(t,r,n){qe();let s={},a={};if(typeof t!="object"||t===null||t instanceof ze||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ze)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of r){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}.`);s[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,w=Object.getOwnPropertyNames(r);for(let y of this.outputNames)if(w.indexOf(y)!==-1){let u=r[y];(u===null||u instanceof ze)&&(h=!0,i=!1,s[y]=u)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)s[h]=null;let d=await this.handler.run(t,s,a),c={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let w=d[h];w instanceof ze?c[h]=w:c[h]=new ze(w.type,w.data,w.dims)}return Ve(),c}async release(){return this.handler.dispose()}static async create(t,r,n,s){qe();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let w=t,y=0,u=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(y=r,!Number.isSafeInteger(y))throw new RangeError("'byteOffset' must be an integer.");if(y<0||y>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(u=t.byteLength-y,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||y+u>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-y}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(w,y,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,c]=await D(i),h=await d.createInferenceSessionHandler(a,c);return Ve(),new Kh(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),gt,vt=B(()=>{ft(),gt=lt}),M=B(()=>{}),W=B(()=>{}),S=B(()=>{}),Q=B(()=>{}),he,Ye,et=B(()=>{ee(),ne(),he="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Ye=class Xh{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",s=t.optimizerModel||"",a=r||{},[i,d]=await D(a);if(i.createTrainingSessionHandler){let c=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,d);return new Xh(c,!!t.optimizerModel,!!t.evalModel)}else throw new Error(he)}typeNarrowingForRunStep(t,r,n,s,a){let i={},d={};if(typeof n!="object"||n===null||n instanceof ze||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let c=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof ze)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.");c=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);i[h]=null}if(typeof a=="object"&&a!==null)d=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,w=Object.getOwnPropertyNames(s);for(let y of r)if(w.indexOf(y)!==-1){let u=s[y];(u===null||u instanceof ze)&&(h=!0,c=!1,i[y]=u)}if(h){if(typeof a=="object"&&a!==null)d=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else d=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of t)if(typeof n[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(c)for(let h of r)i[h]=null;return[i,d]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof ze?r[n]=s:r[n]=new ze(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),i=await this.handler.runTrainStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[s,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),i=await this.handler.runEvalStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),At,mt=B(()=>{et(),At=Ye}),Se={};E(Se,{InferenceSession:()=>gt,TRACE:()=>$e,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>Ve,Tensor:()=>ze,TrainingSession:()=>At,env:()=>A,registerBackend:()=>se});var C=B(()=>{G(),ge(),vt(),ne(),M(),W(),Xe(),S(),Q(),mt()}),K=B(()=>{}),we={};E(we,{default:()=>Ne});var Be,Ae,Ne,ut=B(()=>{var e;fp(),Zr(),Ur(),Be="ort-wasm-proxy-worker",Ae=((e=globalThis.self)==null?void 0:e.name)===Be,Ae&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Fn(n.wasm).then(()=>{Od(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;zd(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=dd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Dd(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":Bd(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:d,options:c}=n;Rd(s,a,i,d,new Array(d.length).fill(null),c).then(h=>{h.some(w=>w[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:h},jd([...i,...h]))},h=>{postMessage({type:r,err:h})});break}case"end-profiling":Nd(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Ne=Ae?null:t=>new Worker(t??Qe,{type:"module",name:Be})}),nt={};E(nt,{default:()=>Tt});var Mt,ht,Tt,Rt=B(()=>{var e;ht=(Mt=self.location.href,async function(t={}){function r(){return dr.buffer!=Zt.buffer&&pn(),Zt}function n(){return dr.buffer!=Zt.buffer&&pn(),fr}function s(){return dr.buffer!=Zt.buffer&&pn(),Le}function a(){return dr.buffer!=Zt.buffer&&pn(),jt}function i(){return dr.buffer!=Zt.buffer&&pn(),rr}function d(){return dr.buffer!=Zt.buffer&&pn(),Br}function c(){return dr.buffer!=Zt.buffer&&pn(),Xr}function h(){return dr.buffer!=Zt.buffer&&pn(),En}var w,y,u=Object.assign({},t),k=new Promise((o,f)=>{w=o,y=f}),T=typeof window=="object",I=typeof importScripts=="function",U=I&&self.name=="em-pthread";u.mountExternalData=(o,f)=>{(u.Fb||(u.Fb=new Map)).set(o,f)},u.unmountExternalData=()=>{delete u.Fb};var q=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let R=()=>{let o=(b,v,z)=>(...de)=>{let We=ts,at=v==null?void 0:v();de=b(...de);let Ct=v==null?void 0:v();return at!==Ct&&(b=Ct,z(at),v=z=null),ts!=We?new Promise((It,Kt)=>{ic={resolve:It,reject:Kt}}):de},f=b=>async(...v)=>{var z;try{if(u.Eb)throw Error("Session already started");let de=u.Eb={bc:v[0],errors:[]},We=await b(...v);if(u.Eb!==de)throw Error("Session mismatch");(z=u.Mb)==null||z.flush();let at=de.errors;if(0It),0u._OrtCreateSession,b=>u._OrtCreateSession=b),u._OrtRun=f(o(u._OrtRun,()=>u._OrtRun,b=>u._OrtRun=b)),u._OrtRunWithBinding=f(o(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,b=>u._OrtRunWithBinding=b)),u._OrtBindInput=o(u._OrtBindInput,()=>u._OrtBindInput,b=>u._OrtBindInput=b),R=void 0};u.jsepInit=(o,f)=>{if(R==null||R(),o==="webgpu"){[u.Mb,u.Tb,u.Xb,u.Nb,u.Wb,u.jb,u.Yb,u.$b,u.Ub,u.Vb,u.Zb]=f;let b=u.Mb;u.jsepRegisterBuffer=(v,z,de,We)=>b.registerBuffer(v,z,de,We),u.jsepGetBuffer=v=>b.getBuffer(v),u.jsepCreateDownloader=(v,z,de)=>b.createDownloader(v,z,de),u.jsepOnReleaseSession=v=>{b.onReleaseSession(v)},u.jsepOnRunStart=v=>b.onRunStart(v)}};var ce,Z,oe=Object.assign({},u),tt="./this.program",Ge=(o,f)=>{throw f},dt="";(T||I)&&(I?dt=self.location.href:typeof document<"u"&&document.currentScript&&(dt=document.currentScript.src),Mt&&(dt=Mt),dt=dt.startsWith("blob:")?"":dt.substr(0,dt.replace(/[?#].*/,"").lastIndexOf("/")+1),I&&(Z=o=>{var f=new XMLHttpRequest;return f.open("GET",o,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),ce=(o,f,b)=>{var v=new XMLHttpRequest;v.open("GET",o,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?f(v.response):b()},v.onerror=b,v.send(null)});var Ot,Dt=console.log.bind(console),pr=console.error.bind(console),gr=Dt,nr=pr;if(Object.assign(u,oe),oe=null,U){let o=function(f){try{var b=f.data,v=b.cmd;if(v==="load"){let z=[];self.onmessage=de=>z.push(de),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let de of z)o(de);self.onmessage=o};for(let de of b.handlers)u[de]&&!u[de].proxy||(u[de]=(...We)=>{postMessage({Lb:"callHandler",kc:de,args:We})},de=="print"&&(gr=u[de]),de=="printErr"&&(nr=u[de]));dr=b.wasmMemory,pn(),Sr(b.wasmModule)}else if(v==="run"){uc(b.pthread_ptr,0,0,1,0,0),rc(b.pthread_ptr),wf(),Rp(),Wr||(Dh(),Wr=!0);try{yf(b.start_routine,b.arg)}catch(z){if(z!="unwind")throw z}}else v==="cancel"?Aa()&&Td(-1):b.target!=="setimmediate"&&(v==="checkMailbox"?Wr&&md():v&&(nr(`worker: received unknown command ${v}`),nr(b)))}catch(z){throw Bh(),z}};var Sr,Wr=!1;nr=function(...f){f=f.join(" "),console.error(f)},self.alert=function(...f){postMessage({Lb:"alert",text:f.join(" "),mc:Aa()})},u.instantiateWasm=(f,b)=>new Promise(v=>{Sr=z=>{z=new WebAssembly.Instance(z,Op()),b(z),v()}}),self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=o}u.wasmBinary&&(Ot=u.wasmBinary);var dr,Rr,Lt,Zt,fr,Le,jt,rr,Br,Xr,an,zs,En,In=!1;function pn(){var o=dr.buffer;u.HEAP8=Zt=new Int8Array(o),u.HEAP16=Le=new Int16Array(o),u.HEAPU8=fr=new Uint8Array(o),u.HEAPU16=jt=new Uint16Array(o),u.HEAP32=rr=new Int32Array(o),u.HEAPU32=Br=new Uint32Array(o),u.HEAPF32=Xr=new Float32Array(o),u.HEAPF64=En=new Float64Array(o),u.HEAP64=an=new BigInt64Array(o),u.HEAPU64=zs=new BigUint64Array(o)}if(!U){if(!((dr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof q))throw nr("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");pn()}var Au=[],hn=[],Tn=[],Nn=0,Ds=null;function hd(){if(--Nn==0&&Ds){var o=Ds;Ds=null,o()}}function Sa(o){throw nr(o="Aborted("+o+")"),In=!0,Lt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),y(o),o}var Wd,Pp=o=>o.startsWith("data:application/octet-stream;base64,"),Ap=o=>o.startsWith("file://");function Ip(o){if(o==Wd&&Ot)return new Uint8Array(Ot);if(Z)return Z(o);throw"both async and sync fetching of the wasm failed"}function Fp(o,f,b){return function(v){if(!Ot&&(T||I)){if(typeof fetch=="function"&&!Ap(v))return fetch(v,{credentials:"same-origin"}).then(z=>{if(!z.ok)throw`failed to load wasm binary file at '${v}'`;return z.arrayBuffer()}).catch(()=>Ip(v));if(ce)return new Promise((z,de)=>{ce(v,We=>z(new Uint8Array(We)),de)})}return Promise.resolve().then(()=>Ip(v))}(o).then(v=>WebAssembly.instantiate(v,f)).then(b,v=>{nr(`failed to asynchronously prepare wasm: ${v}`),Sa(v)})}function Op(){return{a:{M:gf,za:_f,b:Mf,$:Up,z:qp,pa:Hp,X:Xp,Z:Qp,qa:Yp,na:Zp,ga:Jp,ma:eh,J:th,Y:rh,V:nh,oa:sh,W:ih,va:vf,D:xf,P:Tf,O:$f,C:Sf,s:kf,p:Pf,E:Af,y:Lf,Q:Rf,ta:Nf,ja:jf,T:Vf,aa:Uf,F:Wf,ia:rc,sa:Gf,u:qf,B:Xf,o:Qf,m:Zf,c:ec,n:Jf,k:rm,Aa:nm,r:sm,f:im,v:am,l:om,g:lm,i:um,j:dm,h:cm,e:pm,da:hm,ea:fm,fa:mm,ba:yh,ca:bh,S:_m,d:gm,N:wm,G:ym,K:bm,w:Mm,ra:vm,U:xm,t:vh,x:Tm,L:Cm,R:$m,ya:Em,xa:Sm,ka:Ch,la:$h,_:Xd,A:Eh,I:Sh,ha:kh,H:Ph,a:dr,wa:Kd,ua:Fh,q:Am}}}var Gd={848436:(o,f,b,v)=>{if(u===void 0||!u.Fb)return 1;if((o=un(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=u.Fb.get(o)))return 2;if(v>>>=0,(f>>>=0)+(b>>>=0)>o.byteLength)return 3;try{return n().set(o.subarray(f,f+b),v>>>0),0}catch{return 4}},848937:()=>{u.Ub()},848968:()=>{u.Vb()},848997:()=>{u.Zb()},849022:o=>u.Tb(o),849055:o=>u.Xb(o),849087:(o,f,b)=>{u.Nb(o,f,b,!0)},849126:(o,f,b)=>{u.Nb(o,f,b)},849159:()=>typeof wasmOffsetConverter<"u",849216:o=>{u.jb("Abs",o,void 0)},849267:o=>{u.jb("Neg",o,void 0)},849318:o=>{u.jb("Floor",o,void 0)},849371:o=>{u.jb("Ceil",o,void 0)},849423:o=>{u.jb("Reciprocal",o,void 0)},849481:o=>{u.jb("Sqrt",o,void 0)},849533:o=>{u.jb("Exp",o,void 0)},849584:o=>{u.jb("Erf",o,void 0)},849635:o=>{u.jb("Sigmoid",o,void 0)},849690:(o,f,b)=>{u.jb("HardSigmoid",o,{alpha:f,beta:b})},849769:o=>{u.jb("Log",o,void 0)},849820:o=>{u.jb("Sin",o,void 0)},849871:o=>{u.jb("Cos",o,void 0)},849922:o=>{u.jb("Tan",o,void 0)},849973:o=>{u.jb("Asin",o,void 0)},850025:o=>{u.jb("Acos",o,void 0)},850077:o=>{u.jb("Atan",o,void 0)},850129:o=>{u.jb("Sinh",o,void 0)},850181:o=>{u.jb("Cosh",o,void 0)},850233:o=>{u.jb("Asinh",o,void 0)},850286:o=>{u.jb("Acosh",o,void 0)},850339:o=>{u.jb("Atanh",o,void 0)},850392:o=>{u.jb("Tanh",o,void 0)},850444:o=>{u.jb("Not",o,void 0)},850495:(o,f,b)=>{u.jb("Clip",o,{min:f,max:b})},850564:o=>{u.jb("Clip",o,void 0)},850616:(o,f)=>{u.jb("Elu",o,{alpha:f})},850674:o=>{u.jb("Relu",o,void 0)},850726:(o,f)=>{u.jb("LeakyRelu",o,{alpha:f})},850790:(o,f)=>{u.jb("ThresholdedRelu",o,{alpha:f})},850860:(o,f)=>{u.jb("Cast",o,{to:f})},850918:o=>{u.jb("Add",o,void 0)},850969:o=>{u.jb("Sub",o,void 0)},851020:o=>{u.jb("Mul",o,void 0)},851071:o=>{u.jb("Div",o,void 0)},851122:o=>{u.jb("Pow",o,void 0)},851173:o=>{u.jb("Equal",o,void 0)},851226:o=>{u.jb("Greater",o,void 0)},851281:o=>{u.jb("GreaterOrEqual",o,void 0)},851343:o=>{u.jb("Less",o,void 0)},851395:o=>{u.jb("LessOrEqual",o,void 0)},851454:(o,f,b,v,z)=>{u.jb("ReduceMean",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},851613:(o,f,b,v,z)=>{u.jb("ReduceMax",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},851771:(o,f,b,v,z)=>{u.jb("ReduceMin",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},851929:(o,f,b,v,z)=>{u.jb("ReduceProd",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852088:(o,f,b,v,z)=>{u.jb("ReduceSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852246:(o,f,b,v,z)=>{u.jb("ReduceL1",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852403:(o,f,b,v,z)=>{u.jb("ReduceL2",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852560:(o,f,b,v,z)=>{u.jb("ReduceLogSum",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852721:(o,f,b,v,z)=>{u.jb("ReduceSumSquare",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},852885:(o,f,b,v,z)=>{u.jb("ReduceLogSumExp",o,{keepDims:!!f,noopWithEmptyAxes:!!b,axes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},853049:o=>{u.jb("Where",o,void 0)},853102:(o,f,b)=>{u.jb("Transpose",o,{perm:f?Array.from(i().subarray(f>>>0,b>>>0)):[]})},853210:(o,f,b,v)=>{u.jb("DepthToSpace",o,{blocksize:f,mode:un(b),format:v?"NHWC":"NCHW"})},853343:(o,f,b,v)=>{u.jb("DepthToSpace",o,{blocksize:f,mode:un(b),format:v?"NHWC":"NCHW"})},853476:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar)=>{u.jb("ConvTranspose",o,{format:Ct?"NHWC":"NCHW",autoPad:f,dilations:[b],group:v,kernelShape:[z],pads:[de,We],strides:[at],wIsConst:()=>!!r()[It>>>0],outputPadding:Kt?Array.from(i().subarray(Kt>>>0,kr>>>0)):[],outputShape:Fr?Array.from(i().subarray(Fr>>>0,Oe>>>0)):[],activation:un(ar)})},853877:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe)=>{u.jb("ConvTranspose",o,{format:at?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(de>>>0,4+(de>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Ct>>>0],outputPadding:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],outputShape:kr?Array.from(i().subarray(kr>>>0,Fr>>>0)):[],activation:un(Oe)})},854442:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar)=>{u.jb("ConvTranspose",o,{format:Ct?"NHWC":"NCHW",autoPad:f,dilations:[b],group:v,kernelShape:[z],pads:[de,We],strides:[at],wIsConst:()=>!!r()[It>>>0],outputPadding:Kt?Array.from(i().subarray(Kt>>>0,kr>>>0)):[],outputShape:Fr?Array.from(i().subarray(Fr>>>0,Oe>>>0)):[],activation:un(ar)})},854843:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe)=>{u.jb("ConvTranspose",o,{format:at?"NHWC":"NCHW",autoPad:f,dilations:Array.from(i().subarray(b>>>0,2+(b>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(z>>>0,2+(z>>>0)>>>0)),pads:Array.from(i().subarray(de>>>0,4+(de>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Ct>>>0],outputPadding:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],outputShape:kr?Array.from(i().subarray(kr>>>0,Fr>>>0)):[],activation:un(Oe)})},855408:(o,f)=>{u.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},855499:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar,Or)=>{u.jb("AveragePool",o,{format:Or?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[de,We],kernel_shape:[at,Ct],pads:[It,Kt,kr,Fr],strides:[Oe,ar]})},855783:(o,f)=>{u.jb("GlobalAveragePool",o,{format:f?"NHWC":"NCHW"})},855874:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar,Or)=>{u.jb("AveragePool",o,{format:Or?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[de,We],kernel_shape:[at,Ct],pads:[It,Kt,kr,Fr],strides:[Oe,ar]})},856158:(o,f)=>{u.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},856245:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar,Or)=>{u.jb("MaxPool",o,{format:Or?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[de,We],kernel_shape:[at,Ct],pads:[It,Kt,kr,Fr],strides:[Oe,ar]})},856525:(o,f)=>{u.jb("GlobalMaxPool",o,{format:f?"NHWC":"NCHW"})},856612:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar,Or)=>{u.jb("MaxPool",o,{format:Or?"NHWC":"NCHW",auto_pad:f,ceil_mode:b,count_include_pad:v,storage_order:z,dilations:[de,We],kernel_shape:[at,Ct],pads:[It,Kt,kr,Fr],strides:[Oe,ar]})},856892:(o,f,b,v,z)=>{u.jb("Gemm",o,{alpha:f,beta:b,transA:v,transB:z})},856996:o=>{u.jb("MatMul",o,void 0)},857050:(o,f,b,v)=>{u.jb("ArgMax",o,{keepDims:!!f,selectLastIndex:!!b,axis:v})},857158:(o,f,b,v)=>{u.jb("ArgMin",o,{keepDims:!!f,selectLastIndex:!!b,axis:v})},857266:(o,f)=>{u.jb("Softmax",o,{axis:f})},857329:(o,f)=>{u.jb("Concat",o,{axis:f})},857389:(o,f,b,v,z)=>{u.jb("Split",o,{axis:f,numOutputs:b,splitSizes:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},857529:o=>{u.jb("Expand",o,void 0)},857583:(o,f)=>{u.jb("Gather",o,{axis:Number(f)})},857654:(o,f)=>{u.jb("GatherElements",o,{axis:Number(f)})},857733:(o,f,b,v,z,de,We,at,Ct,It,Kt)=>{u.jb("Resize",o,{antialias:f,axes:b?Array.from(i().subarray(b>>>0,v>>>0)):[],coordinateTransformMode:un(z),cubicCoeffA:de,excludeOutside:We,extrapolationValue:at,keepAspectRatioPolicy:un(Ct),mode:un(It),nearestMode:un(Kt)})},858079:(o,f,b,v,z,de,We)=>{u.jb("Slice",o,{starts:f?Array.from(i().subarray(f>>>0,b>>>0)):[],ends:v?Array.from(i().subarray(v>>>0,z>>>0)):[],axes:de?Array.from(i().subarray(de>>>0,We>>>0)):[]})},858295:o=>{u.jb("Tile",o,void 0)},858347:(o,f,b)=>{u.jb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},858461:(o,f,b)=>{u.jb("InstanceNormalization",o,{epsilon:f,format:b?"NHWC":"NCHW"})},858575:o=>{u.jb("Range",o,void 0)},858628:(o,f)=>{u.jb("Einsum",o,{equation:un(f)})},858709:(o,f,b,v,z)=>{u.jb("Pad",o,{mode:f,value:b,pads:v?Array.from(i().subarray(v>>>0,z>>>0)):[]})},858836:(o,f,b,v,z,de)=>{u.jb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!v,format:de?"NHWC":"NCHW"})},859005:(o,f,b,v,z,de)=>{u.jb("BatchNormalization",o,{epsilon:f,momentum:b,spatial:!!z,trainingMode:!!v,format:de?"NHWC":"NCHW"})},859174:(o,f,b)=>{u.jb("CumSum",o,{exclusive:Number(f),reverse:Number(b)})},859271:(o,f,b,v,z,de,We,at,Ct)=>{u.jb("Attention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:v,scale:z,doRotary:de,qkvHiddenSizes:We?Array.from(i().subarray(Number(at)>>>0,Number(at)+We>>>0)):[],pastPresentShareBuffer:!!Ct})},859543:o=>{u.jb("BiasAdd",o,void 0)},859598:o=>{u.jb("BiasSplitGelu",o,void 0)},859659:o=>{u.jb("FastGelu",o,void 0)},859715:(o,f,b,v,z,de,We,at,Ct,It,Kt,kr,Fr,Oe,ar,Or)=>{u.jb("Conv",o,{format:kr?"NHWC":"NCHW",auto_pad:f,dilations:b?Array.from(i().subarray(b>>>0,v>>>0)):[],group:z,kernel_shape:de?Array.from(i().subarray(de>>>0,We>>>0)):[],pads:at?Array.from(i().subarray(at>>>0,Ct>>>0)):[],strides:It?Array.from(i().subarray(It>>>0,Kt>>>0)):[],w_is_const:()=>!!r()[Fr>>>0],activation:un(Oe),activation_params:ar?Array.from(c().subarray(ar>>>0,Or>>>0)):[]})},860211:o=>{u.jb("Gelu",o,void 0)},860263:(o,f,b,v)=>{u.jb("GroupQueryAttention",o,{numHeads:f,kvNumHeads:b,scale:v})},860376:(o,f,b,v)=>{u.jb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!v})},860487:(o,f,b,v)=>{u.jb("LayerNormalization",o,{axis:f,epsilon:b,simplified:!!v})},860598:(o,f,b,v,z,de)=>{u.jb("MatMulNBits",o,{k:f,n:b,accuracyLevel:v,bits:z,blockSize:de})},860725:(o,f,b,v,z,de)=>{u.jb("MultiHeadAttention",o,{numHeads:f,isUnidirectional:b,maskFilterValue:v,scale:z,doRotary:de})},860884:(o,f)=>{u.jb("QuickGelu",o,{alpha:f})},860948:(o,f,b,v,z)=>{u.jb("RotaryEmbedding",o,{interleaved:!!f,numHeads:b,rotaryEmbeddingDim:v,scale:z})},861087:(o,f,b)=>{u.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})},861189:o=>{u.Yb(o)},861223:(o,f)=>u.$b(o,f,u.Eb.bc,u.Eb.errors),861335:(o,f,b)=>{u.jb("SkipLayerNormalization",o,{epsilon:f,simplified:!!b})}};function _f(o,f,b){return fh(async()=>{await u.Wb(o,f,b)})}function gf(){return typeof wasmOffsetConverter<"u"}function qd(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Hd=o=>{o.terminate(),o.onmessage=()=>{}},zp=o=>{Bs.length==0&&(jp(),Np(Bs[0]));var f=Bs.pop();if(!f)return 6;pi.push(f),Jn[o.Ab]=f,f.Ab=o.Ab;var b={cmd:"run",start_routine:o.cc,arg:o.Pb,pthread_ptr:o.Ab};return f.postMessage(b,o.ic),0},ci=0,Gr=(o,f,...b)=>{for(var v=2*b.length,z=pc(),de=cc(8*v),We=de>>>3,at=0;at>>0]=Ct)}return o=Lh(o,0,v,de,f),Cd(z),o};function Kd(o){if(U)return Gr(0,1,o);if(Lt=o,!(0{if(Lt=o,U)throw Dp(o),"unwind";Kd(o)},Bs=[],pi=[],Bp=[],Jn={},Lp=o=>{var f=o.Ab;delete Jn[f],Bs.push(o),pi.splice(pi.indexOf(o),1),o.Ab=0,dc(f)};function Rp(){Bp.forEach(o=>o())}var Np=o=>new Promise(f=>{o.onmessage=z=>{var de=(z=z.data).cmd;if(z.targetThread&&z.targetThread!=Aa()){var We=Jn[z.targetThread];We?We.postMessage(z,z.transferList):nr(`Internal error! Worker sent a message "${de}" to target pthread ${z.targetThread}, but that thread no longer exists!`)}else de==="checkMailbox"?md():de==="spawnThread"?zp(z):de==="cleanupThread"?Lp(Jn[z.thread]):de==="killThread"?(z=z.thread,de=Jn[z],delete Jn[z],Hd(de),dc(z),pi.splice(pi.indexOf(de),1),de.Ab=0):de==="cancelThread"?Jn[z.thread].postMessage({cmd:"cancel"}):de==="loaded"?(o.loaded=!0,f(o)):de==="alert"?alert(`Thread ${z.threadId}: ${z.text}`):z.target==="setimmediate"?o.postMessage(z):de==="callHandler"?u[z.handler](...z.args):de&&nr(`worker sent an unknown command ${de}`)},o.onerror=z=>{throw nr(`worker sent an error! ${z.filename}:${z.lineno}: ${z.message}`),z};var b,v=[];for(b of[])u.hasOwnProperty(b)&&v.push(b);o.postMessage({cmd:"load",handlers:v,wasmMemory:dr,wasmModule:Rr})});function jp(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Bs.push(o)}var fd=o=>{for(;0{var o=Aa(),f=d()[o+52>>>2>>>0];o=d()[o+56>>>2>>>0],Nh(f,f-o),Cd(f)},yf=(o,f)=>{ci=0,o=jh(o,f),0>>=0);throw f>>>=0,b>>>=0,d()[v.Ib+16>>>2>>>0]=0,d()[v.Ib+4>>>2>>>0]=f,d()[v.Ib+8>>>2>>>0]=b,o}function Vp(o,f,b,v){return U?Gr(2,1,o,f,b,v):Up(o,f,b,v)}function Up(o,f,b,v){if(o>>>=0,f>>>=0,b>>>=0,v>>>=0,q===void 0)return nr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var z=[];return U&&z.length===0?Vp(o,f,b,v):(o={cc:b,Ab:o,Pb:v,ic:z},U?(o.Lb="spawnThread",postMessage(o,z),0):zp(o))}var Wp=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Gp=(o,f,b)=>{var v=(f>>>=0)+b;for(b=f;o[b]&&!(b>=v);)++b;if(16(z=(240&z)==224?(15&z)<<12|de<<6|We:(7&z)<<18|de<<12|We<<6|63&o[f++])?v+=String.fromCharCode(z):(z-=65536,v+=String.fromCharCode(55296|z>>10,56320|1023&z))}}else v+=String.fromCharCode(z)}return v},un=(o,f)=>(o>>>=0)?Gp(n(),o,f):"";function qp(o,f,b){return U?Gr(3,1,o,f,b):0}function Hp(o,f){if(U)return Gr(4,1,o,f)}var Qd=o=>{for(var f=0,b=0;b=v?f++:2047>=v?f+=2:55296<=v&&57343>=v?(f+=4,++b):f+=3}return f},Kp=(o,f,b,v)=>{if(!(0>>=0;v=b+v-1;for(var de=0;de=We&&(We=65536+((1023&We)<<10)|1023&o.charCodeAt(++de)),127>=We){if(b>=v)break;f[b++>>>0]=We}else{if(2047>=We){if(b+1>=v)break;f[b++>>>0]=192|We>>6}else{if(65535>=We){if(b+2>=v)break;f[b++>>>0]=224|We>>12}else{if(b+3>=v)break;f[b++>>>0]=240|We>>18,f[b++>>>0]=128|We>>12&63}f[b++>>>0]=128|We>>6&63}f[b++>>>0]=128|63&We}}return f[b>>>0]=0,b-z},ka=(o,f,b)=>Kp(o,n(),f,b);function Xp(o,f){if(U)return Gr(5,1,o,f)}function Qp(o,f,b){if(U)return Gr(6,1,o,f,b)}function Yp(o,f,b){return U?Gr(7,1,o,f,b):0}function Zp(o,f){if(U)return Gr(8,1,o,f)}function Jp(o,f,b){if(U)return Gr(9,1,o,f,b)}function eh(o,f,b,v){if(U)return Gr(10,1,o,f,b,v)}function th(o,f,b,v){if(U)return Gr(11,1,o,f,b,v)}function rh(o,f,b,v){if(U)return Gr(12,1,o,f,b,v)}function nh(o){if(U)return Gr(13,1,o)}function sh(o,f){if(U)return Gr(14,1,o,f)}function ih(o,f,b){if(U)return Gr(15,1,o,f,b)}var ah,Ls,vf=()=>{Sa("")},es=o=>{for(var f="";n()[o>>>0];)f+=ah[n()[o++>>>0]];return f},Yd={},Zd={};function fs(o,f,b={}){if(!("argPackAdvance"in f))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(v,z,de={}){var We=z.name;if(!v)throw new Ls(`type "${We}" must have a positive integer typeid pointer`);if(Zd.hasOwnProperty(v)){if(de.Rb)return;throw new Ls(`Cannot register type '${We}' twice`)}Zd[v]=z,Yd.hasOwnProperty(v)&&(z=Yd[v],delete Yd[v],z.forEach(at=>at()))}(o,f,b)}var oh=(o,f,b)=>{switch(f){case 1:return b?v=>r()[v>>>0]:v=>n()[v>>>0];case 2:return b?v=>s()[v>>>1>>>0]:v=>a()[v>>>1>>>0];case 4:return b?v=>i()[v>>>2>>>0]:v=>d()[v>>>2>>>0];case 8:return b?v=>an[v>>>3]:v=>zs[v>>>3];default:throw new TypeError(`invalid integer width (${f}): ${o}`)}};function xf(o,f,b){b>>>=0,fs(o>>>=0,{name:f=es(f>>>0),fromWireType:v=>v,toWireType:function(v,z){if(typeof z!="bigint"&&typeof z!="number")throw z=z===null?"null":(v=typeof z)=="object"||v==="array"||v==="function"?z.toString():""+z,new TypeError(`Cannot convert "${z}" to ${this.name}`);return typeof z=="number"&&(z=BigInt(z)),z},argPackAdvance:Rs,readValueFromPointer:oh(f,b,f.indexOf("u")==-1),Db:null})}var Rs=8;function Tf(o,f,b,v){fs(o>>>=0,{name:f=es(f>>>0),fromWireType:function(z){return!!z},toWireType:function(z,de){return de?b:v},argPackAdvance:Rs,readValueFromPointer:function(z){return this.fromWireType(n()[z>>>0])},Db:null})}var Jd=[],ms=[];function ec(o){9<(o>>>=0)&&--ms[o+1]==0&&(ms[o]=void 0,Jd.push(o))}var jn=o=>{if(!o)throw new Ls("Cannot use deleted val. handle = "+o);return ms[o]},Vn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Jd.pop()||ms.length;return ms[f]=o,ms[f+1]=1,f}};function tc(o){return this.fromWireType(d()[o>>>2>>>0])}var Cf={name:"emscripten::val",fromWireType:o=>{var f=jn(o);return ec(o),f},toWireType:(o,f)=>Vn(f),argPackAdvance:Rs,readValueFromPointer:tc,Db:null};function $f(o){return fs(o>>>0,Cf)}var Ef=(o,f)=>{switch(f){case 4:return function(b){return this.fromWireType(c()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(h()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${o}`)}};function Sf(o,f,b){b>>>=0,fs(o>>>=0,{name:f=es(f>>>0),fromWireType:v=>v,toWireType:(v,z)=>z,argPackAdvance:Rs,readValueFromPointer:Ef(f,b),Db:null})}function kf(o,f,b,v,z){if(o>>>=0,b>>>=0,f=es(f>>>0),z===-1&&(z=4294967295),z=at=>at,v===0){var de=32-8*b;z=at=>at<>>de}var We=f.includes("unsigned")?function(at,Ct){return Ct>>>0}:function(at,Ct){return Ct};fs(o,{name:f,fromWireType:z,toWireType:We,argPackAdvance:Rs,readValueFromPointer:oh(f,b,v!==0),Db:null})}function Pf(o,f,b){function v(de){var We=d()[de>>>2>>>0];return de=d()[de+4>>>2>>>0],new z(r().buffer,de,We)}var z=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];fs(o>>>=0,{name:b=es(b>>>0),fromWireType:v,argPackAdvance:Rs,readValueFromPointer:v},{Rb:!0})}function Af(o,f){o>>>=0;var b=(f=es(f>>>0))==="std::string";fs(o,{name:f,fromWireType:function(v){var z=d()[v>>>2>>>0],de=v+4;if(b)for(var We=de,at=0;at<=z;++at){var Ct=de+at;if(at==z||n()[Ct>>>0]==0){if(We=un(We,Ct-We),It===void 0)var It=We;else It+="\0",It+=We;We=Ct+1}}else{for(It=Array(z),at=0;at>>0]);It=It.join("")}return rs(v),It},toWireType:function(v,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var de=typeof z=="string";if(!(de||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new Ls("Cannot pass non-string to std::string");var We=b&&de?Qd(z):z.length,at=xd(4+We+1),Ct=at+4;if(d()[at>>>2>>>0]=We,b&&de)ka(z,Ct,We+1);else if(de)for(de=0;de>>0]=It}else for(de=0;de>>0]=z[de];return v!==null&&v.push(rs,at),at},argPackAdvance:Rs,readValueFromPointer:tc,Db(v){rs(v)}})}var lh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,If=(o,f)=>{for(var b=o>>1,v=b+f/2;!(b>=v)&&a()[b>>>0];)++b;if(32<(b<<=1)-o&&lh)return lh.decode(n().slice(o,b));for(b="",v=0;!(v>=f/2);++v){var z=s()[o+2*v>>>1>>>0];if(z==0)break;b+=String.fromCharCode(z)}return b},Ff=(o,f,b)=>{if(b??(b=2147483647),2>b)return 0;var v=f;b=(b-=2)<2*o.length?b/2:o.length;for(var z=0;z>>1>>>0]=de,f+=2}return s()[f>>>1>>>0]=0,f-v},Of=o=>2*o.length,zf=(o,f)=>{for(var b=0,v="";!(b>=f/4);){var z=i()[o+4*b>>>2>>>0];if(z==0)break;++b,65536<=z?(z-=65536,v+=String.fromCharCode(55296|z>>10,56320|1023&z)):v+=String.fromCharCode(z)}return v},Df=(o,f,b)=>{if(f>>>=0,b??(b=2147483647),4>b)return 0;var v=f;b=v+b-4;for(var z=0;z=de&&(de=65536+((1023&de)<<10)|1023&o.charCodeAt(++z)),i()[f>>>2>>>0]=de,(f+=4)+4>b)break}return i()[f>>>2>>>0]=0,f-v},Bf=o=>{for(var f=0,b=0;b=v&&++b,f+=4}return f};function Lf(o,f,b){if(o>>>=0,f>>>=0,b=es(b>>>=0),f===2)var v=If,z=Ff,de=Of,We=at=>a()[at>>>1>>>0];else f===4&&(v=zf,z=Df,de=Bf,We=at=>d()[at>>>2>>>0]);fs(o,{name:b,fromWireType:at=>{for(var Ct,It=d()[at>>>2>>>0],Kt=at+4,kr=0;kr<=It;++kr){var Fr=at+4+kr*f;kr!=It&&We(Fr)!=0||(Kt=v(Kt,Fr-Kt),Ct===void 0?Ct=Kt:(Ct+="\0",Ct+=Kt),Kt=Fr+f)}return rs(at),Ct},toWireType:(at,Ct)=>{if(typeof Ct!="string")throw new Ls(`Cannot pass non-string to C++ string type ${b}`);var It=de(Ct),Kt=xd(4+It+f);return d()[Kt>>>2>>>0]=It/f,z(Ct,Kt+4,It+f),at!==null&&at.push(rs,Kt),Kt},argPackAdvance:Rs,readValueFromPointer:tc,Db(at){rs(at)}})}function Rf(o,f){fs(o>>>=0,{Sb:!0,name:f=es(f>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Nf=()=>1;function jf(o){uc(o>>>0,!I,1,!T,131072,!1),Rp()}var uh=o=>{if(!In)try{if(o(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(i(),o>>>2,o).value.then(md),o+=128,Atomics.store(i(),o>>>2,1))}var md=()=>{var o=Aa();o&&(rc(o),uh(Rh))};function Vf(o,f){(o>>>=0)==f>>>0?setTimeout(md):U?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=Jn[o])&&o.postMessage({cmd:"checkMailbox"})}var nc=[];function Uf(o,f,b,v,z){for(f>>>=0,v/=2,nc.length=v,b=z>>>0>>>3,z=0;z>>0];return(f?Gd[f]:Im[o])(...nc)}function Wf(o){o>>>=0,U?postMessage({cmd:"cleanupThread",thread:o}):Lp(Jn[o])}function Gf(o){}var sc=(o,f)=>{var b=Zd[o];if(b===void 0)throw o=zh(o),b=es(o),rs(o),new Ls(`${f} has unknown type ${b}`);return b},dh=(o,f,b)=>{var v=[];return o=o.toWireType(v,b),v.length&&(d()[f>>>2>>>0]=Vn(v)),o};function qf(o,f,b){return f>>>=0,b>>>=0,o=jn(o>>>0),f=sc(f,"emval::as"),dh(f,b,o)}var _d=o=>{try{o()}catch(f){Sa(f)}},Ns=0,ts=null,ch=0,gd=[],ph={},hh={},Hf=0,ic=null,Kf=[];function fh(o){return function(f){if(!In){if(Ns===0){var b=!1,v=!1;f((z=0)=>{if(!In&&(ch=z,b=!0,v)){Ns=2,_d(()=>Wh(ts)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),z=!1;try{var de=function(){var Ct=i()[ts+8>>>2>>>0];return Ct=qt[hh[Ct]],--ci,Ct()}()}catch(Ct){de=Ct,z=!0}var We=!1;if(!ts){var at=ic;at&&(ic=null,(z?at.reject:at.resolve)(de),We=!0)}if(z&&!We)throw de}}),v=!0,b||(Ns=1,ts=function(){var z=xd(65548),de=z+12;d()[z>>>2>>>0]=de,d()[z+4>>>2>>>0]=de+65536,de=gd[0];var We=ph[de];return We===void 0&&(We=Hf++,ph[de]=We,hh[We]=de),de=We,i()[z+8>>>2>>>0]=de,z}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),_d(()=>Vh(ts)))}else Ns===2?(Ns=0,_d(Gh),rs(ts),ts=null,Kf.forEach(uh)):Sa(`invalid state: ${Ns}`);return ch}}(f=>{o().then(f)})}function Xf(o){return o>>>=0,fh(()=>(o=jn(o)).then(Vn))}var wd=[];function Qf(o,f,b,v){return b>>>=0,v>>>=0,(o=wd[o>>>0])(null,f=jn(f>>>0),b,v)}var Yf={},yd=o=>{var f=Yf[o];return f===void 0?es(o):f};function Zf(o,f,b,v,z){return b>>>=0,v>>>=0,z>>>=0,(o=wd[o>>>0])(f=jn(f>>>0),f[b=yd(b)],v,z)}var mh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Jf(o){return(o>>>=0)==0?Vn(mh()):(o=yd(o),Vn(mh()[o]))}var em=o=>{var f=wd.length;return wd.push(o),f},tm=(o,f)=>{for(var b=Array(o),v=0;v>>2>>>0],"parameter "+v);return b},_h=(o,f)=>Object.defineProperty(f,"name",{value:o});function rm(o,f,b){var v=(f=tm(o,f>>>0)).shift();o--;var z=`return function (obj, func, destructorsRef, args) { +`,de=0,We=[];b===0&&We.push("obj");for(var at=["retType"],Ct=[v],It=0;ItKt.name).join(", ")}) => ${v.name}>`,em(_h(b,o))}function nm(o){return o=yd(o>>>0),Vn(u[o])}function sm(o,f){return f>>>=0,o=jn(o>>>0),f=jn(f),Vn(o[f])}function im(o){9<(o>>>=0)&&(ms[o+1]+=1)}function am(){return Vn([])}function om(o){o=jn(o>>>0);for(var f=Array(o.length),b=0;b>>0))}function um(){return Vn({})}function dm(o){for(var f=jn(o>>>=0);f.length;){var b=f.pop();f.pop()(b)}ec(o)}function cm(o,f,b){f>>>=0,b>>>=0,o=jn(o>>>0),f=jn(f),b=jn(b),o[f]=b}function pm(o,f){return f>>>=0,o=(o=sc(o>>>0,"_emval_take_value")).readValueFromPointer(f),Vn(o)}function hm(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getUTCSeconds(),i()[f+4>>>2>>>0]=o.getUTCMinutes(),i()[f+8>>>2>>>0]=o.getUTCHours(),i()[f+12>>>2>>>0]=o.getUTCDate(),i()[f+16>>>2>>>0]=o.getUTCMonth(),i()[f+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[f+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[f+28>>>2>>>0]=o}var Pa=o=>o%4==0&&(o%100!=0||o%400==0),gh=[0,31,60,91,121,152,182,213,244,274,305,335],wh=[0,31,59,90,120,151,181,212,243,273,304,334];function fm(o,f){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[f>>>2>>>0]=o.getSeconds(),i()[f+4>>>2>>>0]=o.getMinutes(),i()[f+8>>>2>>>0]=o.getHours(),i()[f+12>>>2>>>0]=o.getDate(),i()[f+16>>>2>>>0]=o.getMonth(),i()[f+20>>>2>>>0]=o.getFullYear()-1900,i()[f+24>>>2>>>0]=o.getDay();var b=(Pa(o.getFullYear())?gh:wh)[o.getMonth()]+o.getDate()-1|0;i()[f+28>>>2>>>0]=b,i()[f+36>>>2>>>0]=-60*o.getTimezoneOffset(),b=new Date(o.getFullYear(),6,1).getTimezoneOffset();var v=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(b!=v&&o.getTimezoneOffset()==Math.min(v,b)),i()[f+32>>>2>>>0]=o}function mm(o){o>>>=0;var f=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),b=i()[o+32>>>2>>>0],v=f.getTimezoneOffset(),z=new Date(f.getFullYear(),6,1).getTimezoneOffset(),de=new Date(f.getFullYear(),0,1).getTimezoneOffset(),We=Math.min(de,z);return 0>b?i()[o+32>>>2>>>0]=+(z!=de&&We==v):0>>2>>>0]=f.getDay(),b=(Pa(f.getFullYear())?gh:wh)[f.getMonth()]+f.getDate()-1|0,i()[o+28>>>2>>>0]=b,i()[o>>>2>>>0]=f.getSeconds(),i()[o+4>>>2>>>0]=f.getMinutes(),i()[o+8>>>2>>>0]=f.getHours(),i()[o+12>>>2>>>0]=f.getDate(),i()[o+16>>>2>>>0]=f.getMonth(),i()[o+20>>>2>>>0]=f.getYear(),o=f.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function yh(o,f,b,v,z,de,We){return U?Gr(16,1,o,f,b,v,z,de,We):-52}function bh(o,f,b,v,z,de){if(U)return Gr(17,1,o,f,b,v,z,de)}function _m(o,f,b,v){o>>>=0,f>>>=0,b>>>=0,v>>>=0;var z=new Date().getFullYear(),de=new Date(z,0,1),We=new Date(z,6,1);z=de.getTimezoneOffset();var at=We.getTimezoneOffset(),Ct=Math.max(z,at);d()[o>>>2>>>0]=60*Ct,i()[f>>>2>>>0]=+(z!=at),de=(o=It=>It.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(de),We=o(We),at{ac.length=0;for(var b;b=n()[o++>>>0];){var v=b!=105;f+=(v&=b!=112)&&f%8?4:0,ac.push(b==112?d()[f>>>2>>>0]:b==106?an[f>>>3]:b==105?i()[f>>>2>>>0]:h()[f>>>3>>>0]),f+=v?8:4}return ac};function gm(o,f,b){return o>>>=0,f=Mh(f>>>0,b>>>0),Gd[o](...f)}function wm(o,f,b){return o>>>=0,f=Mh(f>>>0,b>>>0),Gd[o](...f)}var ym=()=>{},bm=()=>Date.now();function Mm(o,f){return nr(un(o>>>0,f>>>0))}var vh,vm=()=>{throw ci+=1,"unwind"};function xm(){return 4294901760}vh=()=>performance.timeOrigin+performance.now();var Tm=()=>navigator.hardwareConcurrency;function Cm(){return Sa("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function $m(o){o>>>=0;var f=n().length;if(o<=f||4294901760=b;b*=2){var v=f*(1+.2/b);v=Math.min(v,o+100663296);var z=Math;v=Math.max(o,v);e:{z=(z.min.call(z,4294901760,v+(65536-v%65536)%65536)-dr.buffer.byteLength+65535)/65536;try{dr.grow(z),pn();var de=1;break e}catch{}de=void 0}if(de)return!0}return!1}var bd=()=>(Sa("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Iu={},xh=o=>{o.forEach(f=>{bd()})};function Em(){var o=Error().stack.toString().split(` +`);return o[0]=="Error"&&o.shift(),xh(o),Iu.Ob=bd(),Iu.ac=o,Iu.Ob}function Sm(o,f,b){if(o>>>=0,f>>>=0,Iu.Ob==o)var v=Iu.ac;else(v=Error().stack.toString().split(` +`))[0]=="Error"&&v.shift(),xh(v);for(var z=3;v[z]&&bd()!=o;)++z;for(o=0;o>>2>>>0]=bd();return o}var oc,lc={},Th=()=>{if(!oc){var o,f={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",_:tt};for(o in lc)lc[o]===void 0?delete f[o]:f[o]=lc[o];var b=[];for(o in f)b.push(`${o}=${f[o]}`);oc=b}return oc};function Ch(o,f){if(U)return Gr(18,1,o,f);o>>>=0,f>>>=0;var b=0;return Th().forEach((v,z)=>{var de=f+b;for(z=d()[o+4*z>>>2>>>0]=de,de=0;de>>0]=v.charCodeAt(de);r()[z>>>0]=0,b+=v.length+1}),0}function $h(o,f){if(U)return Gr(19,1,o,f);o>>>=0,f>>>=0;var b=Th();d()[o>>>2>>>0]=b.length;var v=0;return b.forEach(z=>v+=z.length+1),d()[f>>>2>>>0]=v,0}function Eh(o){return U?Gr(20,1,o):52}function Sh(o,f,b,v){return U?Gr(21,1,o,f,b,v):52}function kh(o,f,b,v){return U?Gr(22,1,o,f,b,v):70}var km=[null,[],[]];function Ph(o,f,b,v){if(U)return Gr(23,1,o,f,b,v);f>>>=0,b>>>=0,v>>>=0;for(var z=0,de=0;de>>2>>>0],at=d()[f+4>>>2>>>0];f+=8;for(var Ct=0;Ct>>0],Kt=km[o];It===0||It===10?((o===1?gr:nr)(Gp(Kt,0)),Kt.length=0):Kt.push(It)}z+=at}return d()[v>>>2>>>0]=z,0}var Ah=[31,29,31,30,31,30,31,31,30,31,30,31],Ih=[31,28,31,30,31,30,31,31,30,31,30,31],Pm=(o,f)=>{r().set(o,f>>>0)};function Fh(o,f,b,v){function z(Oe,ar,Or){for(Oe=typeof Oe=="number"?Oe.toString():Oe||"";Oe.lengthHh?-1:0hi-Oe.getDate())){Oe.setDate(Oe.getDate()+ar);break}ar-=hi-Oe.getDate()+1,Oe.setDate(1),11>Or?Oe.setMonth(Or+1):(Oe.setMonth(0),Oe.setFullYear(Oe.getFullYear()+1))}return Or=new Date(Oe.getFullYear()+1,0,4),ar=at(new Date(Oe.getFullYear(),0,4)),Or=at(Or),0>=We(ar,Oe)?0>=We(Or,Oe)?Oe.getFullYear()+1:Oe.getFullYear():Oe.getFullYear()-1}o>>>=0,f>>>=0,b>>>=0,v>>>=0;var It=d()[v+40>>>2>>>0];for(var Kt in v={fc:i()[v>>>2>>>0],ec:i()[v+4>>>2>>>0],Gb:i()[v+8>>>2>>>0],Kb:i()[v+12>>>2>>>0],Hb:i()[v+16>>>2>>>0],Cb:i()[v+20>>>2>>>0],ub:i()[v+24>>>2>>>0],Bb:i()[v+28>>>2>>>0],nc:i()[v+32>>>2>>>0],dc:i()[v+36>>>2>>>0],hc:It?un(It):""},b=un(b),It={"%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"})b=b.replace(new RegExp(Kt,"g"),It[Kt]);var kr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Fr="January February March April May June July August September October November December".split(" ");for(Kt in It={"%a":Oe=>kr[Oe.ub].substring(0,3),"%A":Oe=>kr[Oe.ub],"%b":Oe=>Fr[Oe.Hb].substring(0,3),"%B":Oe=>Fr[Oe.Hb],"%C":Oe=>de((Oe.Cb+1900)/100|0,2),"%d":Oe=>de(Oe.Kb,2),"%e":Oe=>z(Oe.Kb,2," "),"%g":Oe=>Ct(Oe).toString().substring(2),"%G":Ct,"%H":Oe=>de(Oe.Gb,2),"%I":Oe=>((Oe=Oe.Gb)==0?Oe=12:12{for(var ar=0,Or=0;Or<=Oe.Hb-1;ar+=(Pa(Oe.Cb+1900)?Ah:Ih)[Or++]);return de(Oe.Kb+ar,3)},"%m":Oe=>de(Oe.Hb+1,2),"%M":Oe=>de(Oe.ec,2),"%n":()=>` +`,"%p":Oe=>0<=Oe.Gb&&12>Oe.Gb?"AM":"PM","%S":Oe=>de(Oe.fc,2),"%t":()=>" ","%u":Oe=>Oe.ub||7,"%U":Oe=>de(Math.floor((Oe.Bb+7-Oe.ub)/7),2),"%V":Oe=>{var ar=Math.floor((Oe.Bb+7-(Oe.ub+6)%7)/7);if(2>=(Oe.ub+371-Oe.Bb-2)%7&&ar++,ar)ar==53&&((Or=(Oe.ub+371-Oe.Bb)%7)==4||Or==3&&Pa(Oe.Cb)||(ar=1));else{ar=52;var Or=(Oe.ub+7-Oe.Bb-1)%7;(Or==4||Or==5&&Pa(Oe.Cb%400-1))&&ar++}return de(ar,2)},"%w":Oe=>Oe.ub,"%W":Oe=>de(Math.floor((Oe.Bb+7-(Oe.ub+6)%7)/7),2),"%y":Oe=>(Oe.Cb+1900).toString().substring(2),"%Y":Oe=>Oe.Cb+1900,"%z":Oe=>{var ar=0<=(Oe=Oe.dc);return Oe=Math.abs(Oe)/60,(ar?"+":"-")+("0000"+(Oe/60*100+Oe%60)).slice(-4)},"%Z":Oe=>Oe.hc,"%%":()=>"%"},b=b.replace(/%%/g,"\0\0"),It)b.includes(Kt)&&(b=b.replace(new RegExp(Kt,"g"),It[Kt](v)));return Kt=function(Oe){var ar=Array(Qd(Oe)+1);return Kp(Oe,ar,0,ar.length),ar}(b=b.replace(/\0\0/g,"%")),Kt.length>f?0:(Pm(Kt,o),Kt.length-1)}function Am(o,f,b,v){return Fh(o>>>0,f>>>0,b>>>0,v>>>0)}U||function(){for(var o=u.numThreads-1;o--;)jp();Au.unshift(()=>{Nn++,function(f){U?f():Promise.all(Bs.map(Np)).then(f)}(()=>hd())})}();for(var Oh=Array(256),Md=0;256>Md;++Md)Oh[Md]=String.fromCharCode(Md);ah=Oh,Ls=u.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},u.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},ms.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>ms.length/2-5-Jd.length;var Im=[Kd,Dp,Vp,qp,Hp,Xp,Qp,Yp,Zp,Jp,eh,th,rh,nh,sh,ih,yh,bh,Ch,$h,Eh,Sh,kh,Ph],qt=function(){function o(b,v){return qt=b.exports,qt=function(){var z=qt,de={};for(let[We,at]of Object.entries(z))de[We]=typeof at=="function"?(...Ct)=>{gd.push(We);try{return at(...Ct)}finally{In||(gd.pop(),ts&&Ns===1&&gd.length===0&&(Ns=0,ci+=1,_d(Uh),typeof Fibers<"u"&&Fibers.oc()))}}:at;return de}(),qt=function(){var z=qt,de=at=>Ct=>at(Ct)>>>0,We=at=>()=>at()>>>0;return(z=Object.assign({},z)).Ca=de(z.Ca),z.fb=We(z.fb),z.gb=de(z.gb),z.emscripten_main_runtime_thread_id=We(z.emscripten_main_runtime_thread_id),z.sb=de(z.sb),z.tb=We(z.tb),z}(),Bp.push(qt.ib),hn.unshift(qt.Ba),Rr=v,hd(),qt}var f=Op();if(Nn++,u.instantiateWasm)try{return u.instantiateWasm(f,o)}catch(b){nr(`Module.instantiateWasm callback failed with error: ${b}`),y(b)}return Wd||(Wd=u.locateFile?Pp("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",dt):dt+"ort-wasm-simd-threaded.jsep.wasm":new URL(l("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),l.b).href),function(b,v){var z=Wd;return Ot||typeof WebAssembly.instantiateStreaming!="function"||Pp(z)||Ap(z)||typeof fetch!="function"?Fp(z,b,v):fetch(z,{credentials:"same-origin"}).then(de=>WebAssembly.instantiateStreaming(de,b).then(v,function(We){return nr(`wasm streaming compile failed: ${We}`),nr("falling back to ArrayBuffer instantiation"),Fp(z,b,v)}))}(f,function(b){o(b.instance,b.module)}).catch(y),{}}(),zh=o=>(zh=qt.Ca)(o),Dh=()=>(Dh=qt.Da)();u._OrtInit=(o,f)=>(u._OrtInit=qt.Ea)(o,f),u._OrtGetLastError=(o,f)=>(u._OrtGetLastError=qt.Fa)(o,f),u._OrtCreateSessionOptions=(o,f,b,v,z,de,We,at,Ct,It)=>(u._OrtCreateSessionOptions=qt.Ga)(o,f,b,v,z,de,We,at,Ct,It),u._OrtAppendExecutionProvider=(o,f)=>(u._OrtAppendExecutionProvider=qt.Ha)(o,f),u._OrtAddFreeDimensionOverride=(o,f,b)=>(u._OrtAddFreeDimensionOverride=qt.Ia)(o,f,b),u._OrtAddSessionConfigEntry=(o,f,b)=>(u._OrtAddSessionConfigEntry=qt.Ja)(o,f,b),u._OrtReleaseSessionOptions=o=>(u._OrtReleaseSessionOptions=qt.Ka)(o),u._OrtCreateSession=(o,f,b)=>(u._OrtCreateSession=qt.La)(o,f,b),u._OrtReleaseSession=o=>(u._OrtReleaseSession=qt.Ma)(o),u._OrtGetInputOutputCount=(o,f,b)=>(u._OrtGetInputOutputCount=qt.Na)(o,f,b),u._OrtGetInputName=(o,f)=>(u._OrtGetInputName=qt.Oa)(o,f),u._OrtGetOutputName=(o,f)=>(u._OrtGetOutputName=qt.Pa)(o,f),u._OrtFree=o=>(u._OrtFree=qt.Qa)(o),u._OrtCreateTensor=(o,f,b,v,z,de)=>(u._OrtCreateTensor=qt.Ra)(o,f,b,v,z,de),u._OrtGetTensorData=(o,f,b,v,z)=>(u._OrtGetTensorData=qt.Sa)(o,f,b,v,z),u._OrtReleaseTensor=o=>(u._OrtReleaseTensor=qt.Ta)(o),u._OrtCreateRunOptions=(o,f,b,v)=>(u._OrtCreateRunOptions=qt.Ua)(o,f,b,v),u._OrtAddRunConfigEntry=(o,f,b)=>(u._OrtAddRunConfigEntry=qt.Va)(o,f,b),u._OrtReleaseRunOptions=o=>(u._OrtReleaseRunOptions=qt.Wa)(o),u._OrtCreateBinding=o=>(u._OrtCreateBinding=qt.Xa)(o),u._OrtBindInput=(o,f,b)=>(u._OrtBindInput=qt.Ya)(o,f,b),u._OrtBindOutput=(o,f,b,v)=>(u._OrtBindOutput=qt.Za)(o,f,b,v),u._OrtClearBoundOutputs=o=>(u._OrtClearBoundOutputs=qt._a)(o),u._OrtReleaseBinding=o=>(u._OrtReleaseBinding=qt.$a)(o),u._OrtRunWithBinding=(o,f,b,v,z)=>(u._OrtRunWithBinding=qt.ab)(o,f,b,v,z),u._OrtRun=(o,f,b,v,z,de,We,at)=>(u._OrtRun=qt.bb)(o,f,b,v,z,de,We,at),u._OrtEndProfiling=o=>(u._OrtEndProfiling=qt.cb)(o),u._JsepOutput=(o,f,b)=>(u._JsepOutput=qt.db)(o,f,b),u._JsepGetNodeName=o=>(u._JsepGetNodeName=qt.eb)(o);var vd,Aa=()=>(Aa=qt.fb)(),xd=u._malloc=o=>(xd=u._malloc=qt.gb)(o),rs=u._free=o=>(rs=u._free=qt.hb)(o),uc=(o,f,b,v,z,de)=>(uc=qt.kb)(o,f,b,v,z,de),Bh=()=>(Bh=qt.lb)(),Lh=(o,f,b,v,z)=>(Lh=qt.mb)(o,f,b,v,z),dc=o=>(dc=qt.nb)(o),Td=o=>(Td=qt.ob)(o),Rh=()=>(Rh=qt.pb)(),Nh=(o,f)=>(Nh=qt.qb)(o,f),Cd=o=>(Cd=qt.rb)(o),cc=o=>(cc=qt.sb)(o),pc=()=>(pc=qt.tb)(),jh=u.dynCall_ii=(o,f)=>(jh=u.dynCall_ii=qt.vb)(o,f),Vh=o=>(Vh=qt.wb)(o),Uh=()=>(Uh=qt.xb)(),Wh=o=>(Wh=qt.yb)(o),Gh=()=>(Gh=qt.zb)();function qh(){0pc(),u.stackRestore=o=>Cd(o),u.stackAlloc=o=>cc(o),u.UTF8ToString=un,u.stringToUTF8=ka,u.lengthBytesUTF8=Qd,Ds=function o(){vd||qh(),vd||(Ds=o)},qh(),k}),Tt=ht,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ht()}),Qe,Vt,Nt,Ht,Xt,er,Wt,Tr,Ur=B(()=>{var e,t;K(),Qe=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Vt=typeof location>"u"?void 0:location.origin,Nt=(r,n)=>{try{let s=n??Qe;return(s?new URL(r,s):new URL(r)).origin===Vt}catch{return!1}},Ht=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Xt=(ut(),P(we)).default,er=async()=>{if(!Qe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Qe))return[void 0,Xt()];let r=await Ht(Qe);return[r,Xt(r)]},Wt=(Rt(),P(nt)).default,Tr=async(r,n,s)=>[void 0,Wt]}),Cr,Ze,Et,Bt,qr,Un,Fn,Lr,Zr=B(()=>{Ur(),Ze=!1,Et=!1,Bt=!1,qr=()=>{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}},Un=()=>{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}},Fn=async e=>{if(Ze)return Promise.resolve();if(Et)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Et=!0;let t=e.initTimeout,r=e.numThreads;if(!Un())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=qr();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,d=(i==null?void 0:i.href)??i,c=s==null?void 0:s.wasm,h=(c==null?void 0:c.href)??c,w=e.wasmBinary,[y,u]=await Tr(d,a,r>1),k=!1,T=[];if(t>0&&T.push(new Promise(I=>{setTimeout(()=>{k=!0,I()},t)})),T.push(new Promise((I,U)=>{let q={numThreads:r};w?q.wasmBinary=w:(h||a)&&(q.locateFile=(R,ce)=>h??(a??ce)+R),u(q).then(R=>{Et=!1,Ze=!0,Cr=R,I(),y&&URL.revokeObjectURL(y)},R=>{Et=!1,Bt=!0,U(R)})})),await Promise.race(T),k)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Lr=()=>{if(Ze&&Cr)return Cr;throw new Error("WebAssembly is not initialized yet.")}}),Nr,Sn,Pr,Wn=B(()=>{Zr(),Nr=(e,t)=>{let r=Lr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Sn=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")Sn(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Pr=e=>{let t=Lr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),On,Vs=B(()=>{Zr(),Wn(),On=e=>{let t=Lr(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.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==null?void 0:e.logVerbosityLevel)===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Nr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Pr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Sn(e.extra,"",new WeakSet,(i,d)=>{let c=Nr(i,n),h=Nr(d,n);t._OrtAddRunConfigEntry(r,c,h)!==0&&Pr(`Can't set a run config entry: ${i} - ${d}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),_s,gs,ws,ys,Gn,Us=B(()=>{Zr(),Wn(),_s=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}`)}},gs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ws=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},ys=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let d=Nr("deviceType",r),c=Nr(i,r);Lr()._OrtAddSessionConfigEntry(e,d,c)!==0&&Pr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let d=Nr("preferredLayout",r),c=Nr(i.preferredLayout,r);Lr()._OrtAddSessionConfigEntry(e,d,c)!==0&&Pr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Nr(s,r);Lr()._OrtAppendExecutionProvider(e,a)!==0&&Pr(`Can't append execution provider: ${s}.`)}},Gn=e=>{let t=Lr(),r=0,n=[],s=e||{};ws(s);try{let a=_s(s.graphOptimizationLevel??"all"),i=gs(s.executionMode??"sequential"),d=typeof s.logId=="string"?Nr(s.logId,n):0,c=s.logSeverityLevel??2;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log serverity level is not valid: ${c}`);let h=s.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let w=typeof s.optimizedModelFilePath=="string"?Nr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,d,c,h,w),r===0&&Pr("Can't create session options."),s.executionProviders&&ys(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let y=Nr("enableGraphCapture",n),u=Nr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,y,u)!==0&&Pr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[y,u]of Object.entries(s.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let k=Nr(y,n);t._OrtAddFreeDimensionOverride(r,k,u)!==0&&Pr(`Can't set a free dimension override: ${y} - ${u}.`)}return s.extra!==void 0&&Sn(s.extra,"",new WeakSet,(y,u)=>{let k=Nr(y,n),T=Nr(u,n);t._OrtAddSessionConfigEntry(r,k,T)!==0&&Pr(`Can't set a session config entry: ${y} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),ss,kn,zn,Dn,Qn,is,as,Qt=B(()=>{ss=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},kn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},zn=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Dn=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}`)}},Qn=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}`)}},is=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",as=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}}),Yn,bs=B(()=>{K(),Yn=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 r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let c=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:c,maximum:c}).buffer}else throw d}let i=0;for(;;){let{done:d,value:c}=await s.read();if(d)break;let h=c.byteLength;new Uint8Array(a,i,h).set(c),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ms,os,vs,xs,ls,Ts,Dr,fn=B(()=>{Qt(),Ms=["V","I","W","E","F"],os=(e,t)=>{console.log(`[${Ms[e]},${new Date().toISOString()}]${t}`)},ls=(e,t)=>{vs=e,xs=t},Ts=(e,t)=>{let r=Qn(e),n=Qn(vs);r>=n&&os(r,typeof t=="function"?t():t)},Dr=(...e)=>{xs&&Ts(...e)}}),Me,_=B(()=>{Qt(),Me=(e,t)=>new(Dn(t))(e)}),F=B(()=>{}),Y,le,ue,Ie,_t,yt,wt,Pt,Jt,$r=B(()=>{fn(),F(),Y=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]]),le=[],ue=e=>Math.ceil(e/16)*16,Ie=e=>{for(let t=0;t_t++,wt=async(e,t,r,n)=>{let s=ue(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let c=n();return c.set(new Uint8Array(d,0,r)),c}else return new Uint8Array(d.slice(0,r))}finally{a.destroy()}},Pt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[t]of Y)le.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=ue(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(r,n,s)),d.unmap();let h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(d,0,i.gpuData.buffer,0,a),Dr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(d)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)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(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=ue(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(e===r)return Dr("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!`);this.externalBuffers.delete(r)}else n=yt();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),Dr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),Dr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=Ie(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let d=(s?this.freeBuffers:this.freeUniformBuffers).get(r);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:yt(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),Dr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return Dr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await wt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Y.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.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=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},Jt=(...e)=>new Pt(...e)}),sr,Gt,hr=B(()=>{sr=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}},Gt=e=>new sr(e)}),on,Yr,He,yn,wr,Hr,dn,Yt=B(()=>{on=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Yr=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let d=on.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(d===void 0)return;[i[a-2],i[a-1]]=d}for(let d=r?3:1;d<=a;d++){let c=n-d<0?1:e[n-d],h=s-d<0?1:t[s-d];if(c!==h&&c>1&&h>1)return;let w=Math.max(c,h);if(c&&h)i[a-d]=Math.max(c,h);else{if(w>1)return;i[a-d]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},He=class $d{static size(t){return $d.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){s[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");s[a]=1,r/=t[a],a--}for(a--;a>=0;a--)s[a]=t[a];return s}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return $d.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return $d.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let a=r;a=0;--s)n[s]=n[s+1]*t[s+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((s,a)=>s+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},yn=class Fu{static adjustPoolAttributes(t,r,n,s,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(r[d+2]):n[d]=r[d+2];for(let d=0;d=n[d]||i[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c{Qt(),Yt(),mn=64,Jr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},br=(e,t=1)=>{let r=Jr(e,t);return typeof r=="string"?r:r[0]},Mr=(e,t=1)=>{let r=Jr(e,t);return typeof r=="string"?r:r[1]},St=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:He.computeStrides(r)})}),t},mr=e=>e%4===0?4:e%2===0?2:1,Ar=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,jr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,_n=(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,Ft=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Ws=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,d=[...new Array(i).keys()],c=i<2?"u32":i<=4?`vec${i}`:`array`,h=Jr(t,s),w=typeof h=="string"?h:h[1],y=typeof h=="string"?h:h[0],u={indices:c,value:w,storage:y,tensor:t},k=Le=>typeof Le=="string"?Le:`${Le}u`,T={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},I=a?"uniforms.":"",U=`${I}${e}_shape`,q=`${I}${e}_strides`,R="";for(let Le=0;Le ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${R} + return indices; + }`,Z=Le=>(T.offsetToIndices=!0,i<2?Le:`o2i_${e}(${Le})`),oe=[];if(i>=2)for(let Le=i-1;Le>=0;Le--)oe.push(`${Ft(q,Le,i)} * (indices[${Le}])`);let tt=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${oe.join("+")}; + }`,Ge=Le=>(T.indicesToOffset=!0,i<2?Le:`i2o_${e}(${Le})`),dt=(...Le)=>i===0?"0u":`${u.indices}(${Le.map(k).join(",")})`,Ot=(Le,jt)=>i<2?`${Le}`:`${Ft(Le,jt,i)}`,Dt=(Le,jt,rr)=>i<2?`${Le}=${rr};`:`${Ft(Le,jt,i)}=${rr};`,pr={},gr=(Le,jt)=>{T.broadcastedIndicesToOffset=!0;let rr=`${jt.name}broadcastedIndicesTo${e}Offset`;if(rr in pr)return`${rr}(${Le})`;let Br=[];for(let Xr=i-1;Xr>=0;Xr--){let an=jt.indicesGet("outputIndices",Xr+jt.rank-i);Br.push(`${Ot(q,Xr)} * (${an} % ${Ot(U,Xr)})`)}return pr[rr]=`fn ${rr}(outputIndices: ${jt.type.indices}) -> u32 { + return ${Br.length>0?Br.join("+"):"0u"}; + }`,`${rr}(${Le})`},nr=(Le,jt)=>(()=>{if(u.storage===u.value)return`${e}[${Le}]=${jt};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${Le}]=vec2(u32(${jt}), select(0u, 0xFFFFFFFFu, ${jt} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${Le}]=vec2(u32(${jt}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${Le}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${jt}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Sr=Le=>(()=>{if(u.storage===u.value)return`${e}[${Le}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${Le}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${Le}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${Le}] & 0xFFu), bool(${e}[${Le}] & 0xFF00u), bool(${e}[${Le}] & 0xFF0000u), bool(${e}[${Le}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Wr=i<2?"":` + fn get_${e}ByIndices(indices: ${u.indices}) -> ${w} { + return ${Sr(`i2o_${e}(indices)`)}; + }`,dr=i<2?"":(()=>{let Le=d.map(rr=>`d${rr}: u32`).join(", "),jt=d.map(rr=>`d${rr}`).join(", ");return` + fn get_${e}(${Le}) -> ${w} { + return get_${e}ByIndices(${dt(jt)}); + }`})(),Rr=(...Le)=>{if(Le.length!==i)throw new Error(`indices length must be ${i}`);let jt=Le.map(k).join(",");return i===0?Sr("0u"):i===1?Sr(jt[0]):(T.get=!0,T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}(${jt})`)},Lt=Le=>i<2?Sr(Le):(T.getByIndices=!0,T.indicesToOffset=!0,`get_${e}ByIndices(${Le})`),Zt=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${w}) { + ${nr(`i2o_${e}(indices)`,"value")} + }`,fr=i<2?"":(()=>{let Le=d.map(rr=>`d${rr}: u32`).join(", "),jt=d.map(rr=>`d${rr}`).join(", ");return` + fn set_${e}(${Le}, value: ${w}) { + set_${e}ByIndices(${dt(jt)}, value); + }`})();return{impl:()=>{let Le=[],jt=!1;return T.offsetToIndices&&(Le.push(ce),jt=!0),T.indicesToOffset&&(Le.push(tt),jt=!0),T.broadcastedIndicesToOffset&&(Object.values(pr).forEach(rr=>Le.push(rr)),jt=!0),T.set&&(Le.push(fr),jt=!0),T.setByIndices&&(Le.push(Zt),jt=!0),T.get&&(Le.push(dr),jt=!0),T.getByIndices&&(Le.push(Wr),jt=!0),!a&&jt&&Le.unshift(`const ${U} = ${u.indices}(${r.join(",")});`,`const ${q} = ${u.indices}(${He.computeStrides(r).join(",")});`),Le.join(` +`)},type:u,offsetToIndices:Z,indicesToOffset:Ge,broadcastedIndicesToOffset:gr,indices:dt,indicesGet:Ot,indicesSet:Dt,set:(...Le)=>{if(Le.length!==i+1)throw new Error(`indices length must be ${i}`);let jt=Le[i];if(typeof jt!="string")throw new Error("value must be string");let rr=Le.slice(0,i).map(k).join(",");return i===0?nr("0u",jt):i===1?nr(rr[0],jt):(T.set=!0,T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}(${rr}, ${jt})`)},setByOffset:nr,setByIndices:(Le,jt)=>i<2?nr(Le,jt):(T.setByIndices=!0,T.indicesToOffset=!0,`set_${e}ByIndices(${Le}, ${jt});`),get:Rr,getByOffset:Sr,getByIndices:Lt,usage:n,name:e,strides:q,shape:U,rank:i}},it=(e,t,r,n=1)=>Ws(e,t,r,"input",n),Ut=(e,t,r,n=1)=>Ws(e,t,r,"output",n),fi=(e,t,r,n=1)=>Ws(e,t,r,"internal",n),mi=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=mn){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) + fn main(${a}) { + ${i} + `}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 r=e.usage==="input"?"read":"read_write",n=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,r=1){return this.uniforms.push({name:e,type:t,length:r}),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:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}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])}},Ia=(e,t)=>new mi(e,t),us=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),Fa,_i,Cs,Oa,Pn,za,gi,ds=B(()=>{Qt(),Yt(),hr(),or(),Fa=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},_i=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Cs=(e,t)=>He.sortBasedOnPerm(e,_i(e.length,t)),Oa=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r=e.dataType,n=e.dims.length,s=_i(n,t),a=Cs(e.dims,s),i=Ut("output",r,a.length),d=it("a",r,n),c;if(s.length===2&&s[0]===1&&s[1]===0){let h=i.type.value,w=[16,16,1];c=y=>` + ${y.registerUniform("output_size","u32").declareVariables(d,i)} + var tile : array, ${w[0]}>; + ${y.mainStart(w)} + var x = workgroup_id.x * ${w[0]}u + local_id.x; + var y = workgroup_id.y * ${w[0]}u + local_id.y; + let width = uniforms.output_shape[0]; + let height = uniforms.output_shape[1]; + if (x < width && y < height) { + tile[local_id.y][local_id.x] = ${d.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${w[0]}u + local_id.x; + y = workgroup_id.x * ${w[0]}u + local_id.y; + if (x < height && y < width) { + ${i.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else c=h=>` + ${h.registerUniform("output_size","u32").declareVariables(d,i)} + + ${Oa(s,n,d,i)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${i.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${i.setByOffset("global_idx",d.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:h=>{let w=He.size(a);return{outputs:[{dims:a,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},...St(h[0].dims,a)]}},getShaderSource:c}},za=(e,t)=>{Fa(e.inputs),e.compute(Pn(e.inputs[0],t.perm))},gi=e=>Gt({perm:e.perm})}),Da,Ba,La,Ra,wi,Na,ja,yi,Va,Ua,bn,Wa,Ga,bi,qa,Ha,Mi,Ka,Xa,vi,Qa,zu=B(()=>{Qt(),Yt(),or(),ki(),ds(),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 * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Ba={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"},Ra={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},wi=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},ja=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!yi(e,t)){for(let n=0;nr.push(n))}return r},Ua=(e,t,r,n,s,a,i)=>{let d=r[0].dims,c=He.size(a),h=He.size(i),w=it("_A",r[0].dataType,d),y=Ut("output",s,a),u=32,k=` + var aBestValues : array; + `;return{name:e,shaderCache:t,getShaderSource:T=>` + ${T.registerUniform("reduceSize","u32").declareVariables(w,y)} + ${k} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${T.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${La[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${w.getByOffset("offset + k")}); + bestValue = ${Da[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${u}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 = ${Ba[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${y.setByOffset("outputIndex",`${n==="mean"?`${y.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${y.type.storage}(${Ra[n]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:c},programUniforms:[{type:12,data:h}]})}},bn=(e,t,r,n)=>{let s=e.inputs.length===1?r:qs(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((k,T)=>T));let i=He.normalizeAxes(a,e.inputs[0].dims.length),d=i,c=e.inputs[0],h=Va(d,e.inputs[0].dims.length);h.length>0&&(c=e.compute(Pn(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=wi(d.length,c.dims.length));let[w,y]=Na(c.dims,d),u=w;s.keepDims&&(u=ja(w,i)),e.compute(Ua(t,{hint:s.cacheKey,inputDependencies:["type"]},[c],n,e.inputs[0].dataType,u,y),{inputs:[c]})},Wa=(e,t)=>{bn(e,"ReduceMeanShared",t,"mean")},Ga=(e,t)=>{bn(e,"ReduceL1Shared",t,"l1")},bi=(e,t)=>{bn(e,"ReduceL2Shared",t,"l2")},qa=(e,t)=>{bn(e,"ReduceLogSumExpShared",t,"logSumExp")},Ha=(e,t)=>{bn(e,"ReduceMaxShared",t,"max")},Mi=(e,t)=>{bn(e,"ReduceMinShared",t,"min")},Ka=(e,t)=>{bn(e,"ReduceProdShared",t,"prod")},Xa=(e,t)=>{bn(e,"ReduceSumShared",t,"sum")},vi=(e,t)=>{bn(e,"ReduceSumSquareShared",t,"sumSquare")},Qa=(e,t)=>{bn(e,"ReduceLogSumShared",t,"logSum")}}),Mn,Ya,Gs,qs,Cn,Za,xi,Ja,eo,Ti,to,ro,Ci,no,so,vn,io,ao,$i,oo,lo,Ei,uo,co,Si,po,ki=B(()=>{Qt(),Yt(),hr(),or(),zu(),Mn=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.")},Ya=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Gs=(e,t,r,n,s,a,i=!1,d=!1)=>{let c=[],h=r[0].dims,w=h.length,y=He.normalizeAxes(s,w),u=!d&&y.length===0;h.forEach((I,U)=>{u||y.indexOf(U)>=0?i&&c.push(1):c.push(I)});let k=c.length,T=He.size(c);return{name:e,shaderCache:t,getShaderSource:I=>{let U=[],q=it("_A",r[0].dataType,w),R=Ut("output",a,k),ce=n(q,R,y),Z=ce[2];for(let oe=0,tt=0;oe=0?(i&&tt++,Z=`for(var j${oe}: u32 = 0; j${oe} < ${h[oe]}; j${oe}++) { + ${ce[2].includes("last_index")?`let last_index = j${oe};`:""} + ${q.indicesSet("input_indices",oe,`j${oe}`)} + ${Z} + }`):(U.push(`${q.indicesSet("input_indices",oe,R.indicesGet("output_indices",tt))};`),tt++);return` + + ${I.registerUniform("output_size","u32").declareVariables(q,R)} + + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${q.type.indices}; + let output_indices = ${R.offsetToIndices("global_idx")}; + + ${U.join(` +`)} + ${ce[0]} // init ops for reduce max/min + ${ce[1]} + ${Z} + ${ce[3]} + ${ce.length===4?R.setByOffset("global_idx","value"):ce.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:[{type:12,data:T},...St(h,c)]})}},qs=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),Gt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Cn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:qs(s,r);e.compute(Gs(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ya:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Za=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},xi=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Ja=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},eo=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Ti=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceMax",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},to=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceMean",t,(r,n,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},ro=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceMin",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Ci=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},no=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},so=(e,t)=>{Mn(e.inputs),Cn(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},vn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},io=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?to(e,t):Wa(e,t)},ao=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xi(e,t):Ga(e,t)},$i=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ja(e,t):bi(e,t)},oo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eo(e,t):qa(e,t)},lo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ti(e,t):Ha(e,t)},Ei=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):Mi(e,t)},uo=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ci(e,t):Ka(e,t)},co=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?no(e,t):Xa(e,t)},Si=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):vi(e,t)},po=(e,t)=>{vn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Za(e,t):Qa(e,t)}}),Hs,ho,fo,Ks,Du=B(()=>{Qt(),hr(),ki(),Hs=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.")},ho=(e,t)=>{Hs(e.inputs);let r=(n,s,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.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); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(Gs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},fo=(e,t)=>{Hs(e.inputs);let r=(n,s,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.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); + }`,"",s.setByOffset("global_idx","best_index")]};e.compute(Gs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ks=e=>Gt(e)}),mo,Pi,_o,go,cs,wo,yo,Xs=B(()=>{Qt(),F(),or(),mo=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],d=e[5];if(i&&d)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let c=r.dims[0],h=r.dims[1],w=r.dims[2];if(s.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]!==w)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let y=s.dims[0]/3,u=y,k=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ce of t.qkvHiddenSizes)if(ce%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");y=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],k=t.qkvHiddenSizes[2]}let T=h;if(y!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==y+u+k)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let I=0;if(i){if(u!==k)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==c)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(I=i.dims[3])}let U=T+I,q=-1,R=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");return{batchSize:c,sequenceLength:h,pastSequenceLength:I,kvSequenceLength:T,totalSequenceLength:U,maxSequenceLength:q,inputHiddenSize:w,hiddenSize:y,vHiddenSize:k,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor(k/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:R,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Pi=(e,t,r,n)=>{let s=mr(n),a=64,i=n/s;i{let k=Ut("x",t.dataType,t.dims,s),T=[{name:"d_inv",type:Mr(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${u.registerUniforms(T).declareVariables(k)} + ${u.mainStart([a,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = workgroup_id.x * uniforms.d_comp + local_offset; + + var thread_max_vector = ${w}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${w}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(s){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: ${s}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${a}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${w}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${w}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(s){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: ${s}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${a}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + x[offset + i] = ${k.type.value}(uniforms.d_inv); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${w}(x[offset + i]); + x[offset + i] = ${k.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${a};${h};${s}`},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:c})}},_o=(e,t,r,n,s,a,i,d)=>{let c=d+a.kvSequenceLength,h=[a.batchSize,a.numHeads,a.sequenceLength,c],w=a.kvNumHeads===void 0&&e.outputCount>1,y=w?[a.batchSize,a.numHeads,c,a.headSize]:void 0,u=i.scale===0?1/Math.sqrt(a.headSize):i.scale,k=mr(a.headSize),T=a.headSize/k,I=12,U={x:Math.ceil(c/I),y:Math.ceil(a.sequenceLength/I),z:a.batchSize*a.numHeads},q=[{type:12,data:a.sequenceLength},{type:12,data:T},{type:12,data:c},{type:12,data:a.numHeads},{type:1,data:u},{type:12,data:d},{type:12,data:a.kvSequenceLength}],R=["type","type"];n&&R.push("type"),s&&R.push("type");let ce=[{dims:h,dataType:t.dataType,gpuDataType:0}];w&&ce.push({dims:y,dataType:t.dataType,gpuDataType:0});let Z=oe=>{let tt=it("q",t.dataType,t.dims,k),Ge=it("key",r.dataType,r.dims,k),dt=[tt,Ge];if(n){let nr=it("past_key",n.dataType,n.dims,k);dt.push(nr)}s&&dt.push(it("relative_position_bias",s.dataType,s.dims));let Ot=Ut("output",t.dataType,h),Dt=[Ot];w&&Dt.push(Ut("present_key",t.dataType,y,k));let pr=Mr(1,k),gr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${I}u; + + var tileQ: array<${tt.type.storage}, ${I*I}>; + var tileK: array<${tt.type.storage}, ${I*I}>; + ${oe.registerUniforms(gr).declareVariables(...dt,...Dt)} + ${oe.mainStart([I,I,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${n&&w?` + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; + let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} + ${w?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${pr}(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; + ${n&&w?` + if (n + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else { + tileK[idx] = + key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; + }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} + ${w?"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 += ${pr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; + output[outputIdx] = ${Ot.type.value} (sum * uniforms.alpha) + ${s?"relative_position_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${s!==void 0};${n!==void 0};${e.outputCount}`,inputDependencies:R},getRunData:()=>({outputs:ce,dispatchGroup:U,programUniforms:q}),getShaderSource:Z}},go=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,d=s.nReps?s.nReps:1,c=s.vHiddenSize*d,h=s.kvNumHeads==null&&e.outputCount>1,w=h?[s.batchSize,s.numHeads,i,s.headSize]:void 0,y=[s.batchSize,s.sequenceLength,c],u=12,k={x:Math.ceil(s.vHeadSize/u),y:Math.ceil(s.sequenceLength/u),z:s.batchSize*s.numHeads},T=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:c},{type:12,data:a},{type:12,data:s.kvSequenceLength}],I=n?["type","type","type"]:["type","type"],U=[{dims:y,dataType:t.dataType,gpuDataType:0}];h&&U.push({dims:w,dataType:t.dataType,gpuDataType:0});let q=R=>{let ce=it("probs",t.dataType,t.dims),Z=it("v",r.dataType,r.dims),oe=[ce,Z];n&&oe.push(it("past_value",n.dataType,n.dims));let tt=[Ut("output",t.dataType,y)];h&&tt.push(Ut("present_value",t.dataType,w));let Ge=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${u}u; + var tileQ: array<${ce.type.value}, ${u*u}>; + var tileK: array<${ce.type.value}, ${u*u}>; + ${R.registerUniforms(Ge).declareVariables(...oe,...tt)} + ${R.mainStart([u,u,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + ${n&&h?` + let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; + let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; + `:` + let offsetB = headIdx * uniforms.N * uniforms.K + n; + `} + ${h?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${ce.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; + ${n&&h?` + if (w + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else { + tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; + } + `:` + tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; + `} + ${h?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e.outputCount}`,inputDependencies:I},getRunData:()=>({outputs:U,dispatchGroup:k,programUniforms:T}),getShaderSource:q}},cs=(e,t,r,n,s,a,i,d,c,h,w)=>{let y=e.outputCount,u=h.kvNumHeads!==void 0||y>1?h.pastSequenceLength:0,k=u+h.kvSequenceLength,T=h.kvNumHeads===void 0&&y>1&&i?[t,r,i]:[t,r];c&&T.push(c);let I=e.compute(_o(e,t,r,y>1?i:void 0,c,h,w,u),{inputs:T,outputs:h.kvNumHeads===void 0&&y>1?[-1,1]:[-1]})[0];e.compute(Pi(e,I,h.batchSize*h.numHeads*h.sequenceLength,k),{inputs:[I],outputs:[]});let U=h.kvNumHeads===void 0&&y>1&&d?[I,n,d]:[I,n];e.compute(go(e,I,n,y>1&&d?d:void 0,h,u),{inputs:U,outputs:h.kvNumHeads===void 0&&y>1?[0,2]:[0]})},wo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,d={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},c=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],w=y=>{let u=Ut("output_q",c[0].dataType,r),k=Ut("output_k",c[0].dataType,r),T=Ut("output_v",c[0].dataType,r),I=it("input",c[0].dataType,c[0].dims),U=it("weight",c[1].dataType,c[1].dims),q=it("bias",c[2].dataType,c[2].dims),R=I.type.storage,ce=[{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 = ${i}u; + var tileInput: array<${R}, ${i*i}>; + var tileWeightQ: array<${R}, ${i*i}>; + var tileWeightK: array<${R}, ${i*i}>; + var tileWeightV: array<${R}, ${i*i}>; + ${y.registerUniforms(ce).declareVariables(I,U,q,u,k,T)} + ${y.mainStart([i,i,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 = ${R}(0); + var valueK = ${R}(0); + var valueV = ${R}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:h}),getShaderSource:w},{inputs:c,outputs:[-1,-1,-1]})},yo=(e,t)=>{let r=mo(e.inputs,t),[n,s,a]=wo(e,r);return cs(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),bo,Mo,vo,xo,To=B(()=>{C(),Qt(),Yt(),hr(),or(),bo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((d,c)=>{if(d!==n[c])throw new Error(`${a}: dim[${c}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Mo=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?mr(a[a.length-1]):1,d=s==="NHWC"&&a.length>1?i:1,c=He.size(a)/i,h=n,w=h?a.length:a,y=it("x",e[0].dataType,e[0].dims,i),u=it("scale",e[1].dataType,e[1].dims,d),k=it("bias",e[2].dataType,e[2].dims,d),T=it("inputMean",e[3].dataType,e[3].dims,d),I=it("inputVar",e[4].dataType,e[4].dims,d),U=Ut("y",e[0].dataType,w,i),q=()=>{let ce="";if(n)ce=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")ce=` + ${U.indicesSet("outputIndices","0","0")} + let cOffset = ${U.indicesToOffset("outputIndices")};`;else{ce=`var cIndices = ${u.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let Z=1;Z` + const epsilon = ${r}; + ${ce.registerUniform("outputSize","u32").declareVariables(y,u,k,T,I,U)} + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${U.offsetToIndices(`global_idx * ${i}`)}; + ${q()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${k.getByOffset("cOffset")}; + let inputMean = ${T.getByOffset("cOffset")}; + let inputVar = ${I.getByOffset("cOffset")}; + let x = ${y.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${U.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:R,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h?[{type:12,data:c},...St(a)]:[{type:12,data:c}]})}},vo=e=>Gt(e),xo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=vo({...t,outputCount:n});if(A.webgpu.validateInputContent&&bo(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Mo(r,s))}}),Co,$o,Ai,Bu=B(()=>{Yt(),or(),Co=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")},$o=e=>{let t=e[0].dims,r=e[0].dims[2],n=He.size(t)/4,s=e[0].dataType,a=it("input",s,t,4),i=it("bias",s,[r],4),d=it("residual",s,t,4),c=Ut("output",s,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${r}u / 4; + ${h.declareVariables(a,i,d,c)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; + ${c.setByOffset("global_idx","value")} + }`}},Ai=e=>{Co(e.inputs),e.compute($o(e.inputs))}}),Eo,_r,So,ko,Ii,Po,Ao,Fi,Io,Fo,Qs,Oo,zo,Do,Oi,Bo,ps,Lo,Ys,Ro,zi,No,jo,Vo,Di,Uo,Wo,Bi,Go,qo,Li,Ho,Ko,Ri,Xo,Ni,ji,Vi,Ui,Qo,Yo,Wi,Zo,Jo,el,Gi=B(()=>{Qt(),Yt(),hr(),or(),Eo=(e,t,r,n,s,a)=>{let i=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let c=it("inputData",r,[i],4),h=Ut("outputData",n,[i],4);return` + ${e.registerUniform("vec_size","u32").declareVariables(c,h)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${c.getByOffset("global_idx")}; + ${h.setByOffset("global_idx",d)} + }`},_r=(e,t,r,n,s,a=e.dataType)=>({name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:i=>Eo(i,He.size(e.dims),e.dataType,a,r,n),getRunData:i=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(He.size(i[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(He.size(e.dims)/4)}]})}),So=e=>{e.compute(_r(e.inputs[0],"Abs","abs"))},ko=e=>{e.compute(_r(e.inputs[0],"Acos","acos"))},Ii=e=>{e.compute(_r(e.inputs[0],"Acosh","acosh"))},Po=e=>{e.compute(_r(e.inputs[0],"Asin","asin"))},Ao=e=>{e.compute(_r(e.inputs[0],"Asinh","asinh"))},Fi=e=>{e.compute(_r(e.inputs[0],"Atan","atan"))},Io=e=>{e.compute(_r(e.inputs[0],"Atanh","atanh"))},Fo=e=>Gt(e),Qs=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(_r(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Oo=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Hr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:dn;return Gt({min:t,max:r})},zo=(e,t)=>{let r=e.inputs.length===1?t:Oo(e.inputs),n=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"Clip",s=>`clamp(${s}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); + const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); +`,r.cacheKey),{inputs:[0]})},Do=e=>{e.compute(_r(e.inputs[0],"Ceil","ceil"))},Oi=e=>{e.compute(_r(e.inputs[0],"Cos","cos"))},Bo=e=>{e.compute(_r(e.inputs[0],"Cosh","cosh"))},ps=e=>Gt(e),Lo=(e,t)=>{let r=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},Ys=(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)); +}`,Ro=e=>{let t=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Ys(t)))},zi=e=>{e.compute(_r(e.inputs[0],"Exp","exp"))},No=e=>{e.compute(_r(e.inputs[0],"Floor","floor"))},jo=e=>{let t=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Ys(t)))},Vo=(e,t)=>{let r=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Di=e=>{e.compute(_r(e.inputs[0],"Not",t=>`!${t}`))},Uo=e=>{e.compute(_r(e.inputs[0],"Neg",t=>`-${t}`))},Wo=e=>{e.compute(_r(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Bi=e=>{let t=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Go=e=>{e.compute(_r(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},qo=e=>Gt(e),Li=(e,t)=>{let r=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ho=e=>{e.compute(_r(e.inputs[0],"Sin","sin"))},Ko=e=>{e.compute(_r(e.inputs[0],"Sinh","sinh"))},Ri=e=>{e.compute(_r(e.inputs[0],"Sqrt","sqrt"))},Xo=e=>{e.compute(_r(e.inputs[0],"Tan","tan"))},Ni=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ji=e=>{e.compute(_r(e.inputs[0],"Tanh",Ni))},Vi=(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 ${Ni("v")}; +} +`,Ui=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Qo=e=>{let t=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"FastGelu",Ui,Vi(t),void 0,e.inputs[0].dataType))},Yo=(e,t)=>{let r=Mr(e.inputs[0].dataType);return e.compute(_r(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Wi=e=>{e.compute(_r(e.inputs[0],"Log","log"))},Zo=(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; +} +`,Jo=e=>`quick_gelu_impl(${e})`,el=(e,t)=>{let r=Mr(e.inputs[0].dataType);e.compute(_r(e.inputs[0],"QuickGelu",Jo,Zo(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),qi,tl,rl,nl=B(()=>{Yt(),or(),Gi(),qi=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")},tl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=it("input",e[0].dataType,e[0].dims,4),n=it("bias",e[0].dataType,[e[0].dims[2]],4),s=Ut("output",e[0].dataType,t,4),a=He.size(t)/4,i=br(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${d.declareVariables(r,n,s)} + + ${Ys(i)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} + 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); + + ${s.setByOffset("global_idx","valueLeft * geluRight")} + }`}},rl=e=>{qi(e.inputs),e.compute(tl(e.inputs))}}),sl,il,xn,al,ol,Hi,ll,ul,dl,cl,pl,hl,Ki,Lu=B(()=>{Qt(),Yt(),or(),sl=(e,t,r,n,s,a,i,d,c,h,w,y)=>{let u,k;typeof d=="string"?u=k=(R,ce)=>`${d}((${R}),(${ce}))`:typeof d=="function"?u=k=d:(u=d.scalar,k=d.vector);let T=Ut("outputData",w,n.length,4),I=it("aData",c,t.length,4),U=it("bData",h,r.length,4),q;if(s)if(a){let R=He.size(t)===1,ce=He.size(r)===1,Z=t.length>0&&t[t.length-1]%4===0,oe=r.length>0&&r[r.length-1]%4===0;R||ce?q=T.setByOffset("global_idx",k(R?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"),ce?`${U.type.value}(${U.getByOffset("0")}.x)`:U.getByOffset("global_idx"))):q=` + let outputIndices = ${T.offsetToIndices("global_idx * 4u")}; + let offsetA = ${I.broadcastedIndicesToOffset("outputIndices",T)}; + let offsetB = ${U.broadcastedIndicesToOffset("outputIndices",T)}; + ${T.setByOffset("global_idx",k(i||Z?I.getByOffset("offsetA / 4u"):`${I.type.value}(${I.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||oe?U.getByOffset("offsetB / 4u"):`${U.type.value}(${U.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else q=T.setByOffset("global_idx",k(I.getByOffset("global_idx"),U.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let R=(ce,Z,oe="")=>{let tt=`aData[indexA${Z}][componentA${Z}]`,Ge=`bData[indexB${Z}][componentB${Z}]`;return` + let outputIndices${Z} = ${T.offsetToIndices(`global_idx * 4u + ${Z}u`)}; + let offsetA${Z} = ${I.broadcastedIndicesToOffset(`outputIndices${Z}`,T)}; + let offsetB${Z} = ${U.broadcastedIndicesToOffset(`outputIndices${Z}`,T)}; + let indexA${Z} = offsetA${Z} / 4u; + let indexB${Z} = offsetB${Z} / 4u; + let componentA${Z} = offsetA${Z} % 4u; + let componentB${Z} = offsetB${Z} % 4u; + ${ce}[${Z}] = ${oe}(${u(tt,Ge)}); + `};w===9?q=` + var data = vec4(0); + ${R("data",0,"u32")} + ${R("data",1,"u32")} + ${R("data",2,"u32")} + ${R("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:q=` + ${R("outputData[global_idx]",0)} + ${R("outputData[global_idx]",1)} + ${R("outputData[global_idx]",2)} + ${R("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(I,U,T)} + + ${y??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${q} + }`},il=(e,t,r,n,s,a,i=r.dataType)=>{let d=!He.areEqual(r.dims,n.dims),c=r.dims,h=He.size(r.dims),w=!1,y=!1,u=[d];if(d){let k=Yr.calcShape(r.dims,n.dims,!1);if(!k)throw new Error("Can't perform binary op on the given tensors");c=k,h=He.size(c);let T=He.size(r.dims)===1,I=He.size(n.dims)===1,U=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,q=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;u.push(T),u.push(I),u.push(U),u.push(q);let R=1;for(let ce=1;cek.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:k=>sl(k,r.dims,n.dims,c,w,d,y,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:c,dataType:i}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(He.size(c)/4)},...St(r.dims,n.dims,c)]})}},xn=(e,t,r,n,s,a)=>{e.compute(il(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},al=e=>{xn(e,"Add",(t,r)=>`${t}+${r}`)},ol=e=>{xn(e,"Div",(t,r)=>`${t}/${r}`)},Hi=e=>{xn(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ll=e=>{xn(e,"Mul",(t,r)=>`${t}*${r}`)},ul=e=>{let t=it("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;xn(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${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)); + } + `)},dl=e=>{xn(e,"Sub",(t,r)=>`${t}-${r}`)},cl=e=>{xn(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},pl=e=>{xn(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},hl=e=>{xn(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ki=e=>{xn(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),fl,Xi,ml,_l,qn,gl,Ru=B(()=>{Qt(),Yt(),hr(),or(),fl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,d)=>{if(d!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((c,h)=>{if(h!==t&&c!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Xi=(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; + }`,ml=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=He.size(r),a=new Array(e.length),i=new Array(e.length),d=0,c=[],h=[],w=[{type:12,data:s}];for(let I=0;I`uniforms.sizeInConcatAxis${I}`).join(","),T=I=>` + + ${(()=>{I.registerUniform("outputSize","u32");for(let U=0;U(${k}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${ml(i,y)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:T}},qn=(e,t)=>{let r=e.inputs,n=r[0].dims,s=He.normalizeAxis(t.axis,n.length);fl(r,s);let a=n.slice();a[s]=r.reduce((d,c)=>d+(c.dims.length>s?c.dims[s]:0),0);let i=r.filter(d=>He.size(d.dims)>0);e.compute(_l(i,s,a,r[0].dataType),{inputs:i})},gl=e=>Gt({axis:e.axis})}),Hn,Kn,Bn,Qi,Xn=B(()=>{Qt(),Yt(),Hn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Kn=(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})},Bn=(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"})},Qi=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=(e==null?void 0:e.activation_params)||[Hr,dn];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),en,Yi,hs=B(()=>{en=(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.`)}},Yi=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),Zi,wl=B(()=>{Zi=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)); +} +`}),yl,$s,Zs,Ji,bl,Js,ei,ea,ti=B(()=>{Qt(),Yt(),or(),Xn(),hs(),yl=(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":""}); + `,$s=(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];"} + }`,Zs=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32)=>{let c=t[1]*e[1],h=t[0]*e[0],w=s?c:a,y=s?a:c,u=w/t[0],k=a/t[1];if(!((s&&u===4&&e[1]===4||!s&&(u===3||u===4))&&w%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${u} must be 3 or 4. + tileAWidth ${w} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${w/u}>, ${y}>; +var mm_Bsub: array, ${h/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${u}; +const tileInner = ${a}; + +@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 = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${c}; + + let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${k}; + 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; + ${yl(s,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${k}; 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]; + ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${$s(s,u)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Ji=(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":""}); + `,bl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Js=(e,t,r="f32",n,s=!1,a=32,i=!1,d=32,c=!1)=>{let h=e[1]*t[1],w=e[0]*t[0],y=s?h:a,u=s?a:h;if(!(u%t[1]===0&&y%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${y} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let k=u/t[1],T=y/t[0],I=a/t[1],U=c?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${w}; + + // 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 < ${u}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${y}; inputCol = inputCol + ${t[0]}) { + ${Ji(s,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${w}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${s?`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) * ${k}; +let tileColA = i32(localId.x) * ${T}; +let tileRowB = i32(localId.y) * ${I}; +// 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 < ${k}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${T}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Ji(s,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${I}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${bl(s)} + 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, ${u}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@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 = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; + + var acc : array, rowPerThread>; + ${U} + } +`},ei=(e,t,r,n,s,a=!1)=>{let[i,d,c]=s,[h,w,y,u]=n,k=us(i,c),T=us(d,c),I=br(n[0].type.tensor),U=()=>{let R=w.rank,ce=h.rank,Z=`var aIndices: ${w.type.indices};`;for(let oe=R-2-1,tt=ce-1;oe>=0;oe--,tt--)Z+=` +aIndices[${oe}] = ${ce>1?`batchIndices[${tt}]`:"batchIndices"};`;return k.forEach(oe=>{Z+=` +aIndices[${oe}] = 0;`}),Z+=` +aIndices[${R-2}] = u32(row); + aIndices[${R-1}] = u32(colIn);`,Z},q=()=>{let R=y.rank,ce=h.rank,Z=`var bIndices: ${y.type.indices};`;for(let oe=R-2-1,tt=ce-1;oe>=0;oe--,tt--)Z+=` +bIndices[${oe}] = ${ce>1?`batchIndices[${tt}]`:"batchIndices"};`;return T.forEach(oe=>{Z+=` +bIndices[${oe}] = 0;`}),Z+=` +bIndices[${R-2}] = u32(row); + bIndices[${R-1}] = u32(colIn);`,Z};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${en(e,I)} { + var value = ${en(e,I)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${U()} + value = ${w.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${en(e,I)} { + var value = ${en(e,I)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${q()} + value = ${y.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${en(e,I)}) { + 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 + ${a?"bias[colIn]":`${en(e,I)}(bias[row])`};`:""} + ${r} + ${u.setByIndices("vec3(coords)","value")} + } + } + `},ea=(e,t,r,n,s=!1)=>{let a=e[0].dims,i=e[1].dims,d=a.slice(0,-2),c=i.slice(0,-2),h=n?n.slice(0,-2):r.slice(0,-2),w=He.size(h),y=a[a.length-2],u=a[a.length-1],k=i[i.length-1],T=u%4===0&&k%4===0,I=y<=8?[4,1,1]:[4,4,1],U=[8,8,1],q=[Math.ceil(k/U[0]/I[0]),Math.ceil(y/U[1]/I[1]),Math.ceil(w/U[2]/I[2])],R=T?4:1,ce=[...d,y,u/R],Z=ce.length,oe=[...c,u,k/R],tt=oe.length,Ge=[w,y,k/R],dt=[{type:6,data:y},{type:6,data:k},{type:6,data:u}];Kn(t,dt),dt.push(...St(h,ce,oe));let Ot=["rank","rank"],Dt=e.length>2;Dt&&(dt.push(...St(e[2].dims)),Ot.push("rank")),dt.push(...St(Ge));let pr=gr=>{let nr=h.length,Sr=fi("batchDims",e[0].dataType,nr,1),Wr=br(e[0].dataType),dr=it("a",e[0].dataType,Z,R),Rr=it("b",e[1].dataType,tt,R),Lt=Ut("result",e[0].dataType,Ge.length,R),Zt=[dr,Rr];if(Dt){let Br=s?R:1;Zt.push(it("bias",e[2].dataType,e[2].dims.length,Br))}let fr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Bn(t,fr);let Le=br(Lt.type.tensor),jt=Hn(t,Lt.type.value,Le),rr=ei(R,Dt,jt,[Sr,dr,Rr,Lt],[d,c,h],s);return` + ${gr.registerUniforms(fr).registerInternalVariables(Sr).declareVariables(...Zt,Lt)} + ${rr} + ${T?Zs(I,U,Wr,Sr):Js(I,U,Wr,Sr)} + `};return{name:"MatMul",shaderCache:{hint:`${I};${t.activation};${T};${s}`,inputDependencies:Ot},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:q[0],y:q[1],z:q[2]},programUniforms:dt}),getShaderSource:pr}}}),Ml,Nu,ju=B(()=>{Qt(),fn(),or(),Xn(),hs(),wl(),ti(),Ml=(e,t,r,n,s=!1,a,i=4,d=4,c=4,h="f32")=>{let w=Ot=>{switch(Ot){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 ${Ot} is not supported.`)}},y=Ot=>{switch(Ot){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 ${Ot} is not supported.`)}},u=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,k=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,T=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",I=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",U=e?"row":"col",q=e?"col":"row",R=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${U} / outWidth; + let outCol = ${U} % outWidth; + + let WRow = ${q} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${q} / 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 = ${q} % inChannels; + var resData = ${en(i,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 < ${T} && xCol >= 0 && xCol < ${I}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${w(i)} + } + return resData;`,ce=e?t&&n?` + let col = colIn * ${i}; + ${R}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${R} + } + return ${en(i,h)}(0.0);`:n&&r?` + let col = colIn * ${i}; + ${R}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${R} + } + return ${en(i,h)}(0.0);`,Z=`${y(d)}`,oe=en(c,h),tt=en(e?i:d,h),Ge=en(e?d:i,h),dt=Hn(a,oe,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${tt} { + ${e?ce:Z} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ge} { + ${e?Z:ce} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${oe}) { + let col = colIn * ${c}; + 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])"}; + ${k} + ${Yi(s)} + ${dt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Nu=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",h=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],k=c?r[3]:r[1],T=c&&(h%4===0||h%3===0)&&k%4===0,I=c?k:y*u,U=c?y*u:k,q=[8,8,1],R=n<=8?[4,1,1]:[4,4,1],ce=[Math.ceil(I/q[0]/R[0]),Math.ceil(U/q[1]/R[1]),Math.ceil(w/q[2]/R[2])];Dr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${ce}`);let Z=T?c&&h%4!==0?3:4:1,oe=q[1]*R[1],tt=q[0]*R[0],Ge=Math.max(q[0]*Z,q[1]),dt=n%oe===0,Ot=s%tt===0,Dt=a%Ge===0,pr=T?[Z,4,4]:[1,1,1],gr=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Kn(t,gr),gr.push(...St(e[0].dims,e[1].dims));let nr=["rank","rank"];i&&(gr.push(...St(e[2].dims)),nr.push("rank")),gr.push(...St(r));let Sr=Wr=>{let dr=[{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}];Bn(t,dr);let Rr=T?4:1,Lt=br(e[0].dataType),Zt=` + fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${Lt}>`:Lt}) { + result[flatIndex] = ${T?`vec4<${Lt}>`:Lt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${Lt}>`:Lt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); + }`,fr=it("x",e[0].dataType,e[0].dims.length,Z===3?1:Z),Le=it("w",e[1].dataType,e[1].dims.length,Rr),jt=[fr,Le],rr=Ut("result",e[0].dataType,r.length,Rr);if(i){let Br=it("bias",e[2].dataType,e[2].dims.length,Rr);jt.push(Br),Zt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${Lt}>`:Lt} { + return bias[coords.${c?"w":"y"}${T?"/ 4":""}]; + }`}return` + ${Zi("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 }; + ${Wr.registerUniforms(dr).declareVariables(...jt,rr)} + ${Zt} + ${Ml(c,dt,Ot,Dt,i,t,pr[0],pr[1],pr[2],Lt)} + ${T?Zs(R,q,Lt,void 0,!c,Ge):Js(R,q,Lt,void 0,!c,Ge,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Z};${T};${dt};${Ot};${Dt};${oe};${tt};${Ge}`,inputDependencies:nr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ce[0],y:ce[1],z:ce[2]},programUniforms:gr}),getShaderSource:Sr}}}),vl,ta,Ln,xl,ra,Tl,Cl,$l,na=B(()=>{Qt(),fn(),Yt(),or(),Xn(),hs(),vl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Ln=(e,t)=>t<=1?e:e+(e-1)*(t-1),xl=(e,t,r,n=1)=>{let s=Ln(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},ra=(e,t,r,n,s)=>{s==null&&(s=xl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},Tl=(e,t,r,n,s,a,i,d,c,h)=>{let w,y,u,k;if(e==="VALID"&&(e=0),typeof e=="number"){w={top:e,bottom:e,left:e,right:e,front:e,back:e};let T=ra([t,r,n,1],[d,c,h],1,[s,a,i],e);y=T[0],u=T[1],k=T[2]}else if(Array.isArray(e)){if(!e.every((I,U,q)=>I===q[0]))throw Error(`Unsupported padding parameter: ${e}`);w={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let T=ra([t,r,n,1],[d,c,h],1,[s,a,i],e[0]);y=T[0],u=T[1],k=T[2]}else if(e==="SAME_UPPER"){y=Math.ceil(t/s),u=Math.ceil(r/a),k=Math.ceil(n/i);let T=(y-1)*s+d-t,I=(u-1)*a+c-r,U=(k-1)*i+h-n,q=Math.floor(T/2),R=T-q,ce=Math.floor(I/2),Z=I-ce,oe=Math.floor(U/2),tt=U-oe;w={top:ce,bottom:Z,left:oe,right:tt,front:q,back:R}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:w,outDepth:y,outHeight:u,outWidth:k}},Cl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let d,c,h,w,y;if(i==="channelsLast")[d,c,h,w,y]=e;else if(i==="channelsFirst")[d,y,c,h,w]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,k,T,I]=t,[U,q,R]=ta(r),[ce,Z,oe]=ta(n),tt=Ln(k,ce),Ge=Ln(T,Z),dt=Ln(I,oe),{padInfo:Ot,outDepth:Dt,outHeight:pr,outWidth:gr}=Tl(s,c,h,w,U,q,R,tt,Ge,dt),nr=a?u*y:u,Sr=[0,0,0,0,0];return i==="channelsFirst"?Sr=[d,nr,Dt,pr,gr]:i==="channelsLast"&&(Sr=[d,Dt,pr,gr,nr]),{batchSize:d,dataFormat:i,inDepth:c,inHeight:h,inWidth:w,inChannels:y,outDepth:Dt,outHeight:pr,outWidth:gr,outChannels:nr,padInfo:Ot,strideDepth:U,strideHeight:q,strideWidth:R,filterDepth:k,filterHeight:T,filterWidth:I,effectiveFilterDepth:tt,effectiveFilterHeight:Ge,effectiveFilterWidth:dt,dilationDepth:ce,dilationHeight:Z,dilationWidth:oe,inShape:e,outShape:Sr,filterShape:t}},$l=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],c={x:r.map((U,q)=>q)},h=[Math.ceil(vl(c.x.map(U=>r[U]))/d[0]),1,1];Dr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let w=1,y=He.size(r),u=[{type:12,data:y},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];Kn(t,u),u.push(...St(e[0].dims,e[1].dims));let k=["rank","rank"],T=e.length===3;T&&(u.push(...St(e[2].dims)),k.push("rank")),u.push(...St(r));let I=U=>{let q=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Bn(t,q);let R=1,ce=br(e[0].dataType),Z=it("x",e[0].dataType,e[0].dims.length,w),oe=it("W",e[1].dataType,e[1].dims.length,R),tt=[Z,oe],Ge=Ut("result",e[0].dataType,r.length,R),dt="";if(T){let pr=it("bias",e[2].dataType,e[2].dims.length,R);tt.push(pr),dt+=` + fn getBiasByOutputCoords(coords : array) -> ${ce} { + return bias[${i?Ft("coords",4,5):Ft("coords",1,5)}]; + }`}let Ot=en(w,ce),Dt=Hn(t,Ot,ce);return` + ${dt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Z.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${oe.getByIndices("aIndices")}; + } + ${U.registerUniforms(q).declareVariables(...tt,Ge)} + ${U.mainStart()} + ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ge.offsetToIndices("global_idx")}; + let batch = ${Ft("coords",0,Z.rank)}; + let d2 = ${i?Ft("coords",Z.rank-1,Z.rank):Ft("coords",1,Z.rank)}; + let xFRCCorner = vec3(${i?Ft("coords",1,Z.rank):Ft("coords",2,Z.rank)}, + ${i?Ft("coords",2,Z.rank):Ft("coords",3,Z.rank)}, + ${i?Ft("coords",3,Z.rank):Ft("coords",4,Z.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?Ft("uniforms.x_shape",1,Z.rank):Ft("uniforms.x_shape",2,Z.rank)}; + let xShapeZ = ${i?Ft("uniforms.x_shape",2,Z.rank):Ft("uniforms.x_shape",3,Z.rank)}; + let xShapeW = ${i?Ft("uniforms.x_shape",3,Z.rank):Ft("uniforms.x_shape",4,Z.rank)}; + let xShapeU = ${i?Ft("uniforms.x_shape",4,Z.rank):Ft("uniforms.x_shape",1,Z.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) { + ${i?`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) { + ${i?`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) { + ${i?`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) { + ${i?`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); + } + } + } + } + ${T?"value = value + getBiasByOutputCoords(coords)":""}; + ${Dt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${w};${T}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:I}}}),El,Sl,Vu=B(()=>{Qt(),Yt(),or(),Fl(),Xn(),El=(e,t,r)=>{let n=e.length>2,s=n?"value += b[output_channel];":"",a=e[0].dims,i=e[1].dims,d=i[0]/t.group,c=t.format==="NHWC",h=ri(a,i,t.dilations,t.pads,t.strides,c),w=He.size(h),y=[{type:12,data:w},{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:d}];Kn(t,y),y.push(...St(a,i));let u=["rank","rank"];n&&(y.push(...St(e[2].dims)),u.push("rank")),y.push(...St(h));let k=T=>{let I=Ut("output",e[0].dataType,h.length),U=br(I.type.tensor),q=Hn(t,I.type.value,U),R=it("x",e[0].dataType,a.length),ce=it("w",e[1].dataType,i.length),Z=[R,ce];n&&Z.push(it("b",e[2].dataType,e[2].dims.length));let oe=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Bn(t,oe),` + ${T.registerUniforms(oe).declareVariables(...Z,I)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${I.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${c?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${c?1:2}], outputIndices[${c?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${I.type.value} = ${I.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${c?1:2}]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[${c?2:3}]) { + continue; + } + + let xVal = ${c?R.get("batch","xHeight","xWidth","input_channel"):R.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${ce.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${s} + ${q} + ${I.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:u},getRunData:()=>({outputs:[{dims:r?r(h):h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:y}),getShaderSource:k}},Sl=(e,t,r)=>{let n=e.length>2,s=mr(r[3]),a=mr(r[2]),i=He.size(r)/s/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/s],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/s],h=[r[0],r[1],r[2],r[3]/s],w=[{type:12,data:i},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Kn(t,w),w.push(...St(d,c,h));let y=(a-1)*t.strides[1]+c[1],u=k=>{let T=Ut("output",e[0].dataType,h.length,s),I=br(T.type.tensor),U=Hn(t,T.type.value,I),q=it("x",e[0].dataType,d.length,s),R=it("w",e[1].dataType,c.length,s),ce=[q,R];n&&ce.push(it("b",e[2].dataType,e[2].dims,s));let Z=n?"value += b[output_channel];":"",oe=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Bn(t,oe),` + ${k.registerUniforms(oe).declareVariables(...ce,T)} + ${k.mainStart()} + ${k.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<${q.type.value}, ${y}>; + var values: array<${T.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 < ${c[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 < ${y}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${q.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${q.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + let w_val = ${R.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]; + ${Z} + ${U} + ${T.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${s};${a};${y};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:w}),getShaderSource:u}}}),sa,kl,Pl,ia=B(()=>{Qt(),Yt(),ti(),or(),Xn(),sa=(e,t,r,n,s=!1)=>{let a=e[0].dims,i=e[1].dims,d=a[a.length-2],c=i[i.length-1],h=a[a.length-1],w=mr(c),y=mr(h),u=mr(d),k=He.size(r)/w/u,T=e.length>2,I=n?n.slice(0,-2):r.slice(0,-2),U=[He.size(I),d,c],q=[{type:12,data:k},{type:12,data:d},{type:12,data:c},{type:12,data:h}];Kn(t,q),q.push(...St(I,a,i)),T&&q.push(...St(e[2].dims)),q.push(...St(U));let R=ce=>{let Z=fi("batch_dims",e[0].dataType,I.length),oe=it("a",e[0].dataType,a.length,y),tt=it("b",e[1].dataType,i.length,w),Ge=Ut("output",e[0].dataType,U.length,w),dt=br(Ge.type.tensor),Ot=Hn(t,Ge.type.value,dt),Dt=[oe,tt],pr="";if(T){let Zt=s?w:1;Dt.push(it("bias",e[2].dataType,e[2].dims.length,Zt)),pr=`${s?`value += bias[col / ${Zt}];`:`value += ${Ge.type.value}(bias[row + i]);`}`}let gr=a.slice(0,-2),nr=i.slice(0,-2),Sr=us(gr,I),Wr=us(nr,I),dr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Bn(t,dr);let Rr=(Zt,fr)=>{let Le=Zt.rank,jt=Zt.name;if(Le===2)return`var ${jt}_indices = ${Zt.type.indices}(0u, 0u);`;let rr=Z.rank,Br=`var ${jt}_indices: ${Zt.type.indices};`;for(let Xr=Le-2-1,an=rr-1;Xr>=0;Xr--,an--)Br+=` +${jt}_indices[${Xr}] = ${rr>1?`batch_indices[${an}]`:"batch_indices"};`;return fr.forEach(Xr=>{Br+=` +${jt}_indices[${Xr}] = 0;`}),Br+=`${jt}_indices[${Le-2}] = 0u; + ${jt}_indices[${Le-1}] = 0u;`,Br},Lt=()=>{let Zt=`var a_data: ${oe.type.value};`;for(let fr=0;fr; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) { + ${Lt()} + } + for (var i = 0u; i < ${u}u; i++) { + var value = values[i]; + ${pr} + ${Ot} + let cur_indices = ${Ge.type.indices}(batch, row + i, col); + let offset = ${Ge.indicesToOffset("cur_indices")}; + ${Ge.setByOffset(`offset / ${w}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${w};${y};${u};${s}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:q}),getShaderSource:R}},kl=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.")},Pl=e=>{kl(e.inputs);let t=Yr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(sa(e.inputs,{activation:""},t)):e.compute(ea(e.inputs,{activation:""},t))}}),ri,ni,aa,si,oa,la,Al,Il,Es,Fl=B(()=>{Yt(),ju(),na(),ti(),Vu(),Xn(),ia(),ds(),ri=(e,t,r,n,s,a)=>{let i=e[0],d=e.slice(a?1:2,a?3:4),c=d.length,h=t[0],w=t.slice(2).map((u,k)=>u+(u-1)*(r[k]-1)),y=d.map((u,k)=>u+n[k]+n[k+c]).map((u,k)=>Math.floor((u-w[k]+s[k])/s[k]));return y.splice(0,0,i),y.splice(a?3:1,0,h),y},ni=[2,3,1,0],aa=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},si=(e,t)=>{let r=e.kernelShape.slice();for(let a=2;a{let t=Qi(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,d=e.pads,c=e.strides,h=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:d,strides:c,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},la=(e,t,r)=>{let n=si(r,t),s=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let tt=ri(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),Ge=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ge);let dt=[t[0],Ge];t.length===3&&dt.push(t[2]),e.compute(Sl(dt,n,tt),{inputs:dt})}else e.compute(El(t,n));return}let a=t.length===3,i=t[0].dims[s?1:2],d=t[0].dims[s?2:3],c=t[0].dims[s?3:1],h=t[1].dims[2],w=t[1].dims[3],y=ri(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,s),u=y[s?1:2],k=y[s?2:3],T=y[s?3:1],I=s&&h===i&&w===d&&r.pads[0]===0&&r.pads[1]===0;if(I||h===1&&w===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let tt=y[0],Ge,dt,Ot,Dt=[];if(s){let nr=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=nr),I){let Sr=i*d*c;Ge=t[0].reshape([1,tt,Sr]),dt=nr.reshape([1,Sr,T]),Ot=[1,tt,T]}else Ge=t[0].reshape([tt,i*d,c]),dt=nr.reshape([1,c,T]),Ot=[tt,u*k,T];Dt.push(Ge),Dt.push(dt)}else Ge=t[0].reshape([tt,c,i*d]),dt=t[1].reshape([1,T,c]),Ot=[tt,T,u*k],Dt.push(dt),Dt.push(Ge);a&&Dt.push(t[2]);let pr=Ot[2],gr=Dt[0].dims[Dt[0].dims.length-1];pr<8&&gr<8?e.compute(sa(Dt,n,y,Ot,s),{inputs:Dt}):e.compute(ea(Dt,n,y,Ot,s),{inputs:Dt});return}let U=!0,q=e.kernelCustomData.wT??e.compute(Pn(t[1],ni),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=q);let R=[t[0],q];a&&R.push(t[2]);let ce=s?u*k:T,Z=s?T:u*k,oe=h*w*c;e.compute(Nu(R,n,y,ce,Z,oe,a,U),{inputs:R})},Al=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),d=[1].concat(t.kernelShape),c=si({...t,pads:s,strides:a,dilations:i,kernelShape:d},n);e.compute(El(n,c,h=>r?[h[0],h[2],h[3]]:[]))},Il=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=si(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Cl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute($l(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},Es=(e,t)=>{aa(e.inputs,t),e.inputs[0].dims.length===3?Al(e,t):e.inputs[0].dims.length===5?Il(e,e.inputs,t):la(e,e.inputs,t)}}),Ol,zl,Uu=B(()=>{Qt(),fn(),or(),Xn(),hs(),wl(),ti(),Ol=(e,t=!1,r,n,s=4)=>{let a=U=>{switch(U){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; + let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; + let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; + let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; + return ${n}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${U} is not supported.`)}},i=e?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,d=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,c=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",w=e?"row":"col",y=e?"col":"row",u=` + let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${w} / outWidth; + let outCol = ${w} % outWidth; + + let WRow = ${y} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${y} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${c}) || fract(xR) > 0.0) { + return ${n}(0.0); + } + if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) { + return ${n}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${y} % inChannels; + ${i} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,k=e?` + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${u} + } + return ${n}(0.0);`:` + let col = colIn * ${s}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${u} + } + return ${n}(0.0);`,T=` + let col = colIn * ${s}; + let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${a(s)} + } + return ${n}(0.0); + `,I=Hn(r,n);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?k:T} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?T:k} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { + let col = colIn * ${s}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${d} + ${Yi(t)} + ${I} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; + } + }`},zl=(e,t,r,n,s,a,i,d)=>{let c=t.format==="NHWC",h=c?e[0].dims[3]:e[0].dims[1],w=r[0],y=c?r[2]:r[3],u=c?r[1]:r[2],k=c?r[3]:r[1],T=c&&h%4===0&&h%3&&k%4===0,I=c?k:y*u,U=c?y*u:k,q=[8,8,1],R=n<=8?[4,1,1]:[4,4,1],ce=[Math.ceil(I/q[0]/R[0]),Math.ceil(U/q[1]/R[1]),Math.ceil(w/q[2]/R[2])];Dr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ce}`);let Z=T?4:1,oe=Math.max(q[0]*Z,q[1]),tt=T?4:1,Ge=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],dt=[Ge[0]+(t.dilations[0]<=1?0:(Ge[0]-1)*(t.dilations[0]-1)),Ge[1]+(t.dilations[1]<=1?0:(Ge[1]-1)*(t.dilations[1]-1))],Ot=[dt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),dt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Dt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ge},{type:6,data:Ot}];Kn(t,Dt),Dt.push(...St(e[0].dims,e[1].dims));let pr=["rank","rank"];i&&(Dt.push(...St(e[2].dims)),pr.push("rank")),Dt.push(...St(r));let gr=nr=>{let Sr=it("x",e[0].dataType,e[0].dims.length,tt),Wr=it("w",e[1].dataType,e[1].dims.length,1),dr=Ut("result",e[0].dataType,r.length,tt),Rr=[Sr,Wr],Lt="";if(i){let Le=it("bias",e[2].dataType,e[2].dims.length,tt);Rr.push(Le),Lt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${Le.type.value} { + return bias[coords.${c?"w":"y"}${T?"/ 4":""}]; + }`}let Zt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Ge.length},{name:"pads",type:"i32",length:Ot.length}];Bn(t,Zt);let fr=br(e[0].dataType,1);if(fr!=="f16"&&fr!=="f32")throw new Error(`elemType ${fr} is not supported.`);return` + ${Zi("uniforms.result_strides")} + ${nr.registerUniforms(Zt).declareVariables(...Rr,dr)}; + ${Lt} + ${Ol(c,i,t,Sr.type.value,Z)} + ${T?Zs(R,q,fr,void 0,!c,oe):Js(R,q,fr,void 0,!c,oe,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${R};${q};${T}`,inputDependencies:pr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ce[0],y:ce[1],z:ce[2]},programUniforms:Dt}),getShaderSource:gr}}}),ua,Ss,Ed=B(()=>{Qt(),fn(),Yt(),or(),ua=(e,t,r,n,s,a=!1,i,d,c=!1)=>{let h=c?1:2,w=c?2:3,y=c?3:1,u=a?2:1,k=` + fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { + result[flatIndex] = ${a?`vec4<${i}>`:i}(value); + }`;n&&(k+=` + fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { + return bias[coords.${c?"w":"y"}${a?"/ 4":""}]; + }`);let T=a?4:1,I=it("W",t[1].dataType,t[1].dims.length,T),U=it("Dy",t[0].dataType,t[0].dims.length,T),q=[U,I];n&&q.push(it("bias",t[2].dataType,[r[y]].length,T));let R=Ut("result",t[0].dataType,r.length,T),ce=`{ + let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${s?"global_id.y":"workgroup_id.y"} * ${u}; + let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${u}>; + for (var i = 0; i < ${u}; i++) { + dotProd[i] = vec4<${i}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); + let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${i}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${U.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${U.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${y}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${U.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${I.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${U.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${i}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${u}; i = i + 1) { + let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; + ${R.set("batch","r","c + i","d1","value")}; + } + }`,Z=` + let outputIndices = ${R.offsetToIndices("global_idx")}; + let batch = ${R.indicesGet("outputIndices",0)}; + let d1 = ${R.indicesGet("outputIndices",y)}; + let r = ${R.indicesGet("outputIndices",h)}; + let c = ${R.indicesGet("outputIndices",w)}; + 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 = ${i}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${i}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${w}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${c?U.get("batch","idyR","idyC","inputChannel"):U.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${I.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; + ${R.setByOffset("global_idx","value")}; + `;return` + ${e.registerUniforms(d).declareVariables(...q,R)} + ${k} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${a?ce:Z}}`},Ss=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=He.size(s),i=[Math.ceil(a/64),1,1];Dr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let d=t.format==="NHWC",c=["rank","rank"],h=[t.strides[0],t.strides[1]],w=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],y=[t.dilations[0],t.dilations[1]],u=[w[0]+(t.dilations[0]<=1?0:(t.kernelShape[d?1:2]-1)*(t.dilations[0]-1)),w[1]+(t.dilations[1]<=1?0:(t.kernelShape[d?2:3]-1)*(t.dilations[1]-1))],k=[u[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),u[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],T=!1,I=t.group,U=e[1].dims,q=U[0]/I,R=U[1],ce=[{type:12,data:a},{type:12,data:h},{type:12,data:w},{type:12,data:y},{type:12,data:u},{type:6,data:k},{type:12,data:q},{type:12,data:R},...St(e[0].dims,e[1].dims)];n&&(ce.push(...St(e[2].dims)),c.push("rank")),ce.push(...St(s));let Z=i[1]===1&&i[2]===1,oe=tt=>{let Ge=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:w.length},{name:"dilations",type:"u32",length:w.length},{name:"effective_filter_dims",type:"u32",length:u.length},{name:"pads",type:"i32",length:k.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],dt=br(e[0].dataType);return`${ua(tt,e,s,n,Z,T,dt,Ge,d)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:c},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:ce}),getShaderSource:oe}}}),Dl,Bl,da,ca,Ll,pa,Rl,Nl,ha,Wu,Sd=B(()=>{Uu(),Ed(),Xn(),ds(),Dl=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,Bl=(e,t,r,n,s)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[s]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[s]=a)},da=(e,t,r,n,s,a,i,d,c,h)=>{let w=e.length-2,y=h.length===0;if(c.length===0)for(let T=0;T{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((y,u)=>y*u,1)===0){r.length=0;for(let y=2;yy+u,0)===0){let y=t[0].dims.length-2;c=new Array(y).fill(1)}let h=e.strides.slice();if(h.reduce((y,u)=>y+u,0)===0){let y=t[0].dims.length-2;h=new Array(y).fill(1)}da(d,r,c,e.autoPad,e.group,s,h,n,i,a);let w=Object.assign({},e);return Object.assign(w,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:c,strides:h}),w},Ll=e=>{let t=Qi(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,d=e.pads,c=e.strides,h=e.wIsConst(),w=e.outputPadding,y=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:w,outputShape:y,pads:d,strides:c,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},pa=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,d)=>i+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,d)=>i+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,d)=>i+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,d)=>i+d,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")},Rl=[2,3,1,0],Nl=(e,t,r)=>{let n=ca(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],d=t[0].dims[s?3:1];if(n.group!==1||i===1&&d===1){e.compute(Ss(t,n));return}let c=a[s?1:2],h=a[s?2:3],w=t[1].dims[2],y=t[1].dims[3],u=s?c*h:i,k=s?i:c*h,T=w*y*d,I=!0,U=e.kernelCustomData.wT??e.compute(Pn(t[1],Rl),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=U);let q=[t[0],U],R=t.length===3;R&&(!s&&t[2].dims.length===1?q.push(t[2].reshape([t[2].dims[0],1,1])):q.push(t[2])),e.compute(zl(q,n,a,u,k,T,R,I),{inputs:q})},ha=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let c=ca({...t,pads:d,strides:i,dilations:a,kernelShape:s},n);e.compute(Ss(n,c,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},Wu=(e,t)=>{pa(e.inputs,t),e.inputs[0].dims.length===3?ha(e,t):Nl(e,e.inputs,t)}}),fa,ma,jl,Gu=B(()=>{Qt(),Yt(),hr(),or(),fa=(e,t,r,n)=>{let s=He.size(t),a=t.length,i=it("input",e,a),d=Ut("output",e,a),c=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=He.normalizeAxis(c,a),w=y=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,k=Ft("uniforms.input_shape","uniforms.axis",a),T=n.reverse?u+(n.exclusive?" + 1":""):"0",I=n.reverse?k:u+(n.exclusive?"":" + 1");return` + ${y.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,d)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${d.offsetToIndices("global_idx")}; + var sum = ${d.type.value}(0); + let first : i32 = ${T}; + let last : i32 = ${I}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:h},...St(t,t)]}),getShaderSource:w}},ma=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(fa(n,r,s,t),{inputs:[0]})},jl=e=>{let t=e.exclusive===1,r=e.reverse===1;return Gt({exclusive:t,reverse:r})}}),_a,Vl,Ul,ga,Wl,qu=B(()=>{Qt(),Yt(),hr(),or(),_a=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.")},Vl=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,d,c=t.format==="NHWC",h=t.blocksize,w=t.mode==="DCR";c?([r,n,s,a]=e.dims,i=w?[r,n,s,h,h,a/h**2]:[r,n,s,a/h**2,h,h],d=w?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=w?[r,h,h,a/h**2,n,s]:[r,a/h**2,h,h,n,s],d=w?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let y=e.reshape(i),u=y.dims.length,k=e.dataType,T=it("a",k,u),I=Ut("output",k,u),U=q=>` + ${q.registerUniform("output_size","u32").declareVariables(T,I)} + + ${Vl(d,u,T,I)} + + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${I.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${I.setByOffset("global_idx",T.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:q=>{let R=c?[r,n*h,s*h,a/h**2]:[r,a/h**2,n*h,s*h],ce=He.size(R),Z=y.dims,oe=He.sortBasedOnPerm(Z,d);return{outputs:[{dims:R,dataType:q[0].dataType}],dispatchGroup:{x:Math.ceil(ce/64)},programUniforms:[{type:12,data:ce},...St(Z,oe)]}},getShaderSource:U}},ga=(e,t)=>{_a(e.inputs),e.compute(Ul(e.inputs[0],t))},Wl=e=>Gt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ks,Ps,wa,Ir,Hu,Ku,Xu,ii,Gl,ql,Hl,Qu=B(()=>{Qt(),Yt(),hr(),or(),ks="[a-zA-Z]|\\.\\.\\.",Ps="("+ks+")+",wa="^"+Ps+"$",Ir="("+Ps+",)*"+Ps,Hu="^"+Ir+"$",Ku=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Xu=class{constructor(e,t){var s;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Hu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let d=e[i].dims.slice();if(!a.match(RegExp(wa)))throw new Error("Invalid LHS term");let c=this.processTerm(a,!0,d,i);this.lhs.push(c)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Ps)))throw new Error("Invalid RHS");(s=n.match(RegExp(ks,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);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,r){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(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let s=r.length,a=!1,i=[],d=0;if(!e.match(RegExp(wa))&&!t&&e!=="")throw new Error("Invalid LHS term");let c=e.match(RegExp(ks,"g")),h=new Ku(n);return c==null||c.forEach((w,y)=>{if(w==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=s-c.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let k=0;ke+"_max",Gl=(e,t,r,n)=>{let s=e.map(h=>h.length).map((h,w)=>it(`input${w}`,t,h)),a=He.size(n),i=Ut("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),c=h=>{let w=[],y="var prod = 1.0;",u="var sum = 0.0;",k="sum += prod;",T=[],I=[],U=[],q=[],R=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((Z,oe)=>{var tt;if(r.rhs.symbolToIndices.has(oe)){let Ge=(tt=r.rhs.symbolToIndices.get(oe))==null?void 0:tt[0];Ge!==void 0&&r.lhs.forEach((dt,Ot)=>{if(Z.inputIndices.includes(Ot)){let Dt=dt.symbolToIndices.get(oe);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(pr=>{w.push(`${s[Ot].indicesSet(`input${Ot}Indices`,pr,i.indicesGet("outputIndices",Ge))}`)})}})}else r.lhs.forEach((Ge,dt)=>{if(Z.inputIndices.includes(dt)){let Ot=Ge.symbolToIndices.get(oe);if(Ot===void 0)throw new Error("Invalid symbol error");Ot.forEach(Dt=>{T.push(`${s[dt].indicesSet(`input${dt}Indices`,Dt,`${oe}`)}`)}),q.push(`prod *= ${s[dt].getByIndices(`input${dt}Indices`)};`)}}),I.push(`for(var ${oe}: u32 = 0; ${oe} < uniforms.${ii(oe)}; ${oe}++) {`),U.push("}")});let ce=R?[...w,`let sum = ${s.map((Z,oe)=>Z.getByIndices(`input${oe}Indices`)).join(" * ")};`]:[...w,u,...I,...T,y,...q,k,...U];return` + ${h.registerUniforms(d.map(Z=>({name:`${ii(Z)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${s.map((Z,oe)=>`var input${oe}Indices: ${s[oe].type.indices};`).join(` +`)} + ${ce.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(y=>r.symbolToInfo.has(y)).map(y=>{var u;return{type:12,data:((u=r.symbolToInfo.get(y))==null?void 0:u.dimValue)||0}});h.push({type:12,data:a});let w=e.map((y,u)=>[...St(y)]).reduce((y,u)=>y.concat(u),h);return w.push(...St(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:w}},getShaderSource:c}},ql=(e,t)=>{let r=new Xu(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(Gl(s,e.inputs[0].dataType,r,n))},Hl=e=>{let t=e.equation.replace(/\s+/g,"");return Gt({equation:t})}}),ya,ai,Kl,Xl,ba,kd=B(()=>{Qt(),Yt(),or(),ya=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let s=0;se.length>t.length?ai(e,t):ai(t,e),Xl=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Kl(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(He.size(n)/a),d=h=>{let w=it("input",s,t.length,a),y=Ut("output",s,n.length,a),u;if(s===9){let k=(T,I,U="")=>` + let outputIndices${I} = ${y.offsetToIndices(`outputOffset + ${I}u`)}; + let offset${I} = ${w.broadcastedIndicesToOffset(`outputIndices${I}`,y)}; + let index${I} = offset${I} / 4u; + let component${I} = offset${I} % 4u; + ${T}[${I}] = ${U}(${w.getByOffset(`index${I}`)}[component${I}]); + `;u=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${k("data",0,"u32")} + ${k("data",1,"u32")} + ${k("data",2,"u32")} + ${k("data",3,"u32")} + ${y.setByOffset("global_idx","data")} + }`}else u=` + let outputIndices = ${y.offsetToIndices("global_idx")}; + let inputOffset = ${w.broadcastedIndicesToOffset("outputIndices",y)}; + ${y.setByOffset("global_idx",w.getByOffset("inputOffset"))} + }`;return` + ${h.registerUniform("vec_size","u32").declareVariables(w,y)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u}`},c=[{type:12,data:i},...St(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c})}},ba=e=>{ya(e.inputs),e.compute(Xl(e.inputs),{inputs:[0]})}}),Yu,Ql,Zu=B(()=>{Qt(),Yt(),or(),Gi(),Yu=e=>{let t=e[0].dataType,r=He.size(e[0].dims),n=He.size(e[1].dims),s=n%4===0,a=i=>{let d=it("x",t,[1],4),c=it("bias",t,[1],4),h=Ut("y",t,[1],4),w=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=k=>` + let bias${k}_offset: u32 = (global_idx * 4 + ${k}) % uniforms.bias_size; + let bias${k} = ${c.getByOffset(`bias${k}_offset / 4`)}[bias${k}_offset % 4];`,u=s?` + let bias = ${c.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${y(0)}${y(1)}${y(2)}${y(3)} + let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(w).declareVariables(d,c,h)} + + ${Vi(Mr(t))} + + ${i.mainStart(mn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${d.getByOffset("global_idx")}; + ${u} + let x_in = x + bias; + ${h.setByOffset("global_idx",Ui("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/mn/4)}})}},Ql=e=>{e.inputs.length<2||He.size(e.inputs[1].dims)===0?Qo(e):e.compute(Yu(e.inputs))}}),Yl,Zl,Jl,eu,Ju=B(()=>{Qt(),Yt(),hr(),or(),Yl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Zl=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=He.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let d=r[a],c=e[0].dataType===9?4:1,h=Math.ceil(He.size(i)/c),w=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...St(e[0].dims,e[1].dims,i)],y=u=>{let k=it("data",e[0].dataType,e[0].dims.length,c),T=it("inputIndices",e[1].dataType,e[1].dims.length),I=Ut("output",e[0].dataType,i.length,c),U=R=>{let ce=n.length,Z=`var indicesIndices${R} = ${T.type.indices}(0);`;for(let oe=0;oe1?`indicesIndices${R}[${oe}]`:`indicesIndices${R}`} = ${i.length>1?`outputIndices${R}[uniforms.axis + ${oe}]`:`outputIndices${R}`};`;Z+=` + var idx${R} = ${T.getByIndices(`indicesIndices${R}`)}; + if (idx${R} < 0) { + idx${R} = idx${R} + uniforms.axisDimLimit; + } + var dataIndices${R} : ${k.type.indices}; + `;for(let oe=0,tt=0;oe1?`dataIndices${R}[${oe}]`:`dataIndices${R}`} = u32(idx${R});`,tt+=ce):(Z+=`${s>1?`dataIndices${R}[${oe}]`:`dataIndices${R}`} = ${i.length>1?`outputIndices${R}[${tt}]`:`outputIndices${R}`};`,tt++);return Z},q;if(e[0].dataType===9){let R=(ce,Z,oe="")=>` + let outputIndices${Z} = ${I.offsetToIndices(`outputOffset + ${Z}u`)}; + ${U(Z)}; + let offset${Z} = ${k.indicesToOffset(`dataIndices${Z}`)}; + let index${Z} = offset${Z} / 4u; + let component${Z} = offset${Z} % 4u; + ${ce}[${Z}] = ${oe}(${k.getByOffset(`index${Z}`)}[component${Z}]); + `;q=` + let outputOffset = global_idx * ${c}; + var value = vec4(0); + ${R("value",0,"u32")} + ${R("value",1,"u32")} + ${R("value",2,"u32")} + ${R("value",3,"u32")} + ${I.setByOffset("global_idx","value")} + `}else q=` + let outputIndices = ${I.offsetToIndices("global_idx")}; + ${U("")}; + let value = ${k.getByIndices("dataIndices")}; + ${I.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,T,I)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${q} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:y}},Jl=e=>Gt({axis:e.axis}),eu=(e,t)=>{let r=e.inputs;Yl(r),e.compute(Zl(e.inputs,t))}}),tu,ru,nu,su,ed=B(()=>{Qt(),Yt(),hr(),or(),tu=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.`)},ru=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,d=He.normalizeAxis(t.axis,s),c=r[d],h=a.slice(0),w=He.size(h),y=it("input",n,s),u=it("indicesInput",i,a.length),k=Ut("output",n,h.length),T=[{type:12,data:w},{type:6,data:c},{type:12,data:d}];return T.push(...St(r,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:T}),getShaderSource:I=>` + ${I.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,u,k)} + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${k.offsetToIndices("global_idx")}; + + var idx = ${u.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${y.type.indices}(outputIndices); + ${y.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${y.getByIndices("inputIndices")}; + + ${k.setByOffset("global_idx","value")}; + }`}},nu=e=>Gt({axis:e.axis}),su=(e,t)=>{let r=e.inputs;tu(r),e.compute(ru(e.inputs,t))}}),iu,au,ou,td,lu=B(()=>{Qt(),Yt(),or(),iu=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")},au=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=wr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[s,a];if(!d)throw new Error("Can't use gemm on the given tensors");let c=He.size(d),h=[{type:12,data:c},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],w=["type","type"];e.length===3&&(h.push(...St(e[2].dims)),w.push("rank")),h.push(...St(d));let y=u=>{let k="";t.transA&&t.transB?k="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?k="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?k="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(k="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let T=t.alpha===1?"":"value *= uniforms.alpha;",I=it("a",e[0].dataType,e[0].dims),U=it("b",e[1].dataType,e[1].dims),q=I.type.value,R=null,ce=[I,U];e.length===3&&(R=it("c",e[2].dataType,e[2].dims.length),ce.push(R));let Z=Ut("output",e[0].dataType,d.length);ce.push(Z);let oe=[{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` + ${u.registerUniforms(oe).declareVariables(...ce)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${q}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${k} + } + + ${T} + ${R!=null?`let cOffset = ${R.broadcastedIndicesToOffset("vec2(m, n)",Z)}; value += ${q}(uniforms.beta) * ${R.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:y}},ou=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},td=(e,t)=>{iu(e.inputs),e.compute(au(e.inputs,t))}}),ln,uu,du,Ma,cu,As,pu,hu=B(()=>{Qt(),Yt(),hr(),F(),Xs(),or(),ds(),ln=(e,t)=>e.length>t&&e[t].dims.length>0&&He.size(e[t].dims)>0?e[t]:void 0,uu=(e,t)=>{let r=e[0],n=ln(e,1),s=ln(e,2),a=ln(e,3),i=ln(e,4),d=ln(e,5),c=ln(e,6),h=ln(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let w=!1,y=r.dims[0],u=r.dims[1],k=r.dims.length===3?w?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],T=u,I=0,U=0,q=Math.floor(k/t.numHeads);if(c&&h){if(c.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(c.dims[0]!==y||c.dims[1]!==t.numHeads||c.dims[3]!==q)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==y||h.dims[1]!==t.numHeads||h.dims[3]!==q)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.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');I=c.dims[2],U=c.dims[2]}else if(c||h)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let R;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');R=2,T=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==q)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');R=5,T=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==q)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');R=0,T=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');R=3}if(a){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let ce=0;if(i){ce=8;let dt=i.dims;throw dt.length===1?dt[0]===y?ce=1:dt[0]===3*y+2&&(ce=3):dt.length===2&&dt[0]===y&&dt[1]===T&&(ce=5),ce===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let Z=!1,oe=k;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(T!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(T!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],Z=!0}}let tt=I+T,Ge=!1;if(i)throw new Error("Key padding mask is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(d.dims[0]!==y&&d.dims[0]!==1||d.dims[1]!==t.numHeads||d.dims[2]!==u||d.dims[3]!==tt)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:y,sequenceLength:u,pastSequenceLength:I,kvSequenceLength:T,totalSequenceLength:tt,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:k,vHiddenSize:oe,headSize:q,vHeadSize:Math.floor(oe/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ce,scale:t.scale,broadcastResPosBias:Ge,passPastInKv:Z,qkvFormat:R}},du=e=>Gt({...e}),Ma=Gt({perm:[0,2,1,3]}),cu=(e,t,r,n,s,a,i)=>{let d=[n,s,a],c=He.size(d),h=[{type:12,data:c},{type:12,data:i},{type:12,data:a}],w=y=>{let u=Ut("qkv_with_bias",t.dataType,d),k=it("qkv",t.dataType,d),T=it("bias",r.dataType,d),I=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${y.registerUniforms(I).declareVariables(k,T,u)} + ${y.mainStart()} + ${y.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:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:h}),getShaderSource:w},{inputs:[t,r],outputs:[-1]})[0]},As=(e,t,r,n,s,a,i,d)=>{let c=a;if(i){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return c=cu(e,a,i,t,n,r*s,d),c=c.reshape([t,n,r,s]),e.compute(Pn(c,Ma.perm),{inputs:[c],outputs:[-1]})[0]}else return a.dims.length===3&&(c=a.reshape([t,n,r,s])),e.compute(Pn(c,Ma.perm),{inputs:[c],outputs:[-1]})[0]},pu=(e,t)=>{let r=uu(e.inputs,t),n=e.inputs[0],s=ln(e.inputs,1),a=ln(e.inputs,2),i=ln(e.inputs,3),d=ln(e.inputs,4),c=ln(e.inputs,5),h=ln(e.inputs,6),w=ln(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let y=s&&a&&s.dims.length===4&&a.dims.length===4,u=As(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(y)return cs(e,u,s,a,d,void 0,h,w,c,r,t);if(!s||!a)throw new Error("key and value must be provided");let k=As(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),T=As(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);cs(e,u,k,T,d,void 0,h,w,c,r,t)}}),va,fu,mu,xa,_u,gu=B(()=>{Qt(),Yt(),or(),va=e=>Array.from(e.getBigInt64Array(),Number),fu=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(va(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")},mu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??va(e[1]),s=mu(r,n),a=He.size(s),i=e[0].dataType,d=it("input",i,r.length),c=Ut("output",i,s.length),h=w=>` + const inputShape = ${d.indices(...r)}; + ${w.registerUniform("output_size","u32").declareVariables(d,c)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${c.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + for (var i = 0; i < ${r.length}; i++) { + let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i; + + ${d.indicesSet("input_indices","i","input_dim_value")} + } + ${c.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...St(e[0].dims,s)]}),getShaderSource:h}},_u=e=>{fu(e.inputs),e.compute(xa(e.inputs),{inputs:[0]})}}),wu,Ta,yu,bu,Ca,Mu,rd=B(()=>{Qt(),Yt(),hr(),Xs(),or(),hu(),gu(),ds(),wu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,c=r.dims[0],h=r.dims[1],w=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=h,u=0,k=0,T=Math.floor(w/t.numHeads),I=a&&a.dims.length!==0,U=i&&i.dims.length!==0,q=!0;if(I&&U){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[1],k=a.dims[1]}else if(I||U)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let R;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');R=2,y=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==T)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');R=5,y=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==T)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');R=0,y=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');R=3}let ce=0,Z=!1,oe=w;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(y!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=s.dims[2]}else{if(y!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');oe=s.dims[1]*s.dims[3],Z=!0}}let tt=u+y;return{batchSize:c,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:y,totalSequenceLength:tt,maxSequenceLength:k,inputHiddenSize:0,hiddenSize:w,vHiddenSize:oe,headSize:T,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ce,scale:t.scale,broadcastResPosBias:!1,passPastInKv:Z,qkvFormat:R,isPastkvBSNH:q}},Ta=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=He.size(s)/a,d=n.totalSequenceLength,c=Ut("present_kv",r,s.length,a),h=it("new_kv",e.dataType,e.dims.length,a),w=t?it("past_kv",t.dataType,t.dims.length,a):void 0,y=Math.ceil(n.headSize/a),u={x:d,y:e.dims[0],z:1},k=t?["rank","rank"]:["rank"],T=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],I=[h];w?(T.push(...St(e.dims),...St(t.dims),...St(s)),I.push(w)):T.push(...St(e.dims),...St(s));let U=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],q=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; + var past_head_stride = uniforms.past_seqlen * H; + if (is_bsnh) { + past_head_stride = H; + } + let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; + present_kv[out_offset] = past_kv[in_offset];`,R=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; + let new_row_stride = num_heads * H; + let new_head_stride = H; + let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; + present_kv[out_offset] = new_kv[in_offset];`,ce=t?`if (s < past_seqlen) { + ${q} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${R} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${R} + }`,Z=oe=>` + + ${oe.registerUniforms(U).declareVariables(...I,c)} + ${oe.mainStart([y,n.kvNumHeads,1])} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${c.offsetToIndices("global_idx")}; + let h = local_id.x; + let n = local_id.y; + let s = workgroup_id.x; + let b = workgroup_id.y; + let num_heads = ${n.kvNumHeads}u; + let H = ${y}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${n.isPastkvBSNH}; + + if (is_bsnh) { + row_stride = num_heads * H; + } + var present_head_stride = present_seqlen * H; + if (is_bsnh) { + present_head_stride = H; + } + + let past_seqlen = uniforms.past_seqlen; + + let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; + ${ce} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${y}${!!t}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:u,programUniforms:T}),getShaderSource:Z}},yu=e=>Gt({...e}),bu=Gt({perm:[0,2,1,3]}),Ca=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,d=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(Ta(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(Ta(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],d!==1&&(a=e.compute(xa([a],[1,1,1,d]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*d,n.headSize])),e.compute(Pn(a,bu.perm),{inputs:[a],outputs:[-1]})[0]},Mu=(e,t)=>{var c;let r=wu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((c=e.inputs[1])==null?void 0:c.dims.length)===5)throw new Error("Packed KV is not implemented");let n=As(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,i=Ca(e,e.inputs[1],s,r,1),d=Ca(e,e.inputs[2],a,r,2);cs(e,n,i,d,void 0,void 0,void 0,void 0,void 0,r,t)}}),vu,xu,Tu,Cu,Pd=B(()=>{Qt(),Yt(),or(),vu=(e,t)=>{let r=e[0].dims,n=r,s=2,a=He.sizeToDimension(r,s),i=He.sizeFromDimension(r,s),d=mr(i),c=i/d,h=[r[0],r[1],c],w=["rank","type","type"],y=[{type:12,data:i},{type:12,data:c}];y.push(...St(h,h));let u=k=>{let T=it("x",e[0].dataType,h.length,d),I=it("scale",e[1].dataType,e[1].dims),U=it("bias",e[2].dataType,e[2].dims),q=Ut("output",e[0].dataType,h.length,d),R=[T,I,U,q],ce=T.type.value,Z=d===1?"f32":`vec${d}`,oe=64,tt=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${Z}, ${oe}>; + const workgroupSize = ${oe}u; + ${k.registerUniforms(tt).declareVariables(...R)} + ${k.mainStart(oe)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${Z}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${Z}(${T.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${_n("workgroupShared[0]",d)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${Z}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${Z}(${T.get("batch","channel","h")}) - ${Z}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${_n("workgroupShared[0]",d)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); + let channelScale = invStdDev * f32(${I.getByOffset("channel")}); + let channelShift = f32(${U.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${T.get("batch","channel","h")} * ${ce}(${Z}(channelScale)) + ${ce}(${Z}(channelShift)); + ${q.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${d}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:a},programUniforms:y}),getShaderSource:u}},xu=(e,t,r,n,s,a,i,d)=>{let c=mr(i),h=64,w=c===1?"vec2f":`mat2x${c}f`,y=c===1?"f32":`vec${c}f`,u=(tt,Ge)=>`${w}(${tt}, ${Ge})`,k=s*i/c,T=Math.ceil(a/h),I=["type"],U=[{type:12,data:T},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(a*i/c)}],q=tt=>{let Ge=it("input",t.dataType,t.dims,c);return` + ${tt.declareVariables(Ge)} + @group(0) @binding(1) var output : array<${w}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${tt.mainStart(h)} + let currentImageNumber = global_idx / ${h} / uniforms.C; + let currentChannelNumber = (global_idx / ${h}) % uniforms.C; + let wgOffset = local_id.x * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${Ar("f32",c)}; + var squaredSum = ${Ar("f32",c)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${y}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${u("sum","squaredSum")}; + }`},R=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${c}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:[s,i,h,2],dataType:1}],dispatchGroup:{x:s*i/c},programUniforms:U}),getShaderSource:q},{inputs:[t],outputs:[-1]})[0],ce=[{type:12,data:k},{type:12,data:a},{type:12,data:Math.floor(i/c)},{type:12,data:Math.floor(h*i/c)}],Z=["type","type","type"],oe=tt=>{let Ge=it("scale",r.dataType,r.dims,c),dt=it("bias",n.dataType,n.dims,c);return` + @group(0) @binding(0) var input : array<${w}>; + @group(0) @binding(1) var scale : array<${Ge.type.storage}>; + @group(0) @binding(2) var bias : array<${dt.type.storage}>; + @group(0) @binding(3) var output : array<${w}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${tt.mainStart()} + ${tt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} + let currentImageNumber = global_idx / uniforms.C; + let currentChannelNumber = global_idx % uniforms.C; + + let offset = currentImageNumber * uniforms.image_size; + var sum = ${Ar("f32",c)}; + var squaredSum = ${Ar("f32",c)}; + for (var i: u32 = 0; i < min(${h}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${h}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${d})); + let channelScale = invStdDev * ${y}(scale[currentChannelNumber]); + let channelShift = ${y}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${u("channelScale","channelShift")}; + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${c};${d}`,inputDependencies:Z},getRunData:()=>({outputs:[{dims:[s,i,2],dataType:1}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:ce}),getShaderSource:oe},{inputs:[R,r,n],outputs:[-1]})[0]},Tu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],d=He.sizeFromDimension(n,1)/i,c=mr(i),h=He.size(s)/c,w=[{type:12,data:d},{type:12,data:Math.floor(i/c)}],y=["type","type"],u=xu(e,t[0],t[1],t[2],a,d,i,r.epsilon),k=T=>{let I=br(t[0].dataType),U=c===1?"vec2f":`mat2x${c}f`,q=c===1?I:`vec${c}<${I}>`,R=it("input",t[0].dataType,t[0].dims,c),ce=Ut("output",t[0].dataType,s,c);return` + @group(0) @binding(0) var input : array<${R.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${U}>; + @group(0) @binding(2) var output : array<${ce.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${T.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${q}(scale[0]), ${q}(scale[1])); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:k},{inputs:[t[0],u]})},Cu=(e,t)=>{t.format==="NHWC"?Tu(e,e.inputs,t):e.compute(vu(e.inputs,t))}}),lr,$u,Qr,tn=B(()=>{Qt(),Yt(),or(),lr=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},$u=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],d=s,c=He.normalizeAxis(t.axis,s.length),h=He.sizeToDimension(s,c),w=He.sizeFromDimension(s,c),y=He.size(a.dims),u=i?He.size(i.dims):0;if(y!==w||i&&u!==w)throw new Error(`Size of X.shape()[axis:] == ${w}. + Size of scale and bias (if provided) must match this. + Got scale size of ${y} and bias size of ${u}`);let k=[];for(let oe=0;oe1,R=r>2,ce=oe=>{let tt=br(e[0].dataType),Ge=[it("x",e[0].dataType,e[0].dims,T),it("scale",a.dataType,a.dims,T)];i&&Ge.push(it("bias",i.dataType,i.dims,T)),Ge.push(Ut("output",e[0].dataType,d,T)),q&&Ge.push(Ut("mean_data_output",1,k)),R&&Ge.push(Ut("inv_std_output",1,k));let dt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${oe.registerUniforms(dt).declareVariables(...Ge)} + ${oe.mainStart()} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Ar("f32",T)}; + var mean_square_vector = ${Ar("f32",T)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${jr(tt,T,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${_n("mean_vector",T)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${_n("mean_square_vector",T)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${jr(tt,T,"x[j + offset]")}; + let f32scale = ${jr(tt,T,"scale[j]")}; + output[j + offset] = ${Ge[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${jr(tt,T,"bias[j]")}`:""} + ); + } + + ${q?"mean_data_output[global_idx] = mean":""}; + ${R?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},Z=[{dims:d,dataType:e[0].dataType}];return q&&Z.push({dims:k,dataType:1}),R&&Z.push({dims:k,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${T};${r};${n}`,inputDependencies:I},getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:U}),getShaderSource:ce}},Qr=(e,t)=>{lr(e.inputs),e.compute($u(e.inputs,t,e.outputCount))}}),rn,Zn,nd,Eu,sd=B(()=>{Qt(),Yt(),hr(),or(),rn=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!He.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(He.size(d)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let c=e[3].dims,h=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(He.size(c)!==h)throw new Error("zeroPoints input size error.")}},Zn=(e,t,r,n)=>{let s=e[0].dims,a=s.length,i=Math.floor((t.k+t.blockSize-1)/t.blockSize),d=s[a-2],c=t.k,h=t.n,w=s.slice(0,a-2),y=He.size(w),u=t.blockSize/8*t.bits/4,k=e[0].dataType,T=mr(d),I=mr(t.k),U=mr(u),q=zn(k),R=d*i*q,ce=Math.floor(n/R),Z=i<=r[0]&&ce>0,oe=!Z||ce>=4?mr(h):ce>=2&&mr(h)>=2?2:1,tt=w.concat([d,h]),Ge=He.size(tt)/oe/T,dt=Z?[]:[{type:12,data:Ge},{type:12,data:t.blockSize}],Ot=[y,d,c/I],Dt=He.convertShape(e[1].dims).slice();Dt.splice(-1,1,u/U),dt.push(...St(Ot)),dt.push(...St(Dt)),dt.push(...St(e[2].dims)),e.length===4&&dt.push(...St(He.convertShape(e[3].dims)));let pr=[y,d,h/oe];dt.push(...St(pr));let gr=nr=>{let Sr=Ot.length,Wr=it("a",e[0].dataType,Sr,I),dr=it("b",12,Dt.length,U),Rr=it("scales",e[2].dataType,e[2].dims.length),Lt=[Wr,dr,Rr],Zt=e.length===4?it("zero_points",12,e[3].dims.length):void 0;Zt&&Lt.push(Zt);let fr=pr.length,Le=Ut("output",e[0].dataType,fr,oe),jt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],rr=br(e[0].dataType),Br=(()=>{switch(I){case 1:return`array<${rr}, 8>`;case 2:return`mat4x2<${rr}>`;case 4:return`mat2x4<${rr}>`;default:throw new Error(`${I}-component is not supported.`)}})(),Xr=` + for (var word: u32 = 0; word < ${u}; word += ${U}) { + ${dr.indicesSet("b_indices","2","word")}; + let b_data = ${dr.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${U}; i++) { + let b_value: u32 = ${U===1?"b_data":"b_data[word + i]"}; + let b_mask: u32 = 0x0F0F0F0Fu; + let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); + let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); + let b_quantized_values = ${Br}(${Array.from({length:4},(zs,En)=>`${rr}(b_value_lower[${En}]), ${rr}(b_value_upper[${En}])`).join(", ")}); + let b_dequantized_values = ${I===1?`${Br}(${Array.from({length:8},(zs,En)=>`(b_quantized_values[${En}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Br}(${Array(8).fill("zero_point").join(",")})) * scale;`}; + // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 + for (var m: u32 = 0; m < ${Z?d:T}u; m++) { + ${Wr.indicesSet("a_indices",Sr-2,Z?"m":`row * ${T} + m`)}; + ${Wr.indicesSet("a_indices",Sr-1,"word_offset")}; + var input_offset = ${Wr.indicesToOffset("a_indices")}; + var a_data: ${Br}; + for (var j: u32 = 0; j < ${8/I}; j++) { + a_data[j] = ${Wr.getByOffset("input_offset")}; + input_offset++; + } + ${Z?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${oe>1?"[c]":""} += ${Array.from({length:8/I},(zs,En)=>`${I===1?`a_data[${En}] * b_dequantized_values[${En}]`:`dot(a_data[${En}], b_dequantized_values[${En}])`}`).join(" + ")}; + } + word_offset += ${8/I}; + } + }`,an=Zt?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${Zt.getByOffset("zero_point_index")}; + }`:"";return Z?` + var workgroup_shared: array<${Le.type.value}, ${d*i}>; + ${nr.declareVariables(...Lt,Le)} + ${nr.mainStart([i,1,1])} + var a_indices: ${Wr.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${Wr.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${oe}; c++) { + let col_times_components_plus_c = col * ${oe} + c; + ${Zt?` + var zero_point_bytes_per_col: u32 = (${i} + 1) / 2; + var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); + var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; + var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; + var zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + var zero_point_word: u32 = ${Zt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${dr.type.indices}; + ${dr.indicesSet("b_indices","0","col_times_components_plus_c")}; + // The scale and zero points are computed per block. + var scales_index = col_times_components_plus_c * ${i} + block; + let scale = ${Rr.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${rr}(${Zt?"(zero_point_word) & 0xFu":8}); + ${dr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${t.blockSize/I}; + var workgroup_shared_offset: u32 = block * ${d}; + ${Xr} + } + workgroupBarrier(); + var output_indices: ${Le.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(d/i)}; + ${Le.indicesSet("output_indices","0","batch")}; + ${Le.indicesSet("output_indices",fr-1,"col")}; + ${Le.indicesSet("output_indices",fr-2,"local_id.x * elements_per_thread")}; + var output_offset = ${Le.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${d}) { + var output_value: ${Le.type.value} = ${Le.type.value}(0); + var workgroup_shared_offset: u32 = row; + for (var b: u32 = 0u; b < ${i}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${d}; + } + ${Le.setByOffset("output_offset","output_value")}; + output_offset += ${h/oe}; + } + } + }`:` + ${nr.registerUniforms(jt).declareVariables(...Lt,Le)} + ${nr.mainStart()} + ${nr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${Le.type.value}, ${T}>; + var output_indices = ${Le.offsetToIndices("global_idx")}; + var col = ${Le.indicesGet("output_indices",fr-1)}; + var row = ${Le.indicesGet("output_indices",fr-2)}; + var a_indices: ${Wr.type.indices} = output_indices; + // Two zero points are packed into one byte because uniforms.bits <= 4. + // zero_point_offset is either 0 or 4. It is bit offset within one byte. + // TODO support zero_point_offset for bits > 4 + ${Zt?` + var zero_point_abs_offset = col * ${oe} * ((${i} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${Zt.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${i*oe}; + var b_indices: ${dr.type.indices}; + for (var c: u32 = 0; c < ${oe}; c++) { + ${dr.indicesSet("b_indices","0",`col * ${oe} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${i}; block++) { + // The scale and zero points are computed per block. + let scale = ${Rr.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${rr}(${Zt?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${dr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Xr} + scale_index++; + ${an} + block_offset += uniforms.block_size / ${I}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${Zt?`if (zero_point_offset % 8 > 0) { + ${an} + }`:""} + } + for (var k: u32 = 0u; k < ${T}u; k++) { + ${Le.indicesSet("output_indices",fr-2,`${T} * row + k`)}; + ${Le.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:Z?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${d};${k};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:tt,dataType:k}],name:Z?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Z?{x:1,y:Math.ceil(h/oe),z:y}:{x:Math.ceil(Ge/64)},programUniforms:dt}),getShaderSource:gr}},nd=(e,t)=>{rn(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),n=e.getMaxComputeWorkgroupStoragesize();e.compute(Zn(e.inputs,t,r,n))},Eu=e=>Gt(e)}),m,g,$,H,Fe,Pe,pt,kt,zt,ur=B(()=>{Qt(),Yt(),or(),m=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].")}},g=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; + if (k < 0) { + break; + } + if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { + break; + } + offset += k * i32(${Ft("uniforms.x_strides",s,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]; + } + `},$=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Ft("uniforms.x_shape",s,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Ft("uniforms.x_shape",s,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Ft("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},H=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { + k = i32(${Ft("uniforms.x_shape",s,t)}) - 1; + } + offset += k * i32(${Ft("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Fe=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` + k = i32(${e.indicesGet("indices",s)}) - ${Ft("uniforms.pads",s,r)}; + if (k < 0) { + k += i32(${Ft("uniforms.x_shape",s,t)}]); + } + if (k >= i32(${Ft("uniforms.x_shape",s,t)})) { + k -= i32(${Ft("uniforms.x_shape",s,t)}); + } + offset += k * i32(${Ft("uniforms.x_strides",s,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Pe=(e,t,r)=>{switch(r.mode){case 0:return g(e,t,r.pads.length);case 1:return $(e,t,r.pads.length);case 2:return H(e,t,r.pads.length);case 3:return Fe(e,t,r.pads.length);default:throw new Error("Invalid mode")}},pt=(e,t)=>{let r=He.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=He.size(r),a=[{type:12,data:s},{type:6,data:t.pads}];t.mode===0&&a.push({type:e[0].dataType,data:t.value}),a.push(...St(e[0].dims,r));let i=["rank"],d=c=>{let h=Ut("output",e[0].dataType,r.length),w=it("x",e[0].dataType,n.length),y=w.type.value,u=Pe(h,n.length,t),k=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&k.push({name:"constant_value",type:y}),` + ${c.registerUniforms(k).declareVariables(w,h)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${h.offsetToIndices("global_idx")}; + + var value = ${y}(0); + ${u} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(He.size(r)/64)},programUniforms:a}),getShaderSource:d}},kt=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let c=0;ca[Number(c)]=Number(d));let i=[];return a.forEach(d=>i.push(d)),{mode:t.mode,value:n,pads:i}}else return t},zt=(e,t)=>{m(e.inputs);let r=kt(e.inputs,t);e.compute(pt(e.inputs,r),{inputs:[0]})}}),cr,Er,tr,ir,yr,xr,vr,zr,gn,cn,Rn,nn,Kr,sn,oi,li,$a,Ad,An,Is=B(()=>{C(),Qt(),Yt(),or(),cr=e=>{if(A.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Er=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),d=t.strides.slice(),c=a?t.dilations.slice():[],h=t.pads.slice();yn.adjustPoolAttributes(r,s,i,d,c,h);let w=yn.computePoolOutputShape(r,s,d,c,i,h,t.autoPad),y=Object.assign({},t);a?Object.assign(y,{kernelShape:i,strides:d,pads:h,dilations:c,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:i,strides:d,pads:h,cacheKey:t.cacheKey});let u=w.slice();return u.push(u.splice(1,1)[0]),[y,n?u:w]},tr=(e,t)=>{let r=t.format==="NHWC",n=He.size(e),s=He.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],c=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],w=t.pads[t.pads.length-1],y=!!(h+w);a.push({type:12,data:d},{type:12,data:c},{type:12,data:h},{type:12,data:w}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let k=t.kernelShape[t.kernelShape.length-2],T=t.strides[t.strides.length-2],I=t.pads[t.pads.length/2-2],U=t.pads[t.pads.length-2];u=!!(I+U),a.push({type:12,data:k},{type:12,data:T},{type:12,data:I},{type:12,data:U}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,y,u]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=He.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let c=t.pads.reduce((h,w)=>h+w);return[a,i,!!c,!1,!1]}},ir=(e,t,r,n,s,a,i,d,c,h,w,y)=>{let u=s.format==="NHWC",k=t.type.value,T=Ut("output",t.type.tensor,n);if(s.kernelShape.length<=2){let I="",U="",q="",R=r-(u?2:1);if(w?I=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${R}] = indices[${R}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${R}] < 0 || xIndices[${R}] + >= uniforms.x_shape[${R}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:I=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${R}] = indices[${R}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,s.kernelShape.length===2){let ce=r-(u?3:2);y?U=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ce}] = indices[${ce}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${ce}] < 0 || xIndices[${ce}] >= uniforms.x_shape[${ce}]) { + pad += i32(uniforms.kw); + continue; + } + `:U=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${ce}] = indices[${ce}] * uniforms.sh - uniforms.phStart + j; + `,q=` + } + `}return` + ${e.registerUniforms(c).declareVariables(t,T)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${T.offsetToIndices("global_idx")}; + var xIndices = ${T.offsetToIndices("global_idx")}; + + var value = ${k}(${d}); + var pad = 0; + ${U} + ${I} + ${q} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let I=s.kernelShape.length,U=s.pads.length,q="";return h?q=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:q=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(c).declareVariables(t,T)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${T.offsetToIndices("global_idx")}; + var xIndices = ${T.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${k}(${d}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${I-1}u; j++) { + offsets[j] = offset / ${Ft("uniforms.kernelStrides","j",I)}; + offset -= offsets[j] * ${Ft("uniforms.kernelStrides","j",I)}; + } + offsets[${I-1}] = offset; + + isPad = false; + for (var j = ${r-I}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${Ft("uniforms.strides",`j - ${r-I}u`,I)} + + offsets[j - ${r-I}u] - ${Ft("uniforms.pads","j - 2u",U)}; + ${q} + } + ${i} + + output[global_idx] = value; + }`}},yr=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,xr=e=>`${yr(e)};${e.countIncludePad}`,vr=e=>`${yr(e)};${e.storageOrder};${e.dilations}`,zr=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}),gn=(e,t,r,n)=>{let[s,a]=Er(t,n,r),i=it("x",t.dataType,t.dims.length),d=i.type.value,c="value += x_val;",h="";s.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[w,y,u,k,T]=tr(a,s);w.push(...St(t.dims,a));let I=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${k};${T}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(He.size(a)/64)},programUniforms:w}),getShaderSource:U=>ir(U,i,t.dims.length,a.length,s,c,h,0,y,u,k,T)}},cn=e=>{let t=e.count_include_pad!==0,r=zr(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:xr(n)}},Rn=(e,t)=>{cr(e.inputs),e.compute(gn("AveragePool",e.inputs[0],!1,t))},nn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Kr=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},sn=(e,t)=>{cr(e.inputs),e.compute(gn("GlobalAveragePool",e.inputs[0],!0,t))},oi=(e,t,r,n)=>{let[s,a]=Er(t,n,r),i=` + value = max(x_val, value); + `,d="",c=it("x",t.dataType,t.dims.length),h=["rank"],[w,y,u,k,T]=tr(a,s);return w.push(...St(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${k};${T}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(He.size(a)/64)},programUniforms:w}),getShaderSource:I=>ir(I,c,t.dims.length,a.length,s,i,d,t.dataType===10?-65504:-1e5,y,u,k,T)}},li=(e,t)=>{cr(e.inputs),e.compute(oi("MaxPool",e.inputs[0],!1,t))},$a=e=>{let t=e.storage_order,r=e.dilations,n=zr(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 s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:vr(s)}},Ad=e=>{let t=e.format;return{format:t,...nn,cacheKey:t}},An=(e,t)=>{cr(e.inputs),e.compute(oi("GlobalMaxPool",e.inputs[0],!0,t))}}),id,ad,od,ld=B(()=>{C(),Qt(),or(),id=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},ad=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,d=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...St(a)],c=h=>{let w=Ut("output",n,a.length),y=w.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return` + ${h.registerUniforms(u).declareVariables(w)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${y}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:c,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},od=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),A.webgpu.validateInputContent&&id(t,r,n),e.compute(ad(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),hc,fc,mc,_c,gc,wc,yc,bc,Mc,vc,xc,Id,Tc,Cc,$c,Ec,Sc,kc,Pc,Jh=B(()=>{Qt(),Yt(),hr(),or(),hc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},fc=(e,t,r)=>{t.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((s,a)=>n[s]=e[a]),n},mc=(e,t,r,n,s,a)=>{let[i,d,c]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(w=>a.push(w));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length>0){if(e[d].getFloat32Array().forEach(w=>n.push(w)),n.length!==0&&n.length!==h&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");hc(n,t),t.axes.length>0&&fc(n,t.axes,h).forEach((w,y)=>n[y]=w)}if(c>0&&e.length>c&&(e[c].getBigInt64Array().forEach(w=>s.push(Number(w))),s.length!==h||r>=18&&s.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.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 s<"u"&&n.length>0&&s.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},_c=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",gc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",wc=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=s[i],n[i+r]=s[t.length+i]}),n):s},yc=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>s.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>s[a]=r[i])}else r.forEach(a=>s.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((a,i)=>Math.round(a*t[i]))}return s},bc=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let s=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>s[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),s.forEach((a,i)=>s[i]=Math.round(a*t[i]))),s},Mc=(e,t,r,n,s)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Ft("uniforms.scales","i",n)}; + var roi_low = ${Ft("uniforms.roi","i",s)}; + var roi_hi = ${Ft("uniforms.roi",`i + ${t.length}`,s)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Ft("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Ft("uniforms.output_shape","i",r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,vc=(e,t,r,n,s,a,i)=>` + 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 = ${Ft("uniforms.scales","i",s)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Ft("uniforms.roi","i",a)}; + var roi_hi = ${Ft("uniforms.roi",`i + ${r.length}`,a)}; + var input_shape_i = ${Ft("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${Ft("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (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; + }`,xc=(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 >= ${Ft("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Id=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",Tc=(e,t,r,n,s)=>{let[a,i,d,c]=r.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",i,`max(0, min(row, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; + ${Id(e,c,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${h} = originalIndices[${i}]; + var col:${h} = originalIndices[${d}]; + ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[d]} - 1)) { + return ${s}; + }`:""}; + row = max(0, min(row, ${r[i]} - 1)); + col = max(0, min(col, ${r[d]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length>2?`u32(originalIndices[${c}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"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); + }`},Cc=(e,t,r,n,s,a,i,d,c,h)=>{let w=r.length===2,[y,u]=w?[0,1]:[2,3],k=e.type.value,T=I=>{let U=I===y?"row":"col";return` + fn ${U}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${k} { + var output_index = ${t.indicesGet("output_indices",I)}; + var originalIdx: ${k} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[I]}, + ${n[I]}, ${r[I]}, ${a[I]}, ${a[I]} + ${r.length}); + var fractOriginalIdx: ${k} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${d} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) { + return ${c}; + } + var data: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${U}: ${k} = originalIdx + ${k}(i); + if (${U} < 0 || ${U} >= ${r[I]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:d?`return ${c};`:`${U} = max(0, min(${U}, ${r[I]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",I,`u32(${U})`)}; + data[i + 1] = ${I===y?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${T(y)}; + ${T(u)}; + fn getCubicInterpolationCoefs(s: ${k}) -> array<${k}, 4> { + var absS = abs(s); + var coeffs: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${k} = 1.0 - absS; + var twoMinusAbsS: ${k} = 2.0 - absS; + var onePlusAbsS: ${k} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${k}, 4>, coefs: array<${k}, 4>) -> ${k} { + var coefsSum: ${k} = 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}) -> ${k} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},$c=(e,t,r,n,s)=>{let[a,i,d,c,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],w=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${w} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; + ${e.indicesSet("input_indices",c,`max(0, min(width, ${r[c]} - 1))`)}; + ${Id(e,h,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${w} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${w} = originalIndices[${i}]; + var height:${w} = originalIndices[${d}]; + var width:${w} = originalIndices[${c}]; + ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) { + return ${s}; + }`:""}; + + depth = max(0, min(depth, ${r[i]} - 1)); + height = max(0, min(height, ${r[d]} - 1)); + width = max(0, min(width, ${r[c]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${w} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${w} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${w} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${w} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${w} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${w} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${w} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${w} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${w} = abs(depth - ${w}(depth1)); + var dx2: ${w} = abs(${w}(depth2) - depth); + var dy1: ${w} = abs(height - ${w}(height1)); + var dy2: ${w} = abs(${w}(height2) - height); + var dz1: ${w} = abs(width - ${w}(width1)); + var dz2: ${w} = abs(${w}(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); + }`},Ec=(e,t,r,n,s,a)=>{let i=e.dims,d=wc(a,t.axes,i.length),c=yc(i,n,s,t.axes),h=n.slice();n.length===0&&(h=i.map((R,ce)=>R===0?1:c[ce]/R),t.keepAspectRatioPolicy!=="stretch"&&(c=bc(i,h,t)));let w=Ut("output",e.dataType,c.length),y=it("input",e.dataType,i.length),u=He.size(c),k=i.length===c.length&&i.every((R,ce)=>R===c[ce]),T=t.coordinateTransformMode==="tf_crop_and_resize",I=t.extrapolationValue,U=y.type.value,q=R=>` + ${k?"":` + ${_c(t.coordinateTransformMode,U)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${xc(y,i)}; + ${gc(t.nearestMode,r,U)}; + ${vc(y,w,i,c,h.length,d.length,T)}; + `;case"linear":return` + ${Mc(w,i,c,h.length,d.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${Tc(y,w,i,T,I)}`;if(i.length===3||i.length===5)return`${$c(y,w,i,T,I)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${Cc(y,w,i,c,h,d,t.cubicCoeffA,T,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")}})()}; + `} + ${R.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(y,w)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${k?"output[global_idx] = input[global_idx];":` + let output_indices = ${w.offsetToIndices("global_idx")}; + var input_indices: ${y.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${y.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${s.length>0?s:""}|${d.length>0?d:""}|${k}|${i}`,inputDependencies:["rank"]},getShaderSource:q,getRunData:()=>({outputs:[{dims:c,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:h},{type:1,data:d},...St(i,c)]})}},Sc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},kc=(e,t)=>{let r=[],n=[],s=[],a=Sc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");mc(e.inputs,t,a,r,n,s),e.compute(Ec(e.inputs[0],t,a,r,n,s),{inputs:[0]})},Pc=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,d=e.keepAspectRatioPolicy,c=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return Gt({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:d,mode:c,nearestMode:h})}}),Ac,Ic,Fc,ef=B(()=>{Qt(),Yt(),hr(),or(),Ac=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,rotaryEmbeddingDim:d}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!He.areEqual(n.dims,[])&&!He.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(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!He.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let c=r.dims[0],h=r.dims[r.dims.length-2],w=s.dims[0],y=He.sizeFromDimension(r.dims,1)/h,u=d===0?s.dims[1]*2:y/i;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(c!==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(u/2!==s.dims[1]&&d/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(h>w)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Ic=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],d=He.sizeFromDimension(e[0].dims,1),c=e[0].dims[e[0].dims.length-2],h=d/c,w=e[2].dims[1],y=s===0?w*2:h/n,u=new Array(i,c,h/y,y-w),k=He.computeStrides(u),T=[{type:1,data:a},{type:12,data:u},{type:12,data:k},...e[0].dims.length===3?new Array({type:12,data:[d,h,y,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,y,c*y,1]}):[],...St(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],I=U=>{let q=it("input",e[0].dataType,e[0].dims.length),R=it("position_ids",e[1].dataType,e[1].dims.length),ce=it("cos_cache",e[2].dataType,e[2].dims.length),Z=it("sin_cache",e[3].dataType,e[3].dims.length),oe=Ut("output",e[0].dataType,e[0].dims.length);return U.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:k.length},{name:"input_output_strides",type:"u32",length:k.length}]),` + ${U.declareVariables(q,R,ce,Z,oe)} + + ${U.mainStart(mn)} + let half_rotary_emb_dim = uniforms.${ce.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${U.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${R.broadcastedIndicesToOffset("bsnh.xy",Ut("",R.type.tensor,2))}; + let position_id = + u32(${R.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${q.getByOffset("i")} * ${ce.get("position_id","bsnh[3]")} - + ${q.getByOffset("j")} * ${Z.get("position_id","bsnh[3]")}; + ${oe.setByOffset("i","re")} + let im = ${q.getByOffset("i")} * ${Z.get("position_id","bsnh[3]")} + + ${q.getByOffset("j")} * ${ce.get("position_id","bsnh[3]")}; + ${oe.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${oe.setByOffset("k",q.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Gt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(He.size(u)/mn)},programUniforms:T})}},Fc=(e,t)=>{Ac(e.inputs,t),e.compute(Ic(e.inputs,t))}}),Oc,zc,Dc,tf=B(()=>{Qt(),Yt(),or(),Oc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)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]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},zc=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=He.size(a),d=a,c=i,h=a.slice(-1)[0],w=n?a.slice(0,-1).concat(1):[],y=!s&&e.length>3,u=e.length>4,k=n&&r>1,T=n&&r>2,I=r>3,U=64,q=mr(h),R=[{type:12,data:c},{type:12,data:q},{type:12,data:h},{type:1,data:t.epsilon}],ce=oe=>{let tt=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ge=[it("x",e[0].dataType,e[0].dims,q),it("skip",e[1].dataType,e[1].dims,q),it("gamma",e[2].dataType,e[2].dims,q)];y&&Ge.push(it("beta",e[3].dataType,e[3].dims,q)),u&&Ge.push(it("bias",e[4].dataType,e[4].dims,q)),Ge.push(Ut("output",e[0].dataType,d,q)),k&&Ge.push(Ut("mean_output",1,w)),T&&Ge.push(Ut("inv_std_output",1,w)),I&&Ge.push(Ut("input_skip_bias_sum",e[0].dataType,d,q));let dt=br(e[0].dataType),Ot=br(1,q);return` + + ${oe.registerUniforms(tt).declareVariables(...Ge)} + var sum_shared : array<${Ot}, ${U}>; + var sum_squared_shared : array<${Ot}, ${U}>; + + ${oe.mainStart([U,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${U}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${U}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${U-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[offset1d + i]":dt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${I?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${jr(dt,q,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${U}; + 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 = ${_n("sum",q)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${_n("square_sum",q)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); + ${k?"mean_output[global_idx] = mean;":""} + ${T?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${s?"":`- ${dt}(mean)`}) * + ${dt}(inv_std_dev) * gamma[offset1d + i] + ${y?"+ beta[offset1d + i]":""}; + } + }`},Z=[{dims:d,dataType:e[0].dataType}];return r>1&&Z.push({dims:w,dataType:1}),r>2&&Z.push({dims:w,dataType:1}),r>3&&Z.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${q};${k};${T};${I}`,inputDependencies:e.map((oe,tt)=>"type")},getShaderSource:ce,getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(c/h)},programUniforms:R})}},Dc=(e,t)=>{Oc(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(zc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Bc,Su,Lc,Fd,Rc,Nc,jc,Vc,rf=B(()=>{Qt(),Yt(),hr(),or(),Bc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Su=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Lc=(e,t)=>{if(e.length>1){let r=Su(e,1),n=Su(e,2),s=Su(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),Gt({starts:r,ends:n,axes:s})}else return t},Fd=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},Rc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${Ft("uniforms.input_shape","i",r.length)}; + let steps_i = ${Ft("uniforms.steps","i",r.length)}; + let signs_i = ${Ft("uniforms.signs","i",r.length)}; + let starts_i = ${Ft("uniforms.starts","i",r.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Nc=(e,t)=>{let r=e[0].dims,n=He.size(r),s=t.axes.length>0?He.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=Su(e,4);a.forEach(q=>q!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((q,R)=>Fd(q,R,r,s,a)),d=t.ends.map((q,R)=>Fd(q,R,r,s,a));if(s.length!==i.length||s.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let q=0;qMath.sign(q));a.forEach((q,R,ce)=>{if(q<0){let Z=(d[R]-i[R])/q,oe=i[R],tt=oe+Z*a[R];i[R]=tt,d[R]=oe,ce[R]=-q}});let h=r.slice(0);s.forEach((q,R)=>{h[q]=Math.ceil((d[q]-i[q])/a[q])});let w={dims:h,dataType:e[0].dataType},y=Ut("output",e[0].dataType,h.length),u=it("input",e[0].dataType,e[0].dims.length),k=He.size(h),T=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:c.length},{name:"steps",type:"u32",length:a.length}],I=[{type:12,data:k},{type:12,data:i},{type:6,data:c},{type:12,data:a},...St(e[0].dims,h)],U=q=>` + ${q.registerUniforms(T).declareVariables(u,y)} + ${Rc(u,y,r)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${y.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${y.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${c.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:U,getRunData:()=>({outputs:[w],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:I})}},jc=(e,t)=>{Bc(e.inputs,t);let r=Lc(e.inputs,t);e.compute(Nc(e.inputs,r),{inputs:[0]})},Vc=e=>{let t=e.starts,r=e.ends,n=e.axes;return Gt({starts:t,ends:r,axes:n})}}),Uc,Wc,Gc,qc,nf=B(()=>{Qt(),Yt(),hr(),or(),Uc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Wc=(e,t)=>{let r=e.dims,n=He.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aq===4?`max(max(${U}.x, ${U}.y), max(${U}.z, ${U}.w))`:q===2?`max(${U}.x, ${U}.y)`:q===3?`max(max(${U}.x, ${U}.y), ${U}.z)`:U,y=it("x",e.dataType,e.dims,c),u=Ut("result",e.dataType,e.dims,c),k=y.type.value,T=br(e.dataType)==="f32"?`var threadMax = ${k}(-3.402823e+38f);`:`var threadMax = ${k}(-65504.0h);`,I=U=>` + var rowMaxShared : ${k}; + var rowSumShared : ${k}; + var threadShared : array<${k}, ${s}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${k} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${k}) { + let index = row * row_stride + col; + result[index] = value; + } + ${U.registerUniform("packedCols","i32").declareVariables(y,u)} + ${U.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${s}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${T} + 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 = ${k}(${w("threadShared[0]",c)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${k}(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 = ${k}(${_n("threadShared[0]",c)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`;return{name:"Softmax",shaderCache:{hint:`${c}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:h}]}),getShaderSource:I}},Gc=(e,t)=>{Uc(e.inputs),e.compute(Wc(e.inputs[0],t))},qc=e=>Gt({axis:e.axis})}),Hc,Kc,Xc,Qc,Yc,Zc,Jc,sf=B(()=>{Qt(),Yt(),hr(),or(),Hc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Kc=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),Gt({numOutputs:n,axis:t.axis,splitSizes:r})},Xc=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Ft("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Qc=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=He.size(r),s=e[0].dataType,a=He.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),d=it("input",s,r.length),c=new Array(t.numOutputs),h=[],w=[],y=0,u=[{type:12,data:n}];for(let T=0;T` + ${T.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",c.length).declareVariables(d,...i)} + ${Xc(c.length)} + ${Qc(i)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${d.offsetToIndices("global_idx")}; + var index = ${d.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Ft("uniforms.size_in_split_axis","output_number - 1u",c.length)}; + ${d.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},Zc=(e,t)=>{Hc(e.inputs);let r=e.inputs.length===1?t:Kc(e.inputs,t);e.compute(Yc(e.inputs,r),{inputs:[0]})},Jc=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Gt({axis:t,numOutputs:n,splitSizes:r})}}),ep,tp,rp,af=B(()=>{Qt(),Yt(),or(),ep=(e,t,r,n,s)=>{let a=Ut("output_data",s,r.length,4),i=it("a_data",t[1].dataType,t[1].dims.length,4),d=it("b_data",t[2].dataType,t[2].dims.length,4),c=it("c_data",t[0].dataType,t[0].dims.length,4),h,w=(y,u,k)=>`select(${u}, ${y}, ${k})`;if(!n)h=a.setByOffset("global_idx",w(i.getByOffset("global_idx"),d.getByOffset("global_idx"),c.getByOffset("global_idx")));else{let y=(u,k,T="")=>{let I=`a_data[index_a${k}][component_a${k}]`,U=`b_data[index_b${k}][component_b${k}]`,q=`bool(c_data[index_c${k}] & (0xffu << (component_c${k} * 8)))`;return` + let output_indices${k} = ${a.offsetToIndices(`global_idx * 4u + ${k}u`)}; + let offset_a${k} = ${i.broadcastedIndicesToOffset(`output_indices${k}`,a)}; + let offset_b${k} = ${d.broadcastedIndicesToOffset(`output_indices${k}`,a)}; + let offset_c${k} = ${c.broadcastedIndicesToOffset(`output_indices${k}`,a)}; + let index_a${k} = offset_a${k} / 4u; + let index_b${k} = offset_b${k} / 4u; + let index_c${k} = offset_c${k} / 4u; + let component_a${k} = offset_a${k} % 4u; + let component_b${k} = offset_b${k} % 4u; + let component_c${k} = offset_c${k} % 4u; + ${u}[${k}] = ${T}(${w(I,U,q)}); + `};s===9?h=` + var data = vec4(0); + ${y("data",0,"u32")} + ${y("data",1,"u32")} + ${y("data",2,"u32")} + ${y("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${y("output_data[global_idx]",0)} + ${y("output_data[global_idx]",1)} + ${y("output_data[global_idx]",2)} + ${y("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(c,i,d,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},tp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(He.areEqual(t,r)&&He.areEqual(r,n)),i=t,d=He.size(t);if(a){let h=Yr.calcShape(Yr.calcShape(t,r,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,d=He.size(i)}let c=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>ep(h,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:c},...St(n,t,r,i)]})}},rp=e=>{e.compute(tp(e.inputs))}}),np,of=B(()=>{Du(),Xs(),To(),Bu(),nl(),Lu(),Ru(),Fl(),Sd(),Gu(),qu(),Qu(),kd(),Zu(),Ju(),ed(),lu(),rd(),Pd(),tn(),ia(),sd(),hu(),ur(),Is(),ld(),ki(),Jh(),ef(),tf(),rf(),nf(),sf(),gu(),ds(),Gi(),af(),np=new Map([["Abs",[So]],["Acos",[ko]],["Acosh",[Ii]],["Add",[al]],["ArgMax",[fo,Ks]],["ArgMin",[ho,Ks]],["Asin",[Po]],["Asinh",[Ao]],["Atan",[Fi]],["Atanh",[Io]],["Attention",[yo]],["AveragePool",[Rn,cn]],["BatchNormalization",[xo]],["BiasAdd",[Ai]],["BiasSplitGelu",[rl]],["Cast",[Qs,Fo]],["Ceil",[Do]],["Clip",[zo]],["Concat",[qn,gl]],["Conv",[Es,oa]],["ConvTranspose",[Wu,Ll]],["Cos",[Oi]],["Cosh",[Bo]],["CumSum",[ma,jl]],["DepthToSpace",[ga,Wl]],["Div",[ol]],["Einsum",[ql,Hl]],["Elu",[Lo,ps]],["Equal",[Hi]],["Erf",[Ro]],["Exp",[zi]],["Expand",[ba]],["FastGelu",[Ql]],["Floor",[No]],["FusedConv",[Es,oa]],["Gather",[eu,Jl]],["GatherElements",[su,nu]],["Gelu",[jo]],["Gemm",[td,ou]],["GlobalAveragePool",[sn,Kr]],["GlobalMaxPool",[An,Ad]],["Greater",[cl]],["GreaterOrEqual",[hl]],["GroupQueryAttention",[Mu,yu]],["HardSigmoid",[Li,qo]],["InstanceNormalization",[Cu]],["LayerNormalization",[Qr]],["LeakyRelu",[Vo,ps]],["Less",[pl]],["LessOrEqual",[Ki]],["Log",[Wi]],["MatMul",[Pl]],["MatMulNBits",[nd,Eu]],["MaxPool",[li,$a]],["Mul",[ll]],["MultiHeadAttention",[pu,du]],["Neg",[Uo]],["Not",[Di]],["Pad",[zt]],["Pow",[ul]],["QuickGelu",[el,ps]],["Range",[od]],["Reciprocal",[Wo]],["ReduceMin",[Ei]],["ReduceMean",[io]],["ReduceMax",[lo]],["ReduceSum",[co]],["ReduceProd",[uo]],["ReduceL1",[ao]],["ReduceL2",[$i]],["ReduceLogSum",[po]],["ReduceLogSumExp",[oo]],["ReduceSumSquare",[Si]],["Relu",[Bi]],["Resize",[kc,Pc]],["RotaryEmbedding",[Fc]],["Sigmoid",[Go]],["Sin",[Ho]],["Sinh",[Ko]],["Slice",[jc,Vc]],["SkipLayerNormalization",[Dc]],["Split",[Zc,Jc]],["Sqrt",[Ri]],["Softmax",[Gc,qc]],["Sub",[dl]],["Tan",[Xo]],["Tanh",[ji]],["ThresholdedRelu",[Yo,ps]],["Tile",[_u]],["Transpose",[za,gi]],["Where",[rp]]])}),sp,lf=B(()=>{C(),fn(),or(),sp=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,s){qe(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of r)d.push({binding:d.length,resource:{buffer:h.buffer}});s&&d.push({binding:d.length,resource:s});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}i.setPipeline(e.computePipeline),i.setBindGroup(0,c),i.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(),Ve(e.programInfo.name)}dispose(){}build(e,t){qe(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=Ia(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` +`)} +${s.additionalImplementations} +${a}`,d=r.createShaderModule({code:i,label:e.name});Dr("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let c=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ve(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),ip,ap,op,lp,uf=B(()=>{C(),Qt(),fn(),_(),$r(),of(),lf(),ip=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var s,a;let n=e.name;return(s=e.shaderCache)!=null&&s.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${ip(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},op=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},lp=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=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 r=[],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:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(n),this.adapterInfo=new op(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Jt(this),this.programManager=new sp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ls(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.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;qe(),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(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=k);let I=Number(k-this.queryTimeBase),U=Number(T-this.queryTimeBase);if(!Number.isSafeInteger(I)||!Number.isSafeInteger(U))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:y.map(q=>({dims:q.dims,dataType:kn(q.dataType)})),outputsMetadata:u.map(q=>({dims:q.dims,dataType:kn(q.dataType)})),kernelId:i,kernelType:c,kernelName:h,programName:w,startTime:I,endTime:U});else{let q="";y.forEach((ce,Z)=>{q+=`input[${Z}]: [${ce.dims}] | ${kn(ce.dataType)}, `});let R="";u.forEach((ce,Z)=>{R+=`output[${Z}]: [${ce.dims}] | ${kn(ce.dataType)}, `}),console.log(`[profiling] kernel "${i}|${c}|${h}|${w}" ${q}${R}execution time: ${U-I} ns`)}$e("GPU",`${w}::${k}::${T}`)}e.unmap(),this.pendingQueries.delete(e)}),Ve()}run(e,t,r,n,s,a){qe(e.name);let i=[];for(let R=0;Rce):r;if(w.length!==d.length)throw new Error(`Output size ${w.length} must be equal to ${d.length}.`);let y=[],u=[];for(let R=0;R=a)throw new Error(`Invalid output index: ${w[R]}`);if(w[R]===-3)continue;let ce=w[R]===-1,Z=w[R]===-2,oe=ce||Z?s(d[R].dataType,d[R].dims):n(w[R],d[R].dataType,d[R].dims);if(y.push(oe),oe.data===0)continue;let tt=this.gpuDataManager.get(oe.data);if(!tt)throw new Error(`no GPU data for output: ${oe.data}`);if(ce&&this.temporaryData.push(tt),Z){let Ge=this.kernelPersistentData.get(this.currentKernelId);Ge||(Ge=[],this.kernelPersistentData.set(this.currentKernelId,Ge)),Ge.push(tt)}u.push(tt)}if(i.length!==t.length||u.length!==y.length){if(u.length===0)return Ve(e.name),y;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let k;if(h){let R=0,ce=[];h.forEach(Ge=>{let dt=typeof Ge.data=="number"?[Ge.data]:Ge.data;if(dt.length===0)return;let Ot=Ge.type===10?2:4,Dt,pr;Ge.type===10?(pr=dt.length>4?16:dt.length>2?8:dt.length*Ot,Dt=dt.length>4?16:Ot*dt.length):(pr=dt.length<=2?dt.length*Ot:16,Dt=16),R=Math.ceil(R/pr)*pr,ce.push(R);let gr=Ge.type===10?8:4;R+=dt.length>4?Math.ceil(dt.length/gr)*Dt:dt.length*Ot});let Z=16;R=Math.ceil(R/Z)*Z;let oe=new ArrayBuffer(R);h.forEach((Ge,dt)=>{let Ot=ce[dt],Dt=typeof Ge.data=="number"?[Ge.data]:Ge.data;if(Ge.type===6)new Int32Array(oe,Ot,Dt.length).set(Dt);else if(Ge.type===12)new Uint32Array(oe,Ot,Dt.length).set(Dt);else if(Ge.type===10)new Uint16Array(oe,Ot,Dt.length).set(Dt);else if(Ge.type===1)new Float32Array(oe,Ot,Dt.length).set(Dt);else throw new Error(`Unsupported uniform type: ${kn(Ge.type)}`)});let tt=this.gpuDataManager.create(R,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(tt.buffer,0,oe,0,R),this.gpuDataManager.release(tt.id),k={offset:0,size:R,buffer:tt.buffer}}let T=this.programManager.normalizeDispatchGroupSize(c),I=T[1]===1&&T[2]===1,U=ap(e,t,I),q=this.programManager.getArtifact(U);if(q||(q=this.programManager.build(e,T),this.programManager.setArtifact(U,q),Dr("info",()=>`[artifact] key: ${U}, programName: ${e.name}`)),h&&q.uniformVariablesInfo){if(h.length!==q.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${q.uniformVariablesInfo.length}, got ${h.length} in program "${q.programInfo.name}".`);for(let R=0;R`[ProgramManager] run "${e.name}" (key=${U}) with ${T[0]}x${T[1]}x${T[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let R={kernelId:this.currentKernelId,programName:q.programInfo.name,inputTensorViews:t,outputTensorViews:y};this.pendingKernels.push(R),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(R)}return this.programManager.run(q,i,u,T,k),Ve(e.name),y}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,r,n){let s=np.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let s=n.kernelType,a=n.kernelName,i=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),Dr("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope("validation"),i(t,d[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${h}`)),1}finally{c&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${s}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a==null?void 0:a[1]);return s.set(t,[i,r]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[1])),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,r){return async()=>{let n=await wt(this,e,t);return Me(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.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(){Dr("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(){Dr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}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()}}}),up={};E(up,{init:()=>cp});var ud,dp,cp,df=B(()=>{Qt(),uf(),fn(),Yt(),ud=class Qh{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=He.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=He.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=He.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(He.size(t)!==He.size(this.dims))throw new Error("Invalid new shape");return new Qh(this.module,this.dataType,this.data,t)}},dp=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let d=0;dtypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(d,c,h)=>new ud(this.module,c,this.output(d,h),h),a=(d,c)=>{let h=zn(d);if(!h)throw new Error(`Unsupported data type: ${d}`);let w=h*He.size(c),y=w>0?this.backend.gpuDataManager.create(w).id:0;return new ud(this.module,d,y,c)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new lp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,d,c,h=!1)=>{if(h)Dr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${d}, size=${c}`),a.memcpy(i,d);else{Dr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${d}, size=${c}`);let w=t.HEAPU8.subarray(i>>>0,(i>>>0)+c);a.upload(d,w)}},async(i,d,c)=>{Dr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${d}, size=${c}`),await a.download(i,()=>t.HEAPU8.subarray(d>>>0,(d>>>0)+c))},(i,d,c)=>a.createKernel(i,d,c,t.UTF8ToString(t._JsepGetNodeName(d))),i=>a.releaseKernel(i),(i,d,c,h)=>{Dr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${i}, contextDataOffset=${d}`);let w=new dp(t,a,d);return a.computeKernel(i,w,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else s("webnn")}}),pp,Od,zd,Fs,hp,dd,Dd,Bd,Ld,Rd,Nd,jd,fp=B(()=>{Vs(),Us(),Qt(),Zr(),Wn(),bs(),pp=(e,t)=>{Lr()._OrtInit(e,t)!==0&&Pr("Can't initialize onnxruntime.")},Od=async e=>{pp(e.wasm.numThreads,Qn(e.logLevel))},zd=async(e,t)=>{{let r=(df(),P(up)).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 s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",Lr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Lr(),e)}}},Fs=new Map,hp=e=>{let t=Lr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Pr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},dd=e=>{let t=Lr(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Dd=async(e,t)=>{var y,u;let r,n,s=Lr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=dd(e);let a=0,i=0,d=0,c=[],h=[],w=[];try{if([i,c]=Gn(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let Z=[];for(let oe of t.externalData){let tt=typeof oe=="string"?oe:oe.path;Z.push(Yn(typeof oe=="string"?oe:oe.data).then(Ge=>{s.mountExternalData(tt,Ge)}))}await Promise.all(Z)}for(let Z of(t==null?void 0:t.executionProviders)??[])if((typeof Z=="string"?Z:Z.name)==="webnn"){if(s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Z!="string"){let oe=Z,tt=oe==null?void 0:oe.context,Ge=oe==null?void 0:oe.gpuDevice,dt=oe==null?void 0:oe.deviceType,Ot=oe==null?void 0:oe.numThreads,Dt=oe==null?void 0:oe.powerPreference;tt?s.currentContext=tt:Ge?s.currentContext=await navigator.ml.createContext(Ge):s.currentContext=await navigator.ml.createContext({deviceType:dt,numThreads:Ot,powerPreference:Dt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Pr("Can't create a session."),s.currentContext&&(s.currentContext=void 0);let[k,T]=hp(a),I=!!(t!=null&&t.enableGraphCapture),U=[],q=[],R=[];for(let Z=0;ZZ==="gpu-buffer")&&(d=s._OrtCreateBinding(a),d===0&&Pr("Can't create IO binding."),ce={handle:d,outputPreferredLocations:R,outputPreferredLocationsEncoded:R.map(Z=>as(Z))}),Fs.set(a,[a,h,w,ce,I,!1]),[a,U,q]}catch(k){throw h.forEach(T=>s._OrtFree(T)),w.forEach(T=>s._OrtFree(T)),d!==0&&s._OrtReleaseBinding(d),a!==0&&s._OrtReleaseSession(a),k}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),c.forEach(k=>s._free(k)),(u=s.unmountExternalData)==null||u.call(s)}},Bd=e=>{var c;let t=Lr(),r=Fs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,d]=r;i&&(d&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(c=t.jsepOnReleaseSession)==null||c.call(t,e),s.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n),Fs.delete(e)},Ld=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=Lr(),d=e[0],c=e[1],h=e[3],w,y;if(d==="string"&&h==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let T=e[2].gpuBuffer,I=zn(ss(d));y=c.reduce((q,R)=>q*R,1)*I;let U=i.jsepRegisterBuffer;if(!U)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=U(n,s,T,y)}else{let T=e[2];if(Array.isArray(T)){y=4*T.length,w=i._malloc(y),r.push(w);let I=w/4;for(let U=0;Ui.HEAP32[T++]=U);let I=i._OrtCreateTensor(ss(d),w,y,k,c.length,as(h));I===0&&Pr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(I)}finally{i.stackRestore(u)}},Rd=async(e,t,r,n,s,a)=>{var Dt,pr;let i=Lr(),d=Fs.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],h=d[1],w=d[2],y=d[3],u=d[4],k=d[5],T=t.length,I=n.length,U=0,q=[],R=[],ce=[],Z=[],oe=i.stackSave(),tt=i.stackAlloc(T*4),Ge=i.stackAlloc(T*4),dt=i.stackAlloc(I*4),Ot=i.stackAlloc(I*4);try{[U,q]=On(a);for(let Lt=0;Lthn*Tn,1);rr=kn(an);let Au=y==null?void 0:y.outputPreferredLocations[n[Lt]];if(rr==="string"){if(Au==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let hn=[],Tn=Br/4;for(let Nn=0;Nn0){let hn=i.jsepGetBuffer;if(!hn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Tn=hn(Br),Nn=zn(an);if(Nn===void 0||!is(rr))throw new Error(`Unsupported data type: ${rr}`);jt=!0,Rr.push([rr,In,{gpuBuffer:Tn,download:i.jsepCreateDownloader(Tn,pn*Nn,rr),dispose:()=>{i._OrtReleaseTensor(Zt)}},"gpu-buffer"])}else{let hn=Dn(rr),Tn=new hn(pn);new Uint8Array(Tn.buffer,Tn.byteOffset,Tn.byteLength).set(i.HEAPU8.subarray(Br,Br+Tn.byteLength)),Rr.push([rr,In,Tn,"cpu"])}}finally{i.stackRestore(fr),rr==="string"&&Br&&i._free(Br),jt||i._OrtReleaseTensor(Zt)}}return y&&!u&&(i._OrtClearBoundOutputs(y.handle),Fs.set(e,[c,h,w,y,u,!1])),Rr}finally{i.stackRestore(oe),R.forEach(gr=>i._OrtReleaseTensor(gr)),ce.forEach(gr=>i._OrtReleaseTensor(gr)),Z.forEach(gr=>i._free(gr)),U!==0&&i._OrtReleaseRunOptions(U),q.forEach(gr=>i._free(gr))}},Nd=e=>{let t=Lr(),r=Fs.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Pr("Can't get an profile file name."),t._OrtFree(s)},jd=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Os,$n,Ea,ku,Pu,cd,Vd,pd,ui,di,mp,_p,gp,wp,yp,bp,Mp,vp,xp=B(()=>{C(),fp(),Zr(),Ur(),Os=()=>!!A.wasm.proxy&&typeof document<"u",Ea=!1,ku=!1,Pu=!1,pd=new Map,ui=(e,t)=>{let r=pd.get(e);r?r.push(t):pd.set(e,[t])},di=()=>{if(Ea||!ku||Pu||!$n)throw new Error("worker not ready")},mp=e=>{switch(e.data.type){case"init-wasm":Ea=!1,e.data.err?(Pu=!0,Vd[1](e.data.err)):(ku=!0,Vd[0]()),cd&&(URL.revokeObjectURL(cd),cd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=pd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},_p=async()=>{if(!ku){if(Ea)throw new Error("multiple calls to 'initWasm()' detected.");if(Pu)throw new Error("previous call to 'initWasm()' failed.");if(Ea=!0,Os())return new Promise((e,t)=>{$n==null||$n.terminate(),er().then(([r,n])=>{try{$n=n,$n.onerror=a=>t(a),$n.onmessage=mp,Vd=[e,t];let s={type:"init-wasm",in:A};$n.postMessage(s),cd=r}catch(s){t(s)}},t)});try{await Fn(A.wasm),await Od(A),ku=!0}catch(e){throw Pu=!0,e}finally{Ea=!1}}},gp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:A}};$n.postMessage(n)});await zd(A,e)},wp=async e=>Os()?(di(),new Promise((t,r)=>{ui("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};$n.postMessage(n,[e.buffer])})):dd(e),yp=async(e,t)=>{if(Os()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return di(),new Promise((r,n)=>{ui("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),$n.postMessage(s,a)})}else return Dd(e,t)},bp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("release",[t,r]);let n={type:"release",in:e};$n.postMessage(n)});Bd(e)},Mp=async(e,t,r,n,s,a)=>{if(Os()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return di(),new Promise((i,d)=>{ui("run",[i,d]);let c=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:c,outputIndices:n,options:a}};$n.postMessage(h,jd(c))})}else return Rd(e,t,r,n,s,a)},vp=async e=>{if(Os())return di(),new Promise((t,r)=>{ui("end-profiling",[t,r]);let n={type:"end-profiling",in:e};$n.postMessage(n)});Nd(e)}}),Ud,Tp,Cp,cf=B(()=>{C(),xp(),Qt(),K(),bs(),Ud=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Tp=e=>{switch(e[3]){case"cpu":return new ze(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!is(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return ze.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},Cp=class{async fetchModelAndCopyToWasmMemory(e){return wp(await Yn(e))}async loadModel(e,t){qe();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await yp(r,t),Ve()}async dispose(){return bp(this.sessionId)}async run(e,t,r){qe();let n=[],s=[];Object.entries(e).forEach(y=>{let u=y[0],k=y[1],T=this.inputNames.indexOf(u);if(T===-1)throw new Error(`invalid input '${u}'`);n.push(k),s.push(T)});let a=[],i=[];Object.entries(t).forEach(y=>{let u=y[0],k=y[1],T=this.outputNames.indexOf(u);if(T===-1)throw new Error(`invalid output '${u}'`);a.push(k),i.push(T)});let d=n.map((y,u)=>Ud(y,()=>`input "${this.inputNames[s[u]]}"`)),c=a.map((y,u)=>y?Ud(y,()=>`output "${this.outputNames[i[u]]}"`):null),h=await Mp(this.sessionId,s,d,i,c,r),w={};for(let y=0;y{C(),xp(),cf(),Ur(),$p=()=>{if((typeof A.wasm.initTimeout!="number"||A.wasm.initTimeout<0)&&(A.wasm.initTimeout=0),A.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 A.wasm.proxy!="boolean"&&(A.wasm.proxy=!1),typeof A.wasm.trace!="boolean"&&(A.wasm.trace=!1),typeof A.wasm.numThreads!="number"||!Number.isInteger(A.wasm.numThreads)||A.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)A.wasm.numThreads=1;else{let e=typeof navigator>"u"?Te("node:os").cpus().length:navigator.hardwareConcurrency;A.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Ep=class{async init(e){$p(),await _p(),await gp(e)}async createInferenceSessionHandler(e,t){let r=new Cp;return await r.loadModel(e,t),Promise.resolve(r)}}}),Sp={};E(Sp,{wasmBackend:()=>kp});var kp,hf=B(()=>{pf(),kp=new Ep});C(),C(),C();var ff="1.19.0-dev.20240804-ee2fe87e2d",mf=Se;{let e=(hf(),P(Sp)).wasmBackend;se("webgpu",e,5),se("webnn",e,5),se("cpu",e,10),se("wasm",e,10)}Object.defineProperty(A.versions,"web",{value:ff,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":($t,me,l)=>{var x;l.r(me),l.d(me,{Tensor:()=>Te.Tensor,createInferenceSession:()=>se,deviceToExecutionProviders:()=>te,isONNXProxy:()=>ee,isONNXTensor:()=>ae});var X=l("./src/env.js"),ye=l("?2ce3"),ve=l("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Te=l("./node_modules/onnxruntime-common/dist/esm/index.js");const B=[];let E,N;X.apis.IS_NODE_ENV?(N=ye??(x||(x=l.t(ye,2))),B.push("cpu"),E=["cpu"]):(N=ve,X.apis.IS_WEBGPU_AVAILABLE&&B.push("webgpu"),B.push("wasm"),E=["wasm"]);const P=N.InferenceSession;function te(G){let ie=E;if(G){if(!B.includes(G))throw new Error(`Unsupported device: "${G}". Should be one of: ${B.join(", ")}.`);ie=[G]}return ie}let J=null;async function se(G,ie){J&&await J;const fe=P.create(G,ie);return J??(J=fe),await fe}function ae(G){return G instanceof N.Tensor}const D=N==null?void 0:N.env;D!=null&&D.wasm&&(D.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${X.env.version}/dist/`,D.wasm.proxy=!X.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(D.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(D.wasm.simd=!1)),D!=null&&D.webgpu&&(D.webgpu.powerPreference="high-performance");function ee(){var G;return(G=D==null?void 0:D.wasm)==null?void 0:G.proxy}X.env.backends.onnx=D},"./src/configs.js":($t,me,l)=>{l.r(me),l.d(me,{AutoConfig:()=>E,PretrainedConfig:()=>B,getKeyValueShapes:()=>Te});var x=l("./src/utils/core.js"),X=l("./src/utils/hub.js");async function ye(N,P){return await(0,X.getModelJSON)(N,"config.json",!0,P)}function ve(N){const P={};let te={};switch(N.model_type){case"llava":case"paligemma":case"florence2":te=ve(N.text_config);break;case"moondream1":te=ve(N.phi_config);break;case"musicgen":te=ve(N.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":P.num_heads="num_attention_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size",P.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.dim_kv="head_dim";break;case"openelm":P.num_heads="num_kv_heads",P.num_layers="num_transformer_layers",P.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":P.num_heads="num_heads",P.num_layers="num_layers",P.hidden_size="hidden_size";break;case"bloom":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="hidden_size";break;case"mpt":P.num_heads="n_heads",P.num_layers="n_layers",P.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":P.num_decoder_layers="num_decoder_layers",P.num_decoder_heads="num_heads",P.decoder_dim_kv="d_kv",P.num_encoder_layers="num_layers",P.num_encoder_heads="num_heads",P.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":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="d_model",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="d_model";break;case"speecht5":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="hidden_size",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="hidden_size";break;case"trocr":P.num_encoder_layers=P.num_decoder_layers="decoder_layers",P.num_encoder_heads=P.num_decoder_heads="decoder_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="d_model";break;case"musicgen_decoder":P.num_encoder_layers=P.num_decoder_layers="num_hidden_layers",P.num_encoder_heads=P.num_decoder_heads="num_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const se=ve(N.decoder),ae="num_decoder_layers"in se,D=(0,x.pick)(N,["model_type","is_encoder_decoder"]);return ae?(D.num_decoder_layers=se.num_decoder_layers,D.num_decoder_heads=se.num_decoder_heads,D.decoder_hidden_size=se.decoder_hidden_size,D.num_encoder_layers=se.num_encoder_layers,D.num_encoder_heads=se.num_encoder_heads,D.encoder_hidden_size=se.encoder_hidden_size):(D.num_layers=se.num_layers,D.num_heads=se.num_heads,D.hidden_size=se.hidden_size),D}const J={...te,...(0,x.pick)(N,["model_type","multi_query","is_encoder_decoder"])};for(const se in P)J[se]=N[P[se]];return J}function Te(N,{prefix:P="past_key_values"}={}){const te={},J=N.normalized_config,se=1;if(J.is_encoder_decoder&&"num_encoder_heads"in J&&"num_decoder_heads"in J){const ae=J.encoder_dim_kv??J.encoder_hidden_size/J.num_encoder_heads,D=J.decoder_dim_kv??J.decoder_hidden_size/J.num_decoder_heads,ee=[se,J.num_encoder_heads,0,ae],G=[se,J.num_decoder_heads,0,D];for(let ie=0;ie{var j;l.r(me),l.d(me,{apis:()=>ae,env:()=>L});var x=l("?569f"),X=l("?3f59"),ye=l("?154a");const ve="3.0.0-alpha.5",Te=typeof self<"u",B=Te&&self.constructor.name==="DedicatedWorkerGlobalScope",E=Te&&"caches"in self,N=typeof navigator<"u"&&"gpu"in navigator,P=typeof process<"u",te=P&&((j=process==null?void 0:process.release)==null?void 0:j.name)==="node",J=!O(x),se=!O(X),ae=Object.freeze({IS_BROWSER_ENV:Te,IS_WEBWORKER_ENV:B,IS_WEB_CACHE_AVAILABLE:E,IS_WEBGPU_AVAILABLE:N,IS_PROCESS_AVAILABLE:P,IS_NODE_ENV:te,IS_FS_AVAILABLE:J,IS_PATH_AVAILABLE:se}),D=J&&se,ee=D?X.dirname(X.dirname(ye.fileURLToPath(self.location.href))):"./",G=D?X.join(ee,"/.cache/"):null,ie="/models/",fe=D?X.join(ee,ie):ie,L={version:ve,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Te,localModelPath:fe,useFS:J,useBrowserCache:E,useFSCache:J,cacheDir:G,useCustomCache:!1,customCache:null};function O(A){return Object.keys(A).length===0}},"./src/generation/configuration_utils.js":($t,me,l)=>{l.r(me),l.d(me,{GenerationConfig:()=>X});var x=l("./src/utils/core.js");class X{constructor(ve){xe(this,"max_length",20);xe(this,"max_new_tokens",null);xe(this,"min_length",0);xe(this,"min_new_tokens",null);xe(this,"early_stopping",!1);xe(this,"max_time",null);xe(this,"do_sample",!1);xe(this,"num_beams",1);xe(this,"num_beam_groups",1);xe(this,"penalty_alpha",null);xe(this,"use_cache",!0);xe(this,"temperature",1);xe(this,"top_k",50);xe(this,"top_p",1);xe(this,"typical_p",1);xe(this,"epsilon_cutoff",0);xe(this,"eta_cutoff",0);xe(this,"diversity_penalty",0);xe(this,"repetition_penalty",1);xe(this,"encoder_repetition_penalty",1);xe(this,"length_penalty",1);xe(this,"no_repeat_ngram_size",0);xe(this,"bad_words_ids",null);xe(this,"force_words_ids",null);xe(this,"renormalize_logits",!1);xe(this,"constraints",null);xe(this,"forced_bos_token_id",null);xe(this,"forced_eos_token_id",null);xe(this,"remove_invalid_values",!1);xe(this,"exponential_decay_length_penalty",null);xe(this,"suppress_tokens",null);xe(this,"begin_suppress_tokens",null);xe(this,"forced_decoder_ids",null);xe(this,"guidance_scale",null);xe(this,"num_return_sequences",1);xe(this,"output_attentions",!1);xe(this,"output_hidden_states",!1);xe(this,"output_scores",!1);xe(this,"return_dict_in_generate",!1);xe(this,"pad_token_id",null);xe(this,"bos_token_id",null);xe(this,"eos_token_id",null);xe(this,"encoder_no_repeat_ngram_size",0);xe(this,"decoder_start_token_id",null);xe(this,"generation_kwargs",{});Object.assign(this,(0,x.pick)(ve,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":($t,me,l)=>{l.r(me),l.d(me,{ClassifierFreeGuidanceLogitsProcessor:()=>ee,ForcedBOSTokenLogitsProcessor:()=>B,ForcedEOSTokenLogitsProcessor:()=>E,LogitsProcessor:()=>ye,LogitsProcessorList:()=>Te,LogitsWarper:()=>ve,MinLengthLogitsProcessor:()=>se,MinNewTokensLengthLogitsProcessor:()=>ae,NoBadWordsLogitsProcessor:()=>D,NoRepeatNGramLogitsProcessor:()=>te,RepetitionPenaltyLogitsProcessor:()=>J,SuppressTokensAtBeginLogitsProcessor:()=>N,TemperatureLogitsWarper:()=>G,TopKLogitsWarper:()=>fe,TopPLogitsWarper:()=>ie,WhisperTimeStampLogitsProcessor:()=>P});var x=l("./src/utils/generic.js");l("./src/utils/tensor.js");var X=l("./src/utils/maths.js");class ye extends x.Callable{_call(O,j){throw Error("`_call` should be implemented in a subclass")}}class ve extends x.Callable{_call(O,j){throw Error("`_call` should be implemented in a subclass")}}class Te extends x.Callable{constructor(){super(),this.processors=[]}push(O){this.processors.push(O)}extend(O){this.processors.push(...O)}_call(O,j){let A=j;for(const ge of this.processors)A=ge(O,A);return A}[Symbol.iterator](){return this.processors.values()}}class B extends ye{constructor(O){super(),this.bos_token_id=O}_call(O,j){for(let A=0;A=1&&Ce[Ce.length-1]>=this.timestamp_begin,De=Ce.length<2||Ce[Ce.length-2]>=this.timestamp_begin;if(ke&&(De?be.subarray(this.timestamp_begin).fill(-1/0):be.subarray(0,this.eos_token_id).fill(-1/0)),O[A].length===this.begin_index&&this.max_initial_timestamp_index!==null){const _e=this.timestamp_begin+this.max_initial_timestamp_index;be.subarray(_e+1).fill(-1/0)}const Je=(0,X.log_softmax)(be),Ue=Math.log(Je.subarray(this.timestamp_begin).map(Math.exp).reduce((_e,V)=>_e+V)),bt=(0,X.max)(Je.subarray(0,this.timestamp_begin))[0];Ue>bt&&be.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class te extends ye{constructor(O){super(),this.no_repeat_ngram_size=O}getNgrams(O){const j=O.length,A=[];for(let be=0;be1 to use the classifier free guidance processor, got guidance scale ${O}.`);this.guidance_scale=O}_call(O,j){if(j.dims[0]!==2*O.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 ${j.dims[0]} for the logits and ${O.length} for the input ids.`);const A=O.length,ge=j.slice([0,A],null),be=j.slice([A,j.dims[0]],null);for(let Ce=0;Ce1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${O}`);if(!Number.isInteger(A)||A<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${A}`);this.top_p=O,this.filter_value=j,this.min_tokens_to_keep=A}}class fe extends ve{constructor(O,{filter_value:j=-1/0,min_tokens_to_keep:A=1}={}){if(super(),!Number.isInteger(O)||O<0)throw new Error(`\`top_k\` must be a positive integer, but is ${O}`);this.top_k=Math.max(O,A),this.filter_value=j}}},"./src/generation/logits_sampler.js":($t,me,l)=>{l.r(me),l.d(me,{LogitsSampler:()=>ve});var x=l("./src/utils/generic.js"),X=l("./src/utils/tensor.js"),ye=l("./src/utils/maths.js");l("./src/generation/configuration_utils.js");class ve extends x.Callable{constructor(P){super(),this.generation_config=P}async _call(P){return this.sample(P)}async sample(P){throw Error("sample should be implemented in subclasses.")}getLogits(P,te){let J=P.dims.at(-1),se=P.data;if(te===-1)se=se.slice(-J);else{let ae=te*J;se=se.slice(ae,ae+J)}return se}randomSelect(P){let te=0;for(let se=0;se1)return new E(P);if(P.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${P.num_return_sequences}.`);return new Te(P)}}class Te extends ve{async sample(P){const te=(0,ye.max)(P.data)[1];return[[BigInt(te),0]]}}class B extends ve{async sample(P){let te=P.dims.at(-1);this.generation_config.top_k>0&&(te=Math.min(this.generation_config.top_k,te));const[J,se]=await(0,X.topk)(P,te),ae=(0,ye.softmax)(J.data);return Array.from({length:this.generation_config.num_beams},()=>{const D=this.randomSelect(ae);return[se.data[D],Math.log(ae[D])]})}}class E extends ve{async sample(P){let te=P.dims.at(-1);this.generation_config.top_k>0&&(te=Math.min(this.generation_config.top_k,te));const[J,se]=await(0,X.topk)(P,te),ae=(0,ye.softmax)(J.data);return Array.from({length:this.generation_config.num_beams},(D,ee)=>[se.data[ee],Math.log(ae[ee])])}}},"./src/generation/stopping_criteria.js":($t,me,l)=>{l.r(me),l.d(me,{EosTokenCriteria:()=>Te,InterruptableStoppingCriteria:()=>B,MaxLengthCriteria:()=>ve,StoppingCriteria:()=>X,StoppingCriteriaList:()=>ye});var x=l("./src/utils/generic.js");class X extends x.Callable{_call(N,P){throw Error("StoppingCriteria needs to be subclassed")}}class ye extends x.Callable{constructor(){super(),this.criteria=[]}push(N){this.criteria.push(N)}extend(N){N instanceof ye?N=N.criteria:N instanceof X&&(N=[N]),this.criteria.push(...N)}_call(N,P){const te=new Array(N.length).fill(!1);for(const J of this.criteria){const se=J(N,P);for(let ae=0;aeP.length>=this.max_length)}}class Te extends X{constructor(N){super(),Array.isArray(N)||(N=[N]),this.eos_token_id=N}_call(N,P){return N.map(te=>{const J=te.at(-1);return this.eos_token_id.some(se=>J==se)})}}class B extends X{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(N,P){return new Array(N.length).fill(this.interrupted)}}},"./src/generation/streamers.js":($t,me,l)=>{l.r(me),l.d(me,{BaseStreamer:()=>ve,TextStreamer:()=>B,WhisperTextStreamer:()=>E});var x=l("./src/utils/core.js"),X=l("./src/tokenizers.js"),ye=l("./src/env.js");class ve{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Te=ye.apis.IS_PROCESS_AVAILABLE?N=>process.stdout.write(N):N=>console.log(N);class B extends ve{constructor(P,{skip_prompt:te=!1,callback_function:J=null,token_callback_function:se=null,decode_kwargs:ae={},...D}={}){super(),this.tokenizer=P,this.skip_prompt=te,this.callback_function=J??Te,this.token_callback_function=se,this.decode_kwargs={...ae,...D},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(P){var ae;if(P.length>1)throw Error("TextStreamer only supports batch size of 1");const te=P[0];if((ae=this.token_callback_function)==null||ae.call(this,te),this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}this.token_cache=(0,x.mergeArrays)(this.token_cache,te);const J=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let se;J.endsWith(` +`)?(se=J.slice(this.print_len),this.token_cache=[],this.print_len=0):J.length>0&&(0,X.is_chinese_char)(J.charCodeAt(J.length-1))?(se=J.slice(this.print_len),this.print_len+=se.length):(se=J.slice(this.print_len,J.lastIndexOf(" ")+1),this.print_len+=se.length),this.on_finalized_text(se,!1)}end(){let P;this.token_cache.length>0?(P=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):P="",this.next_tokens_are_prompt=!0,this.on_finalized_text(P,!0)}on_finalized_text(P,te){var J,se;P.length>0&&((J=this.callback_function)==null||J.call(this,P)),te&&this.callback_function===Te&&ye.apis.IS_PROCESS_AVAILABLE&&((se=this.callback_function)==null||se.call(this,` +`))}}class E extends B{constructor(P,{skip_prompt:te=!1,callback_function:J=null,token_callback_function:se=null,on_chunk_start:ae=null,on_chunk_end:D=null,on_finalize:ee=null,time_precision:G=.02,skip_special_tokens:ie=!0,decode_kwargs:fe={}}={}){super(P,{skip_prompt:te,callback_function:J,token_callback_function:se,decode_kwargs:{skip_special_tokens:ie,...fe}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=ae,this.on_chunk_end=D,this.on_finalize=ee,this.time_precision=G,this.waiting_for_timestamp=!1}put(P){var J,se;if(P.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const te=P[0];if(te.length===1){const ae=Number(te[0])-this.timestamp_begin;if(ae>=0){const D=ae*this.time_precision;this.waiting_for_timestamp?(J=this.on_chunk_end)==null||J.call(this,D):(se=this.on_chunk_start)==null||se.call(this,D),this.waiting_for_timestamp=!this.waiting_for_timestamp,P=[[]]}}return super.put(P)}end(){var P;super.end(),(P=this.on_finalize)==null||P.call(this)}}},"./src/models.js":($t,me,l)=>{l.r(me),l.d(me,{ASTForAudioClassification:()=>Ws,ASTModel:()=>Ft,ASTPreTrainedModel:()=>_n,AlbertForMaskedLM:()=>Qt,AlbertForQuestionAnswering:()=>as,AlbertForSequenceClassification:()=>is,AlbertModel:()=>Qn,AlbertPreTrainedModel:()=>Dn,AutoModel:()=>lu,AutoModelForAudioClassification:()=>bu,AutoModelForAudioFrameClassification:()=>Mu,AutoModelForCTC:()=>yu,AutoModelForCausalLM:()=>pu,AutoModelForDepthEstimation:()=>Tu,AutoModelForDocumentQuestionAnswering:()=>rd,AutoModelForImageClassification:()=>mu,AutoModelForImageFeatureExtraction:()=>Cu,AutoModelForImageMatting:()=>vu,AutoModelForImageSegmentation:()=>xa,AutoModelForImageToImage:()=>xu,AutoModelForMaskGeneration:()=>Ta,AutoModelForMaskedLM:()=>hu,AutoModelForObjectDetection:()=>gu,AutoModelForQuestionAnswering:()=>va,AutoModelForSemanticSegmentation:()=>_u,AutoModelForSeq2SeqLM:()=>du,AutoModelForSequenceClassification:()=>ln,AutoModelForSpeechSeq2Seq:()=>Ma,AutoModelForTextToSpectrogram:()=>cu,AutoModelForTextToWaveform:()=>As,AutoModelForTokenClassification:()=>uu,AutoModelForVision2Seq:()=>fu,AutoModelForXVector:()=>Ca,AutoModelForZeroShotObjectDetection:()=>wu,BartForConditionalGeneration:()=>_,BartForSequenceClassification:()=>F,BartModel:()=>Me,BartPretrainedModel:()=>fn,BaseModelOutput:()=>ct,BeitForImageClassification:()=>Fo,BeitModel:()=>Io,BeitPreTrainedModel:()=>Fi,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>xt,BertModel:()=>ot,BertPreTrainedModel:()=>rt,BlenderbotForConditionalGeneration:()=>Pt,BlenderbotModel:()=>wt,BlenderbotPreTrainedModel:()=>yt,BlenderbotSmallForConditionalGeneration:()=>sr,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>Jt,BloomForCausalLM:()=>fo,BloomModel:()=>ho,BloomPreTrainedModel:()=>Hs,CLIPModel:()=>Oa,CLIPPreTrainedModel:()=>Cs,CLIPSegForImageSegmentation:()=>ja,CLIPSegModel:()=>Na,CLIPSegPreTrainedModel:()=>wi,CLIPTextModelWithProjection:()=>Pn,CLIPVisionModelWithProjection:()=>za,CamembertForMaskedLM:()=>we,CamembertForQuestionAnswering:()=>Ne,CamembertForSequenceClassification:()=>Be,CamembertForTokenClassification:()=>Ae,CamembertModel:()=>K,CamembertPreTrainedModel:()=>C,CausalLMOutput:()=>Zn,CausalLMOutputWithPast:()=>nd,ChineseCLIPModel:()=>Ra,ChineseCLIPPreTrainedModel:()=>La,ClapAudioModelWithProjection:()=>zl,ClapModel:()=>Fl,ClapPreTrainedModel:()=>Es,ClapTextModelWithProjection:()=>Ol,CodeGenForCausalLM:()=>Gs,CodeGenModel:()=>Ya,CodeGenPreTrainedModel:()=>Mn,CohereForCausalLM:()=>eo,CohereModel:()=>Ja,CoherePreTrainedModel:()=>xi,ConvBertForMaskedLM:()=>M,ConvBertForQuestionAnswering:()=>Q,ConvBertForSequenceClassification:()=>W,ConvBertForTokenClassification:()=>S,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>gt,ConvNextForImageClassification:()=>rl,ConvNextModel:()=>tl,ConvNextPreTrainedModel:()=>qi,ConvNextV2ForImageClassification:()=>il,ConvNextV2Model:()=>sl,ConvNextV2PreTrainedModel:()=>nl,DPTForDepthEstimation:()=>Ui,DPTModel:()=>Vi,DPTPreTrainedModel:()=>ji,DebertaForMaskedLM:()=>Mt,DebertaForQuestionAnswering:()=>Rt,DebertaForSequenceClassification:()=>ht,DebertaForTokenClassification:()=>Tt,DebertaModel:()=>nt,DebertaPreTrainedModel:()=>ut,DebertaV2ForMaskedLM:()=>Nt,DebertaV2ForQuestionAnswering:()=>er,DebertaV2ForSequenceClassification:()=>Ht,DebertaV2ForTokenClassification:()=>Xt,DebertaV2Model:()=>Vt,DebertaV2PreTrainedModel:()=>Qe,DeiTForImageClassification:()=>Wo,DeiTModel:()=>Uo,DeiTPreTrainedModel:()=>Di,DepthAnythingForDepthEstimation:()=>Yo,DepthAnythingPreTrainedModel:()=>Qo,DetrForObjectDetection:()=>zo,DetrForSegmentation:()=>Do,DetrModel:()=>Oo,DetrObjectDetectionOutput:()=>Oi,DetrPreTrainedModel:()=>Qs,DetrSegmentationOutput:()=>Bo,Dinov2ForImageClassification:()=>ol,Dinov2Model:()=>al,Dinov2PreTrainedModel:()=>xn,DistilBertForMaskedLM:()=>Et,DistilBertForQuestionAnswering:()=>Ze,DistilBertForSequenceClassification:()=>Ur,DistilBertForTokenClassification:()=>Cr,DistilBertModel:()=>Tr,DistilBertPreTrainedModel:()=>Wt,DonutSwinModel:()=>Gi,DonutSwinPreTrainedModel:()=>el,EfficientNetForImageClassification:()=>Nl,EfficientNetModel:()=>Rl,EfficientNetPreTrainedModel:()=>pa,ElectraForMaskedLM:()=>et,ElectraForQuestionAnswering:()=>Se,ElectraForSequenceClassification:()=>At,ElectraForTokenClassification:()=>mt,ElectraModel:()=>Ye,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>Un,EsmForSequenceClassification:()=>Fn,EsmForTokenClassification:()=>Lr,EsmModel:()=>qr,EsmPreTrainedModel:()=>Bt,FalconForCausalLM:()=>Il,FalconModel:()=>Al,FalconPreTrainedModel:()=>la,FastViTForImageClassification:()=>Mo,FastViTModel:()=>bo,FastViTPreTrainedModel:()=>Xs,Florence2ForConditionalGeneration:()=>_i,Florence2PreTrainedModel:()=>Fa,GLPNForDepthEstimation:()=>Jo,GLPNModel:()=>Zo,GLPNPreTrainedModel:()=>Wi,GPT2LMHeadModel:()=>Ua,GPT2Model:()=>Va,GPT2PreTrainedModel:()=>yi,GPTBigCodeForCausalLM:()=>zu,GPTBigCodeModel:()=>Qa,GPTBigCodePreTrainedModel:()=>vi,GPTJForCausalLM:()=>Xa,GPTJModel:()=>Ka,GPTJPreTrainedModel:()=>Mi,GPTNeoForCausalLM:()=>Ga,GPTNeoModel:()=>Wa,GPTNeoPreTrainedModel:()=>bn,GPTNeoXForCausalLM:()=>Ha,GPTNeoXModel:()=>qa,GPTNeoXPreTrainedModel:()=>bi,Gemma2ForCausalLM:()=>so,Gemma2Model:()=>no,Gemma2PreTrainedModel:()=>Ci,GemmaForCausalLM:()=>ro,GemmaModel:()=>to,GemmaPreTrainedModel:()=>Ti,HubertForCTC:()=>vl,HubertForSequenceClassification:()=>ta,HubertModel:()=>ju,HubertPreTrainedModel:()=>Nu,ImageMattingOutput:()=>Eu,LlamaForCausalLM:()=>Za,LlamaModel:()=>Cn,LlamaPreTrainedModel:()=>qs,LlavaForConditionalGeneration:()=>us,LlavaPreTrainedModel:()=>Ia,LongT5ForConditionalGeneration:()=>xs,LongT5Model:()=>vs,LongT5PreTrainedModel:()=>os,M2M100ForConditionalGeneration:()=>_l,M2M100Model:()=>ml,M2M100PreTrainedModel:()=>Xi,MBartForCausalLM:()=>_t,MBartForConditionalGeneration:()=>ue,MBartForSequenceClassification:()=>Ie,MBartModel:()=>le,MBartPreTrainedModel:()=>Y,MPNetForMaskedLM:()=>_s,MPNetForQuestionAnswering:()=>ys,MPNetForSequenceClassification:()=>gs,MPNetForTokenClassification:()=>ws,MPNetModel:()=>Vs,MPNetPreTrainedModel:()=>On,MT5ForConditionalGeneration:()=>Dr,MT5Model:()=>Ts,MT5PreTrainedModel:()=>ls,MarianMTModel:()=>fl,MarianModel:()=>Lu,MarianPreTrainedModel:()=>Ki,MaskedLMOutput:()=>tn,MistralForCausalLM:()=>ni,MistralModel:()=>ri,MistralPreTrainedModel:()=>ia,MobileBertForMaskedLM:()=>Sn,MobileBertForQuestionAnswering:()=>Wn,MobileBertForSequenceClassification:()=>Pr,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>Zr,MobileNetV1ForImageClassification:()=>Gu,MobileNetV1Model:()=>jl,MobileNetV1PreTrainedModel:()=>ma,MobileNetV2ForImageClassification:()=>Ul,MobileNetV2Model:()=>Vl,MobileNetV2PreTrainedModel:()=>_a,MobileNetV3ForImageClassification:()=>qu,MobileNetV3Model:()=>Wl,MobileNetV3PreTrainedModel:()=>ga,MobileNetV4ForImageClassification:()=>wa,MobileNetV4Model:()=>Ps,MobileNetV4PreTrainedModel:()=>ks,MobileViTForImageClassification:()=>$o,MobileViTModel:()=>Co,MobileViTPreTrainedModel:()=>To,MobileViTV2ForImageClassification:()=>Eo,MobileViTV2Model:()=>Bu,MobileViTV2PreTrainedModel:()=>Ai,ModelOutput:()=>Ke,Moondream1ForConditionalGeneration:()=>or,MptForCausalLM:()=>mo,MptModel:()=>Du,MptPreTrainedModel:()=>Ks,MusicgenForCausalLM:()=>Sd,MusicgenForConditionalGeneration:()=>fa,MusicgenModel:()=>Wu,MusicgenPreTrainedModel:()=>ha,NomicBertModel:()=>$e,NomicBertPreTrainedModel:()=>ne,OPTForCausalLM:()=>go,OPTModel:()=>_o,OPTPreTrainedModel:()=>Pi,OpenELMForCausalLM:()=>ao,OpenELMModel:()=>io,OpenELMPreTrainedModel:()=>vn,OwlViTForObjectDetection:()=>ko,OwlViTModel:()=>So,OwlViTPreTrainedModel:()=>_r,Owlv2ForObjectDetection:()=>Ao,Owlv2Model:()=>Po,Owlv2PreTrainedModel:()=>Ii,Phi3ForCausalLM:()=>ki,Phi3Model:()=>po,Phi3PreTrainedModel:()=>Si,PhiForCausalLM:()=>co,PhiModel:()=>uo,PhiPreTrainedModel:()=>Ei,PreTrainedModel:()=>re,PretrainedMixin:()=>Ir,PyAnnoteForAudioFrameClassification:()=>Xn,PyAnnoteModel:()=>Qi,PyAnnotePreTrainedModel:()=>Bn,QuestionAnsweringModelOutput:()=>rn,Qwen2ForCausalLM:()=>lo,Qwen2Model:()=>oo,Qwen2PreTrainedModel:()=>$i,RTDetrForObjectDetection:()=>Ys,RTDetrModel:()=>Lo,RTDetrObjectDetectionOutput:()=>Ro,RTDetrPreTrainedModel:()=>ps,ResNetForImageClassification:()=>qo,ResNetModel:()=>Go,ResNetPreTrainedModel:()=>Bi,RoFormerForMaskedLM:()=>Ve,RoFormerForQuestionAnswering:()=>ft,RoFormerForSequenceClassification:()=>Xe,RoFormerForTokenClassification:()=>lt,RoFormerModel:()=>qe,RoFormerPreTrainedModel:()=>je,RobertaForMaskedLM:()=>on,RobertaForQuestionAnswering:()=>yn,RobertaForSequenceClassification:()=>Yr,RobertaForTokenClassification:()=>He,RobertaModel:()=>hr,RobertaPreTrainedModel:()=>Gt,SamImageSegmentationOutput:()=>hl,SamModel:()=>pl,SamPreTrainedModel:()=>cl,SegformerForImageClassification:()=>Dl,SegformerForSemanticSegmentation:()=>Bl,SegformerModel:()=>Ed,SegformerPreTrainedModel:()=>Ss,Seq2SeqLMOutput:()=>Pd,SequenceClassifierOutput:()=>lr,SiglipModel:()=>ds,SiglipPreTrainedModel:()=>gi,SiglipTextModel:()=>Da,SiglipVisionModel:()=>Ba,SpeechT5ForSpeechToText:()=>Sl,SpeechT5ForTextToSpeech:()=>Vu,SpeechT5HifiGan:()=>sa,SpeechT5Model:()=>El,SpeechT5PreTrainedModel:()=>na,SqueezeBertForMaskedLM:()=>ss,SqueezeBertForQuestionAnswering:()=>zn,SqueezeBertForSequenceClassification:()=>kn,SqueezeBertModel:()=>Us,SqueezeBertPreTrainedModel:()=>Gn,StableLmForCausalLM:()=>Ll,StableLmModel:()=>ca,StableLmPreTrainedModel:()=>da,Starcoder2ForCausalLM:()=>oa,Starcoder2Model:()=>si,Starcoder2PreTrainedModel:()=>aa,Swin2SRForImageSuperResolution:()=>Ni,Swin2SRModel:()=>Xo,Swin2SRPreTrainedModel:()=>Ri,SwinForImageClassification:()=>Ko,SwinModel:()=>Ho,SwinPreTrainedModel:()=>Li,T5ForConditionalGeneration:()=>Ms,T5Model:()=>bs,T5PreTrainedModel:()=>Yn,TableTransformerForObjectDetection:()=>jo,TableTransformerModel:()=>No,TableTransformerObjectDetectionOutput:()=>Vo,TableTransformerPreTrainedModel:()=>zi,TokenClassifierOutput:()=>Qr,TrOCRForCausalLM:()=>Pl,TrOCRPreTrainedModel:()=>kl,UniSpeechForCTC:()=>wl,UniSpeechForSequenceClassification:()=>yl,UniSpeechModel:()=>Zi,UniSpeechPreTrainedModel:()=>hs,UniSpeechSatForAudioFrameClassification:()=>Js,UniSpeechSatForCTC:()=>Ji,UniSpeechSatForSequenceClassification:()=>bl,UniSpeechSatModel:()=>Zs,UniSpeechSatPreTrainedModel:()=>$s,ViTForImageClassification:()=>yo,ViTModel:()=>wo,ViTPreTrainedModel:()=>cs,VisionEncoderDecoderModel:()=>mi,VitMatteForImageMatting:()=>xo,VitMattePreTrainedModel:()=>vo,VitsModel:()=>ua,VitsModelOutput:()=>sd,VitsPreTrainedModel:()=>Uu,Wav2Vec2BertForCTC:()=>ti,Wav2Vec2BertForSequenceClassification:()=>Ml,Wav2Vec2BertModel:()=>ea,Wav2Vec2BertPreTrainedModel:()=>ei,Wav2Vec2ForAudioFrameClassification:()=>Kn,Wav2Vec2ForCTC:()=>Ru,Wav2Vec2ForSequenceClassification:()=>Hn,Wav2Vec2Model:()=>gl,Wav2Vec2PreTrainedModel:()=>qn,WavLMForAudioFrameClassification:()=>$l,WavLMForCTC:()=>ra,WavLMForSequenceClassification:()=>Tl,WavLMForXVector:()=>Cl,WavLMModel:()=>xl,WavLMPreTrainedModel:()=>Ln,WeSpeakerResNetModel:()=>Yi,WeSpeakerResNetPreTrainedModel:()=>en,WhisperForConditionalGeneration:()=>fi,WhisperModel:()=>Ut,WhisperPreTrainedModel:()=>it,XLMForQuestionAnswering:()=>Jr,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>mn,XLMModel:()=>Hr,XLMPreTrainedModel:()=>wr,XLMRobertaForMaskedLM:()=>St,XLMRobertaForQuestionAnswering:()=>jr,XLMRobertaForSequenceClassification:()=>mr,XLMRobertaForTokenClassification:()=>Ar,XLMRobertaModel:()=>Mr,XLMRobertaPreTrainedModel:()=>br,XLMWithLMHeadModel:()=>dn,XVectorOutput:()=>$u,YolosForObjectDetection:()=>ul,YolosModel:()=>ll,YolosObjectDetectionOutput:()=>dl,YolosPreTrainedModel:()=>Hi});var x=l("./src/configs.js"),X=l("./src/backends/onnx.js"),ye=l("./src/utils/dtypes.js"),ve=l("./src/utils/generic.js"),Te=l("./src/utils/core.js"),B=l("./src/utils/hub.js"),E=l("./src/generation/logits_process.js"),N=l("./src/generation/configuration_utils.js"),P=l("./src/utils/tensor.js"),te=l("./src/utils/maths.js"),J=l("./src/generation/stopping_criteria.js"),se=l("./src/generation/logits_sampler.js"),ae=l("./src/env.js"),D=l("./src/models/whisper/generation_whisper.js"),ee=l("./src/models/whisper/common_whisper.js");const G={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ie=new Map,fe=new Map,L=new Map;async function O(m,g,$){let H=$.device;H&&typeof H!="string"&&(H.hasOwnProperty(g)?H=H[g]:(console.warn(`device not specified for "${g}". Using the default device.`),H=null));const Fe=(0,X.deviceToExecutionProviders)(H);let Pe=$.dtype;if(typeof Pe!="string"&&(Pe&&Pe.hasOwnProperty(g)?Pe=Pe[g]:(Pe=ye.DEFAULT_DEVICE_DTYPE_MAPPING[Fe[0]],console.warn(`dtype not specified for "${g}". Using the default dtype for this device (${Pe}).`))),ye.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Pe)){if(Pe===ye.DATA_TYPES.fp16&&H==="webgpu"&&!await(0,ye.isWebGpuFp16Supported)())throw new Error(`The device (${H}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Pe}. Should be one of: ${Object.keys(ye.DATA_TYPES).join(", ")}`);const pt=ye.DEFAULT_DTYPE_SUFFIX_MAPPING[Pe],kt=`${$.subfolder??""}/${g}${pt}.onnx`,zt={...$.session_options};zt.executionProviders??(zt.executionProviders=Fe);const ur=(0,B.getModelFile)(m,kt,!0,$);let cr=[];if($.use_external_data_format&&($.use_external_data_format===!0||typeof $.use_external_data_format=="object"&&$.use_external_data_format.hasOwnProperty(g)&&$.use_external_data_format[g]===!0)){if(ae.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const tr=`${g}${pt}.onnx_data`,ir=`${$.subfolder??""}/${tr}`;cr.push(new Promise(async(yr,xr)=>{const vr=await(0,B.getModelFile)(m,ir,!0,$);yr({path:tr,data:vr})}))}else zt.externalData!==void 0&&(cr=zt.externalData.map(async tr=>{if(typeof tr.data=="string"){const ir=await(0,B.getModelFile)(m,tr.data,!0,$);return{...tr,data:ir}}return tr}));if(cr.length>0&&(zt.externalData=await Promise.all(cr)),H==="webgpu"){const tr=(0,x.getKeyValueShapes)($.config,{prefix:"present"});if(Object.keys(tr).length>0&&!(0,X.isONNXProxy)()){const ir={};for(const yr in tr)ir[yr]="gpu-buffer";zt.preferredOutputLocation=ir}}return{buffer:await ur,session_options:zt}}async function j(m,g,$){return Object.fromEntries(await Promise.all(Object.keys(g).map(async H=>{const{buffer:Fe,session_options:Pe}=await O(m,g[H],$),pt=await(0,X.createInferenceSession)(Fe,Pe);return[H,pt]})))}function A(m,g){const $=Object.create(null),H=[];for(const pt of m.inputNames){const kt=g[pt];if(!(kt instanceof P.Tensor)){H.push(pt);continue}$[pt]=(0,X.isONNXProxy)()?kt.clone():kt}if(H.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${H.join(", ")}.`);const Fe=Object.keys(g).length,Pe=m.inputNames.length;if(Fe>Pe){let pt=Object.keys(g).filter(kt=>!m.inputNames.includes(kt));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${Pe}). The following inputs will be ignored: "${pt.join(", ")}".`)}return $}async function ge(m,g){const $=A(m,g);try{const H=Object.fromEntries(Object.entries($).map(([Pe,pt])=>[Pe,pt.ort_tensor]));let Fe=await m.run(H);return Fe=be(Fe),Fe}catch(H){throw console.error(`An error occurred during model execution: "${H}".`),console.error("Inputs given to model:",$),H}}function be(m){for(let g in m)(0,X.isONNXTensor)(m[g])?m[g]=new P.Tensor(m[g]):typeof m[g]=="object"&&be(m[g]);return m}function Ce(m){if(m instanceof P.Tensor)return m;if(m.length===0)throw Error("items must be non-empty");if(Array.isArray(m[0])){if(m.some(g=>g.length!==m[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 P.Tensor("int64",BigInt64Array.from(m.flat().map(g=>BigInt(g))),[m.length,m[0].length])}else return new P.Tensor("int64",BigInt64Array.from(m.map(g=>BigInt(g))),[1,m.length])}function ke(m){return new P.Tensor("bool",[m],[1])}async function De(m,g){let{encoder_outputs:$,input_ids:H,decoder_input_ids:Fe,...Pe}=g;if(!$){const kt=(0,Te.pick)(g,m.sessions.model.inputNames);$=(await Je(m,kt)).last_hidden_state}return Pe.input_ids=Fe,Pe.encoder_hidden_states=$,m.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Pe.encoder_attention_mask=g.attention_mask),await Ue(m,Pe,!0)}async function Je(m,g){const $=m.sessions.model,H=(0,Te.pick)(g,$.inputNames);if($.inputNames.includes("inputs_embeds")&&!H.inputs_embeds){if(!g.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");H.inputs_embeds=await m.encode_text({input_ids:g.input_ids})}return $.inputNames.includes("token_type_ids")&&!H.token_type_ids&&(H.token_type_ids=new P.Tensor("int64",new BigInt64Array(H.input_ids.data.length),H.input_ids.dims)),await ge($,H)}async function Ue(m,g,$=!1){const H=m.sessions[$?"decoder_model_merged":"model"],{past_key_values:Fe,...Pe}=g;H.inputNames.includes("use_cache_branch")&&(Pe.use_cache_branch=ke(!!Fe)),H.inputNames.includes("position_ids")&&Pe.attention_mask&&!Pe.position_ids&&(Pe.position_ids=_e(Pe,Fe)),m.addPastKeyValues(Pe,Fe);const pt=(0,Te.pick)(Pe,H.inputNames);return await ge(H,pt)}async function bt(m,{input_ids:g=null,attention_mask:$=null,pixel_values:H=null,position_ids:Fe=null,inputs_embeds:Pe=null,past_key_values:pt=null,generation_config:kt=null,logits_processor:zt=null,...ur}){if(!Pe){if(Pe=await m.encode_text({input_ids:g}),H&&g.dims[1]!==1){const Er=await m.encode_image({pixel_values:H});({inputs_embeds:Pe,attention_mask:$}=m._merge_input_ids_with_image_features({image_features:Er,inputs_embeds:Pe,input_ids:g,attention_mask:$}))}else if(pt&&H&&g.dims[1]===1){const Er=g.dims[1],tr=Object.values(pt)[0].dims.at(-2);$=(0,P.cat)([(0,P.ones)([g.dims[0],tr]),$.slice(null,[$.dims[1]-Er,$.dims[1]])],1)}}return await Ue(m,{inputs_embeds:Pe,past_key_values:pt,attention_mask:$,position_ids:Fe,generation_config:kt,logits_processor:zt},!0)}function _e(m,g=null){const{input_ids:$,inputs_embeds:H,attention_mask:Fe}=m,[Pe,pt]=Fe.dims,kt=new BigInt64Array(Fe.data.length);for(let ur=0;urPe.dims[1])){if(Fekt==m.config.image_token_index)){const kt=m.config.num_image_tokens;if(!kt)throw new Error("`num_image_tokens` is missing in the model configuration.");const zt=Pe.dims[1]-(Fe-kt);$.input_ids=Pe.slice(null,[-zt,null]),$.attention_mask=(0,P.ones)([1,Fe+zt])}}}return $}function pe(m,g,$,H){return $.past_key_values&&(g=g.map(Fe=>[Fe.at(-1)])),{...$,decoder_input_ids:Ce(g)}}function Ee(m,...g){return m.config.is_encoder_decoder?pe(m,...g):V(m,...g)}class re extends ve.Callable{constructor($,H){super();xe(this,"main_input_name","input_ids");xe(this,"forward_params",["input_ids","attention_mask"]);this.config=$,this.sessions=H;const Fe=L.get(this.constructor),Pe=ie.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Pe){case G.DecoderOnly:this.can_generate=!0,this._forward=Ue,this._prepare_inputs_for_generation=V;break;case G.Seq2Seq:case G.Vision2Seq:case G.Musicgen:this.can_generate=!0,this._forward=De,this._prepare_inputs_for_generation=pe;break;case G.EncoderDecoder:this._forward=De;break;case G.ImageTextToText:this.can_generate=!0,this._forward=bt,this._prepare_inputs_for_generation=Ee;break;default:this._forward=Je;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var H;const $=[];for(const Fe of Object.values(this.sessions))(H=Fe==null?void 0:Fe.handler)!=null&&H.dispose&&$.push(Fe.handler.dispose());return await Promise.all($)}static async from_pretrained($,{progress_callback:H=null,config:Fe=null,cache_dir:Pe=null,local_files_only:pt=!1,revision:kt="main",model_file_name:zt=null,subfolder:ur="onnx",device:cr=null,dtype:Er=null,use_external_data_format:tr=null,session_options:ir={}}={}){let yr={progress_callback:H,config:Fe,cache_dir:Pe,local_files_only:pt,revision:kt,model_file_name:zt,subfolder:ur,device:cr,dtype:Er,use_external_data_format:tr,session_options:ir};const xr=L.get(this),vr=ie.get(xr);Fe=yr.config=await x.AutoConfig.from_pretrained($,yr);let zr;if(vr===G.DecoderOnly)zr=await Promise.all([j($,{model:yr.model_file_name??"model"},yr),(0,B.getModelJSON)($,"generation_config.json",!1,yr)]);else if(vr===G.Seq2Seq||vr===G.Vision2Seq)zr=await Promise.all([j($,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},yr),(0,B.getModelJSON)($,"generation_config.json",!1,yr)]);else if(vr===G.MaskGeneration)zr=await Promise.all([j($,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},yr)]);else if(vr===G.EncoderDecoder)zr=await Promise.all([j($,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},yr)]);else if(vr===G.ImageTextToText){const gn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(gn.model="encoder_model"),zr=await Promise.all([j($,gn,yr),(0,B.getModelJSON)($,"generation_config.json",!1,yr)])}else vr===G.Musicgen?zr=await Promise.all([j($,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},yr),(0,B.getModelJSON)($,"generation_config.json",!1,yr)]):(vr!==G.EncoderOnly&&console.warn(`Model type for '${xr??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),zr=await Promise.all([j($,{model:yr.model_file_name??"model"},yr)]));return new this(Fe,...zr)}async _call($){return await this.forward($)}async forward($){return await this._forward(this,$)}_get_logits_warper($){const H=new E.LogitsProcessorList;return $.temperature!==null&&$.temperature!==1&&H.push(new E.TemperatureLogitsWarper($.temperature)),$.top_k!==null&&$.top_k!==0&&H.push(new E.TopKLogitsWarper($.top_k)),$.top_p!==null&&$.top_p<1&&H.push(new E.TopPLogitsWarper($.top_p)),H}_get_logits_processor($,H,Fe=null){const Pe=new E.LogitsProcessorList;if($.repetition_penalty!==null&&$.repetition_penalty!==1&&Pe.push(new E.RepetitionPenaltyLogitsProcessor($.repetition_penalty)),$.no_repeat_ngram_size!==null&&$.no_repeat_ngram_size>0&&Pe.push(new E.NoRepeatNGramLogitsProcessor($.no_repeat_ngram_size)),$.bad_words_ids!==null&&Pe.push(new E.NoBadWordsLogitsProcessor($.bad_words_ids,$.eos_token_id)),$.min_length!==null&&$.eos_token_id!==null&&$.min_length>0&&Pe.push(new E.MinLengthLogitsProcessor($.min_length,$.eos_token_id)),$.min_new_tokens!==null&&$.eos_token_id!==null&&$.min_new_tokens>0&&Pe.push(new E.MinNewTokensLengthLogitsProcessor(H,$.min_new_tokens,$.eos_token_id)),$.forced_bos_token_id!==null&&Pe.push(new E.ForcedBOSTokenLogitsProcessor($.forced_bos_token_id)),$.forced_eos_token_id!==null&&Pe.push(new E.ForcedEOSTokenLogitsProcessor($.max_length,$.forced_eos_token_id)),$.begin_suppress_tokens!==null){const pt=H>1||$.forced_bos_token_id===null?H:H+1;Pe.push(new E.SuppressTokensAtBeginLogitsProcessor($.begin_suppress_tokens,pt))}return $.guidance_scale!==null&&$.guidance_scale>1&&Pe.push(new E.ClassifierFreeGuidanceLogitsProcessor($.guidance_scale)),Fe!==null&&Pe.extend(Fe),Pe}_prepare_generation_config($,H,Fe=N.GenerationConfig){const Pe={...this.config};for(const kt of["decoder","generator","text_config"])kt in Pe&&Object.assign(Pe,Pe[kt]);const pt=new Fe(Pe);return"generation_config"in this&&Object.assign(pt,this.generation_config),$&&Object.assign(pt,$),H&&Object.assign(pt,(0,Te.pick)(H,Object.getOwnPropertyNames(pt))),pt}_get_stopping_criteria($,H=null){const Fe=new J.StoppingCriteriaList;return $.max_length!==null&&Fe.push(new J.MaxLengthCriteria($.max_length,this.config.max_position_embeddings??null)),$.eos_token_id!==null&&Fe.push(new J.EosTokenCriteria($.eos_token_id)),H&&Fe.extend(H),Fe}_validate_model_class(){if(!this.can_generate){const $=[ai,ba,ya,ii],H=L.get(this.constructor),Fe=new Set,Pe=this.config.model_type;for(const kt of $){const zt=kt.get(Pe);zt&&Fe.add(zt[0])}let pt=`The current model class (${H}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(pt+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(pt)}}prepare_inputs_for_generation(...$){return this._prepare_inputs_for_generation(this,...$)}_update_model_kwargs_for_generation({generated_input_ids:$,outputs:H,model_inputs:Fe,is_encoder_decoder:Pe}){return Fe.past_key_values=this.getPastKeyValues(H,Fe.past_key_values),Fe.input_ids=new P.Tensor("int64",$.flat(),[$.length,1]),Pe||(Fe.attention_mask=(0,P.cat)([Fe.attention_mask,(0,P.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:$,bos_token_id:H,model_kwargs:Fe}){const Pe=(0,Te.pick)(Fe,this.forward_params),pt=this.main_input_name;if(pt in Pe){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 Pe[pt]=$;return{inputs_tensor:Pe[pt],model_inputs:Pe,model_input_name:pt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:$,model_inputs:H,model_input_name:Fe,generation_config:Pe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!H.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:kt,pixel_values:zt,attention_mask:ur,...cr}=H,Er=await this._prepare_inputs_embeds(H);H={...cr,...(0,Te.pick)(Er,["inputs_embeds","attention_mask"])}}let{last_hidden_state:pt}=await Je(this,H);if(Pe.guidance_scale!==null&&Pe.guidance_scale>1)pt=(0,P.cat)([pt,(0,P.full_like)(pt,0)],0),"attention_mask"in H&&(H.attention_mask=(0,P.cat)([H.attention_mask,(0,P.zeros_like)(H.attention_mask)],0));else if(H.decoder_input_ids){const kt=Ce(H.decoder_input_ids).dims[0];if(kt!==pt.dims[0]){if(pt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${pt.dims[0]}) than the decoder inputs (${kt}).`);pt=(0,P.cat)(Array.from({length:kt},()=>pt),0)}}return H.encoder_outputs=pt,H}_prepare_decoder_input_ids_for_generation({batch_size:$,model_input_name:H,model_kwargs:Fe,decoder_start_token_id:Pe,bos_token_id:pt,generation_config:kt}){let{decoder_input_ids:zt,...ur}=Fe;if(zt)Array.isArray(zt[0])||(zt=Array.from({length:$},()=>zt));else if(Pe??(Pe=pt),this.config.model_type==="musicgen")zt=Array.from({length:$*this.config.decoder.num_codebooks},()=>[Pe]);else if(Array.isArray(Pe)){if(Pe.length!==$)throw new Error(`\`decoder_start_token_id\` expcted to have length ${$} but got ${Pe.length}`);zt=Pe}else zt=Array.from({length:$},()=>[Pe]);return zt=Ce(zt),Fe.decoder_attention_mask=(0,P.ones_like)(zt),{input_ids:zt,model_inputs:ur}}async generate({inputs:$=null,generation_config:H=null,logits_processor:Fe=null,stopping_criteria:Pe=null,streamer:pt=null,...kt}){this._validate_model_class(),H=this._prepare_generation_config(H,kt);let{inputs_tensor:zt,model_inputs:ur,model_input_name:cr}=this._prepare_model_inputs({inputs:$,model_kwargs:kt});const Er=this.config.is_encoder_decoder;Er&&("encoder_outputs"in ur||(ur=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:zt,model_inputs:ur,model_input_name:cr,generation_config:H})));let tr;Er?{input_ids:tr,model_inputs:ur}=this._prepare_decoder_input_ids_for_generation({batch_size:ur[cr].dims.at(0),model_input_name:cr,model_kwargs:ur,decoder_start_token_id:H.decoder_start_token_id,bos_token_id:H.bos_token_id,generation_config:H}):tr=ur[cr];let ir=tr.dims.at(-1);H.max_new_tokens!==null&&(H.max_length=ir+H.max_new_tokens);const yr=this._get_logits_processor(H,ir,Fe),xr=this._get_stopping_criteria(H,Pe),vr=ur[cr].dims.at(0),zr=se.LogitsSampler.getSampler(H),gn=new Array(vr).fill(0),cn=tr.tolist();pt&&pt.put(cn);let Rn=null,nn={};for(;;){ur=this.prepare_inputs_for_generation(cn,ur,H);const sn=await this.forward(ur);if(H.output_attentions&&H.return_dict_in_generate){const An=this.getAttentions(sn);for(const Is in An)Is in nn||(nn[Is]=[]),nn[Is].push(An[Is])}const oi=sn.logits.slice(null,-1,null),li=yr(cn,oi),$a=[];for(let An=0;AnAn)){H.return_dict_in_generate&&(Rn=this.getPastKeyValues(sn,ur.past_key_values,!1));break}ur=this._update_model_kwargs_for_generation({generated_input_ids:$a,outputs:sn,model_inputs:ur,is_encoder_decoder:Er})}pt&&pt.end();const Kr=new P.Tensor("int64",cn.flat(),[cn.length,cn[0].length]);return H.return_dict_in_generate?{sequences:Kr,past_key_values:Rn,...nn}:Kr}getPastKeyValues($,H,Fe=!0){const Pe=Object.create(null);for(const pt in $)if(pt.startsWith("present")){const kt=pt.replace("present","past_key_values");if(H&&pt.includes("encoder"))Pe[kt]=H[kt];else{if(Fe&&H){const zt=H[kt];zt.location==="gpu-buffer"&&zt.dispose()}Pe[kt]=$[pt]}}return Pe}getAttentions($){const H={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Pe in $)Pe.startsWith(Fe)&&(Fe in H||(H[Fe]=[]),H[Fe].push($[Pe]));return H}addPastKeyValues($,H){if(H)Object.assign($,H);else{const Fe=this.custom_config.kv_cache_dtype??"float32",Pe=Fe==="float16"?new Uint16Array:[],pt=(0,x.getKeyValueShapes)(this.config);for(const kt in pt)$[kt]=new P.Tensor(Fe,Pe,pt[kt])}}async encode_image({pixel_values:$}){const H=(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 (${H.dims[1]}).`),this.config.num_image_tokens=H.dims[1]),H}async encode_text({input_ids:$}){return(await ge(this.sessions.embed_tokens,{input_ids:$})).inputs_embeds}}class Ke{}class ct extends Ke{constructor({last_hidden_state:g,hidden_states:$=null,attentions:H=null}){super(),this.last_hidden_state=g,this.hidden_states=$,this.attentions=H}}class rt extends re{}class ot extends rt{}class Re extends rt{async _call(g){return new tn(await super._call(g))}}class st extends rt{async _call(g){return new lr(await super._call(g))}}class xt extends rt{async _call(g){return new Qr(await super._call(g))}}class ze extends rt{async _call(g){return new rn(await super._call(g))}}class ne extends re{}class $e extends ne{}class je extends re{}class qe extends je{}class Ve extends je{async _call(g){return new tn(await super._call(g))}}class Xe extends je{async _call(g){return new lr(await super._call(g))}}class lt extends je{async _call(g){return new Qr(await super._call(g))}}class ft extends je{async _call(g){return new rn(await super._call(g))}}class gt extends re{}class vt extends gt{}class M extends gt{async _call(g){return new tn(await super._call(g))}}class W extends gt{async _call(g){return new lr(await super._call(g))}}class S extends gt{async _call(g){return new Qr(await super._call(g))}}class Q extends gt{async _call(g){return new rn(await super._call(g))}}class he extends re{}class Ye extends he{}class et extends he{async _call(g){return new tn(await super._call(g))}}class At extends he{async _call(g){return new lr(await super._call(g))}}class mt extends he{async _call(g){return new Qr(await super._call(g))}}class Se extends he{async _call(g){return new rn(await super._call(g))}}class C extends re{}class K extends C{}class we extends C{async _call(g){return new tn(await super._call(g))}}class Be extends C{async _call(g){return new lr(await super._call(g))}}class Ae extends C{async _call(g){return new Qr(await super._call(g))}}class Ne extends C{async _call(g){return new rn(await super._call(g))}}class ut extends re{}class nt extends ut{}class Mt extends ut{async _call(g){return new tn(await super._call(g))}}class ht extends ut{async _call(g){return new lr(await super._call(g))}}class Tt extends ut{async _call(g){return new Qr(await super._call(g))}}class Rt extends ut{async _call(g){return new rn(await super._call(g))}}class Qe extends re{}class Vt extends Qe{}class Nt extends Qe{async _call(g){return new tn(await super._call(g))}}class Ht extends Qe{async _call(g){return new lr(await super._call(g))}}class Xt extends Qe{async _call(g){return new Qr(await super._call(g))}}class er extends Qe{async _call(g){return new rn(await super._call(g))}}class Wt extends re{}class Tr extends Wt{}class Ur extends Wt{async _call(g){return new lr(await super._call(g))}}class Cr extends Wt{async _call(g){return new Qr(await super._call(g))}}class Ze extends Wt{async _call(g){return new rn(await super._call(g))}}class Et extends Wt{async _call(g){return new tn(await super._call(g))}}class Bt extends re{}class qr extends Bt{}class Un extends Bt{async _call(g){return new tn(await super._call(g))}}class Fn extends Bt{async _call(g){return new lr(await super._call(g))}}class Lr extends Bt{async _call(g){return new Qr(await super._call(g))}}class Zr extends re{}class Nr extends Zr{}class Sn extends Zr{async _call(g){return new tn(await super._call(g))}}class Pr extends Zr{async _call(g){return new lr(await super._call(g))}}class Wn extends Zr{async _call(g){return new rn(await super._call(g))}}class On extends re{}class Vs extends On{}class _s extends On{async _call(g){return new tn(await super._call(g))}}class gs extends On{async _call(g){return new lr(await super._call(g))}}class ws extends On{async _call(g){return new Qr(await super._call(g))}}class ys extends On{async _call(g){return new rn(await super._call(g))}}class Gn extends re{}class Us extends Gn{}class ss extends Gn{async _call(g){return new tn(await super._call(g))}}class kn extends Gn{async _call(g){return new lr(await super._call(g))}}class zn extends Gn{async _call(g){return new rn(await super._call(g))}}class Dn extends re{}class Qn extends Dn{}class is extends Dn{async _call(g){return new lr(await super._call(g))}}class as extends Dn{async _call(g){return new rn(await super._call(g))}}class Qt extends Dn{async _call(g){return new tn(await super._call(g))}}class Yn extends re{constructor($,H,Fe){super($,H);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class bs extends Yn{}class Ms extends Yn{}class os extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class vs extends os{}class xs extends os{}class ls extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class Ts extends ls{}class Dr extends ls{}class fn extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class Me extends fn{}class _ extends fn{}class F extends fn{async _call(g){return new lr(await super._call(g))}}class Y extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class le extends Y{}class ue extends Y{}class Ie extends Y{async _call(g){return new lr(await super._call(g))}}class _t extends Y{}class yt extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class wt extends yt{}class Pt extends yt{}class Jt extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class $r extends Jt{}class sr extends Jt{}class Gt extends re{}class hr extends Gt{}class on extends Gt{async _call(g){return new tn(await super._call(g))}}class Yr extends Gt{async _call(g){return new lr(await super._call(g))}}class He extends Gt{async _call(g){return new Qr(await super._call(g))}}class yn extends Gt{async _call(g){return new rn(await super._call(g))}}class wr extends re{}class Hr extends wr{}class dn extends wr{async _call(g){return new tn(await super._call(g))}}class Yt extends wr{async _call(g){return new lr(await super._call(g))}}class mn extends wr{async _call(g){return new Qr(await super._call(g))}}class Jr extends wr{async _call(g){return new rn(await super._call(g))}}class br extends re{}class Mr extends br{}class St extends br{async _call(g){return new tn(await super._call(g))}}class mr extends br{async _call(g){return new lr(await super._call(g))}}class Ar extends br{async _call(g){return new Qr(await super._call(g))}}class jr extends br{async _call(g){return new rn(await super._call(g))}}class _n extends re{}class Ft extends _n{}class Ws extends _n{}class it extends re{constructor($,H,Fe){super($,H);xe(this,"requires_attention_mask",!1);xe(this,"main_input_name","input_features");xe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Ut extends it{}class fi extends it{_prepare_generation_config(g,$){return super._prepare_generation_config(g,$,D.WhisperGenerationConfig)}_retrieve_init_tokens(g){const $=[g.decoder_start_token_id];let H=g.language;const Fe=g.task;if(g.is_multilingual){H||(console.warn("No language specified - defaulting to English (en)."),H="en");const pt=`<|${(0,ee.whisper_language_to_code)(H)}|>`;$.push(g.lang_to_id[pt]),$.push(g.task_to_id[Fe??"transcribe"])}else if(H||Fe)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!g.return_timestamps&&g.no_timestamps_token_id&&$.at(-1)!==g.no_timestamps_token_id?$.push(g.no_timestamps_token_id):g.return_timestamps&&$.at(-1)===g.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),$.pop()),$.filter(Pe=>Pe!=null)}async generate({inputs:g=null,generation_config:$=null,logits_processor:H=null,stopping_criteria:Fe=null,...Pe}){$=this._prepare_generation_config($,Pe);const pt=Pe.decoder_input_ids??this._retrieve_init_tokens($);if($.return_timestamps&&(H??(H=new E.LogitsProcessorList),H.push(new E.WhisperTimeStampLogitsProcessor($,pt))),$.begin_suppress_tokens&&(H??(H=new E.LogitsProcessorList),H.push(new E.SuppressTokensAtBeginLogitsProcessor($.begin_suppress_tokens,pt.length))),$.return_token_timestamps){if(!$.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.");$.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),$.output_attentions=!0,$.return_dict_in_generate=!0}const kt=await super.generate({inputs:g,generation_config:$,logits_processor:H,decoder_input_ids:pt,...Pe});return $.return_token_timestamps&&(kt.token_timestamps=this._extract_token_timestamps(kt,$.alignment_heads,$.num_frames)),kt}_extract_token_timestamps(g,$,H=null,Fe=.02){if(!g.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`.");H==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 Pe=this.config.median_filter_width;Pe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Pe=7);const pt=g.cross_attentions,kt=Array.from({length:this.config.decoder_layers},(xr,vr)=>(0,P.cat)(pt.map(zr=>zr[vr]),2)),zt=(0,P.stack)($.map(([xr,vr])=>{if(xr>=kt.length)throw new Error(`Layer index ${xr} is out of bounds for cross attentions (length ${kt.length}).`);return H?kt[xr].slice(null,vr,null,[0,H]):kt[xr].slice(null,vr)})).transpose(1,0,2,3),[ur,cr]=(0,P.std_mean)(zt,-2,0,!0),Er=zt.clone();for(let xr=0;xrzr[sn+1]-zr[sn]),Rn=(0,Te.mergeArrays)([1],cn).map(Kr=>!!Kr),nn=[];for(let Kr=0;Krtr.findIndex(ir=>ir==Pe)),zt=kt.every(tr=>tr===-1),ur=kt.every(tr=>tr!==-1);if(!zt&&!ur)throw new Error("Every input should contain either 0 or 1 image token.");if(zt)return{inputs_embeds:g,attention_mask:Fe};const cr=[],Er=[];for(let tr=0;trPe*pt,1);g.input_labels=new P.Tensor("int64",new BigInt64Array(Fe).fill(1n),H)}const $={image_embeddings:g.image_embeddings,image_positional_embeddings:g.image_positional_embeddings};return g.input_points&&($.input_points=g.input_points),g.input_labels&&($.input_labels=g.input_labels),g.input_boxes&&($.input_boxes=g.input_boxes),await ge(this.sessions.prompt_encoder_mask_decoder,$)}async _call(g){return new hl(await super._call(g))}}class hl extends Ke{constructor({iou_scores:g,pred_masks:$}){super(),this.iou_scores=g,this.pred_masks=$}}class Ki extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class Lu extends Ki{}class fl extends Ki{}class Xi extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class ml extends Xi{}class _l extends Xi{}class qn extends re{}class gl extends qn{}class Ru extends qn{async _call(g){return new Zn(await super._call(g))}}class Hn extends qn{async _call(g){return new lr(await super._call(g))}}class Kn extends qn{async _call(g){return new Qr(await super._call(g))}}class Bn extends re{}class Qi extends Bn{}class Xn extends Bn{async _call(g){return new Qr(await super._call(g))}}class en extends re{}class Yi extends en{}class hs extends re{}class Zi extends hs{}class wl extends hs{async _call(g){return new Zn(await super._call(g))}}class yl extends hs{async _call(g){return new lr(await super._call(g))}}class $s extends re{}class Zs extends $s{}class Ji extends $s{async _call(g){return new Zn(await super._call(g))}}class bl extends $s{async _call(g){return new lr(await super._call(g))}}class Js extends $s{async _call(g){return new Qr(await super._call(g))}}class ei extends re{}class ea extends ei{}class ti extends ei{async _call(g){return new Zn(await super._call(g))}}class Ml extends ei{async _call(g){return new lr(await super._call(g))}}class Nu extends re{}class ju extends qn{}class vl extends qn{async _call(g){return new Zn(await super._call(g))}}class ta extends qn{async _call(g){return new lr(await super._call(g))}}class Ln extends re{}class xl extends Ln{}class ra extends Ln{async _call(g){return new Zn(await super._call(g))}}class Tl extends Ln{async _call(g){return new lr(await super._call(g))}}class Cl extends Ln{async _call(g){return new $u(await super._call(g))}}class $l extends Ln{async _call(g){return new Qr(await super._call(g))}}class na extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class El extends na{}class Sl extends na{}class Vu extends na{async generate_speech(g,$,{threshold:H=.5,minlenratio:Fe=0,maxlenratio:Pe=20,vocoder:pt=null}={}){const kt={input_ids:g},{encoder_outputs:zt,encoder_attention_mask:ur}=await Je(this,kt),cr=zt.dims[1]/this.config.reduction_factor,Er=Math.floor(cr*Pe),tr=Math.floor(cr*Fe),ir=this.config.num_mel_bins;let yr=[],xr=null,vr=null,zr=0;for(;;){++zr;const Rn=ke(!!vr);let nn;vr?nn=vr.output_sequence_out:nn=new P.Tensor("float32",new Float32Array(ir),[1,1,ir]);let Kr={use_cache_branch:Rn,output_sequence:nn,encoder_attention_mask:ur,speaker_embeddings:$,encoder_hidden_states:zt};this.addPastKeyValues(Kr,xr),vr=await ge(this.sessions.decoder_model_merged,Kr),xr=this.getPastKeyValues(vr,xr);const{prob:sn,spectrum:oi}=vr;if(yr.push(oi),zr>=tr&&(Array.from(sn.data).filter(li=>li>=H).length>0||zr>=Er))break}const gn=(0,P.cat)(yr),{waveform:cn}=await ge(pt.sessions.model,{spectrogram:gn});return{spectrogram:gn,waveform:cn}}}class sa extends re{constructor(){super(...arguments);xe(this,"main_input_name","spectrogram")}}class kl extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class Pl extends kl{}class ia extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class ri extends ia{}class ni extends ia{}class aa extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class si extends aa{}class oa extends aa{}class la extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class Al extends la{}class Il extends la{}class Es extends re{}class Fl extends Es{}class Ol extends Es{static async from_pretrained(g,$={}){return $.model_file_name??($.model_file_name="text_model"),super.from_pretrained(g,$)}}class zl extends Es{static async from_pretrained(g,$={}){return $.model_file_name??($.model_file_name="audio_model"),super.from_pretrained(g,$)}}class Uu extends re{}class ua extends Uu{async _call(g){return new sd(await super._call(g))}}class Ss extends re{}class Ed extends Ss{}class Dl extends Ss{}class Bl extends Ss{}class da extends re{constructor(g,$,H){super(g,$),this.generation_config=H}}class ca extends da{}class Ll extends da{}class pa extends re{}class Rl extends pa{}class Nl extends pa{async _call(g){return new lr(await super._call(g))}}class ha extends re{}class Wu extends ha{}class Sd extends ha{}class fa extends re{constructor($,H,Fe){super($,H);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}_apply_and_filter_by_delay_pattern_mask($){const[H,Fe]=$.dims,Pe=this.config.decoder.num_codebooks,pt=Fe-Pe;let kt=0;for(let cr=0;cr<$.size;++cr){if($.data[cr]===this.config.decoder.pad_token_id)continue;const Er=cr%Fe,tr=Math.floor(cr/Fe)%Pe,ir=Er-tr;ir>0&&ir<=pt&&($.data[kt++]=$.data[cr])}const zt=Math.floor(H/Pe),ur=kt/(zt*Pe);return new P.Tensor($.type,$.data.slice(0,kt),[zt,Pe,ur])}prepare_inputs_for_generation($,H,Fe){let Pe=structuredClone($);for(let kt=0;kt=zt&&(Pe[kt][zt]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(Pe=Pe.concat(Pe)),super.prepare_inputs_for_generation(Pe,H,Fe)}async generate($){const H=await super.generate($),Fe=this._apply_and_filter_by_delay_pattern_mask(H).unsqueeze_(0),{audio_values:Pe}=await ge(this.sessions.encodec_decode,{audio_codes:Fe});return Pe}}class ma extends re{}class jl extends ma{}class Gu extends ma{async _call(g){return new lr(await super._call(g))}}class _a extends re{}class Vl extends _a{}class Ul extends _a{async _call(g){return new lr(await super._call(g))}}class ga extends re{}class Wl extends ga{}class qu extends ga{async _call(g){return new lr(await super._call(g))}}class ks extends re{}class Ps extends ks{}class wa extends ks{async _call(g){return new lr(await super._call(g))}}class Ir{static async from_pretrained(g,{progress_callback:$=null,config:H=null,cache_dir:Fe=null,local_files_only:Pe=!1,revision:pt="main",model_file_name:kt=null,subfolder:zt="onnx",device:ur=null,dtype:cr=null,use_external_data_format:Er=null,session_options:tr={}}={}){let ir={progress_callback:$,config:H,cache_dir:Fe,local_files_only:Pe,revision:pt,model_file_name:kt,subfolder:zt,device:ur,dtype:cr,use_external_data_format:Er,session_options:tr};if(ir.config=await x.AutoConfig.from_pretrained(g,ir),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let yr of this.MODEL_CLASS_MAPPINGS){const xr=yr.get(ir.config.model_type);if(xr)return await xr[1].from_pretrained(g,ir)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${ir.config.model_type}", attempting to construct from base class.`),await re.from_pretrained(g,ir);throw Error(`Unsupported model type: ${ir.config.model_type}`)}}xe(Ir,"MODEL_CLASS_MAPPINGS",null),xe(Ir,"BASE_IF_FAIL",!1);const Hu=new Map([["bert",["BertModel",ot]],["nomic_bert",["NomicBertModel",$e]],["roformer",["RoFormerModel",qe]],["electra",["ElectraModel",Ye]],["esm",["EsmModel",qr]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",K]],["deberta",["DebertaModel",nt]],["deberta-v2",["DebertaV2Model",Vt]],["mpnet",["MPNetModel",Vs]],["albert",["AlbertModel",Qn]],["distilbert",["DistilBertModel",Tr]],["roberta",["RobertaModel",hr]],["xlm",["XLMModel",Hr]],["xlm-roberta",["XLMRobertaModel",Mr]],["clap",["ClapModel",Fl]],["clip",["CLIPModel",Oa]],["clipseg",["CLIPSegModel",Na]],["chinese_clip",["ChineseCLIPModel",Ra]],["siglip",["SiglipModel",ds]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",Us]],["wav2vec2",["Wav2Vec2Model",gl]],["wav2vec2-bert",["Wav2Vec2BertModel",ea]],["unispeech",["UniSpeechModel",Zi]],["unispeech-sat",["UniSpeechSatModel",Zs]],["hubert",["HubertModel",ju]],["wavlm",["WavLMModel",xl]],["audio-spectrogram-transformer",["ASTModel",Ft]],["vits",["VitsModel",ua]],["pyannote",["PyAnnoteModel",Qi]],["wespeaker-resnet",["WeSpeakerResNetModel",Yi]],["detr",["DetrModel",Oo]],["rt_detr",["RTDetrModel",Lo]],["table-transformer",["TableTransformerModel",No]],["vit",["ViTModel",wo]],["fastvit",["FastViTModel",bo]],["mobilevit",["MobileViTModel",Co]],["mobilevitv2",["MobileViTV2Model",Bu]],["owlvit",["OwlViTModel",So]],["owlv2",["Owlv2Model",Po]],["beit",["BeitModel",Io]],["deit",["DeiTModel",Uo]],["convnext",["ConvNextModel",tl]],["convnextv2",["ConvNextV2Model",sl]],["dinov2",["Dinov2Model",al]],["resnet",["ResNetModel",Go]],["swin",["SwinModel",Ho]],["swin2sr",["Swin2SRModel",Xo]],["donut-swin",["DonutSwinModel",Gi]],["yolos",["YolosModel",ll]],["dpt",["DPTModel",Vi]],["glpn",["GLPNModel",Zo]],["hifigan",["SpeechT5HifiGan",sa]],["efficientnet",["EfficientNetModel",Rl]],["mobilenet_v1",["MobileNetV1Model",jl]],["mobilenet_v2",["MobileNetV2Model",Vl]],["mobilenet_v3",["MobileNetV3Model",Wl]],["mobilenet_v4",["MobileNetV4Model",Ps]]]),Ku=new Map([["t5",["T5Model",bs]],["longt5",["LongT5Model",vs]],["mt5",["MT5Model",Ts]],["bart",["BartModel",Me]],["mbart",["MBartModel",le]],["marian",["MarianModel",Lu]],["whisper",["WhisperModel",Ut]],["m2m_100",["M2M100Model",ml]],["blenderbot",["BlenderbotModel",wt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),Xu=new Map([["bloom",["BloomModel",ho]],["gpt2",["GPT2Model",Va]],["gptj",["GPTJModel",Ka]],["gpt_bigcode",["GPTBigCodeModel",Qa]],["gpt_neo",["GPTNeoModel",Wa]],["gpt_neox",["GPTNeoXModel",qa]],["codegen",["CodeGenModel",Ya]],["llama",["LlamaModel",Cn]],["cohere",["CohereModel",Ja]],["gemma",["GemmaModel",to]],["gemma2",["Gemma2Model",no]],["openelm",["OpenELMModel",io]],["qwen2",["Qwen2Model",oo]],["phi",["PhiModel",uo]],["phi3",["Phi3Model",po]],["mpt",["MptModel",Du]],["opt",["OPTModel",_o]],["mistral",["MistralModel",ri]],["starcoder2",["Starcoder2Model",si]],["falcon",["FalconModel",Al]],["stablelm",["StableLmModel",ca]]]),ii=new Map([["speecht5",["SpeechT5ForSpeechToText",Sl]],["whisper",["WhisperForConditionalGeneration",fi]]]),Gl=new Map([["speecht5",["SpeechT5ForTextToSpeech",Vu]]]),ql=new Map([["vits",["VitsModel",ua]],["musicgen",["MusicgenForConditionalGeneration",fa]]]),Hl=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",Xe]],["electra",["ElectraForSequenceClassification",At]],["esm",["EsmForSequenceClassification",Fn]],["convbert",["ConvBertForSequenceClassification",W]],["camembert",["CamembertForSequenceClassification",Be]],["deberta",["DebertaForSequenceClassification",ht]],["deberta-v2",["DebertaV2ForSequenceClassification",Ht]],["mpnet",["MPNetForSequenceClassification",gs]],["albert",["AlbertForSequenceClassification",is]],["distilbert",["DistilBertForSequenceClassification",Ur]],["roberta",["RobertaForSequenceClassification",Yr]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",mr]],["bart",["BartForSequenceClassification",F]],["mbart",["MBartForSequenceClassification",Ie]],["mobilebert",["MobileBertForSequenceClassification",Pr]],["squeezebert",["SqueezeBertForSequenceClassification",kn]]]),Qu=new Map([["bert",["BertForTokenClassification",xt]],["roformer",["RoFormerForTokenClassification",lt]],["electra",["ElectraForTokenClassification",mt]],["esm",["EsmForTokenClassification",Lr]],["convbert",["ConvBertForTokenClassification",S]],["camembert",["CamembertForTokenClassification",Ae]],["deberta",["DebertaForTokenClassification",Tt]],["deberta-v2",["DebertaV2ForTokenClassification",Xt]],["mpnet",["MPNetForTokenClassification",ws]],["distilbert",["DistilBertForTokenClassification",Cr]],["roberta",["RobertaForTokenClassification",He]],["xlm",["XLMForTokenClassification",mn]],["xlm-roberta",["XLMRobertaForTokenClassification",Ar]]]),ya=new Map([["t5",["T5ForConditionalGeneration",Ms]],["longt5",["LongT5ForConditionalGeneration",xs]],["mt5",["MT5ForConditionalGeneration",Dr]],["bart",["BartForConditionalGeneration",_]],["mbart",["MBartForConditionalGeneration",ue]],["marian",["MarianMTModel",fl]],["m2m_100",["M2M100ForConditionalGeneration",_l]],["blenderbot",["BlenderbotForConditionalGeneration",Pt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",sr]]]),ai=new Map([["bloom",["BloomForCausalLM",fo]],["gpt2",["GPT2LMHeadModel",Ua]],["gptj",["GPTJForCausalLM",Xa]],["gpt_bigcode",["GPTBigCodeForCausalLM",zu]],["gpt_neo",["GPTNeoForCausalLM",Ga]],["gpt_neox",["GPTNeoXForCausalLM",Ha]],["codegen",["CodeGenForCausalLM",Gs]],["llama",["LlamaForCausalLM",Za]],["cohere",["CohereForCausalLM",eo]],["gemma",["GemmaForCausalLM",ro]],["gemma2",["Gemma2ForCausalLM",so]],["openelm",["OpenELMForCausalLM",ao]],["qwen2",["Qwen2ForCausalLM",lo]],["phi",["PhiForCausalLM",co]],["phi3",["Phi3ForCausalLM",ki]],["mpt",["MptForCausalLM",mo]],["opt",["OPTForCausalLM",go]],["mbart",["MBartForCausalLM",_t]],["mistral",["MistralForCausalLM",ni]],["starcoder2",["Starcoder2ForCausalLM",oa]],["falcon",["FalconForCausalLM",Il]],["trocr",["TrOCRForCausalLM",Pl]],["stablelm",["StableLmForCausalLM",Ll]]]),Kl=new Map([["bert",["BertForMaskedLM",Re]],["roformer",["RoFormerForMaskedLM",Ve]],["electra",["ElectraForMaskedLM",et]],["esm",["EsmForMaskedLM",Un]],["convbert",["ConvBertForMaskedLM",M]],["camembert",["CamembertForMaskedLM",we]],["deberta",["DebertaForMaskedLM",Mt]],["deberta-v2",["DebertaV2ForMaskedLM",Nt]],["mpnet",["MPNetForMaskedLM",_s]],["albert",["AlbertForMaskedLM",Qt]],["distilbert",["DistilBertForMaskedLM",Et]],["roberta",["RobertaForMaskedLM",on]],["xlm",["XLMWithLMHeadModel",dn]],["xlm-roberta",["XLMRobertaForMaskedLM",St]],["mobilebert",["MobileBertForMaskedLM",Sn]],["squeezebert",["SqueezeBertForMaskedLM",ss]]]),Xl=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",ft]],["electra",["ElectraForQuestionAnswering",Se]],["convbert",["ConvBertForQuestionAnswering",Q]],["camembert",["CamembertForQuestionAnswering",Ne]],["deberta",["DebertaForQuestionAnswering",Rt]],["deberta-v2",["DebertaV2ForQuestionAnswering",er]],["mpnet",["MPNetForQuestionAnswering",ys]],["albert",["AlbertForQuestionAnswering",as]],["distilbert",["DistilBertForQuestionAnswering",Ze]],["roberta",["RobertaForQuestionAnswering",yn]],["xlm",["XLMForQuestionAnswering",Jr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",jr]],["mobilebert",["MobileBertForQuestionAnswering",Wn]],["squeezebert",["SqueezeBertForQuestionAnswering",zn]]]),ba=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",mi]]]),kd=new Map([["llava",["LlavaForConditionalGeneration",us]],["moondream1",["Moondream1ForConditionalGeneration",or]],["florence2",["Florence2ForConditionalGeneration",_i]]]),Yu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",mi]]]),Ql=new Map([["vit",["ViTForImageClassification",yo]],["fastvit",["FastViTForImageClassification",Mo]],["mobilevit",["MobileViTForImageClassification",$o]],["mobilevitv2",["MobileViTV2ForImageClassification",Eo]],["beit",["BeitForImageClassification",Fo]],["deit",["DeiTForImageClassification",Wo]],["convnext",["ConvNextForImageClassification",rl]],["convnextv2",["ConvNextV2ForImageClassification",il]],["dinov2",["Dinov2ForImageClassification",ol]],["resnet",["ResNetForImageClassification",qo]],["swin",["SwinForImageClassification",Ko]],["segformer",["SegformerForImageClassification",Dl]],["efficientnet",["EfficientNetForImageClassification",Nl]],["mobilenet_v1",["MobileNetV1ForImageClassification",Gu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ul]],["mobilenet_v3",["MobileNetV3ForImageClassification",qu]],["mobilenet_v4",["MobileNetV4ForImageClassification",wa]]]),Zu=new Map([["detr",["DetrForObjectDetection",zo]],["rt_detr",["RTDetrForObjectDetection",Ys]],["table-transformer",["TableTransformerForObjectDetection",jo]],["yolos",["YolosForObjectDetection",ul]]]),Yl=new Map([["owlvit",["OwlViTForObjectDetection",ko]],["owlv2",["Owlv2ForObjectDetection",Ao]]]),Zl=new Map([["detr",["DetrForSegmentation",Do]],["clipseg",["CLIPSegForImageSegmentation",ja]]]),Jl=new Map([["segformer",["SegformerForSemanticSegmentation",Bl]]]),eu=new Map([["sam",["SamModel",pl]]]),Ju=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ru]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ti]],["unispeech",["UniSpeechForCTC",wl]],["unispeech-sat",["UniSpeechSatForCTC",Ji]],["wavlm",["WavLMForCTC",ra]],["hubert",["HubertForCTC",vl]]]),tu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Hn]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Ml]],["unispeech",["UniSpeechForSequenceClassification",yl]],["unispeech-sat",["UniSpeechSatForSequenceClassification",bl]],["wavlm",["WavLMForSequenceClassification",Tl]],["hubert",["HubertForSequenceClassification",ta]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ws]]]),ru=new Map([["wavlm",["WavLMForXVector",Cl]]]),nu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Js]],["wavlm",["WavLMForAudioFrameClassification",$l]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Kn]],["pyannote",["PyAnnoteForAudioFrameClassification",Xn]]]),su=new Map([["vitmatte",["VitMatteForImageMatting",xo]]]),ed=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ni]]]),iu=new Map([["dpt",["DPTForDepthEstimation",Ui]],["depth_anything",["DepthAnythingForDepthEstimation",Yo]],["glpn",["GLPNForDepthEstimation",Jo]]]),au=new Map([["clip",["CLIPVisionModelWithProjection",za]],["siglip",["SiglipVisionModel",Ba]]]),ou=[[Hu,G.EncoderOnly],[Ku,G.EncoderDecoder],[Xu,G.DecoderOnly],[Hl,G.EncoderOnly],[Qu,G.EncoderOnly],[ya,G.Seq2Seq],[ii,G.Seq2Seq],[ai,G.DecoderOnly],[Kl,G.EncoderOnly],[Xl,G.EncoderOnly],[ba,G.Vision2Seq],[kd,G.ImageTextToText],[Ql,G.EncoderOnly],[Zl,G.EncoderOnly],[Jl,G.EncoderOnly],[su,G.EncoderOnly],[ed,G.EncoderOnly],[iu,G.EncoderOnly],[Zu,G.EncoderOnly],[Yl,G.EncoderOnly],[eu,G.MaskGeneration],[Ju,G.EncoderOnly],[tu,G.EncoderOnly],[Gl,G.Seq2Seq],[ql,G.EncoderOnly],[ru,G.EncoderOnly],[nu,G.EncoderOnly],[au,G.EncoderOnly]];for(const[m,g]of ou)for(const[$,H]of m.values())ie.set($,g),L.set(H,$),fe.set($,H);const td=[["MusicgenForConditionalGeneration",fa,G.Musicgen],["CLIPTextModelWithProjection",Pn,G.EncoderOnly],["SiglipTextModel",Da,G.EncoderOnly],["ClapTextModelWithProjection",Ol,G.EncoderOnly],["ClapAudioModelWithProjection",zl,G.EncoderOnly]];for(const[m,g,$]of td)ie.set(m,$),L.set(g,m),fe.set(m,g);class lu extends Ir{}xe(lu,"MODEL_CLASS_MAPPINGS",ou.map(g=>g[0])),xe(lu,"BASE_IF_FAIL",!0);class ln extends Ir{}xe(ln,"MODEL_CLASS_MAPPINGS",[Hl]);class uu extends Ir{}xe(uu,"MODEL_CLASS_MAPPINGS",[Qu]);class du extends Ir{}xe(du,"MODEL_CLASS_MAPPINGS",[ya]);class Ma extends Ir{}xe(Ma,"MODEL_CLASS_MAPPINGS",[ii]);class cu extends Ir{}xe(cu,"MODEL_CLASS_MAPPINGS",[Gl]);class As extends Ir{}xe(As,"MODEL_CLASS_MAPPINGS",[ql]);class pu extends Ir{}xe(pu,"MODEL_CLASS_MAPPINGS",[ai]);class hu extends Ir{}xe(hu,"MODEL_CLASS_MAPPINGS",[Kl]);class va extends Ir{}xe(va,"MODEL_CLASS_MAPPINGS",[Xl]);class fu extends Ir{}xe(fu,"MODEL_CLASS_MAPPINGS",[ba]);class mu extends Ir{}xe(mu,"MODEL_CLASS_MAPPINGS",[Ql]);class xa extends Ir{}xe(xa,"MODEL_CLASS_MAPPINGS",[Zl]);class _u extends Ir{}xe(_u,"MODEL_CLASS_MAPPINGS",[Jl]);class gu extends Ir{}xe(gu,"MODEL_CLASS_MAPPINGS",[Zu]);class wu extends Ir{}xe(wu,"MODEL_CLASS_MAPPINGS",[Yl]);class Ta extends Ir{}xe(Ta,"MODEL_CLASS_MAPPINGS",[eu]);class yu extends Ir{}xe(yu,"MODEL_CLASS_MAPPINGS",[Ju]);class bu extends Ir{}xe(bu,"MODEL_CLASS_MAPPINGS",[tu]);class Ca extends Ir{}xe(Ca,"MODEL_CLASS_MAPPINGS",[ru]);class Mu extends Ir{}xe(Mu,"MODEL_CLASS_MAPPINGS",[nu]);class rd extends Ir{}xe(rd,"MODEL_CLASS_MAPPINGS",[Yu]);class vu extends Ir{}xe(vu,"MODEL_CLASS_MAPPINGS",[su]);class xu extends Ir{}xe(xu,"MODEL_CLASS_MAPPINGS",[ed]);class Tu extends Ir{}xe(Tu,"MODEL_CLASS_MAPPINGS",[iu]);class Cu extends Ir{}xe(Cu,"MODEL_CLASS_MAPPINGS",[au]);class Pd extends Ke{constructor({logits:g,past_key_values:$,encoder_outputs:H,decoder_attentions:Fe=null,cross_attentions:Pe=null}){super(),this.logits=g,this.past_key_values=$,this.encoder_outputs=H,this.decoder_attentions=Fe,this.cross_attentions=Pe}}class lr extends Ke{constructor({logits:g}){super(),this.logits=g}}class $u extends Ke{constructor({logits:g,embeddings:$}){super(),this.logits=g,this.embeddings=$}}class Qr extends Ke{constructor({logits:g}){super(),this.logits=g}}class tn extends Ke{constructor({logits:g}){super(),this.logits=g}}class rn extends Ke{constructor({start_logits:g,end_logits:$}){super(),this.start_logits=g,this.end_logits=$}}class Zn extends Ke{constructor({logits:g}){super(),this.logits=g}}class nd extends Ke{constructor({logits:g,past_key_values:$}){super(),this.logits=g,this.past_key_values=$}}class Eu extends Ke{constructor({alphas:g}){super(),this.alphas=g}}class sd extends Ke{constructor({waveform:g,spectrogram:$}){super(),this.waveform=g,this.spectrogram=$}}},"./src/models/whisper/common_whisper.js":($t,me,l)=>{l.r(me),l.d(me,{WHISPER_LANGUAGE_MAPPING:()=>X,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ye,whisper_language_to_code:()=>ve});const x=[["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"]],X=new Map(x),ye=new Map([...x.map(([Te,B])=>[B,Te]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ve(Te){Te=Te.toLowerCase();let B=ye.get(Te);if(B===void 0)if(X.has(Te))B=Te;else{const N=Te.length===2?X.keys():X.values();throw new Error(`Language "${Te}" is not supported. Must be one of: ${JSON.stringify(N)}`)}return B}},"./src/models/whisper/generation_whisper.js":($t,me,l)=>{l.r(me),l.d(me,{WhisperGenerationConfig:()=>X});var x=l("./src/generation/configuration_utils.js");class X extends x.GenerationConfig{constructor(){super(...arguments);xe(this,"return_timestamps",null);xe(this,"return_token_timestamps",null);xe(this,"num_frames",null);xe(this,"alignment_heads",null);xe(this,"task",null);xe(this,"language",null);xe(this,"no_timestamps_token_id",null);xe(this,"prompt_ids",null);xe(this,"is_multilingual",null);xe(this,"lang_to_id",null);xe(this,"task_to_id",null);xe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":($t,me,l)=>{l.r(me),l.d(me,{TensorOpRegistry:()=>ve});var x=l("./src/backends/onnx.js"),X=l("./src/utils/tensor.js");const ye=async(Te,B,E)=>{const N=await(0,x.createInferenceSession)(new Uint8Array(Te),B);return async P=>{const te=Object.fromEntries(Object.entries(P).map(([se,ae])=>[se,ae.ort_tensor])),J=await N.run(te);return Array.isArray(E)?E.map(se=>new X.Tensor(J[se])):new X.Tensor(J[E])}};class ve{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ye([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=ye([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=ye([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=ye([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=ye([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=ye([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,["v","i"])),this._top_k}}xe(ve,"session_options",{})},"./src/pipelines.js":($t,me,l)=>{l.r(me),l.d(me,{AudioClassificationPipeline:()=>ke,AutomaticSpeechRecognitionPipeline:()=>Je,DepthEstimationPipeline:()=>rt,DocumentQuestionAnsweringPipeline:()=>re,FeatureExtractionPipeline:()=>be,FillMaskPipeline:()=>ie,ImageClassificationPipeline:()=>bt,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>_e,ImageToImagePipeline:()=>ct,ImageToTextPipeline:()=>Ue,ObjectDetectionPipeline:()=>pe,Pipeline:()=>ae,QuestionAnsweringPipeline:()=>G,SummarizationPipeline:()=>L,Text2TextGenerationPipeline:()=>fe,TextClassificationPipeline:()=>D,TextGenerationPipeline:()=>A,TextToAudioPipeline:()=>Ke,TokenClassificationPipeline:()=>ee,TranslationPipeline:()=>O,ZeroShotAudioClassificationPipeline:()=>De,ZeroShotClassificationPipeline:()=>ge,ZeroShotImageClassificationPipeline:()=>V,ZeroShotObjectDetectionPipeline:()=>Ee,pipeline:()=>st});var x=l("./src/tokenizers.js"),X=l("./src/models.js"),ye=l("./src/processors.js"),ve=l("./src/utils/generic.js"),Te=l("./src/utils/core.js"),B=l("./src/utils/maths.js"),E=l("./src/utils/audio.js"),N=l("./src/utils/tensor.js"),P=l("./src/utils/image.js");async function te(ze){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map(ne=>P.RawImage.read(ne)))}async function J(ze,ne){return Array.isArray(ze)||(ze=[ze]),await Promise.all(ze.map($e=>typeof $e=="string"||$e instanceof URL?(0,E.read_audio)($e,ne):$e instanceof Float64Array?new Float32Array($e):$e))}function se(ze,ne){ne&&(ze=ze.map(Xe=>Xe|0));const[$e,je,qe,Ve]=ze;return{xmin:$e,ymin:je,xmax:qe,ymax:Ve}}class ae extends ve.Callable{constructor({task:ne,model:$e,tokenizer:je=null,processor:qe=null}){super(),this.task=ne,this.model=$e,this.tokenizer=je,this.processor=qe}async dispose(){await this.model.dispose()}}class D extends ae{constructor(ne){super(ne)}async _call(ne,{top_k:$e=1}={}){const je=this.tokenizer(ne,{padding:!0,truncation:!0}),qe=await this.model(je),Ve=this.model.config.problem_type==="multi_label_classification"?ft=>ft.sigmoid():ft=>new N.Tensor("float32",(0,B.softmax)(ft.data),ft.dims),Xe=this.model.config.id2label,lt=[];for(const ft of qe.logits){const gt=Ve(ft),vt=await(0,N.topk)(gt,$e),M=vt[0].tolist(),S=vt[1].tolist().map((Q,he)=>({label:Xe?Xe[Q]:`LABEL_${Q}`,score:M[he]}));$e===1?lt.push(...S):lt.push(S)}return Array.isArray(ne)||$e===1?lt:lt[0]}}class ee extends ae{constructor(ne){super(ne)}async _call(ne,{ignore_labels:$e=["O"]}={}){const je=Array.isArray(ne),qe=this.tokenizer(je?ne:[ne],{padding:!0,truncation:!0}),Xe=(await this.model(qe)).logits,lt=this.model.config.id2label,ft=[];for(let gt=0;gtmt==this.tokenizer.sep_token_id);ft[M].map((mt,Se)=>mt==1&&(Se===0||Se>S&>.findIndex(C=>C==W[Se])===-1));const Q=Ve[M].tolist(),he=Xe[M].tolist();for(let mt=1;mtSe==W[mt])!==-1)&&(Q[mt]=-1/0,he[mt]=-1/0);const Ye=(0,B.softmax)(Q).map((mt,Se)=>[mt,Se]),et=(0,B.softmax)(he).map((mt,Se)=>[mt,Se]);Ye[0][0]=0,et[0][0]=0;const At=(0,Te.product)(Ye,et).filter(mt=>mt[0][1]<=mt[1][1]).map(mt=>[mt[0][1],mt[1][1],mt[0][0]*mt[1][0]]).sort((mt,Se)=>Se[2]-mt[2]);for(let mt=0;mtQ==this.tokenizer.mask_token_id);if(gt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const vt=qe[lt][gt],M=await(0,N.topk)(new N.Tensor("float32",(0,B.softmax)(vt.data),vt.dims),$e),W=M[0].tolist(),S=M[1].tolist();Ve.push(S.map((Q,he)=>{const Ye=ft.slice();return Ye[gt]=Q,{score:W[he],token:Number(Q),token_str:this.tokenizer.model.vocab[Q],sequence:this.tokenizer.decode(Ye,{skip_special_tokens:!0})}}))}return Array.isArray(ne)?Ve:Ve[0]}}class fe extends ae{constructor($e){super($e);xe(this,"_key","generated_text")}async _call($e,je={}){Array.isArray($e)||($e=[$e]),this.model.config.prefix&&($e=$e.map(gt=>this.model.config.prefix+gt));const qe=this.model.config.task_specific_params;qe&&qe[this.task]&&qe[this.task].prefix&&($e=$e.map(gt=>qe[this.task].prefix+gt));const Ve=this.tokenizer,Xe={padding:!0,truncation:!0};let lt;this instanceof O&&"_build_translation_inputs"in Ve?lt=Ve._build_translation_inputs($e,Xe,je):lt=Ve($e,Xe);const ft=await this.model.generate({...lt,...je});return Ve.batch_decode(ft,{skip_special_tokens:!0}).map(gt=>({[this._key]:gt}))}}class L extends fe{constructor($e){super($e);xe(this,"_key","summary_text")}}class O extends fe{constructor($e){super($e);xe(this,"_key","translation_text")}}function j(ze){return Array.isArray(ze)&&ze.every(ne=>"role"in ne&&"content"in ne)}class A extends ae{constructor(ne){super(ne)}async _call(ne,$e={}){let je=!1,qe=!1,Ve;if(typeof ne=="string")Ve=ne=[ne];else if(Array.isArray(ne)&&ne.every(S=>typeof S=="string"))je=!0,Ve=ne;else{if(j(ne))ne=[ne];else if(Array.isArray(ne)&&ne.every(j))je=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");qe=!0,Ve=ne.map(S=>this.tokenizer.apply_chat_template(S,{tokenize:!1,add_generation_prompt:!0}))}const Xe=$e.add_special_tokens??!1,lt=qe?!1:$e.return_full_text??!0;this.tokenizer.padding_side="left";const ft=this.tokenizer(Ve,{add_special_tokens:Xe,padding:!0,truncation:!0}),gt=await this.model.generate({...ft,...$e}),vt=this.tokenizer.batch_decode(gt,{skip_special_tokens:!0});let M;!lt&&ft.input_ids.dims.at(-1)>0&&(M=this.tokenizer.batch_decode(ft.input_ids,{skip_special_tokens:!0}).map(S=>S.length));const W=Array.from({length:ne.length},S=>[]);for(let S=0;S[$e.toLowerCase(),je])),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)}async _call(ne,$e,{hypothesis_template:je="This example is {}.",multi_label:qe=!1}={}){const Ve=Array.isArray(ne);Ve||(ne=[ne]),Array.isArray($e)||($e=[$e]);const Xe=$e.map(gt=>je.replace("{}",gt)),lt=qe||$e.length===1,ft=[];for(const gt of ne){const vt=[];for(const S of Xe){const Q=this.tokenizer(gt,{text_pair:S,padding:!0,truncation:!0}),he=await this.model(Q);lt?vt.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):vt.push(he.logits.data[this.entailment_id])}const W=(lt?vt.map(S=>(0,B.softmax)(S)[1]):(0,B.softmax)(vt)).map((S,Q)=>[S,Q]).sort((S,Q)=>Q[0]-S[0]);ft.push({sequence:gt,labels:W.map(S=>$e[S[1]]),scores:W.map(S=>S[0])})}return Ve?ft:ft[0]}}class be extends ae{constructor(ne){super(ne)}async _call(ne,{pooling:$e="none",normalize:je=!1,quantize:qe=!1,precision:Ve="binary"}={}){const Xe=this.tokenizer(ne,{padding:!0,truncation:!0}),lt=await this.model(Xe);let ft=lt.last_hidden_state??lt.logits??lt.token_embeddings;if($e!=="none")if($e==="mean")ft=(0,N.mean_pooling)(ft,Xe.attention_mask);else if($e==="cls")ft=ft.slice(null,0);else throw Error(`Pooling method '${$e}' not supported.`);return je&&(ft=ft.normalize(2,-1)),qe&&(ft=(0,N.quantize_embeddings)(ft,Ve)),ft}}class Ce extends ae{constructor(ne){super(ne)}async _call(ne,{pool:$e=null}={}){const je=await te(ne),{pixel_values:qe}=await this.processor(je),Ve=await this.model({pixel_values:qe});let Xe;if($e){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.");Xe=Ve.pooler_output}else Xe=Ve.last_hidden_state??Ve.logits??Ve.image_embeds;return Xe}}class ke extends ae{constructor(ne){super(ne)}async _call(ne,{top_k:$e=5}={}){const je=this.processor.feature_extractor.config.sampling_rate,qe=await J(ne,je),Ve=this.model.config.id2label,Xe=[];for(const lt of qe){const ft=await this.processor(lt),vt=(await this.model(ft)).logits[0],M=await(0,N.topk)(new N.Tensor("float32",(0,B.softmax)(vt.data),vt.dims),$e),W=M[0].tolist(),Q=M[1].tolist().map((he,Ye)=>({label:Ve?Ve[he]:`LABEL_${he}`,score:W[Ye]}));Xe.push(Q)}return Array.isArray(ne)?Xe:Xe[0]}}class De extends ae{constructor(ne){super(ne)}async _call(ne,$e,{hypothesis_template:je="This is a sound of {}."}={}){const qe=!Array.isArray(ne);qe&&(ne=[ne]);const Ve=$e.map(vt=>je.replace("{}",vt)),Xe=this.tokenizer(Ve,{padding:!0,truncation:!0}),lt=this.processor.feature_extractor.config.sampling_rate,ft=await J(ne,lt),gt=[];for(const vt of ft){const M=await this.processor(vt),W=await this.model({...Xe,...M}),S=(0,B.softmax)(W.logits_per_audio.data);gt.push([...S].map((Q,he)=>({score:Q,label:$e[he]})))}return qe?gt[0]:gt}}class Je extends ae{constructor(ne){super(ne)}async _call(ne,$e={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ne,$e);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ne,$e);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ne,$e){$e.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),$e.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const je=!Array.isArray(ne);je&&(ne=[ne]);const qe=this.processor.feature_extractor.config.sampling_rate,Ve=await J(ne,qe),Xe=[];for(const lt of Ve){const ft=await this.processor(lt),vt=(await this.model(ft)).logits[0],M=[];for(const S of vt)M.push((0,B.max)(S.data)[1]);const W=this.tokenizer.decode(M);Xe.push({text:W})}return je?Xe[0]:Xe}async _call_whisper(ne,$e){const je=$e.return_timestamps??!1,qe=$e.chunk_length_s??0,Ve=$e.force_full_sequences??!1;let Xe=$e.stride_length_s??null;const lt={...$e};je==="word"&&(lt.return_token_timestamps=!0,lt.return_timestamps=!1);const ft=!Array.isArray(ne);ft&&(ne=[ne]);const gt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,vt=this.processor.feature_extractor.config.hop_length,M=this.processor.feature_extractor.config.sampling_rate,W=await J(ne,M),S=[];for(const Q of W){let he=[];if(qe>0){if(Xe===null)Xe=qe/6;else if(qe<=Xe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const At=M*qe,mt=M*Xe,Se=At-2*mt;let C=0;for(;;){const K=C+At,we=Q.subarray(C,K),Be=await this.processor(we),Ae=C===0,Ne=K>=Q.length;if(he.push({stride:[we.length,Ae?0:mt,Ne?0:mt],input_features:Be.input_features,is_last:Ne}),Ne)break;C+=Se}}else he=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const At of he){lt.num_frames=Math.floor(At.stride[0]/vt);const mt=await this.model.generate({inputs:At.input_features,...lt});je==="word"?(At.tokens=mt.sequences.tolist()[0],At.token_timestamps=mt.token_timestamps.tolist()[0].map(Se=>(0,B.round)(Se,2))):At.tokens=mt[0].tolist(),At.stride=At.stride.map(Se=>Se/M)}const[Ye,et]=this.tokenizer._decode_asr(he,{time_precision:gt,return_timestamps:je,force_full_sequences:Ve});S.push({text:Ye,...et})}return ft?S[0]:S}}class Ue extends ae{constructor(ne){super(ne)}async _call(ne,$e={}){const je=Array.isArray(ne),qe=await te(ne),{pixel_values:Ve}=await this.processor(qe),Xe=[];for(const lt of Ve){lt.dims=[1,...lt.dims];const ft=await this.model.generate({inputs:lt,...$e}),gt=this.tokenizer.batch_decode(ft,{skip_special_tokens:!0}).map(vt=>({generated_text:vt.trim()}));Xe.push(gt)}return je?Xe:Xe[0]}}class bt extends ae{constructor(ne){super(ne)}async _call(ne,{top_k:$e=5}={}){const je=await te(ne),{pixel_values:qe}=await this.processor(je),Ve=await this.model({pixel_values:qe}),Xe=this.model.config.id2label,lt=[];for(const ft of Ve.logits){const gt=await(0,N.topk)(new N.Tensor("float32",(0,B.softmax)(ft.data),ft.dims),$e),vt=gt[0].tolist(),W=gt[1].tolist().map((S,Q)=>({label:Xe?Xe[S]:`LABEL_${S}`,score:vt[Q]}));lt.push(W)}return Array.isArray(ne)?lt:lt[0]}}class _e extends ae{constructor(ne){super(ne),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ne,{threshold:$e=.5,mask_threshold:je=.5,overlap_mask_area_threshold:qe=.8,label_ids_to_fuse:Ve=null,target_sizes:Xe=null,subtask:lt=null}={}){if(Array.isArray(ne)&&ne.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const gt=await te(ne),vt=gt.map(et=>[et.height,et.width]),{pixel_values:M,pixel_mask:W}=await this.processor(gt),S=await this.model({pixel_values:M,pixel_mask:W});let Q=null;if(lt!==null)Q=this.subtasks_mapping[lt];else for(let[et,At]of Object.entries(this.subtasks_mapping))if(At in this.processor.feature_extractor){Q=this.processor.feature_extractor[At].bind(this.processor.feature_extractor),lt=et;break}const he=this.model.config.id2label,Ye=[];if(lt==="panoptic"||lt==="instance"){const et=Q(S,$e,je,qe,Ve,Xe??vt)[0],At=et.segmentation;for(const mt of et.segments_info){const Se=new Uint8ClampedArray(At.data.length);for(let K=0;Kje.replace("{}",W)),lt=this.tokenizer(Xe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ft}=await this.processor(Ve),gt=await this.model({...lt,pixel_values:ft}),vt=this.model.config.model_type==="siglip"?W=>W.sigmoid().data:W=>(0,B.softmax)(W.data),M=[];for(const W of gt.logits_per_image){const Q=[...vt(W)].map((he,Ye)=>({score:he,label:$e[Ye]}));Q.sort((he,Ye)=>Ye.score-he.score),M.push(Q)}return qe?M:M[0]}}class pe extends ae{constructor(ne){super(ne)}async _call(ne,{threshold:$e=.9,percentage:je=!1}={}){const qe=Array.isArray(ne);if(qe&&ne.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ve=await te(ne),Xe=je?null:Ve.map(S=>[S.height,S.width]),{pixel_values:lt,pixel_mask:ft}=await this.processor(Ve),gt=await this.model({pixel_values:lt,pixel_mask:ft}),vt=this.processor.feature_extractor.post_process_object_detection(gt,$e,Xe),M=this.model.config.id2label,W=vt.map(S=>S.boxes.map((Q,he)=>({score:S.scores[he],label:M[S.classes[he]],box:se(Q,!je)})));return qe?W:W[0]}}class Ee extends ae{constructor(ne){super(ne)}async _call(ne,$e,{threshold:je=.1,top_k:qe=null,percentage:Ve=!1}={}){const Xe=Array.isArray(ne),lt=await te(ne),ft=this.tokenizer($e,{padding:!0,truncation:!0}),gt=await this.processor(lt),vt=[];for(let M=0;M({score:Ye.scores[mt],label:$e[Ye.classes[mt]],box:se(At,!Ve)})).sort((At,mt)=>mt.score-At.score);qe!==null&&(et=et.slice(0,qe)),vt.push(et)}return Xe?vt:vt[0]}}class re extends ae{constructor(ne){super(ne)}async _call(ne,$e,je={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class Ke extends ae{constructor($e){super($e);xe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=$e.vocoder??null}async _call($e,{speaker_embeddings:je=null}={}){return this.processor?this._call_text_to_spectrogram($e,{speaker_embeddings:je}):this._call_text_to_waveform($e)}async _call_text_to_waveform($e){const je=this.tokenizer($e,{padding:!0,truncation:!0}),{waveform:qe}=await this.model(je),Ve=this.model.config.sampling_rate;return{audio:qe.data,sampling_rate:Ve}}async _call_text_to_spectrogram($e,{speaker_embeddings:je}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await X.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof je=="string"||je instanceof URL)&&(je=new Float32Array(await(await fetch(je)).arrayBuffer())),je instanceof Float32Array)je=new N.Tensor("float32",je,[1,je.length]);else if(!(je instanceof N.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:qe}=this.tokenizer($e,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model.generate_speech(qe,je,{vocoder:this.vocoder}),Xe=this.processor.feature_extractor.config.sampling_rate;return{audio:Ve.data,sampling_rate:Xe}}}class ct extends ae{constructor(ne){super(ne)}async _call(ne){const $e=await te(ne),je=await this.processor($e),qe=await this.model(je),Ve=[];for(const Xe of qe.reconstruction){const lt=Xe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ve.push(P.RawImage.fromTensor(lt))}return Ve.length>1?Ve:Ve[0]}}class rt extends ae{constructor(ne){super(ne)}async _call(ne){const $e=await te(ne),je=await this.processor($e),{predicted_depth:qe}=await this.model(je),Ve=[];for(let Xe=0;Xe<$e.length;++Xe){const lt=(0,N.interpolate)(qe[Xe],$e[Xe].size.reverse(),"bilinear",!1),ft=lt.mul_(255/(0,B.max)(lt.data)[0]).to("uint8");Ve.push({predicted_depth:qe[Xe],depth:P.RawImage.fromTensor(ft)})}return Ve.length>1?Ve:Ve[0]}}const ot=Object.freeze({"text-classification":{tokenizer:x.AutoTokenizer,pipeline:D,model:X.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:x.AutoTokenizer,pipeline:ee,model:X.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:x.AutoTokenizer,pipeline:G,model:X.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:x.AutoTokenizer,pipeline:ie,model:X.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:x.AutoTokenizer,pipeline:L,model:X.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:x.AutoTokenizer,pipeline:O,model:X.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:x.AutoTokenizer,pipeline:fe,model:X.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:x.AutoTokenizer,pipeline:A,model:X.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:x.AutoTokenizer,pipeline:ge,model:X.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ke,model:X.AutoModelForAudioClassification,processor:ye.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:x.AutoTokenizer,pipeline:De,model:X.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:x.AutoTokenizer,pipeline:Je,model:[X.AutoModelForSpeechSeq2Seq,X.AutoModelForCTC],processor:ye.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:x.AutoTokenizer,pipeline:Ke,model:[X.AutoModelForTextToWaveform,X.AutoModelForTextToSpectrogram],processor:[ye.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:x.AutoTokenizer,pipeline:Ue,model:X.AutoModelForVision2Seq,processor:ye.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:bt,model:X.AutoModelForImageClassification,processor:ye.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:_e,model:[X.AutoModelForImageSegmentation,X.AutoModelForSemanticSegmentation],processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:x.AutoTokenizer,pipeline:V,model:X.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:X.AutoModelForObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:x.AutoTokenizer,pipeline:Ee,model:X.AutoModelForZeroShotObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:x.AutoTokenizer,pipeline:re,model:X.AutoModelForDocumentQuestionAnswering,processor:ye.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ct,model:X.AutoModelForImageToImage,processor:ye.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:rt,model:X.AutoModelForDepthEstimation,processor:ye.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:x.AutoTokenizer,pipeline:be,model:X.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ye.AutoProcessor,pipeline:Ce,model:[X.AutoModelForImageFeatureExtraction,X.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Re=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function st(ze,ne=null,{progress_callback:$e=null,config:je=null,cache_dir:qe=null,local_files_only:Ve=!1,revision:Xe="main",device:lt=null,dtype:ft=null,model_file_name:gt=null,session_options:vt={}}={}){ze=Re[ze]??ze;const M=ot[ze.split("_",1)[0]];if(!M)throw Error(`Unsupported pipeline: ${ze}. Must be one of [${Object.keys(ot)}]`);ne||(ne=M.default.model,console.log(`No model specified. Using default model: "${ne}".`));const W={progress_callback:$e,config:je,cache_dir:qe,local_files_only:Ve,revision:Xe,device:lt,dtype:ft,model_file_name:gt,session_options:vt},S=new Map([["tokenizer",M.tokenizer],["model",M.model],["processor",M.processor]]),Q=await xt(S,ne,W);Q.task=ze,(0,Te.dispatchCallback)($e,{status:"ready",task:ze,model:ne});const he=M.pipeline;return new he(Q)}async function xt(ze,ne,$e){const je=Object.create(null),qe=[];for(let[Ve,Xe]of ze.entries()){if(!Xe)continue;let lt;Array.isArray(Xe)?lt=new Promise(async(ft,gt)=>{var M,W;let vt;for(let S of Xe){if(S===null){ft(null);return}try{ft(await S.from_pretrained(ne,$e));return}catch(Q){if((M=Q.message)!=null&&M.includes("Unsupported model type"))vt=Q;else if((W=Q.message)!=null&&W.includes("Could not locate file"))vt=Q;else{gt(Q);return}}}gt(vt)}):lt=Xe.from_pretrained(ne,$e),je[Ve]=lt,qe.push(lt)}await Promise.all(qe);for(let[Ve,Xe]of Object.entries(je))je[Ve]=await Xe;return je}},"./src/processors.js":($t,me,l)=>{l.r(me),l.d(me,{ASTFeatureExtractor:()=>Xe,AutoProcessor:()=>mt,BeitFeatureExtractor:()=>rt,BitImageProcessor:()=>ie,CLIPFeatureExtractor:()=>L,CLIPImageProcessor:()=>O,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>lt,ConvNextFeatureExtractor:()=>ge,ConvNextImageProcessor:()=>be,DPTFeatureExtractor:()=>ee,DPTImageProcessor:()=>G,DeiTFeatureExtractor:()=>ct,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>ot,EfficientNetImageProcessor:()=>De,FeatureExtractor:()=>se,Florence2Processor:()=>At,GLPNFeatureExtractor:()=>fe,ImageFeatureExtractor:()=>ae,MobileNetV1FeatureExtractor:()=>Je,MobileNetV2FeatureExtractor:()=>Ue,MobileNetV3FeatureExtractor:()=>bt,MobileNetV4FeatureExtractor:()=>_e,MobileViTFeatureExtractor:()=>V,MobileViTImageProcessor:()=>pe,NougatImageProcessor:()=>Re,OwlViTFeatureExtractor:()=>Ee,OwlViTProcessor:()=>et,Owlv2ImageProcessor:()=>re,Processor:()=>M,PyAnnoteFeatureExtractor:()=>ft,PyAnnoteProcessor:()=>he,RTDetrImageProcessor:()=>Ke,SamImageProcessor:()=>ze,SamProcessor:()=>W,SeamlessM4TFeatureExtractor:()=>Ve,SegformerFeatureExtractor:()=>D,SiglipImageProcessor:()=>A,SpeechT5FeatureExtractor:()=>vt,SpeechT5Processor:()=>Ye,Swin2SRImageProcessor:()=>ne,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>ke,VitMatteImageProcessor:()=>$e,Wav2Vec2FeatureExtractor:()=>qe,Wav2Vec2ProcessorWithLM:()=>Q,WeSpeakerFeatureExtractor:()=>gt,WhisperFeatureExtractor:()=>je,WhisperProcessor:()=>S,YolosFeatureExtractor:()=>xt});var x=l("./src/utils/generic.js"),X=l("./src/utils/core.js"),ye=l("./src/utils/hub.js"),ve=l("./src/utils/maths.js"),Te=l("./src/utils/tensor.js");l("./src/utils/image.js");var B=l("./src/utils/audio.js");function E([Se,C,K,we]){return[Se-K/2,C-we/2,Se+K/2,C+we/2]}function N(Se,C=.5,K=null,we=!1){const Be=Se.logits,Ae=Se.pred_boxes,[Ne,ut,nt]=Be.dims;if(K!==null&&K.length!==Ne)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Mt=[];for(let ht=0;htC&&Xt.push(Wt)}else{let Wt=(0,ve.max)(Ht.data)[1];if(Wt===nt-1||(er=(0,ve.softmax)(Ht.data),er[Wt]Ur*Tt[(Cr+1)%2])),Rt.boxes.push(Tr),Rt.classes.push(Wt),Rt.scores.push(er[Wt])}}Mt.push(Rt)}return Mt}function P(Se,C){var K;if(!(Se instanceof Float32Array||Se instanceof Float64Array))throw new Error(`${C} expects input to be a Float32Array or a Float64Array, but got ${((K=Se==null?void 0:Se.constructor)==null?void 0:K.name)??typeof Se} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function te(Se,C,K=0,we=null){const Be=Se/C;let Ae=(0,ve.bankers_round)(Be)*C;return we!==null&&Ae>we&&(Ae=Math.floor(Be)*C),AeAe?Mt=Math.floor(Ae*nt/Be):Ae>Be&&(nt=Math.floor(Be*Mt/Ae)),await C.resize(Mt,nt,{resample:we}))}async crop_margin(C,K=200){const we=C.clone().grayscale(),Be=(0,ve.min)(we.data)[0],Ne=(0,ve.max)(we.data)[0]-Be;if(Ne===0)return C;const ut=K/255;let nt=we.width,Mt=we.height,ht=0,Tt=0;const Rt=we.data;for(let Qe=0;Qethis.preprocess(Ae)));return{pixel_values:(0,Te.stack)(we.map(Ae=>Ae.pixel_values),0),original_sizes:we.map(Ae=>Ae.original_size),reshaped_input_sizes:we.map(Ae=>Ae.reshaped_input_size)}}}class D extends ae{post_process_semantic_segmentation(C,K=null){const we=C.logits,Be=we.dims[0];if(K!==null&&K.length!==Be)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Ae=[];for(let Ne=0;NeRt[Wt]&&(Rt[Wt]=er[Wt],Qe[Wt]=Xt)}const Vt=new Array(nt.dims[0]),Nt=Tt.data;for(let Xt=0;XtXt!==void 0);Ae.push({segmentation:Tt,labels:Ht})}return Ae}}class ee extends ae{}class G extends ee{}class ie extends ae{}class fe extends ae{}class L extends ae{}class O extends L{}class j extends ae{}class A extends ae{}class ge extends ae{constructor(C){super(C),this.crop_pct=this.config.crop_pct??.875}async resize(C){var we;const K=(we=this.size)==null?void 0:we.shortest_edge;if(K===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(K<384){const Be=Math.floor(K/this.crop_pct),[Ae,Ne]=this.get_resize_output_image_size(C,{shortest_edge:Be});C=await C.resize(Ae,Ne,{resample:this.resample}),C=await C.center_crop(K,K)}else C=await C.resize(K,K,{resample:this.resample});return C}}class be extends ge{}class Ce extends ae{}class ke extends ae{}class De extends ae{constructor(C){super(C),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(K=>K*K))}}class Je extends ae{}class Ue extends ae{}class bt extends ae{}class _e extends ae{}class V extends ae{}class pe extends V{}class Ee extends ae{post_process_object_detection(...C){return N(...C)}}class re extends Ee{}class Ke extends ae{post_process_object_detection(...C){return N(...C)}}class ct extends ae{}class rt extends ae{}class ot extends ae{pad_image(C,K,we,Be={}){const[Ae,Ne,ut]=K;let nt=this.image_mean;Array.isArray(this.image_mean)||(nt=new Array(ut).fill(nt));let Mt=this.image_std;Array.isArray(Mt)||(Mt=new Array(ut).fill(nt));const ht=nt.map((Tt,Rt)=>-Tt/Mt[Rt]);return super.pad_image(C,K,we,{center:!0,constant_values:ht,...Be})}}class Re extends ot{}class st extends ae{async _call(C){const K=await super._call(C),we=[K.pixel_values.dims[0],64,64],Be=new Te.Tensor("int64",new BigInt64Array(we.reduce((Ae,Ne)=>Ae*Ne)).fill(1n),we);return{...K,pixel_mask:Be}}post_process_object_detection(...C){return N(...C)}remove_low_and_no_objects(C,K,we,Be){let Ae=[],Ne=[],ut=[];for(let nt=0;ntwe&&(Ae.push(ht),Ne.push(Qe),ut.push(Tt))}return[Ae,Ne,ut]}check_segment_validity(C,K,we,Be=.5,Ae=.8){let Ne=[],ut=0,nt=0;const Mt=K[we].data;for(let Tt=0;Tt=Be&&++nt;let ht=ut>0&&nt>0;return ht&&(ht=ut/nt>Ae),[ht,Ne]}compute_segments(C,K,we,Be,Ae,Ne=null,ut=null){let[nt,Mt]=ut??C[0].dims,ht=new Te.Tensor("int32",new Int32Array(nt*Mt),[nt,Mt]),Tt=[];if(ut!==null)for(let Ht=0;HtQe[Wt]&&(Rt[Wt]=Ht,Qe[Wt]=er[Wt])}let Vt=0;const Nt=ht.data;for(let Ht=0;HtBe!==K.dims[Ae]))throw Error(`The first ${we.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Te.Tensor("int64",C.flat(1/0).map(BigInt),we)}async _call(C,{input_points:K=null,input_labels:we=null,input_boxes:Be=null}={}){const Ae=await super._call(C);if(K&&(Ae.input_points=this.reshape_input_points(K,Ae.original_sizes,Ae.reshaped_input_sizes)),we){if(!Ae.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Ae.input_labels=this.add_input_labels(we,Ae.input_points)}return Be&&(Ae.input_boxes=this.reshape_input_points(Be,Ae.original_sizes,Ae.reshaped_input_sizes,!0)),Ae}async post_process_masks(C,K,we,{mask_threshold:Be=0,binarize:Ae=!0,pad_size:Ne=null}={}){const ut=[];Ne=Ne??this.pad_size;const nt=[Ne.height,Ne.width];for(let Mt=0;MtBe&&(Vt[Nt]=1);Rt=new Te.Tensor("bool",Vt,Rt.dims)}ut.push(Rt)}return ut}generate_crop_boxes(C,K,{crop_n_layers:we=0,overlap_ratio:Be=.3413333333333333,points_per_crop:Ae=32,crop_n_points_downscale_factor:Ne=1}={}){}}class ne extends ae{pad_image(C,K,we,Be={}){const[Ae,Ne,ut]=K;return super.pad_image(C,K,{width:Ne+(we-Ne%we)%we,height:Ae+(we-Ae%we)%we},{mode:"symmetric",center:!1,constant_values:-1,...Be})}}class $e extends ae{async _call(C,K){Array.isArray(C)||(C=[C]),Array.isArray(K)||(K=[K]);const we=await Promise.all(C.map(Ne=>this.preprocess(Ne))),Be=await Promise.all(K.map(Ne=>this.preprocess(Ne,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Te.stack)(we.map((Ne,ut)=>(0,Te.cat)([Ne.pixel_values,Be[ut].pixel_values],0)),0),original_sizes:we.map(Ne=>Ne.original_size),reshaped_input_sizes:we.map(Ne=>Ne.reshaped_input_size)}}}class je extends se{constructor(C){var K;super(C),(K=this.config).mel_filters??(K.mel_filters=(0,B.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,B.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(C){const K=await(0,B.spectrogram)(C,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),we=K.data,Be=(0,ve.max)(we)[0];for(let Ae=0;Aethis.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`."),K=C.slice(0,this.config.n_samples)):(K=new Float32Array(this.config.n_samples),K.set(C)),{input_features:(await this._extract_fbank_features(K)).unsqueeze_(0)}}}class qe extends se{_zero_mean_unit_var_norm(C){const we=C.reduce((Ae,Ne)=>Ae+Ne,0)/C.length,Be=C.reduce((Ae,Ne)=>Ae+(Ne-we)**2,0)/C.length;return C.map(Ae=>(Ae-we)/Math.sqrt(Be+1e-7))}async _call(C){P(C,"Wav2Vec2FeatureExtractor"),C instanceof Float64Array&&(C=new Float32Array(C));let K=C;this.config.do_normalize&&(K=this._zero_mean_unit_var_norm(K));const we=[1,K.length];return{input_values:new Te.Tensor("float32",K,we),attention_mask:new Te.Tensor("int64",new BigInt64Array(K.length).fill(1n),we)}}}class Ve extends se{constructor(C){super(C);const K=this.config.sampling_rate,we=(0,B.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(K/2),K,null,"kaldi",!0);for(let Be=0;Bewe*32768),(0,B.spectrogram)(C,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:K,transpose:!0})}async _call(C,{padding:K=!0,pad_to_multiple_of:we=2,do_normalize_per_mel_bins:Be=!0,return_attention_mask:Ae=!0}={}){P(C,"SeamlessM4TFeatureExtractor");let Ne=await this._extract_fbank_features(C,this.config.max_length);if(Be){const[Vt,Nt]=Ne.dims,Ht=Ne.data;for(let Xt=0;Xt0){const er=new Float32Array(Nt*(Vt+Xt));er.set(Ht),er.fill(this.config.padding_value,Ht.length);const Wt=Vt+Xt;Ne=new Te.Tensor(Ne.type,er,[Wt,Nt]),Ae&&(ut=new Te.Tensor("int64",new BigInt64Array(Wt),[1,Wt]),ut.data.fill(1n,0,Vt))}}const[nt,Mt]=Ne.dims,ht=this.config.stride;if(nt%ht!==0)throw new Error(`The number of frames (${nt}) must be a multiple of the stride (${ht}).`);const Rt=Ne.view(1,Math.floor(nt/ht),Mt*ht),Qe={input_features:Rt};if(Ae){const Vt=Rt.dims[1],Nt=new BigInt64Array(Vt);if(ut){const Ht=ut.data;for(let Xt=1,er=0;Xt0)if(we==="rand_trunc"){const ut=Math.floor(Math.random()*(Ne+1));C=C.subarray(ut,ut+K),Ae=await this._extract_fbank_features(C,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${we}" not implemented`);else{if(Ne<0){let ut=new Float64Array(K);if(ut.set(C),Be==="repeat")for(let nt=C.length;nt({id:nt,start:Mt*we,end:ht*we,confidence:Tt/(ht-Mt)})))}return Be}}class gt extends se{constructor(C){super(C);const K=this.config.sampling_rate,we=(0,B.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(K/2),K,null,"kaldi",!0);for(let Be=0;BeK*32768),(0,B.spectrogram)(C,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(C){P(C,"WeSpeakerFeatureExtractor");const K=(await this._extract_fbank_features(C)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const we=K.mean(1).data,Be=K.data,[Ae,Ne,ut]=K.dims;for(let nt=0;nt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(C){typeof C=="string"&&(C=[C]);const K=[];for(const we of C)if(this.task_prompts_without_inputs.has(we))K.push(this.task_prompts_without_inputs.get(we));else{for(const[Be,Ae]of this.task_prompts_with_input)if(we.includes(Be)){K.push(Ae.replaceAll("{input}",we).replaceAll(Be,""));break}K.length!==C.length&&K.push(we)}return K}post_process_generation(C,K,we){const Be=this.tasks_answer_post_processing_type.get(K)??"pure_text";C=C.replaceAll("","").replaceAll("","");let Ae;switch(Be){case"pure_text":Ae=C;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Ne=Be==="ocr"?"quad_boxes":"bboxes",ut=C.matchAll(this.regexes[Ne]),nt=[],Mt=[];for(const[ht,Tt,...Rt]of ut)nt.push(Tt?Tt.trim():nt.at(-1)??""),Mt.push(Rt.map((Qe,Vt)=>(Number(Qe)+.5)/this.size_per_bin*we[Vt%2]));Ae={labels:nt,[Ne]:Mt};break;default:throw new Error(`Task "${K}" (of type "${Be}") not yet implemented.`)}return{[K]:Ae}}}class mt{static async from_pretrained(C,{progress_callback:K=null,config:we=null,cache_dir:Be=null,local_files_only:Ae=!1,revision:Ne="main"}={}){let ut=we??await(0,ye.getModelJSON)(C,"preprocessor_config.json",!0,{progress_callback:K,config:we,cache_dir:Be,local_files_only:Ae,revision:Ne}),nt=ut.feature_extractor_type??ut.image_processor_type,Mt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[nt];if(!Mt)if(ut.size!==void 0)console.warn(`Feature extractor type "${nt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Mt=ae;else throw new Error(`Unknown Feature Extractor type: ${nt}`);let ht=this.PROCESSOR_CLASS_MAPPING[ut.processor_class]??M,Tt=new Mt(ut);return new ht(Tt)}}xe(mt,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:ae,WhisperFeatureExtractor:je,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:V,MobileViTImageProcessor:pe,MobileNetV1FeatureExtractor:Je,MobileNetV2FeatureExtractor:Ue,MobileNetV3FeatureExtractor:bt,MobileNetV4FeatureExtractor:_e,OwlViTFeatureExtractor:Ee,Owlv2ImageProcessor:re,CLIPFeatureExtractor:L,CLIPImageProcessor:O,Florence2Processor:At,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:A,ConvNextFeatureExtractor:ge,ConvNextImageProcessor:be,SegformerFeatureExtractor:D,BitImageProcessor:ie,DPTImageProcessor:G,DPTFeatureExtractor:ee,GLPNFeatureExtractor:fe,BeitFeatureExtractor:rt,DeiTFeatureExtractor:ct,DetrFeatureExtractor:st,RTDetrImageProcessor:Ke,YolosFeatureExtractor:xt,DonutFeatureExtractor:ot,NougatImageProcessor:Re,EfficientNetImageProcessor:De,ViTImageProcessor:ke,VitMatteImageProcessor:$e,SamImageProcessor:ze,Swin2SRImageProcessor:ne,Wav2Vec2FeatureExtractor:qe,SeamlessM4TFeatureExtractor:Ve,SpeechT5FeatureExtractor:vt,ASTFeatureExtractor:Xe,ClapFeatureExtractor:lt,PyAnnoteFeatureExtractor:ft,WeSpeakerFeatureExtractor:gt}),xe(mt,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:S,Wav2Vec2ProcessorWithLM:Q,PyAnnoteProcessor:he,SamProcessor:W,SpeechT5Processor:Ye,OwlViTProcessor:et,Florence2Processor:At})},"./src/tokenizers.js":($t,me,l)=>{l.r(me),l.d(me,{AlbertTokenizer:()=>Nt,AutoTokenizer:()=>fn,BartTokenizer:()=>Lr,BertTokenizer:()=>Vt,BlenderbotSmallTokenizer:()=>vs,BlenderbotTokenizer:()=>os,BloomTokenizer:()=>Pr,CLIPTokenizer:()=>Qt,CamembertTokenizer:()=>Et,CodeGenTokenizer:()=>as,CodeLlamaTokenizer:()=>Vs,CohereTokenizer:()=>Dr,ConvBertTokenizer:()=>Ur,DebertaTokenizer:()=>er,DebertaV2Tokenizer:()=>Wt,DistilBertTokenizer:()=>Ze,ElectraTokenizer:()=>qr,EsmTokenizer:()=>Gn,FalconTokenizer:()=>ws,GPT2Tokenizer:()=>Fn,GPTNeoXTokenizer:()=>ys,GemmaTokenizer:()=>ss,Grok1Tokenizer:()=>kn,HerbertTokenizer:()=>Tr,LlamaTokenizer:()=>On,M2M100Tokenizer:()=>Qn,MBart50Tokenizer:()=>Nr,MBartTokenizer:()=>Zr,MPNetTokenizer:()=>gs,MarianTokenizer:()=>bs,MobileBertTokenizer:()=>Ht,NllbTokenizer:()=>Dn,NougatTokenizer:()=>ls,PreTrainedTokenizer:()=>Qe,Qwen2Tokenizer:()=>Us,RoFormerTokenizer:()=>Cr,RobertaTokenizer:()=>Sn,SiglipTokenizer:()=>Yn,SpeechT5Tokenizer:()=>xs,SqueezeBertTokenizer:()=>Xt,T5Tokenizer:()=>Un,TokenizerModel:()=>Ce,VitsTokenizer:()=>Ts,Wav2Vec2CTCTokenizer:()=>Ms,WhisperTokenizer:()=>is,XLMRobertaTokenizer:()=>_s,XLMTokenizer:()=>Bt,is_chinese_char:()=>fe});var x=l("./src/utils/generic.js"),X=l("./src/utils/core.js"),ye=l("./src/utils/hub.js"),ve=l("./src/utils/maths.js"),Te=l("./src/utils/tensor.js"),B=l("./src/utils/data-structures.js"),E=l("./node_modules/@huggingface/jinja/dist/index.js"),N=l("./src/models/whisper/common_whisper.js"),P=l("./src/utils/constants.js");async function te(Me,_){const F=await Promise.all([(0,ye.getModelJSON)(Me,"tokenizer.json",!0,_),(0,ye.getModelJSON)(Me,"tokenizer_config.json",!0,_)]);return _.legacy!==null&&(F[1].legacy=_.legacy),F}function J(Me,_){const F=[];let Y=0;for(const le of Me.matchAll(_)){const ue=le[0];Y0&&F.push(ue),Y=le.index+ue.length}return Y=19968&&Me<=40959||Me>=13312&&Me<=19903||Me>=131072&&Me<=173791||Me>=173824&&Me<=177983||Me>=177984&&Me<=178207||Me>=178208&&Me<=183983||Me>=63744&&Me<=64255||Me>=194560&&Me<=195103}function L(Me,_,F){const Y=[];let le=0;for(;lethis.tokens_to_ids.get(F)??this.unk_token_id)}convert_ids_to_tokens(_){return _.map(F=>this.vocab[F]??this.unk_token)}}class ke extends Ce{constructor(_){super(_),this.tokens_to_ids=ae(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.max_input_chars_per_word=_.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[F,Y]of this.tokens_to_ids)this.vocab[Y]=F}encode(_){const F=[];for(const Y of _){const le=[...Y];if(le.length>this.max_input_chars_per_word){F.push(this.unk_token);continue}let ue=!1,Ie=0;const _t=[];for(;Ie0&&(Pt=this.config.continuing_subword_prefix+Pt),this.tokens_to_ids.has(Pt)){wt=Pt;break}--yt}if(wt===null){ue=!0;break}_t.push(wt),Ie=yt}ue?F.push(this.unk_token):F.push(..._t)}return F}}class De extends Ce{constructor(_,F){super(_);const Y=_.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let le=0;le[le,ue])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=F.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,ve.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new B.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(_){const F=_.sentence,Y=F.length;let le=0;for(;le{const Me=[...Array.from({length:94},(le,ue)=>ue+33),...Array.from({length:12},(le,ue)=>ue+161),...Array.from({length:82},(le,ue)=>ue+174)],_=Me.slice();let F=0;for(let le=0;le<256;++le)Me.includes(le)||(Me.push(le),_.push(256+F),F+=1);const Y=_.map(le=>String.fromCharCode(le));return Object.fromEntries(Me.map((le,ue)=>[le,Y[ue]]))})(),Ue=(0,X.reverseDictionary)(Je);class bt extends Ce{constructor(_){super(_),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ae(_.vocab),this.unk_token_id=this.tokens_to_ids.get(_.unk_token),this.unk_token=_.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[F,Y]of this.tokens_to_ids)this.vocab[Y]=F;this.bpe_ranks=new Map(_.merges.map((F,Y)=>[F,Y])),this.merges=_.merges.map(F=>F.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=_.end_of_word_suffix,this.continuing_subword_suffix=_.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=new Map}bpe(_){if(_.length===0)return[];const F=this.cache.get(_);if(F!==void 0)return F;const Y=Array.from(_);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let le=[];if(Y.length>1){const ue=new B.PriorityQueue((yt,wt)=>yt.score`<0x${Ie.toString(16).toUpperCase().padStart(2,"0")}>`)):F.push(this.unk_token)}return F}}class _e extends Ce{constructor(_,F){super(_),this.tokens_to_ids=ae(F.target_lang?_.vocab[F.target_lang]:_.vocab),this.bos_token=F.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=F.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=F.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=F.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[Y,le]of this.tokens_to_ids)this.vocab[le]=Y}encode(_){return _}}class V extends x.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"BertNormalizer":return new xt(_);case"Precompiled":return new Ae(_);case"Sequence":return new st(_);case"Replace":return new pe(_);case"NFC":return new Ee(_);case"NFKC":return new re(_);case"NFKD":return new Ke(_);case"Strip":return new ct(_);case"StripAccents":return new rt(_);case"Lowercase":return new ot(_);case"Prepend":return new Re(_);default:throw new Error(`Unknown Normalizer type: ${_.type}`)}}normalize(_){throw Error("normalize should be implemented in subclass.")}_call(_){return this.normalize(_)}}class pe extends V{normalize(_){const F=se(this.config.pattern);return F===null?_:_.replaceAll(F,this.config.content)}}class Ee extends V{normalize(_){return _=_.normalize("NFC"),_}}class re extends V{normalize(_){return _=_.normalize("NFKC"),_}}class Ke extends V{normalize(_){return _=_.normalize("NFKD"),_}}class ct extends V{normalize(_){return this.config.strip_left&&this.config.strip_right?_=_.trim():(this.config.strip_left&&(_=_.trimStart()),this.config.strip_right&&(_=_.trimEnd())),_}}class rt extends V{normalize(_){return _=G(_),_}}class ot extends V{normalize(_){return _=_.toLowerCase(),_}}class Re extends V{normalize(_){return _=this.config.prepend+_,_}}class st extends V{constructor(_){super(_),this.normalizers=_.normalizers.map(F=>V.fromConfig(F))}normalize(_){return this.normalizers.reduce((F,Y)=>Y.normalize(F),_)}}class xt extends V{_tokenize_chinese_chars(_){const F=[];for(let Y=0;Y<_.length;++Y){const le=_[Y],ue=le.charCodeAt(0);fe(ue)?(F.push(" "),F.push(le),F.push(" ")):F.push(le)}return F.join("")}stripAccents(_){return _.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(_){switch(_){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(_)}}_clean_text(_){const F=[];for(const Y of _){const le=Y.charCodeAt(0);le===0||le===65533||this._is_control(Y)||(/^\s$/.test(Y)?F.push(" "):F.push(Y))}return F.join("")}normalize(_){return this.config.clean_text&&(_=this._clean_text(_)),this.config.handle_chinese_chars&&(_=this._tokenize_chinese_chars(_)),this.config.lowercase?(_=_.toLowerCase(),this.config.strip_accents!==!1&&(_=this.stripAccents(_))):this.config.strip_accents&&(_=this.stripAccents(_)),_}}class ze extends x.Callable{static fromConfig(_){if(_===null)return null;switch(_.type){case"BertPreTokenizer":return new ne(_);case"Sequence":return new Ne(_);case"Whitespace":return new ut(_);case"WhitespaceSplit":return new nt(_);case"Metaspace":return new we(_);case"ByteLevel":return new $e(_);case"Split":return new je(_);case"Punctuation":return new qe(_);case"Digits":return new Ve(_);case"Replace":return new Mt(_);default:throw new Error(`Unknown PreTokenizer type: ${_.type}`)}}pre_tokenize_text(_,F){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(_,F){return(Array.isArray(_)?_.map(Y=>this.pre_tokenize_text(Y,F)):this.pre_tokenize_text(_,F)).flat()}_call(_,F){return this.pre_tokenize(_,F)}}class ne extends ze{constructor(_){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(_,F){return _.trim().match(this.pattern)||[]}}class $e extends ze{constructor(_){super(),this.config=_,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=Je,this.text_encoder=new TextEncoder}pre_tokenize_text(_,F){return this.add_prefix_space&&!_.startsWith(" ")&&(_=" "+_),(this.use_regex?_.match(this.pattern)||[]:[_]).map(le=>Array.from(this.text_encoder.encode(le),ue=>this.byte_encoder[ue]).join(""))}}class je extends ze{constructor(_){super(),this.config=_,this.pattern=se(this.config.pattern,this.config.invert)}pre_tokenize_text(_,F){return this.pattern===null?[]:this.config.invert?_.match(this.pattern)||[]:J(_,this.pattern)}}class qe extends ze{constructor(_){super(),this.config=_,this.pattern=new RegExp(`[^${j}]+|[${j}]+`,"gu")}pre_tokenize_text(_,F){return _.match(this.pattern)||[]}}class Ve extends ze{constructor(_){super(),this.config=_;const F=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(F,"gu")}pre_tokenize_text(_,F){return _.match(this.pattern)||[]}}class Xe extends x.Callable{constructor(_){super(),this.config=_}static fromConfig(_){if(_===null)return null;switch(_.type){case"TemplateProcessing":return new gt(_);case"ByteLevel":return new vt(_);case"RobertaProcessing":return new ft(_);case"BertProcessing":return new lt(_);case"Sequence":return new M(_);default:throw new Error(`Unknown PostProcessor type: ${_.type}`)}}post_process(_,...F){throw Error("post_process should be implemented in subclass.")}_call(_,...F){return this.post_process(_,...F)}}class lt extends Xe{constructor(_){super(_),this.cls=_.cls[0],this.sep=_.sep[0]}post_process(_,F=null,{add_special_tokens:Y=!0}={}){Y&&(_=(0,X.mergeArrays)([this.cls],_,[this.sep]));let le=new Array(_.length).fill(0);if(F!==null){const ue=Y&&this instanceof ft?[this.sep]:[],Ie=Y?[this.sep]:[];_=(0,X.mergeArrays)(_,ue,F,Ie),le=(0,X.mergeArrays)(le,new Array(F.length+ue.length+Ie.length).fill(1))}return{tokens:_,token_type_ids:le}}}class ft extends lt{}class gt extends Xe{constructor(_){super(_),this.single=_.single,this.pair=_.pair}post_process(_,F=null,{add_special_tokens:Y=!0}={}){const le=F===null?this.single:this.pair;let ue=[],Ie=[];for(const _t of le)"SpecialToken"in _t?Y&&(ue.push(_t.SpecialToken.id),Ie.push(_t.SpecialToken.type_id)):"Sequence"in _t&&(_t.Sequence.id==="A"?(ue=(0,X.mergeArrays)(ue,_),Ie=(0,X.mergeArrays)(Ie,new Array(_.length).fill(_t.Sequence.type_id))):_t.Sequence.id==="B"&&(ue=(0,X.mergeArrays)(ue,F),Ie=(0,X.mergeArrays)(Ie,new Array(F.length).fill(_t.Sequence.type_id))));return{tokens:ue,token_type_ids:Ie}}}class vt extends Xe{post_process(_,F=null){return F&&(_=(0,X.mergeArrays)(_,F)),{tokens:_}}}class M extends Xe{constructor(_){super(_),this.processors=_.processors.map(F=>Xe.fromConfig(F))}post_process(_,F=null,Y={}){let le;for(const ue of this.processors)if(ue instanceof vt)_=ue.post_process(_).tokens,F&&(F=ue.post_process(F).tokens);else{const Ie=ue.post_process(_,F,Y);_=Ie.tokens,le=Ie.token_type_ids}return{tokens:_,token_type_ids:le}}}class W extends x.Callable{constructor(_){super(),this.config=_,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=_.trim_offsets}static fromConfig(_){if(_===null)return null;switch(_.type){case"WordPiece":return new et(_);case"Metaspace":return new Be(_);case"ByteLevel":return new At(_);case"Replace":return new S(_);case"ByteFallback":return new Q(_);case"Fuse":return new he(_);case"Strip":return new Ye(_);case"Sequence":return new Se(_);case"CTC":return new mt(_);case"BPEDecoder":return new C(_);default:throw new Error(`Unknown Decoder type: ${_.type}`)}}_call(_){return this.decode(_)}decode(_){return this.decode_chain(_).join("")}decode_chain(_){throw Error("`decode_chain` should be implemented in subclass.")}}class S extends W{decode_chain(_){const F=se(this.config.pattern);return F===null?_:_.map(Y=>Y.replaceAll(F,this.config.content))}}class Q extends W{constructor(_){super(_),this.text_decoder=new TextDecoder}decode_chain(_){const F=[];let Y=[];for(const le of _){let ue=null;if(le.length===6&&le.startsWith("<0x")&&le.endsWith(">")){const Ie=parseInt(le.slice(3,5),16);isNaN(Ie)||(ue=Ie)}if(ue!==null)Y.push(ue);else{if(Y.length>0){const Ie=this.text_decoder.decode(Uint8Array.from(Y));F.push(Ie),Y=[]}F.push(le)}}if(Y.length>0){const le=this.text_decoder.decode(Uint8Array.from(Y));F.push(le),Y=[]}return F}}class he extends W{decode_chain(_){return[_.join("")]}}class Ye extends W{constructor(_){super(_),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(_){return _.map(F=>{let Y=0;for(let ue=0;ue(Y!==0&&(F.startsWith(this.config.prefix)?F=F.replace(this.config.prefix,""):F=" "+F),this.cleanup&&(F=ee(F)),F))}}class At extends W{constructor(_){super(_),this.byte_decoder=Ue,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(_){const F=_.join(""),Y=new Uint8Array([...F].map(ue=>this.byte_decoder[ue]));return this.text_decoder.decode(Y)}decode_chain(_){const F=[];let Y=[];for(const le of _)this.added_tokens.find(ue=>ue.content===le)!==void 0?(Y.length>0&&(F.push(this.convert_tokens_to_string(Y)),Y=[]),F.push(le)):Y.push(le);return Y.length>0&&F.push(this.convert_tokens_to_string(Y)),F}}class mt extends W{constructor(_){super(_),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(_){if(_.length===0)return"";const F=[_[0]];for(let ue=1;ue<_.length;++ue)_[ue]!==F.at(-1)&&F.push(_[ue]);let le=F.filter(ue=>ue!==this.pad_token).join("");return this.cleanup&&(le=ee(le).replaceAll(this.word_delimiter_token," ").trim()),le}decode_chain(_){return[this.convert_tokens_to_string(_)]}}class Se extends W{constructor(_){super(_),this.decoders=_.decoders.map(F=>W.fromConfig(F))}decode_chain(_){return this.decoders.reduce((F,Y)=>Y.decode_chain(F),_)}}class C extends W{constructor(_){super(_),this.suffix=this.config.suffix}decode_chain(_){return _.map((F,Y)=>F.replaceAll(this.suffix,Y===_.length-1?"":" "))}}class K extends W{decode_chain(_){let F="";for(let Y=1;Y<_.length;Y+=2)F+=_[Y];return[F]}}class we extends ze{constructor(_){super(),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement,this.strRep=_.str_rep||this.replacement,this.prepend_scheme=_.prepend_scheme??"always"}pre_tokenize_text(_,{section_index:F=void 0}={}){let Y=_.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Y.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&F===0)&&(Y=this.strRep+Y),[Y]}}class Be extends W{constructor(_){super(_),this.addPrefixSpace=_.add_prefix_space,this.replacement=_.replacement}decode_chain(_){const F=[];for(let Y=0;Y<_.length;++Y){let le=_[Y].replaceAll(this.replacement," ");this.addPrefixSpace&&Y==0&&le.startsWith(" ")&&(le=le.substring(1)),F.push(le)}return F}}class Ae extends V{constructor(_){super(_),this.charsmap=_.precompiled_charsmap}normalize(_){return _=_.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),_=_.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm," "),_.includes("~")?_=_.split("~").map(Y=>Y.normalize("NFKC")).join("~"):_=_.normalize("NFKC"),_}}class Ne extends ze{constructor(_){super(),this.tokenizers=_.pretokenizers.map(F=>ze.fromConfig(F))}pre_tokenize_text(_,F){return this.tokenizers.reduce((Y,le)=>le.pre_tokenize(Y,F),[_])}}class ut extends ze{constructor(_){super()}pre_tokenize_text(_,F){return _.match(/\w+|[^\w\s]+/g)||[]}}class nt extends ze{constructor(_){super()}pre_tokenize_text(_,F){return O(_)}}class Mt extends ze{constructor(_){super(),this.config=_,this.pattern=se(this.config.pattern),this.content=this.config.content}pre_tokenize_text(_,F){return this.pattern===null?[_]:[_.replaceAll(this.pattern,this.config.content)]}}const ht=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Tt(Me,_,F,Y){for(const le of Object.keys(Me)){const ue=_-Me[le].length,Ie=F(le),_t=new Array(ue).fill(Ie);Me[le]=Y==="right"?(0,X.mergeArrays)(Me[le],_t):(0,X.mergeArrays)(_t,Me[le])}}function Rt(Me,_){for(const F of Object.keys(Me))Me[F].length=_}class Qe extends x.Callable{constructor(F,Y){super();xe(this,"return_token_type_ids",!1);xe(this,"padding_side","right");this._tokenizer_config=Y,this.normalizer=V.fromConfig(F.normalizer),this.pre_tokenizer=ze.fromConfig(F.pre_tokenizer),this.model=Ce.fromConfig(F.model,Y),this.post_processor=Xe.fromConfig(F.post_processor),this.decoder=W.fromConfig(F.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const le of F.added_tokens){const ue=new be(le);this.added_tokens.push(ue),this.model.tokens_to_ids.set(ue.content,ue.id),this.model.vocab[ue.id]=ue.content,ue.special&&(this.special_tokens.push(ue.content),this.all_special_ids.push(ue.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.toSorted((le,ue)=>ue.content.length-le.content.length).map(le=>`${le.lstrip?"\\s*":""}(${(0,X.escapeRegExp)(le.content)})${le.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=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 le=Object.create(null);for(const{name:ue,template:Ie}of this.chat_template){if(typeof ue!="string"||typeof Ie!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');le[ue]=Ie}this.chat_template=le}this._compiled_template_cache=new Map}getToken(...F){for(const Y of F){const le=this._tokenizer_config[Y];if(le)if(typeof le=="object"){if(le.__type==="AddedToken")return le.content;throw Error(`Unknown token: ${le}`)}else return le}return null}static async from_pretrained(F,{progress_callback:Y=null,config:le=null,cache_dir:ue=null,local_files_only:Ie=!1,revision:_t="main",legacy:yt=null}={}){const wt=await te(F,{progress_callback:Y,config:le,cache_dir:ue,local_files_only:Ie,revision:_t,legacy:yt});return new this(...wt)}_call(F,{text_pair:Y=null,add_special_tokens:le=!0,padding:ue=!1,truncation:Ie=null,max_length:_t=null,return_tensor:yt=!0,return_token_type_ids:wt=null}={}){const Pt=Array.isArray(F);let Jt;if(Pt){if(F.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(F.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Jt=F.map((sr,Gt)=>this._encode_plus(sr,{text_pair:Y[Gt],add_special_tokens:le,return_token_type_ids:wt}))}else Jt=F.map(sr=>this._encode_plus(sr,{add_special_tokens:le,return_token_type_ids:wt}))}else{if(F==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).");Jt=[this._encode_plus(F,{text_pair:Y,add_special_tokens:le,return_token_type_ids:wt})]}if(_t===null?ue==="max_length"?_t=this.model_max_length:_t=(0,ve.max)(Jt.map(sr=>sr.input_ids.length))[0]:Ie||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."),_t=Math.min(_t,this.model_max_length??1/0),ue||Ie)for(let sr=0;sr_t?Ie&&Rt(Jt[sr],_t):ue&&Tt(Jt[sr],_t,Gt=>Gt==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(yt){if(!(ue&&Ie)&&Jt.some(Gt=>{var hr;for(const on of Object.keys(Gt))if(Gt[on].length!==((hr=Jt[0][on])==null?void 0:hr.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 sr=[Jt.length,Jt[0].input_ids.length];for(const Gt of Object.keys(Jt[0]))$r[Gt]=new Te.Tensor("int64",BigInt64Array.from(Jt.flatMap(hr=>hr[Gt]).map(BigInt)),sr)}else{for(const sr of Object.keys(Jt[0]))$r[sr]=Jt.map(Gt=>Gt[sr]);if(!Pt)for(const sr of Object.keys($r))$r[sr]=$r[sr][0]}return $r}_encode_text(F){return F===null?null:(this.added_tokens_regex?F.split(this.added_tokens_regex).filter(ue=>ue):[F]).map((ue,Ie)=>{if(this.added_tokens.find(yt=>yt.content===ue)!==void 0)return ue;{if(this.remove_space===!0&&(ue=ue.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ue=ie(ue)),this.normalizer!==null&&(ue=this.normalizer(ue)),ue.length===0)return[];const yt=this.pre_tokenizer!==null?this.pre_tokenizer(ue,{section_index:Ie}):[ue];return this.model(yt)}}).flat()}_encode_plus(F,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:ue=null}={}){const{tokens:Ie,token_type_ids:_t}=this._tokenize_helper(F,{pair:Y,add_special_tokens:le}),yt=this.model.convert_tokens_to_ids(Ie),wt={input_ids:yt,attention_mask:new Array(yt.length).fill(1)};return(ue??this.return_token_type_ids)&&_t&&(wt.token_type_ids=_t),wt}_tokenize_helper(F,{pair:Y=null,add_special_tokens:le=!1}={}){const ue=this._encode_text(F),Ie=this._encode_text(Y);return this.post_processor?this.post_processor(ue,Ie,{add_special_tokens:le}):{tokens:(0,X.mergeArrays)(ue??[],Ie??[])}}tokenize(F,{pair:Y=null,add_special_tokens:le=!1}={}){return this._tokenize_helper(F,{pair:Y,add_special_tokens:le}).tokens}encode(F,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:ue=null}={}){return this._encode_plus(F,{text_pair:Y,add_special_tokens:le,return_token_type_ids:ue}).input_ids}batch_decode(F,Y={}){return F instanceof Te.Tensor&&(F=F.tolist()),F.map(le=>this.decode(le,Y))}decode(F,Y={}){if(F instanceof Te.Tensor&&(F=D(F)),!Array.isArray(F)||F.length===0||!(0,X.isIntegralNumber)(F[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(F,Y)}decode_single(F,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:le=null}){let ue=this.model.convert_ids_to_tokens(F);Y&&(ue=ue.filter(_t=>!this.special_tokens.includes(_t)));let Ie=this.decoder?this.decoder(ue):ue.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ie=Ie.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Ie=Ie.trim())),(le??this.clean_up_tokenization_spaces)&&(Ie=ee(Ie)),Ie}apply_chat_template(F,{tools:Y=null,documents:le=null,chat_template:ue=null,add_generation_prompt:Ie=!1,tokenize:_t=!0,padding:yt=!1,truncation:wt=!1,max_length:Pt=null,return_tensor:Jt=!0,return_dict:$r=!1,tokenizer_kwargs:sr={},...Gt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const He=this.chat_template;if(ue!==null&&Object.hasOwn(He,ue))ue=He[ue];else if(ue===null&&"default"in He)ue=He.default;else if(ue===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(He).sort()}.`)}else if(this.chat_template)ue=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");if(typeof ue!="string")throw Error(`chat_template must be a string, but got ${typeof ue}`);let hr=this._compiled_template_cache.get(ue);hr===void 0&&(hr=new E.Template(ue),this._compiled_template_cache.set(ue,hr));const on=Object.create(null);for(const He of ht){const yn=this.getToken(He);yn&&(on[He]=yn)}const Yr=hr.render({messages:F,add_generation_prompt:Ie,tools:Y,documents:le,...on,...Gt});if(_t){const He=this._call(Yr,{add_special_tokens:!1,padding:yt,truncation:wt,max_length:Pt,return_tensor:Jt,...sr});return $r?He:He.input_ids}return Yr}}class Vt extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Nt extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Ht extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Xt extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class er extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Wt extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Tr extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Ur extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Cr extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Ze extends Qe{}class Et extends Qe{}class Bt extends Qe{constructor(F,Y){super(F,Y);xe(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class qr extends Qe{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Un extends Qe{}class Fn extends Qe{}class Lr extends Qe{}class Zr extends Qe{constructor(_,F){super(_,F),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(_,F,Y){return zn(this,_,F,Y)}}class Nr extends Zr{}class Sn extends Qe{}class Pr extends Qe{constructor(_,F){var ue,Ie;const Y=".,!?…。,、।۔،",le=(Ie=(ue=_.pre_tokenizer)==null?void 0:ue.pretokenizers[0])==null?void 0:Ie.pattern;le&&le.Regex===` ?[^(\\s|[${Y}])]+`&&(le.Regex=` ?[^\\s${Y}]+`),super(_,F)}}const Wn="▁";class On extends Qe{constructor(F,Y){super(F,Y);xe(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new we({replacement:Wn,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(F){if(F===null)return null;if(this.legacy||F.length===0)return super._encode_text(F);let Y=super._encode_text(Wn+F.replaceAll(Wn," "));return Y.length>1&&Y[0]===Wn&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class Vs extends Qe{}class _s extends Qe{}class gs extends Qe{}class ws extends Qe{}class ys extends Qe{}class Gn extends Qe{}class Us extends Qe{}class ss extends Qe{}class kn extends Qe{}function zn(Me,_,F,Y){if(!("language_codes"in Me)||!Array.isArray(Me.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Me)||!(Me.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Me)||typeof Me.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const le=Y.src_lang,ue=Y.tgt_lang;if(!Me.language_codes.includes(ue))throw new Error(`Target language code "${ue}" is not valid. Must be one of: {${Me.language_codes.join(", ")}}`);if(le!==void 0){if(!Me.language_codes.includes(le))throw new Error(`Source language code "${le}" is not valid. Must be one of: {${Me.language_codes.join(", ")}}`);for(const Ie of Me.post_processor.config.single)if("SpecialToken"in Ie&&Me.languageRegex.test(Ie.SpecialToken.id)){Ie.SpecialToken.id=Me.lang_to_token(le);break}}return Y.forced_bos_token_id=Me.model.convert_tokens_to_ids([Me.lang_to_token(ue)])[0],Me._call(_,F)}class Dn extends Qe{constructor(_,F){super(_,F),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(_,F,Y){return zn(this,_,F,Y)}}class Qn extends Qe{constructor(_,F){super(_,F),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(_,F,Y){return zn(this,_,F,Y)}}class is extends Qe{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(_,{return_timestamps:F=!1,return_language:Y=!1,time_precision:le=null,force_full_sequences:ue=!0}={}){if(le===null)throw Error("Must specify time_precision");let Ie=null;const _t=F==="word";function yt(){return{language:Ie,timestamp:[null,null],text:""}}const wt=[];let Pt=yt(),Jt=0;const $r=this.timestamp_begin;let sr=[],Gt=[],hr=!1,on=null;const Yr=new Set(this.all_special_ids);for(const wr of _){const Hr=wr.tokens,dn=_t?wr.token_timestamps:null;let Yt=null,mn=$r;if("stride"in wr){const[Mr,St,mr]=wr.stride;if(Jt-=St,on=Mr-mr,St&&(mn=St/le+$r),mr)for(let Ar=Hr.length-1;Ar>=0;--Ar){const jr=Number(Hr[Ar]);if(jr>=$r){if(Yt!==null&&(jr-$r)*le=$r){const mr=(St-$r)*le+Jt,Ar=(0,ve.round)(mr,2);if(Yt!==null&&St>=Yt)hr=!0;else if(hr||sr.length>0&&St0?(sr.push(Jr),_t&&Gt.push(br)):sr.every(Mr=>Mr.length===0)&&(Pt=yt(),sr=[],Jr=[],Gt=[],br=[])}if(sr.length>0){if(ue&&F)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[wr,Hr]=this.findLongestCommonSequence(sr,Gt),dn=this.decode(wr);Pt.text=dn,_t&&(Pt.words=this.collateWordTimestamps(wr,Hr,Ie)),wt.push(Pt)}let He=Object.create(null);const yn=wt.map(wr=>wr.text).join("");if(F||Y){for(let wr=0;wr0;let _t=Ie?[]:null,yt=Ie?F[0]:null;for(let wt=1;wt<_.length;++wt){const Pt=_[wt];let Jt=0,$r=[le,le,0,0];const sr=Pt.length;for(let wr=1;wrAr===br[jr]&&yt[Hr+jr]<=F[wt][mn+jr]).length:Mr=Yt.filter((Ar,jr)=>Ar===br[jr]).length;const St=wr/1e4,mr=Mr/wr+St;Mr>1&&mr>Jt&&(Jt=mr,$r=[Hr,dn,mn,Jr])}const[Gt,hr,on,Yr]=$r,He=Math.floor((hr+Gt)/2),yn=Math.floor((Yr+on)/2);ue.push(...Y.slice(0,He)),Y=Pt.slice(yn),le=Y.length,Ie&&(_t.push(...yt.slice(0,He)),yt=F[wt].slice(yn))}return ue.push(...Y),Ie?(_t.push(...yt),[ue,_t]):[ue,[]]}collateWordTimestamps(_,F,Y){const[le,ue,Ie]=this.combineTokensIntoWords(_,Y),_t=[];for(let yt=0;yt=le){const _t=((Ie-le)*Y).toFixed(2);ue.push(`<|${_t}|>`),ue.push([])}else ue[ue.length-1].push(Ie);return ue=ue.map(Ie=>typeof Ie=="string"?Ie:super.decode(Ie,F)),ue.join("")}splitTokensOnUnicode(_){const F=this.decode(_,{decode_with_timestamps:!0}),Y="�",le=[],ue=[],Ie=[];let _t=[],yt=[],wt=0;for(let Pt=0;Pt<_.length;++Pt){const Jt=_[Pt];_t.push(Jt),yt.push(Pt);const $r=this.decode(_t,{decode_with_timestamps:!0});(!$r.includes(Y)||F[wt+$r.indexOf(Y)]===Y)&&(le.push($r),ue.push(_t),Ie.push(yt),_t=[],yt=[],wt+=$r.length)}return[le,ue,Ie]}splitTokensOnSpaces(_){const[F,Y,le]=this.splitTokensOnUnicode(_),ue=[],Ie=[],_t=[],yt=new RegExp(`^[${j}]$`,"gu");for(let wt=0;wt=this.model.tokens_to_ids.get("<|endoftext|>"),Gt=Pt.startsWith(" "),hr=Pt.trim(),on=yt.test(hr);if(sr||Gt||on||ue.length===0)ue.push(Pt),Ie.push(Jt),_t.push($r);else{const Yr=ue.length-1;ue[Yr]+=Pt,Ie[Yr].push(...Jt),_t[Yr].push(...$r)}}return[ue,Ie,_t]}mergePunctuations(_,F,Y,le,ue){const Ie=structuredClone(_),_t=structuredClone(F),yt=structuredClone(Y);let wt=Ie.length-2,Pt=Ie.length-1;for(;wt>=0;)Ie[wt].startsWith(" ")&&le.includes(Ie[wt].trim())?(Ie[Pt]=Ie[wt]+Ie[Pt],_t[Pt]=(0,X.mergeArrays)(_t[wt],_t[Pt]),yt[Pt]=(0,X.mergeArrays)(yt[wt],yt[Pt]),Ie[wt]="",_t[wt]=[],yt[wt]=[]):Pt=wt,--wt;for(wt=0,Pt=1;PtJt),_t.filter(Jt=>Jt.length>0),yt.filter(Jt=>Jt.length>0)]}get_decoder_prompt_ids({language:_=null,task:F=null,no_timestamps:Y=!0}={}){const le=[];if(_){const ue=(0,N.whisper_language_to_code)(_),Ie=this.model.tokens_to_ids.get(`<|${ue}|>`);if(Ie===void 0)throw new Error(`Unable to find language "${ue}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);le.push(Ie)}else le.push(null);if(F){if(F=F.toLowerCase(),F!=="transcribe"&&F!=="translate")throw new Error(`Task "${F}" is not supported. Must be one of: ["transcribe", "translate"]`);const ue=this.model.tokens_to_ids.get(`<|${F}|>`);if(ue===void 0)throw new Error(`Unable to find task "${F}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);le.push(ue)}else le.push(null);if(Y){const ue=this.model.tokens_to_ids.get("<|notimestamps|>");if(ue===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);le.push(ue)}return le.map((ue,Ie)=>[Ie+1,ue]).filter(ue=>ue[1]!==null)}}class as extends Qe{}class Qt extends Qe{}class Yn extends Qe{}class bs extends Qe{constructor(_,F){super(_,F),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(_){if(_===null)return null;const[F,...Y]=_.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(F);if(Y.length===2){const[le,ue]=Y;return this.supported_language_codes.includes(le)||console.warn(`Unsupported language code "${le}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,X.mergeArrays)([le],super._encode_text(ue))}}}class Ms extends Qe{}class os extends Qe{}class vs extends Qe{}class xs extends Qe{}class ls extends Qe{}class Ts extends Qe{constructor(_,F){super(_,F),this.decoder=new K({})}}class Dr extends Qe{}class fn{static async from_pretrained(_,{progress_callback:F=null,config:Y=null,cache_dir:le=null,local_files_only:ue=!1,revision:Ie="main",legacy:_t=null}={}){var $r;const[yt,wt]=await te(_,{progress_callback:F,config:Y,cache_dir:le,local_files_only:ue,revision:Ie,legacy:_t}),Pt=(($r=wt.tokenizer_class)==null?void 0:$r.replace(/Fast$/,""))??"PreTrainedTokenizer";let Jt=this.TOKENIZER_CLASS_MAPPING[Pt];return Jt||(console.warn(`Unknown tokenizer class "${Pt}", attempting to construct from base class.`),Jt=Qe),new Jt(yt,wt)}}xe(fn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Un,DistilBertTokenizer:Ze,CamembertTokenizer:Et,DebertaTokenizer:er,DebertaV2Tokenizer:Wt,BertTokenizer:Vt,HerbertTokenizer:Tr,ConvBertTokenizer:Ur,RoFormerTokenizer:Cr,XLMTokenizer:Bt,ElectraTokenizer:qr,MobileBertTokenizer:Ht,SqueezeBertTokenizer:Xt,AlbertTokenizer:Nt,GPT2Tokenizer:Fn,BartTokenizer:Lr,MBartTokenizer:Zr,MBart50Tokenizer:Nr,RobertaTokenizer:Sn,WhisperTokenizer:is,CodeGenTokenizer:as,CLIPTokenizer:Qt,SiglipTokenizer:Yn,MarianTokenizer:bs,BloomTokenizer:Pr,NllbTokenizer:Dn,M2M100Tokenizer:Qn,LlamaTokenizer:On,CodeLlamaTokenizer:Vs,XLMRobertaTokenizer:_s,MPNetTokenizer:gs,FalconTokenizer:ws,GPTNeoXTokenizer:ys,EsmTokenizer:Gn,Wav2Vec2CTCTokenizer:Ms,BlenderbotTokenizer:os,BlenderbotSmallTokenizer:vs,SpeechT5Tokenizer:xs,NougatTokenizer:ls,VitsTokenizer:Ts,Qwen2Tokenizer:Us,GemmaTokenizer:ss,Grok1Tokenizer:kn,CohereTokenizer:Dr,PreTrainedTokenizer:Qe})},"./src/utils/audio.js":($t,me,l)=>{l.r(me),l.d(me,{hamming:()=>N,hanning:()=>E,mel_filter_bank:()=>ee,read_audio:()=>Te,spectrogram:()=>O,window_function:()=>j});var x=l("./src/utils/hub.js"),X=l("./src/utils/maths.js"),ye=l("./src/utils/core.js"),ve=l("./src/utils/tensor.js");async function Te(A,ge){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 be=await(await(0,x.getFile)(A)).arrayBuffer(),Ce=new AudioContext({sampleRate:ge});typeof ge>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const ke=await Ce.decodeAudioData(be);let De;if(ke.numberOfChannels===2){const Je=Math.sqrt(2),Ue=ke.getChannelData(0),bt=ke.getChannelData(1);De=new Float32Array(Ue.length);for(let _e=0;_e2595*Math.log10(1+A/700),kaldi:A=>1127*Math.log(1+A/700),slaney:(A,ge=1e3,be=15,Ce=27/Math.log(6.4))=>A>=ge?be+Math.log(A/ge)*Ce:3*A/200};function te(A,ge="htk"){const be=P[ge];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof A=="number"?be(A):A.map(Ce=>be(Ce))}const J={htk:A=>700*(10**(A/2595)-1),kaldi:A=>700*(Math.exp(A/1127)-1),slaney:(A,ge=1e3,be=15,Ce=Math.log(6.4)/27)=>A>=be?ge*Math.exp(Ce*(A-be)):200*A/3};function se(A,ge="htk"){const be=J[ge];if(!be)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof A=="number"?be(A):A.map(Ce=>be(Ce))}function ae(A,ge){const be=Float64Array.from({length:ge.length-1},(Je,Ue)=>ge[Ue+1]-ge[Ue]),Ce=Array.from({length:A.length},()=>new Array(ge.length));for(let Je=0;Jenew Array(A.length));for(let Je=0;JeA+Ce*De)}function ee(A,ge,be,Ce,ke,De=null,Je="htk",Ue=!1){if(De!==null&&De!=="slaney")throw new Error('norm must be one of null or "slaney"');const bt=te(be,Je),_e=te(Ce,Je),V=D(bt,_e,ge+2);let pe=se(V,Je),Ee;if(Ue){const Ke=ke/(A*2);Ee=te(Float64Array.from({length:A},(ct,rt)=>rt*Ke),Je),pe=V}else Ee=D(0,Math.floor(ke/2),A);const re=ae(Ee,pe);if(De!==null&&De==="slaney")for(let Ke=0;Keke)throw Error(`frame_length (${be}) may not be larger than fft_length (${ke})`);if(ze!==be)throw new Error(`Length of the window (${ze}) must equal frame_length (${be})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(De===null&&V!==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 W=Math.floor((ke-1)/2)+1;A=G(A,W,W)}let ne=Math.floor(1+Math.floor((A.length-be)/Ce));ot!==null&&nene?st&&(qe=Re):qe=je=Re);const Ve=new X.FFT(ke),Xe=new Float64Array(ke),lt=new Float64Array(Ve.outputBufferSize),ft=new Float32Array($e*qe);for(let W=0;W=1;--he)Xe[he]-=_e*Xe[he-1];Xe[0]*=1-_e}for(let he=0;heMath.pow(Ue,.85));break;default:throw new Error(`Unknown window type ${ge}.`)}if(be&&(Je=Je.subarray(0,A)),Ce===null)return Je;if(A>Ce)throw new Error(`Length of the window (${A}) may not be larger than frame_length (${Ce})`);return Je}},"./src/utils/constants.js":($t,me,l)=>{l.r(me),l.d(me,{GITHUB_ISSUE_URL:()=>x});const x="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":($t,me,l)=>{l.r(me),l.d(me,{calculateDimensions:()=>B,calculateReflectOffset:()=>te,dispatchCallback:()=>x,escapeRegExp:()=>ye,isIntegralNumber:()=>Te,isTypedArray:()=>ve,mergeArrays:()=>N,pick:()=>J,pop:()=>E,product:()=>P,reverseDictionary:()=>X});function x(se,ae){se&&se(ae)}function X(se){return Object.fromEntries(Object.entries(se).map(([ae,D])=>[D,ae]))}function ye(se){return se.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(se){var ae,D,ee;return((ee=(D=(ae=se==null?void 0:se.prototype)==null?void 0:ae.__proto__)==null?void 0:D.constructor)==null?void 0:ee.name)==="TypedArray"}function Te(se){return Number.isInteger(se)||typeof se=="bigint"}function B(se){const ae=[];let D=se;for(;Array.isArray(D);)ae.push(D.length),D=D[0];return ae}function E(se,ae,D=void 0){const ee=se[ae];if(ee!==void 0)return delete se[ae],ee;if(D===void 0)throw Error(`Key ${ae} does not exist in object.`);return D}function N(...se){return Array.prototype.concat.apply([],se)}function P(...se){return se.reduce((ae,D)=>ae.flatMap(ee=>D.map(G=>[ee,G])))}function te(se,ae){return Math.abs((se+ae)%(2*ae)-ae)}function J(se,ae){return Object.assign({},...ae.map(D=>{if(se[D]!==void 0)return{[D]:se[D]}}))}},"./src/utils/data-structures.js":($t,me,l)=>{l.r(me),l.d(me,{CharTrie:()=>X,PriorityQueue:()=>x,TokenLattice:()=>ve});class x{constructor(E=(P,te)=>P>te,N=1/0){this._heap=[],this._comparator=E,this._maxSize=N}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...E){return this.extend(E)}extend(E){for(const N of E)if(this.size0&&this._swap(0,N),this._heap.pop(),this._siftDown(),E}replace(E){const N=this.peek();return this._heap[0]=E,this._siftDown(),N}_parent(E){return(E+1>>>1)-1}_left(E){return(E<<1)+1}_right(E){return E+1<<1}_greater(E,N){return this._comparator(this._heap[E],this._heap[N])}_swap(E,N){const P=this._heap[E];this._heap[E]=this._heap[N],this._heap[N]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(E){for(;E>0&&this._greater(E,this._parent(E));)this._swap(E,this._parent(E)),E=this._parent(E)}_siftDown(){let E=0;for(;this._left(E)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const te=new Te(this.bosTokenId,0,0,0,0),J=new Te(this.eosTokenId,1,this.len,0,0);this.nodes.push(te.clone()),this.nodes.push(J.clone()),this.beginNodes[this.len].push(J),this.endNodes[0].push(te)}insert(E,N,P,te){const J=this.nodes.length,se=new Te(te,J,E,N,P);this.beginNodes[E].push(se),this.endNodes[E+N].push(se),this.nodes.push(se)}viterbi(){const E=this.len;let N=0;for(;N<=E;){if(this.beginNodes[N].length==0)return[];for(let ae of this.beginNodes[N]){ae.prev=null;let D=0,ee=null;for(let G of this.endNodes[N]){const ie=G.backtraceScore+ae.score;(ee===null||ie>D)&&(ee=G.clone(),D=ie)}if(ee!==null)ae.prev=ee,ae.backtraceScore=D;else return[]}++N}const P=[],J=this.beginNodes[E][0].prev;if(J===null)return[];let se=J.clone();for(;se.prev!==null;)P.push(se.clone()),se=se.clone().prev.clone();return P.reverse(),P}piece(E){return this.sentence.slice(E.pos,E.pos+E.length)}tokens(){return this.viterbi().map(N=>this.piece(N))}tokenIds(){return this.viterbi().map(N=>N.tokenId)}}class Te{constructor(E,N,P,te,J){this.tokenId=E,this.nodeId=N,this.pos=P,this.length=te,this.score=J,this.prev=null,this.backtraceScore=0}clone(){const E=new Te(this.tokenId,this.nodeId,this.pos,this.length,this.score);return E.prev=this.prev,E.backtraceScore=this.backtraceScore,E}}},"./src/utils/devices.js":($t,me,l)=>{l.r(me),l.d(me,{DEVICE_TYPES:()=>x});const x=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"})},"./src/utils/dtypes.js":($t,me,l)=>{l.r(me),l.d(me,{DATA_TYPES:()=>ve,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Te,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>B,isWebGpuFp16Supported:()=>ye});var x=l("./src/env.js"),X=l("./src/utils/devices.js");const ye=function(){let E;return async function(){if(E===void 0)if(!x.apis.IS_WEBGPU_AVAILABLE)E=!1;else try{E=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{E=!1}return E}}(),ve=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Te=Object.freeze({[X.DEVICE_TYPES.cpu]:ve.q8,[X.DEVICE_TYPES.gpu]:ve.fp32,[X.DEVICE_TYPES.wasm]:ve.q8,[X.DEVICE_TYPES.webgpu]:ve.fp32}),B=Object.freeze({[ve.fp32]:"",[ve.fp16]:"_fp16",[ve.int8]:"_int8",[ve.uint8]:"_uint8",[ve.q8]:"_quantized",[ve.q4]:"_q4",[ve.q4f16]:"_q4f16",[ve.bnb4]:"_bnb4"})},"./src/utils/generic.js":($t,me,l)=>{l.r(me),l.d(me,{Callable:()=>x});const x=class{constructor(){let X=function(...ye){return X._call(...ye)};return Object.setPrototypeOf(X,new.target.prototype)}_call(...X){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":($t,me,l)=>{l.r(me),l.d(me,{getFile:()=>E,getModelFile:()=>se,getModelJSON:()=>ae});var x=l("?7a2c"),X=l("?a42a"),ye=l("./src/env.js"),ve=l("./src/utils/core.js");class Te{constructor(ie){xe(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=ie,this.headers=new Headers,this.exists=x.existsSync(ie),this.exists){this.status=200,this.statusText="OK";let fe=x.statSync(ie);this.headers.set("content-length",fe.size.toString()),this.updateContentType();let L=this;this.body=new ReadableStream({start(O){L.arrayBuffer().then(j=>{O.enqueue(new Uint8Array(j)),O.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const ie=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[ie]??"application/octet-stream")}clone(){let ie=new Te(this.filePath);return ie.exists=this.exists,ie.status=this.status,ie.statusText=this.statusText,ie.headers=new Headers(this.headers),ie}async arrayBuffer(){return(await x.promises.readFile(this.filePath)).buffer}async blob(){const ie=await x.promises.readFile(this.filePath);return new Blob([ie],{type:this.headers.get("content-type")})}async text(){return await x.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function B(G,ie=null,fe=null){let L;try{L=new URL(G)}catch{return!1}return!(ie&&!ie.includes(L.protocol)||fe&&!fe.includes(L.hostname))}async function E(G){var ie;if(ye.env.useFS&&!B(G,["http:","https:","blob:"]))return new Te(G);if(typeof process<"u"&&((ie=process==null?void 0:process.release)==null?void 0:ie.name)==="node"){const fe=!!(wn!=null&&wn.TESTING_REMOTELY),L=ye.env.version,O=new Headers;if(O.set("User-Agent",`transformers.js/${L}; is_ci/${fe};`),B(G,["http:","https:"],["huggingface.co","hf.co"])){const A=(wn==null?void 0:wn.HF_TOKEN)??(wn==null?void 0:wn.HF_ACCESS_TOKEN);A&&O.set("Authorization",`Bearer ${A}`)}return fetch(G,{headers:O})}else return fetch(G)}const N={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",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 P(G,ie,fe){if(!fe)return null;const L=N[G]??`Error (${G}) occurred while trying to load file`;throw Error(`${L}: "${ie}".`)}class te{constructor(ie){this.path=ie}async match(ie){let fe=X.join(this.path,ie),L=new Te(fe);if(L.exists)return L}async put(ie,fe){const L=Buffer.from(await fe.arrayBuffer());let O=X.join(this.path,ie);try{await x.promises.mkdir(X.dirname(O),{recursive:!0}),await x.promises.writeFile(O,L)}catch(j){console.warn("An error occurred while writing the file to cache:",j)}}}async function J(G,...ie){for(let fe of ie)try{let L=await G.match(fe);if(L)return L}catch{continue}}async function se(G,ie,fe=!0,L={}){if(!ye.env.allowLocalModels){if(L.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(!ye.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,ve.dispatchCallback)(L.progress_callback,{status:"initiate",name:G,file:ie});let O;if(!O&&ye.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{O=await caches.open("transformers-cache")}catch(pe){console.warn("An error occurred while opening the browser cache:",pe)}}if(!O&&ye.env.useFSCache&&(O=new te(L.cache_dir??ye.env.cacheDir)),!O&&ye.env.useCustomCache){if(!ye.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ye.env.customCache.match||!ye.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");O=ye.env.customCache}const j=L.revision??"main";let A=ee(G,ie),ge=ee(ye.env.localModelPath,A),be=ee(ye.env.remoteHost,ye.env.remotePathTemplate.replaceAll("{model}",G).replaceAll("{revision}",encodeURIComponent(j)),ie),Ce=j==="main"?A:ee(G,j,ie),ke,De=O instanceof te?Ce:be,Je=!1,Ue;O&&(Ue=await J(O,ge,De));const bt=Ue!==void 0;if(Ue===void 0){if(ye.env.allowLocalModels)if(B(A,["http:","https:"])){if(L.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${A}.`);if(!ye.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${A}.`)}else try{Ue=await E(ge),ke=ge}catch(Ee){console.warn(`Unable to load from local path "${ge}": "${Ee}"`)}if(Ue===void 0||Ue.status===404){if(L.local_files_only||!ye.env.allowRemoteModels){if(fe)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ge}".`);return null}if(Ue=await E(be),Ue.status!==200)return P(Ue.status,be,fe);ke=De}Je=O&&typeof Response<"u"&&Ue instanceof Response&&Ue.status===200}(0,ve.dispatchCallback)(L.progress_callback,{status:"download",name:G,file:ie});const _e={status:"progress",name:G,file:ie};let V;return L.progress_callback?bt&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(V=new Uint8Array(await Ue.arrayBuffer()),(0,ve.dispatchCallback)(L.progress_callback,{..._e,progress:100,loaded:V.length,total:V.length})):V=await D(Ue,pe=>{(0,ve.dispatchCallback)(L.progress_callback,{..._e,...pe})}):V=new Uint8Array(await Ue.arrayBuffer()),Je&&ke&&await O.match(ke)===void 0&&await O.put(ke,new Response(V,{headers:Ue.headers})).catch(pe=>{console.warn(`Unable to add response to browser cache: ${pe}.`)}),(0,ve.dispatchCallback)(L.progress_callback,{status:"done",name:G,file:ie}),V}async function ae(G,ie,fe=!0,L={}){let O=await se(G,ie,fe,L);if(O===null)return{};let A=new TextDecoder("utf-8").decode(O);return JSON.parse(A)}async function D(G,ie){const fe=G.headers.get("Content-Length");fe===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let L=parseInt(fe??"0"),O=new Uint8Array(L),j=0;const A=G.body.getReader();async function ge(){const{done:be,value:Ce}=await A.read();if(be)return;let ke=j+Ce.length;if(ke>L){L=ke;let Je=new Uint8Array(L);Je.set(O),O=Je}O.set(Ce,j),j=ke;const De=j/L*100;return ie({progress:De,loaded:j,total:L}),ge()}return await ge(),O}function ee(...G){return G=G.map((ie,fe)=>(fe&&(ie=ie.replace(new RegExp("^/"),"")),fe!==G.length-1&&(ie=ie.replace(new RegExp("/$"),"")),ie)),G.join("/")}},"./src/utils/image.js":($t,me,l)=>{l.r(me),l.d(me,{RawImage:()=>se});var x=l("./src/utils/hub.js"),X=l("./src/env.js"),ye=l("./src/utils/tensor.js"),ve=l("?2b25");const Te=typeof self<"u",B=Te&&self.constructor.name==="DedicatedWorkerGlobalScope";let E,N,P;if(Te)E=(ae,D)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ae,D)},P=self.createImageBitmap,N=self.ImageData;else if(ve)P=async ae=>{const ee=(await ae.metadata()).channels,{data:G,info:ie}=await ae.rotate().raw().toBuffer({resolveWithObject:!0}),fe=new se(new Uint8ClampedArray(G),ie.width,ie.height,ie.channels);return ee!==void 0&&ee!==ie.channels&&fe.convert(ee),fe};else throw new Error("Unable to load image processing library.");const te={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},J=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class se{constructor(D,ee,G,ie){this.data=D,this.width=ee,this.height=G,this.channels=ie}get size(){return[this.width,this.height]}static async read(D){if(D instanceof se)return D;if(typeof D=="string"||D instanceof URL)return await this.fromURL(D);throw new Error(`Unsupported input type: ${typeof D}`)}static fromCanvas(D){if(!Te)throw new Error("fromCanvas() is only supported in browser environments.");const G=D.getContext("2d").getImageData(0,0,D.width,D.height).data;return new se(G,D.width,D.height,4)}static async fromURL(D){const ee=await(0,x.getFile)(D);if(ee.status!==200)throw new Error(`Unable to read image from "${D}" (${ee.status} ${ee.statusText})`);const G=await ee.blob();return this.fromBlob(G)}static async fromBlob(D){if(Te){const ee=await P(D),G=E(ee.width,ee.height).getContext("2d");return G.drawImage(ee,0,0),new this(G.getImageData(0,0,ee.width,ee.height).data,ee.width,ee.height,4)}else{const ee=ve(await D.arrayBuffer());return await P(ee)}}static fromTensor(D,ee="CHW"){if(D.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${D.dims.length} dimensions.`);if(ee==="CHW")D=D.transpose(1,2,0);else if(ee!=="HWC")throw new Error(`Unsupported channel format: ${ee}`);if(!(D.data instanceof Uint8ClampedArray||D.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${D.type}`);switch(D.dims[2]){case 1:case 2:case 3:case 4:return new se(D.data,D.dims[1],D.dims[0],D.dims[2]);default:throw new Error(`Unsupported number of channels: ${D.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const D=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let ee=0,G=0;ee=0?j=G:ge=-G,ie>=0?A=ie:be=-ie,O.drawImage(L,j,A,D,ee,ge,be,D,ee),new se(O.getImageData(0,0,D,ee).data,D,ee,4).convert(fe)}else{let fe=this.toSharp();if(G>=0&&ie>=0)fe=fe.extract({left:Math.floor(G),top:Math.floor(ie),width:D,height:ee});else if(G<=0&&ie<=0){const L=Math.floor(-ie),O=Math.floor(-G);fe=fe.extend({top:L,left:O,right:D-this.width-O,bottom:ee-this.height-L})}else{let L=[0,0],O=0;ie<0?(L[0]=Math.floor(-ie),L[1]=ee-this.height-L[0]):O=Math.floor(ie);let j=[0,0],A=0;G<0?(j[0]=Math.floor(-G),j[1]=D-this.width-j[0]):A=Math.floor(G),fe=fe.extend({top:L[0],bottom:L[1],left:j[0],right:j[1]}).extract({left:A,top:O,width:D,height:ee})}return await P(fe)}}async toBlob(D="image/png",ee=1){if(!Te)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:D,quality:ee})}toTensor(D="CHW"){let ee=new ye.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(D!=="HWC")if(D==="CHW")ee=ee.permute(2,0,1);else throw new Error(`Unsupported channel format: ${D}`);return ee}toCanvas(){if(!Te)throw new Error("toCanvas() is only supported in browser environments.");const D=this.clone().rgba(),ee=E(D.width,D.height),G=new N(D.data,D.width,D.height);return ee.getContext("2d").putImageData(G,0,0),ee}_update(D,ee,G,ie=null){return this.data=D,this.width=ee,this.height=G,ie!==null&&(this.channels=ie),this}clone(){return new se(this.data.slice(),this.width,this.height,this.channels)}convert(D){if(this.channels===D)return this;switch(D){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}async save(D){if(Te){if(B)throw new Error("Unable to save an image from a Web Worker.");const ee=D.split(".").pop().toLowerCase(),G=J.get(ee)??"image/png",ie=await this.toBlob(G),fe=URL.createObjectURL(ie),L=document.createElement("a");L.href=fe,L.download=D,L.click(),L.remove()}else{if(X.env.useFS)return await this.toSharp().toFile(D);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Te)throw new Error("toSharp() is only supported in server-side environments.");return ve(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":($t,me,l)=>{l.r(me),l.d(me,{FFT:()=>ae,bankers_round:()=>G,cos_sim:()=>B,dot:()=>Te,dynamic_time_warping:()=>ie,interpolate_data:()=>x,log_softmax:()=>ve,magnitude:()=>E,max:()=>P,medianFilter:()=>D,min:()=>N,permute_data:()=>X,round:()=>ee,softmax:()=>ye});function x(fe,[L,O,j],[A,ge],be="bilinear",Ce=!1){const ke=ge/j,De=A/O,Je=new fe.constructor(A*ge*L),Ue=O*j,bt=A*ge;for(let _e=0;_e=0;--Ce)A[Ce]=ke,j[Ce]=L[O[Ce]],ke*=j[Ce];const ge=O.map((Ce,ke)=>A[O.indexOf(ke)]),be=new fe.constructor(fe.length);for(let Ce=0;Ce=0;--De)ke+=Je%L[De]*ge[De],Je=Math.floor(Je/L[De]);be[ke]=fe[Ce]}return[be,j]}function ye(fe){const L=P(fe)[0],O=fe.map(ge=>Math.exp(ge-L)),j=O.reduce((ge,be)=>ge+be,0);return O.map(ge=>ge/j)}function ve(fe){return ye(fe).map(j=>Math.log(j))}function Te(fe,L){let O=0;for(let j=0;jL+O*O,0))}function N(fe){if(fe.length===0)throw Error("Array must not be empty");let L=fe[0],O=0;for(let j=1;jL&&(L=fe[j],O=j);return[Number(L),O]}function te(fe){return fe>0&&(fe&fe-1)===0}class J{constructor(L){if(this.size=L|0,this.size<=1||!te(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=L<<1,this.table=new Float64Array(this.size*2);for(let j=0;jj;j<<=1)++O;this._width=O%2===0?O-1:O,this._bitrev=new Int32Array(1<>>A&3)<>>1);for(let A=0;A>>1]=L[A];return j}toComplexArray(L,O){const j=O||this.createComplexArray();for(let A=0;A>>1],j[A+1]=0;return j}transform(L,O){if(L===O)throw new Error("Input and output buffers must be different");this._transform4(L,O,1)}realTransform(L,O){if(L===O)throw new Error("Input and output buffers must be different");this._realTransform4(L,O,1)}inverseTransform(L,O){if(L===O)throw new Error("Input and output buffers must be different");this._transform4(L,O,-1);for(let j=0;j>=2;be>=2;be>>=2){Ce=A/be<<1;const bt=Ce>>>2;for(ke=0;ke>>1,be>>>1)}else for(ke=0,De=0;ke>>1,be>>>1,j)}const Ue=this.table;for(be>>=2;be>=2;be>>=2){Ce=A/be<<1;const _e=Ce>>>1,V=_e>>>1,pe=V>>>1;for(ke=0;ke>>1;for(let _e=2;_e>1;++Je){const Ue=(Je+1-L)**2/2,bt=Math.sqrt(ke**2+De**2)**Ue,_e=Ue*Math.atan2(De,ke),V=2*Je;ge[V]=bt*Math.cos(_e),ge[V+1]=bt*Math.sin(_e),be[V]=ge[V],be[V+1]=-ge[V+1]}this._slicedChirpBuffer=ge.subarray(O,j),this._f=new J(A>>1),this._f.transform(this._chirpBuffer,be)}_transform(L,O,j){const A=this._buffer1,ge=this._buffer2,be=this._outBuffer1,Ce=this._outBuffer2,ke=this._chirpBuffer,De=this._slicedChirpBuffer,Je=this._a;if(j)for(let Ue=0;Ue>1,V=O[_e];A[Ue]=V*De[Ue],A[bt]=V*De[bt]}else for(let Ue=0;Ue=fe.length&&(ke=2*(fe.length-1)-ke),j[be++]=fe[ke]}j.sort(),O[ge]=j[A]}return O}function ee(fe,L){const O=Math.pow(10,L);return Math.round(fe*O)/O}function G(fe){const L=Math.round(fe);return Math.abs(fe)%1===.5?L%2===0?L:L-1:L}function ie(fe){const L=fe.length,O=fe[0].length,j=[L+1,O+1],A=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));A[0][0]=0;const ge=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let Je=1;Je0||Ce>0;)switch(ke.push(be-1),De.push(Ce-1),ge[be][Ce]){case 0:--be,--Ce;break;case 1:--be;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${be}, ${Ce}]. Please file a bug report.`)}return ke.reverse(),De.reverse(),[ke,De]}},"./src/utils/tensor.js":($t,me,l)=>{l.r(me),l.d(me,{Tensor:()=>Te,cat:()=>fe,full:()=>be,full_like:()=>Ce,interpolate:()=>N,interpolate_4d:()=>P,layer_norm:()=>D,matmul:()=>te,mean:()=>j,mean_pooling:()=>ae,ones:()=>ke,ones_like:()=>De,permute:()=>E,quantize_embeddings:()=>bt,rfft:()=>J,stack:()=>L,std_mean:()=>O,topk:()=>se,zeros:()=>Je,zeros_like:()=>Ue});var x=l("./src/utils/maths.js"),X=l("./src/backends/onnx.js"),ye=l("./src/ops/registry.js");const ve=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Te{constructor(...V){xe(this,"ort_tensor");return(0,X.isONNXTensor)(V[0])?this.ort_tensor=V[0]:this.ort_tensor=new X.Tensor(V[0],V[1],V[2]),new Proxy(this,{get:(pe,Ee)=>{if(typeof Ee=="string"){let re=Number(Ee);if(Number.isInteger(re))return pe._getitem(re)}return pe[Ee]},set:(pe,Ee,re)=>pe[Ee]=re})}get dims(){return this.ort_tensor.dims}set dims(V){this.ort_tensor.dims=V}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[V,...pe]=this.dims;if(pe.length>0){const Ee=pe.reduce((re,Ke)=>re*Ke);for(let re=0;re0){const re=Ee.reduce((Ke,ct)=>Ke*ct);return this._subarray(V,re,Ee)}else return new Te(this.type,[this.data[V]],Ee)}indexOf(V){const pe=this.data;for(let Ee=0;Eeze)throw new Error(`Invalid slice: ${st}`);const ne=[Math.max(xt,0),Math.min(ze,this.dims[Re])];Ee.push(ne),pe.push(ne[1]-ne[0])}else throw new Error(`Invalid slice: ${st}`)}const re=Ee.map(([Re,st])=>st-Re),Ke=re.reduce((Re,st)=>Re*st),ct=this.data,rt=new ct.constructor(Ke),ot=this.stride();for(let Re=0;Re=0;--xt){const ne=re[xt];st+=(ze%ne+Ee[xt][0])*ot[xt],ze=Math.floor(ze/ne)}rt[Re]=ct[st]}return new Te(this.type,rt,pe)}permute(...V){return E(this,V)}transpose(...V){return this.permute(...V)}sum(V=null,pe=!1){return this.norm(1,V,pe)}norm(V="fro",pe=null,Ee=!1){if(V==="fro")V=2;else if(typeof V=="string")throw Error(`Unsupported norm: ${V}`);const re=this.data;if(pe===null){let rt=re.reduce((ot,Re)=>ot+Re**V,0)**(1/V);return new Te(this.type,[rt],[])}pe=ie(pe,this.dims.length);const Ke=this.dims.slice();Ke[pe]=1;const ct=new re.constructor(re.length/this.dims[pe]);for(let rt=0;rt=0;--Re){const ze=this.dims[Re];if(Re!==pe){const ne=st%ze;ot+=ne*xt,xt*=Ke[Re]}st=Math.floor(st/ze)}ct[ot]+=re[rt]**V}if(V!==1)for(let rt=0;rt=0;--ot){const xt=this.dims[ot];if(ot!==pe){const ze=Re%xt;rt+=ze*st,st*=this.dims[ot]}Re=Math.floor(Re/xt)}re[ct]/=Ke[rt]}return this}normalize(V=2,pe=1){return this.clone().normalize_(V,pe)}stride(){return A(this.dims)}squeeze(V=null){return new Te(this.type,this.data,ee(this.dims,V))}squeeze_(V=null){return this.dims=ee(this.dims,V),this}unsqueeze(V=null){return new Te(this.type,this.data,G(this.dims,V))}unsqueeze_(V=null){return this.dims=G(this.dims,V),this}flatten_(V=0,pe=-1){pe=(pe+this.dims.length)%this.dims.length;let Ee=this.dims.slice(0,V),re=this.dims.slice(V,pe+1),Ke=this.dims.slice(pe+1);return this.dims=[...Ee,re.reduce((ct,rt)=>ct*rt,1),...Ke],this}flatten(V=0,pe=-1){return this.clone().flatten_(V,pe)}view(...V){let pe=-1;for(let re=0;rert!==pe?Ke*ct:Ke,1);V[pe]=Ee.length/re}return new Te(this.type,Ee,V)}neg_(){const V=this.data;for(let pe=0;peKe*ct);if(pe!==Ee)throw Error(`cannot reshape array of size ${pe} into shape (${V})`);let re=_e;for(let Ke=V.length-1;Ke>=0;Ke--)re=re.reduce((ct,rt)=>{let ot=ct[ct.length-1];return ot.lengthpe!==1):typeof V=="number"?_e[V]===1&&_e.splice(V,1):Array.isArray(V)&&(_e=_e.filter((pe,Ee)=>pe!==1||!V.includes(Ee))),_e}function G(_e,V){return V=ie(V,_e.length+1),_e=_e.slice(),_e.splice(V,0,1),_e}function ie(_e,V,pe=null,Ee=!0){if(Ee&&(_e<-V||_e>=V))throw new Error(`IndexError: index ${_e} is out of bounds for dimension${pe===null?"":" "+pe} with size ${V}`);return _e<0&&(_e=(_e%V+V)%V),_e}function fe(_e,V=0){V=ie(V,_e[0].dims.length);const pe=_e[0].dims.slice();pe[V]=_e.reduce((ct,rt)=>ct+rt.dims[V],0);const Ee=pe.reduce((ct,rt)=>ct*rt,1),re=new _e[0].data.constructor(Ee),Ke=_e[0].type;if(V===0){let ct=0;for(const rt of _e){const ot=rt.data;re.set(ot,ct),ct+=ot.length}}else{let ct=0;for(let rt=0;rt<_e.length;++rt){const{data:ot,dims:Re}=_e[rt];for(let st=0;st=0;--ze){const je=Re[ze];let qe=ne%je;ze===V&&(qe+=ct),xt+=qe*$e,$e*=pe[ze],ne=Math.floor(ne/je)}re[xt]=ot[st]}ct+=Re[V]}}return new Te(Ke,re,pe)}function L(_e,V=0){return fe(_e.map(pe=>pe.unsqueeze(V)),V)}function O(_e,V=null,pe=1,Ee=!1){const re=_e.data,Ke=_e.dims;if(V===null){const ze=re.reduce((qe,Ve)=>qe+Ve,0)/re.length,ne=Math.sqrt(re.reduce((qe,Ve)=>qe+(Ve-ze)**2,0)/(re.length-pe)),$e=new Te(_e.type,[ze],[]);return[new Te(_e.type,[ne],[]),$e]}V=ie(V,Ke.length);const ct=j(_e,V,Ee),rt=ct.data,ot=Ke.slice();ot[V]=1;const Re=new re.constructor(re.length/Ke[V]);for(let xt=0;xt=0;--ne){const qe=Ke[ne];if(ne!==V){const Ve=$e%qe;ze+=Ve*je,je*=ot[ne]}$e=Math.floor($e/qe)}Re[ze]+=(re[xt]-rt[ze])**2}for(let xt=0;xtot+Re,0);return new Te(_e.type,[rt/Ee.length],[])}const re=_e.dims;V=ie(V,re.length);const Ke=re.slice();Ke[V]=1;const ct=new Ee.constructor(Ee.length/re[V]);for(let rt=0;rt=0;--Re){const ze=re[Re];if(Re!==V){const ne=st%ze;ot+=ne*xt,xt*=Ke[Re]}st=Math.floor(st/ze)}ct[ot]+=Ee[rt]}if(re[V]!==1)for(let rt=0;rt=0;--pe)V[pe]=Ee,Ee*=_e[pe];return V}function ge(_e,V,pe,Ee){const re=_e.reduce((Ke,ct)=>Ke*ct,1);return new Te(pe,new Ee(re).fill(V),_e)}function be(_e,V){let pe,Ee;if(typeof V=="number")pe="float32",Ee=Float32Array;else if(typeof V=="bigint")pe="int64",Ee=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof V}`);return ge(_e,V,pe,Ee)}function Ce(_e,V){return be(_e.dims,V)}function ke(_e){return ge(_e,1n,"int64",BigInt64Array)}function De(_e){return ke(_e.dims)}function Je(_e){return ge(_e,0n,"int64",BigInt64Array)}function Ue(_e){return Je(_e.dims)}function bt(_e,V){if(_e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(_e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(V))throw new Error("The precision must be either 'binary' or 'ubinary'");const pe=V==="binary",Ee=pe?"int8":"uint8",re=pe?Int8Array:Uint8Array,Ke=_e.data,ct=new re(Ke.length/8);for(let rt=0;rt0?1:0,Re=Math.floor(rt/8),st=rt%8;ct[Re]|=ot<<7-st,pe&&st===0&&(ct[Re]-=128)}return new Te(Ee,ct,[_e.dims[0],_e.dims[1]/8])}}},js={};function Vr($t){var me=js[$t];if(me!==void 0)return me.exports;var l=js[$t]={exports:{}};return ns[$t](l,l.exports,Vr),l.exports}(()=>{var $t=Object.getPrototypeOf?l=>Object.getPrototypeOf(l):l=>l.__proto__,me;Vr.t=function(l,x){if(x&1&&(l=this(l)),x&8||typeof l=="object"&&l&&(x&4&&l.__esModule||x&16&&typeof l.then=="function"))return l;var X=Object.create(null);Vr.r(X);var ye={};me=me||[null,$t({}),$t([]),$t($t)];for(var ve=x&2&&l;typeof ve=="object"&&!~me.indexOf(ve);ve=$t(ve))Object.getOwnPropertyNames(ve).forEach(Te=>ye[Te]=()=>l[Te]);return ye.default=()=>l,Vr.d(X,ye),X}})(),Vr.d=($t,me)=>{for(var l in me)Vr.o(me,l)&&!Vr.o($t,l)&&Object.defineProperty($t,l,{enumerable:!0,get:me[l]})},Vr.o=($t,me)=>Object.prototype.hasOwnProperty.call($t,me),Vr.r=$t=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty($t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty($t,"__esModule",{value:!0})},(()=>{var $t;if(typeof self.location.href=="string"&&($t=self.location.href),!$t)throw new Error("Automatic publicPath is not supported in this browser");$t=$t.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Vr.p=$t})(),Vr.b=void 0;var p={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Vr.r(p),Vr.d(p,{ASTFeatureExtractor:()=>X.ASTFeatureExtractor,ASTForAudioClassification:()=>l.ASTForAudioClassification,ASTModel:()=>l.ASTModel,ASTPreTrainedModel:()=>l.ASTPreTrainedModel,AlbertForMaskedLM:()=>l.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>l.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>l.AlbertForSequenceClassification,AlbertModel:()=>l.AlbertModel,AlbertPreTrainedModel:()=>l.AlbertPreTrainedModel,AlbertTokenizer:()=>x.AlbertTokenizer,AudioClassificationPipeline:()=>me.AudioClassificationPipeline,AutoConfig:()=>ye.AutoConfig,AutoModel:()=>l.AutoModel,AutoModelForAudioClassification:()=>l.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>l.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>l.AutoModelForCTC,AutoModelForCausalLM:()=>l.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>l.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>l.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>l.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>l.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>l.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>l.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>l.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>l.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>l.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>l.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>l.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>l.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>l.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>l.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>l.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>l.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>l.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>l.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>l.AutoModelForVision2Seq,AutoModelForXVector:()=>l.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>l.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>X.AutoProcessor,AutoTokenizer:()=>x.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>me.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>l.BartForConditionalGeneration,BartForSequenceClassification:()=>l.BartForSequenceClassification,BartModel:()=>l.BartModel,BartPretrainedModel:()=>l.BartPretrainedModel,BartTokenizer:()=>x.BartTokenizer,BaseModelOutput:()=>l.BaseModelOutput,BaseStreamer:()=>N.BaseStreamer,BeitFeatureExtractor:()=>X.BeitFeatureExtractor,BeitForImageClassification:()=>l.BeitForImageClassification,BeitModel:()=>l.BeitModel,BeitPreTrainedModel:()=>l.BeitPreTrainedModel,BertForMaskedLM:()=>l.BertForMaskedLM,BertForQuestionAnswering:()=>l.BertForQuestionAnswering,BertForSequenceClassification:()=>l.BertForSequenceClassification,BertForTokenClassification:()=>l.BertForTokenClassification,BertModel:()=>l.BertModel,BertPreTrainedModel:()=>l.BertPreTrainedModel,BertTokenizer:()=>x.BertTokenizer,BitImageProcessor:()=>X.BitImageProcessor,BlenderbotForConditionalGeneration:()=>l.BlenderbotForConditionalGeneration,BlenderbotModel:()=>l.BlenderbotModel,BlenderbotPreTrainedModel:()=>l.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>l.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>l.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>l.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>x.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>x.BlenderbotTokenizer,BloomForCausalLM:()=>l.BloomForCausalLM,BloomModel:()=>l.BloomModel,BloomPreTrainedModel:()=>l.BloomPreTrainedModel,BloomTokenizer:()=>x.BloomTokenizer,CLIPFeatureExtractor:()=>X.CLIPFeatureExtractor,CLIPImageProcessor:()=>X.CLIPImageProcessor,CLIPModel:()=>l.CLIPModel,CLIPPreTrainedModel:()=>l.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>l.CLIPSegForImageSegmentation,CLIPSegModel:()=>l.CLIPSegModel,CLIPSegPreTrainedModel:()=>l.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>l.CLIPTextModelWithProjection,CLIPTokenizer:()=>x.CLIPTokenizer,CLIPVisionModelWithProjection:()=>l.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>l.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>l.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>l.CamembertForSequenceClassification,CamembertForTokenClassification:()=>l.CamembertForTokenClassification,CamembertModel:()=>l.CamembertModel,CamembertPreTrainedModel:()=>l.CamembertPreTrainedModel,CamembertTokenizer:()=>x.CamembertTokenizer,CausalLMOutput:()=>l.CausalLMOutput,CausalLMOutputWithPast:()=>l.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>X.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>l.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>l.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>l.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>X.ClapFeatureExtractor,ClapModel:()=>l.ClapModel,ClapPreTrainedModel:()=>l.ClapPreTrainedModel,ClapTextModelWithProjection:()=>l.ClapTextModelWithProjection,CodeGenForCausalLM:()=>l.CodeGenForCausalLM,CodeGenModel:()=>l.CodeGenModel,CodeGenPreTrainedModel:()=>l.CodeGenPreTrainedModel,CodeGenTokenizer:()=>x.CodeGenTokenizer,CodeLlamaTokenizer:()=>x.CodeLlamaTokenizer,CohereForCausalLM:()=>l.CohereForCausalLM,CohereModel:()=>l.CohereModel,CoherePreTrainedModel:()=>l.CoherePreTrainedModel,CohereTokenizer:()=>x.CohereTokenizer,ConvBertForMaskedLM:()=>l.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>l.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>l.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>l.ConvBertForTokenClassification,ConvBertModel:()=>l.ConvBertModel,ConvBertPreTrainedModel:()=>l.ConvBertPreTrainedModel,ConvBertTokenizer:()=>x.ConvBertTokenizer,ConvNextFeatureExtractor:()=>X.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>l.ConvNextForImageClassification,ConvNextImageProcessor:()=>X.ConvNextImageProcessor,ConvNextModel:()=>l.ConvNextModel,ConvNextPreTrainedModel:()=>l.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>l.ConvNextV2ForImageClassification,ConvNextV2Model:()=>l.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>l.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>X.DPTFeatureExtractor,DPTForDepthEstimation:()=>l.DPTForDepthEstimation,DPTImageProcessor:()=>X.DPTImageProcessor,DPTModel:()=>l.DPTModel,DPTPreTrainedModel:()=>l.DPTPreTrainedModel,DebertaForMaskedLM:()=>l.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>l.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>l.DebertaForSequenceClassification,DebertaForTokenClassification:()=>l.DebertaForTokenClassification,DebertaModel:()=>l.DebertaModel,DebertaPreTrainedModel:()=>l.DebertaPreTrainedModel,DebertaTokenizer:()=>x.DebertaTokenizer,DebertaV2ForMaskedLM:()=>l.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>l.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>l.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>l.DebertaV2ForTokenClassification,DebertaV2Model:()=>l.DebertaV2Model,DebertaV2PreTrainedModel:()=>l.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>x.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>X.DeiTFeatureExtractor,DeiTForImageClassification:()=>l.DeiTForImageClassification,DeiTModel:()=>l.DeiTModel,DeiTPreTrainedModel:()=>l.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>l.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>l.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>me.DepthEstimationPipeline,DetrFeatureExtractor:()=>X.DetrFeatureExtractor,DetrForObjectDetection:()=>l.DetrForObjectDetection,DetrForSegmentation:()=>l.DetrForSegmentation,DetrModel:()=>l.DetrModel,DetrObjectDetectionOutput:()=>l.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>l.DetrPreTrainedModel,DetrSegmentationOutput:()=>l.DetrSegmentationOutput,Dinov2ForImageClassification:()=>l.Dinov2ForImageClassification,Dinov2Model:()=>l.Dinov2Model,Dinov2PreTrainedModel:()=>l.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>l.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>l.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>l.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>l.DistilBertForTokenClassification,DistilBertModel:()=>l.DistilBertModel,DistilBertPreTrainedModel:()=>l.DistilBertPreTrainedModel,DistilBertTokenizer:()=>x.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>me.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>X.DonutFeatureExtractor,DonutSwinModel:()=>l.DonutSwinModel,DonutSwinPreTrainedModel:()=>l.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>l.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>X.EfficientNetImageProcessor,EfficientNetModel:()=>l.EfficientNetModel,EfficientNetPreTrainedModel:()=>l.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>l.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>l.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>l.ElectraForSequenceClassification,ElectraForTokenClassification:()=>l.ElectraForTokenClassification,ElectraModel:()=>l.ElectraModel,ElectraPreTrainedModel:()=>l.ElectraPreTrainedModel,ElectraTokenizer:()=>x.ElectraTokenizer,EosTokenCriteria:()=>P.EosTokenCriteria,EsmForMaskedLM:()=>l.EsmForMaskedLM,EsmForSequenceClassification:()=>l.EsmForSequenceClassification,EsmForTokenClassification:()=>l.EsmForTokenClassification,EsmModel:()=>l.EsmModel,EsmPreTrainedModel:()=>l.EsmPreTrainedModel,EsmTokenizer:()=>x.EsmTokenizer,FFT:()=>E.FFT,FalconForCausalLM:()=>l.FalconForCausalLM,FalconModel:()=>l.FalconModel,FalconPreTrainedModel:()=>l.FalconPreTrainedModel,FalconTokenizer:()=>x.FalconTokenizer,FastViTForImageClassification:()=>l.FastViTForImageClassification,FastViTModel:()=>l.FastViTModel,FastViTPreTrainedModel:()=>l.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>me.FeatureExtractionPipeline,FeatureExtractor:()=>X.FeatureExtractor,FillMaskPipeline:()=>me.FillMaskPipeline,Florence2ForConditionalGeneration:()=>l.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>l.Florence2PreTrainedModel,Florence2Processor:()=>X.Florence2Processor,GLPNFeatureExtractor:()=>X.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>l.GLPNForDepthEstimation,GLPNModel:()=>l.GLPNModel,GLPNPreTrainedModel:()=>l.GLPNPreTrainedModel,GPT2LMHeadModel:()=>l.GPT2LMHeadModel,GPT2Model:()=>l.GPT2Model,GPT2PreTrainedModel:()=>l.GPT2PreTrainedModel,GPT2Tokenizer:()=>x.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>l.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>l.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>l.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>l.GPTJForCausalLM,GPTJModel:()=>l.GPTJModel,GPTJPreTrainedModel:()=>l.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>l.GPTNeoForCausalLM,GPTNeoModel:()=>l.GPTNeoModel,GPTNeoPreTrainedModel:()=>l.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>l.GPTNeoXForCausalLM,GPTNeoXModel:()=>l.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>l.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>x.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>l.Gemma2ForCausalLM,Gemma2Model:()=>l.Gemma2Model,Gemma2PreTrainedModel:()=>l.Gemma2PreTrainedModel,GemmaForCausalLM:()=>l.GemmaForCausalLM,GemmaModel:()=>l.GemmaModel,GemmaPreTrainedModel:()=>l.GemmaPreTrainedModel,GemmaTokenizer:()=>x.GemmaTokenizer,Grok1Tokenizer:()=>x.Grok1Tokenizer,HerbertTokenizer:()=>x.HerbertTokenizer,HubertForCTC:()=>l.HubertForCTC,HubertForSequenceClassification:()=>l.HubertForSequenceClassification,HubertModel:()=>l.HubertModel,HubertPreTrainedModel:()=>l.HubertPreTrainedModel,ImageClassificationPipeline:()=>me.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>me.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>X.ImageFeatureExtractor,ImageMattingOutput:()=>l.ImageMattingOutput,ImageSegmentationPipeline:()=>me.ImageSegmentationPipeline,ImageToImagePipeline:()=>me.ImageToImagePipeline,ImageToTextPipeline:()=>me.ImageToTextPipeline,InterruptableStoppingCriteria:()=>P.InterruptableStoppingCriteria,LlamaForCausalLM:()=>l.LlamaForCausalLM,LlamaModel:()=>l.LlamaModel,LlamaPreTrainedModel:()=>l.LlamaPreTrainedModel,LlamaTokenizer:()=>x.LlamaTokenizer,LlavaForConditionalGeneration:()=>l.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>l.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>l.LongT5ForConditionalGeneration,LongT5Model:()=>l.LongT5Model,LongT5PreTrainedModel:()=>l.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>l.M2M100ForConditionalGeneration,M2M100Model:()=>l.M2M100Model,M2M100PreTrainedModel:()=>l.M2M100PreTrainedModel,M2M100Tokenizer:()=>x.M2M100Tokenizer,MBart50Tokenizer:()=>x.MBart50Tokenizer,MBartForCausalLM:()=>l.MBartForCausalLM,MBartForConditionalGeneration:()=>l.MBartForConditionalGeneration,MBartForSequenceClassification:()=>l.MBartForSequenceClassification,MBartModel:()=>l.MBartModel,MBartPreTrainedModel:()=>l.MBartPreTrainedModel,MBartTokenizer:()=>x.MBartTokenizer,MPNetForMaskedLM:()=>l.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>l.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>l.MPNetForSequenceClassification,MPNetForTokenClassification:()=>l.MPNetForTokenClassification,MPNetModel:()=>l.MPNetModel,MPNetPreTrainedModel:()=>l.MPNetPreTrainedModel,MPNetTokenizer:()=>x.MPNetTokenizer,MT5ForConditionalGeneration:()=>l.MT5ForConditionalGeneration,MT5Model:()=>l.MT5Model,MT5PreTrainedModel:()=>l.MT5PreTrainedModel,MarianMTModel:()=>l.MarianMTModel,MarianModel:()=>l.MarianModel,MarianPreTrainedModel:()=>l.MarianPreTrainedModel,MarianTokenizer:()=>x.MarianTokenizer,MaskedLMOutput:()=>l.MaskedLMOutput,MaxLengthCriteria:()=>P.MaxLengthCriteria,MistralForCausalLM:()=>l.MistralForCausalLM,MistralModel:()=>l.MistralModel,MistralPreTrainedModel:()=>l.MistralPreTrainedModel,MobileBertForMaskedLM:()=>l.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>l.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>l.MobileBertForSequenceClassification,MobileBertModel:()=>l.MobileBertModel,MobileBertPreTrainedModel:()=>l.MobileBertPreTrainedModel,MobileBertTokenizer:()=>x.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>X.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>l.MobileNetV1ForImageClassification,MobileNetV1Model:()=>l.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>l.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>X.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>l.MobileNetV2ForImageClassification,MobileNetV2Model:()=>l.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>l.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>X.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>l.MobileNetV3ForImageClassification,MobileNetV3Model:()=>l.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>l.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>X.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>l.MobileNetV4ForImageClassification,MobileNetV4Model:()=>l.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>l.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>X.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>l.MobileViTForImageClassification,MobileViTImageProcessor:()=>X.MobileViTImageProcessor,MobileViTModel:()=>l.MobileViTModel,MobileViTPreTrainedModel:()=>l.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>l.MobileViTV2ForImageClassification,MobileViTV2Model:()=>l.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>l.MobileViTV2PreTrainedModel,ModelOutput:()=>l.ModelOutput,Moondream1ForConditionalGeneration:()=>l.Moondream1ForConditionalGeneration,MptForCausalLM:()=>l.MptForCausalLM,MptModel:()=>l.MptModel,MptPreTrainedModel:()=>l.MptPreTrainedModel,MusicgenForCausalLM:()=>l.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>l.MusicgenForConditionalGeneration,MusicgenModel:()=>l.MusicgenModel,MusicgenPreTrainedModel:()=>l.MusicgenPreTrainedModel,NllbTokenizer:()=>x.NllbTokenizer,NomicBertModel:()=>l.NomicBertModel,NomicBertPreTrainedModel:()=>l.NomicBertPreTrainedModel,NougatImageProcessor:()=>X.NougatImageProcessor,NougatTokenizer:()=>x.NougatTokenizer,OPTForCausalLM:()=>l.OPTForCausalLM,OPTModel:()=>l.OPTModel,OPTPreTrainedModel:()=>l.OPTPreTrainedModel,ObjectDetectionPipeline:()=>me.ObjectDetectionPipeline,OpenELMForCausalLM:()=>l.OpenELMForCausalLM,OpenELMModel:()=>l.OpenELMModel,OpenELMPreTrainedModel:()=>l.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>X.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>l.OwlViTForObjectDetection,OwlViTModel:()=>l.OwlViTModel,OwlViTPreTrainedModel:()=>l.OwlViTPreTrainedModel,OwlViTProcessor:()=>X.OwlViTProcessor,Owlv2ForObjectDetection:()=>l.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>X.Owlv2ImageProcessor,Owlv2Model:()=>l.Owlv2Model,Owlv2PreTrainedModel:()=>l.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>l.Phi3ForCausalLM,Phi3Model:()=>l.Phi3Model,Phi3PreTrainedModel:()=>l.Phi3PreTrainedModel,PhiForCausalLM:()=>l.PhiForCausalLM,PhiModel:()=>l.PhiModel,PhiPreTrainedModel:()=>l.PhiPreTrainedModel,Pipeline:()=>me.Pipeline,PreTrainedModel:()=>l.PreTrainedModel,PreTrainedTokenizer:()=>x.PreTrainedTokenizer,PretrainedConfig:()=>ye.PretrainedConfig,PretrainedMixin:()=>l.PretrainedMixin,Processor:()=>X.Processor,PyAnnoteFeatureExtractor:()=>X.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>l.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>l.PyAnnoteModel,PyAnnotePreTrainedModel:()=>l.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>X.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>l.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>me.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>l.Qwen2ForCausalLM,Qwen2Model:()=>l.Qwen2Model,Qwen2PreTrainedModel:()=>l.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>x.Qwen2Tokenizer,RTDetrForObjectDetection:()=>l.RTDetrForObjectDetection,RTDetrImageProcessor:()=>X.RTDetrImageProcessor,RTDetrModel:()=>l.RTDetrModel,RTDetrObjectDetectionOutput:()=>l.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>l.RTDetrPreTrainedModel,RawImage:()=>Te.RawImage,ResNetForImageClassification:()=>l.ResNetForImageClassification,ResNetModel:()=>l.ResNetModel,ResNetPreTrainedModel:()=>l.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>l.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>l.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>l.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>l.RoFormerForTokenClassification,RoFormerModel:()=>l.RoFormerModel,RoFormerPreTrainedModel:()=>l.RoFormerPreTrainedModel,RoFormerTokenizer:()=>x.RoFormerTokenizer,RobertaForMaskedLM:()=>l.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>l.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>l.RobertaForSequenceClassification,RobertaForTokenClassification:()=>l.RobertaForTokenClassification,RobertaModel:()=>l.RobertaModel,RobertaPreTrainedModel:()=>l.RobertaPreTrainedModel,RobertaTokenizer:()=>x.RobertaTokenizer,SamImageProcessor:()=>X.SamImageProcessor,SamImageSegmentationOutput:()=>l.SamImageSegmentationOutput,SamModel:()=>l.SamModel,SamPreTrainedModel:()=>l.SamPreTrainedModel,SamProcessor:()=>X.SamProcessor,SeamlessM4TFeatureExtractor:()=>X.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>X.SegformerFeatureExtractor,SegformerForImageClassification:()=>l.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>l.SegformerForSemanticSegmentation,SegformerModel:()=>l.SegformerModel,SegformerPreTrainedModel:()=>l.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>l.Seq2SeqLMOutput,SequenceClassifierOutput:()=>l.SequenceClassifierOutput,SiglipImageProcessor:()=>X.SiglipImageProcessor,SiglipModel:()=>l.SiglipModel,SiglipPreTrainedModel:()=>l.SiglipPreTrainedModel,SiglipTextModel:()=>l.SiglipTextModel,SiglipTokenizer:()=>x.SiglipTokenizer,SiglipVisionModel:()=>l.SiglipVisionModel,SpeechT5FeatureExtractor:()=>X.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>l.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>l.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>l.SpeechT5HifiGan,SpeechT5Model:()=>l.SpeechT5Model,SpeechT5PreTrainedModel:()=>l.SpeechT5PreTrainedModel,SpeechT5Processor:()=>X.SpeechT5Processor,SpeechT5Tokenizer:()=>x.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>l.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>l.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>l.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>l.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>l.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>x.SqueezeBertTokenizer,StableLmForCausalLM:()=>l.StableLmForCausalLM,StableLmModel:()=>l.StableLmModel,StableLmPreTrainedModel:()=>l.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>l.Starcoder2ForCausalLM,Starcoder2Model:()=>l.Starcoder2Model,Starcoder2PreTrainedModel:()=>l.Starcoder2PreTrainedModel,StoppingCriteria:()=>P.StoppingCriteria,StoppingCriteriaList:()=>P.StoppingCriteriaList,SummarizationPipeline:()=>me.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>l.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>X.Swin2SRImageProcessor,Swin2SRModel:()=>l.Swin2SRModel,Swin2SRPreTrainedModel:()=>l.Swin2SRPreTrainedModel,SwinForImageClassification:()=>l.SwinForImageClassification,SwinModel:()=>l.SwinModel,SwinPreTrainedModel:()=>l.SwinPreTrainedModel,T5ForConditionalGeneration:()=>l.T5ForConditionalGeneration,T5Model:()=>l.T5Model,T5PreTrainedModel:()=>l.T5PreTrainedModel,T5Tokenizer:()=>x.T5Tokenizer,TableTransformerForObjectDetection:()=>l.TableTransformerForObjectDetection,TableTransformerModel:()=>l.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>l.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>l.TableTransformerPreTrainedModel,Tensor:()=>B.Tensor,Text2TextGenerationPipeline:()=>me.Text2TextGenerationPipeline,TextClassificationPipeline:()=>me.TextClassificationPipeline,TextGenerationPipeline:()=>me.TextGenerationPipeline,TextStreamer:()=>N.TextStreamer,TextToAudioPipeline:()=>me.TextToAudioPipeline,TokenClassificationPipeline:()=>me.TokenClassificationPipeline,TokenClassifierOutput:()=>l.TokenClassifierOutput,TokenizerModel:()=>x.TokenizerModel,TrOCRForCausalLM:()=>l.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>l.TrOCRPreTrainedModel,TranslationPipeline:()=>me.TranslationPipeline,UniSpeechForCTC:()=>l.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>l.UniSpeechForSequenceClassification,UniSpeechModel:()=>l.UniSpeechModel,UniSpeechPreTrainedModel:()=>l.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>l.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>l.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>l.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>l.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>l.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>X.ViTFeatureExtractor,ViTForImageClassification:()=>l.ViTForImageClassification,ViTImageProcessor:()=>X.ViTImageProcessor,ViTModel:()=>l.ViTModel,ViTPreTrainedModel:()=>l.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>l.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>l.VitMatteForImageMatting,VitMatteImageProcessor:()=>X.VitMatteImageProcessor,VitMattePreTrainedModel:()=>l.VitMattePreTrainedModel,VitsModel:()=>l.VitsModel,VitsModelOutput:()=>l.VitsModelOutput,VitsPreTrainedModel:()=>l.VitsPreTrainedModel,VitsTokenizer:()=>x.VitsTokenizer,Wav2Vec2BertForCTC:()=>l.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>l.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>l.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>l.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>x.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>X.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>l.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>l.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>l.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>l.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>l.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>X.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>l.WavLMForAudioFrameClassification,WavLMForCTC:()=>l.WavLMForCTC,WavLMForSequenceClassification:()=>l.WavLMForSequenceClassification,WavLMForXVector:()=>l.WavLMForXVector,WavLMModel:()=>l.WavLMModel,WavLMPreTrainedModel:()=>l.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>X.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>l.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>l.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>X.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>l.WhisperForConditionalGeneration,WhisperModel:()=>l.WhisperModel,WhisperPreTrainedModel:()=>l.WhisperPreTrainedModel,WhisperProcessor:()=>X.WhisperProcessor,WhisperTextStreamer:()=>N.WhisperTextStreamer,WhisperTokenizer:()=>x.WhisperTokenizer,XLMForQuestionAnswering:()=>l.XLMForQuestionAnswering,XLMForSequenceClassification:()=>l.XLMForSequenceClassification,XLMForTokenClassification:()=>l.XLMForTokenClassification,XLMModel:()=>l.XLMModel,XLMPreTrainedModel:()=>l.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>l.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>l.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>l.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>l.XLMRobertaForTokenClassification,XLMRobertaModel:()=>l.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>l.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>x.XLMRobertaTokenizer,XLMTokenizer:()=>x.XLMTokenizer,XLMWithLMHeadModel:()=>l.XLMWithLMHeadModel,XVectorOutput:()=>l.XVectorOutput,YolosFeatureExtractor:()=>X.YolosFeatureExtractor,YolosForObjectDetection:()=>l.YolosForObjectDetection,YolosModel:()=>l.YolosModel,YolosObjectDetectionOutput:()=>l.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>l.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>me.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>me.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>me.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>me.ZeroShotObjectDetectionPipeline,bankers_round:()=>E.bankers_round,cat:()=>B.cat,cos_sim:()=>E.cos_sim,dot:()=>E.dot,dynamic_time_warping:()=>E.dynamic_time_warping,env:()=>$t.env,full:()=>B.full,full_like:()=>B.full_like,getKeyValueShapes:()=>ye.getKeyValueShapes,hamming:()=>ve.hamming,hanning:()=>ve.hanning,interpolate:()=>B.interpolate,interpolate_4d:()=>B.interpolate_4d,interpolate_data:()=>E.interpolate_data,is_chinese_char:()=>x.is_chinese_char,layer_norm:()=>B.layer_norm,log_softmax:()=>E.log_softmax,magnitude:()=>E.magnitude,matmul:()=>B.matmul,max:()=>E.max,mean:()=>B.mean,mean_pooling:()=>B.mean_pooling,medianFilter:()=>E.medianFilter,mel_filter_bank:()=>ve.mel_filter_bank,min:()=>E.min,ones:()=>B.ones,ones_like:()=>B.ones_like,permute:()=>B.permute,permute_data:()=>E.permute_data,pipeline:()=>me.pipeline,quantize_embeddings:()=>B.quantize_embeddings,read_audio:()=>ve.read_audio,rfft:()=>B.rfft,round:()=>E.round,softmax:()=>E.softmax,spectrogram:()=>ve.spectrogram,stack:()=>B.stack,std_mean:()=>B.std_mean,topk:()=>B.topk,window_function:()=>ve.window_function,zeros:()=>B.zeros,zeros_like:()=>B.zeros_like});var $t=Vr("./src/env.js"),me=Vr("./src/pipelines.js"),l=Vr("./src/models.js"),x=Vr("./src/tokenizers.js"),X=Vr("./src/processors.js"),ye=Vr("./src/configs.js"),ve=Vr("./src/utils/audio.js"),Te=Vr("./src/utils/image.js"),B=Vr("./src/utils/tensor.js"),E=Vr("./src/utils/maths.js"),N=Vr("./src/generation/streamers.js"),P=Vr("./src/generation/stopping_criteria.js")})(),p.ASTFeatureExtractor,p.ASTForAudioClassification,p.ASTModel,p.ASTPreTrainedModel,p.AlbertForMaskedLM,p.AlbertForQuestionAnswering,p.AlbertForSequenceClassification,p.AlbertModel,p.AlbertPreTrainedModel,p.AlbertTokenizer,p.AudioClassificationPipeline,p.AutoConfig,p.AutoModel,p.AutoModelForAudioClassification,p.AutoModelForAudioFrameClassification,p.AutoModelForCTC,p.AutoModelForCausalLM,p.AutoModelForDepthEstimation,p.AutoModelForDocumentQuestionAnswering,p.AutoModelForImageClassification,p.AutoModelForImageFeatureExtraction,p.AutoModelForImageMatting,p.AutoModelForImageSegmentation,p.AutoModelForImageToImage,p.AutoModelForMaskGeneration,p.AutoModelForMaskedLM,p.AutoModelForObjectDetection,p.AutoModelForQuestionAnswering,p.AutoModelForSemanticSegmentation,p.AutoModelForSeq2SeqLM,p.AutoModelForSequenceClassification,p.AutoModelForSpeechSeq2Seq,p.AutoModelForTextToSpectrogram,p.AutoModelForTextToWaveform,p.AutoModelForTokenClassification,p.AutoModelForVision2Seq,p.AutoModelForXVector,p.AutoModelForZeroShotObjectDetection,p.AutoProcessor,p.AutoTokenizer,p.AutomaticSpeechRecognitionPipeline,p.BartForConditionalGeneration,p.BartForSequenceClassification,p.BartModel,p.BartPretrainedModel,p.BartTokenizer,p.BaseModelOutput,p.BaseStreamer,p.BeitFeatureExtractor,p.BeitForImageClassification,p.BeitModel,p.BeitPreTrainedModel,p.BertForMaskedLM,p.BertForQuestionAnswering,p.BertForSequenceClassification,p.BertForTokenClassification,p.BertModel,p.BertPreTrainedModel,p.BertTokenizer,p.BitImageProcessor,p.BlenderbotForConditionalGeneration,p.BlenderbotModel,p.BlenderbotPreTrainedModel,p.BlenderbotSmallForConditionalGeneration,p.BlenderbotSmallModel,p.BlenderbotSmallPreTrainedModel,p.BlenderbotSmallTokenizer,p.BlenderbotTokenizer,p.BloomForCausalLM,p.BloomModel,p.BloomPreTrainedModel,p.BloomTokenizer,p.CLIPFeatureExtractor,p.CLIPImageProcessor,p.CLIPModel,p.CLIPPreTrainedModel,p.CLIPSegForImageSegmentation,p.CLIPSegModel,p.CLIPSegPreTrainedModel,p.CLIPTextModelWithProjection,p.CLIPTokenizer,p.CLIPVisionModelWithProjection,p.CamembertForMaskedLM,p.CamembertForQuestionAnswering,p.CamembertForSequenceClassification,p.CamembertForTokenClassification,p.CamembertModel,p.CamembertPreTrainedModel,p.CamembertTokenizer,p.CausalLMOutput,p.CausalLMOutputWithPast,p.ChineseCLIPFeatureExtractor,p.ChineseCLIPModel,p.ChineseCLIPPreTrainedModel,p.ClapAudioModelWithProjection,p.ClapFeatureExtractor,p.ClapModel,p.ClapPreTrainedModel,p.ClapTextModelWithProjection,p.CodeGenForCausalLM,p.CodeGenModel,p.CodeGenPreTrainedModel,p.CodeGenTokenizer,p.CodeLlamaTokenizer,p.CohereForCausalLM,p.CohereModel,p.CoherePreTrainedModel,p.CohereTokenizer,p.ConvBertForMaskedLM,p.ConvBertForQuestionAnswering,p.ConvBertForSequenceClassification,p.ConvBertForTokenClassification,p.ConvBertModel,p.ConvBertPreTrainedModel,p.ConvBertTokenizer,p.ConvNextFeatureExtractor,p.ConvNextForImageClassification,p.ConvNextImageProcessor,p.ConvNextModel,p.ConvNextPreTrainedModel,p.ConvNextV2ForImageClassification,p.ConvNextV2Model,p.ConvNextV2PreTrainedModel,p.DPTFeatureExtractor,p.DPTForDepthEstimation,p.DPTImageProcessor,p.DPTModel,p.DPTPreTrainedModel,p.DebertaForMaskedLM,p.DebertaForQuestionAnswering,p.DebertaForSequenceClassification,p.DebertaForTokenClassification,p.DebertaModel,p.DebertaPreTrainedModel,p.DebertaTokenizer,p.DebertaV2ForMaskedLM,p.DebertaV2ForQuestionAnswering,p.DebertaV2ForSequenceClassification,p.DebertaV2ForTokenClassification,p.DebertaV2Model,p.DebertaV2PreTrainedModel,p.DebertaV2Tokenizer,p.DeiTFeatureExtractor,p.DeiTForImageClassification,p.DeiTModel,p.DeiTPreTrainedModel,p.DepthAnythingForDepthEstimation,p.DepthAnythingPreTrainedModel,p.DepthEstimationPipeline,p.DetrFeatureExtractor,p.DetrForObjectDetection,p.DetrForSegmentation,p.DetrModel,p.DetrObjectDetectionOutput,p.DetrPreTrainedModel,p.DetrSegmentationOutput,p.Dinov2ForImageClassification,p.Dinov2Model,p.Dinov2PreTrainedModel,p.DistilBertForMaskedLM,p.DistilBertForQuestionAnswering,p.DistilBertForSequenceClassification,p.DistilBertForTokenClassification,p.DistilBertModel,p.DistilBertPreTrainedModel,p.DistilBertTokenizer,p.DocumentQuestionAnsweringPipeline,p.DonutFeatureExtractor,p.DonutSwinModel,p.DonutSwinPreTrainedModel,p.EfficientNetForImageClassification,p.EfficientNetImageProcessor,p.EfficientNetModel,p.EfficientNetPreTrainedModel,p.ElectraForMaskedLM,p.ElectraForQuestionAnswering,p.ElectraForSequenceClassification,p.ElectraForTokenClassification,p.ElectraModel,p.ElectraPreTrainedModel,p.ElectraTokenizer,p.EosTokenCriteria,p.EsmForMaskedLM,p.EsmForSequenceClassification,p.EsmForTokenClassification,p.EsmModel,p.EsmPreTrainedModel,p.EsmTokenizer,p.FFT,p.FalconForCausalLM,p.FalconModel,p.FalconPreTrainedModel,p.FalconTokenizer,p.FastViTForImageClassification,p.FastViTModel,p.FastViTPreTrainedModel,p.FeatureExtractionPipeline,p.FeatureExtractor,p.FillMaskPipeline,p.Florence2ForConditionalGeneration,p.Florence2PreTrainedModel,p.Florence2Processor,p.GLPNFeatureExtractor,p.GLPNForDepthEstimation,p.GLPNModel,p.GLPNPreTrainedModel,p.GPT2LMHeadModel,p.GPT2Model,p.GPT2PreTrainedModel,p.GPT2Tokenizer,p.GPTBigCodeForCausalLM,p.GPTBigCodeModel,p.GPTBigCodePreTrainedModel,p.GPTJForCausalLM,p.GPTJModel,p.GPTJPreTrainedModel,p.GPTNeoForCausalLM,p.GPTNeoModel,p.GPTNeoPreTrainedModel,p.GPTNeoXForCausalLM,p.GPTNeoXModel,p.GPTNeoXPreTrainedModel,p.GPTNeoXTokenizer,p.Gemma2ForCausalLM,p.Gemma2Model,p.Gemma2PreTrainedModel,p.GemmaForCausalLM,p.GemmaModel,p.GemmaPreTrainedModel,p.GemmaTokenizer,p.Grok1Tokenizer,p.HerbertTokenizer,p.HubertForCTC,p.HubertForSequenceClassification,p.HubertModel,p.HubertPreTrainedModel,p.ImageClassificationPipeline,p.ImageFeatureExtractionPipeline,p.ImageFeatureExtractor,p.ImageMattingOutput,p.ImageSegmentationPipeline,p.ImageToImagePipeline,p.ImageToTextPipeline,p.InterruptableStoppingCriteria,p.LlamaForCausalLM,p.LlamaModel,p.LlamaPreTrainedModel,p.LlamaTokenizer,p.LlavaForConditionalGeneration,p.LlavaPreTrainedModel,p.LongT5ForConditionalGeneration,p.LongT5Model,p.LongT5PreTrainedModel,p.M2M100ForConditionalGeneration,p.M2M100Model,p.M2M100PreTrainedModel,p.M2M100Tokenizer,p.MBart50Tokenizer,p.MBartForCausalLM,p.MBartForConditionalGeneration,p.MBartForSequenceClassification,p.MBartModel,p.MBartPreTrainedModel,p.MBartTokenizer,p.MPNetForMaskedLM,p.MPNetForQuestionAnswering,p.MPNetForSequenceClassification,p.MPNetForTokenClassification,p.MPNetModel,p.MPNetPreTrainedModel,p.MPNetTokenizer,p.MT5ForConditionalGeneration,p.MT5Model,p.MT5PreTrainedModel,p.MarianMTModel,p.MarianModel,p.MarianPreTrainedModel,p.MarianTokenizer,p.MaskedLMOutput,p.MaxLengthCriteria,p.MistralForCausalLM,p.MistralModel,p.MistralPreTrainedModel,p.MobileBertForMaskedLM,p.MobileBertForQuestionAnswering,p.MobileBertForSequenceClassification,p.MobileBertModel,p.MobileBertPreTrainedModel,p.MobileBertTokenizer,p.MobileNetV1FeatureExtractor,p.MobileNetV1ForImageClassification,p.MobileNetV1Model,p.MobileNetV1PreTrainedModel,p.MobileNetV2FeatureExtractor,p.MobileNetV2ForImageClassification,p.MobileNetV2Model,p.MobileNetV2PreTrainedModel,p.MobileNetV3FeatureExtractor,p.MobileNetV3ForImageClassification,p.MobileNetV3Model,p.MobileNetV3PreTrainedModel,p.MobileNetV4FeatureExtractor,p.MobileNetV4ForImageClassification,p.MobileNetV4Model,p.MobileNetV4PreTrainedModel,p.MobileViTFeatureExtractor,p.MobileViTForImageClassification,p.MobileViTImageProcessor,p.MobileViTModel,p.MobileViTPreTrainedModel,p.MobileViTV2ForImageClassification,p.MobileViTV2Model,p.MobileViTV2PreTrainedModel,p.ModelOutput,p.Moondream1ForConditionalGeneration,p.MptForCausalLM,p.MptModel,p.MptPreTrainedModel,p.MusicgenForCausalLM,p.MusicgenForConditionalGeneration,p.MusicgenModel,p.MusicgenPreTrainedModel,p.NllbTokenizer,p.NomicBertModel,p.NomicBertPreTrainedModel,p.NougatImageProcessor,p.NougatTokenizer,p.OPTForCausalLM,p.OPTModel,p.OPTPreTrainedModel,p.ObjectDetectionPipeline,p.OpenELMForCausalLM,p.OpenELMModel,p.OpenELMPreTrainedModel,p.OwlViTFeatureExtractor,p.OwlViTForObjectDetection,p.OwlViTModel,p.OwlViTPreTrainedModel,p.OwlViTProcessor,p.Owlv2ForObjectDetection,p.Owlv2ImageProcessor,p.Owlv2Model,p.Owlv2PreTrainedModel,p.Phi3ForCausalLM,p.Phi3Model,p.Phi3PreTrainedModel,p.PhiForCausalLM,p.PhiModel,p.PhiPreTrainedModel,p.Pipeline,p.PreTrainedModel,p.PreTrainedTokenizer,p.PretrainedConfig,p.PretrainedMixin,p.Processor,p.PyAnnoteFeatureExtractor,p.PyAnnoteForAudioFrameClassification,p.PyAnnoteModel,p.PyAnnotePreTrainedModel,p.PyAnnoteProcessor,p.QuestionAnsweringModelOutput,p.QuestionAnsweringPipeline,p.Qwen2ForCausalLM,p.Qwen2Model,p.Qwen2PreTrainedModel,p.Qwen2Tokenizer,p.RTDetrForObjectDetection,p.RTDetrImageProcessor,p.RTDetrModel,p.RTDetrObjectDetectionOutput,p.RTDetrPreTrainedModel,p.RawImage,p.ResNetForImageClassification,p.ResNetModel,p.ResNetPreTrainedModel,p.RoFormerForMaskedLM,p.RoFormerForQuestionAnswering,p.RoFormerForSequenceClassification,p.RoFormerForTokenClassification,p.RoFormerModel,p.RoFormerPreTrainedModel,p.RoFormerTokenizer,p.RobertaForMaskedLM,p.RobertaForQuestionAnswering,p.RobertaForSequenceClassification,p.RobertaForTokenClassification,p.RobertaModel,p.RobertaPreTrainedModel,p.RobertaTokenizer,p.SamImageProcessor,p.SamImageSegmentationOutput,p.SamModel,p.SamPreTrainedModel,p.SamProcessor,p.SeamlessM4TFeatureExtractor,p.SegformerFeatureExtractor,p.SegformerForImageClassification,p.SegformerForSemanticSegmentation,p.SegformerModel,p.SegformerPreTrainedModel,p.Seq2SeqLMOutput,p.SequenceClassifierOutput,p.SiglipImageProcessor,p.SiglipModel,p.SiglipPreTrainedModel,p.SiglipTextModel,p.SiglipTokenizer,p.SiglipVisionModel,p.SpeechT5FeatureExtractor,p.SpeechT5ForSpeechToText,p.SpeechT5ForTextToSpeech,p.SpeechT5HifiGan,p.SpeechT5Model,p.SpeechT5PreTrainedModel,p.SpeechT5Processor,p.SpeechT5Tokenizer,p.SqueezeBertForMaskedLM,p.SqueezeBertForQuestionAnswering,p.SqueezeBertForSequenceClassification,p.SqueezeBertModel,p.SqueezeBertPreTrainedModel,p.SqueezeBertTokenizer,p.StableLmForCausalLM,p.StableLmModel,p.StableLmPreTrainedModel,p.Starcoder2ForCausalLM,p.Starcoder2Model,p.Starcoder2PreTrainedModel,p.StoppingCriteria,p.StoppingCriteriaList,p.SummarizationPipeline,p.Swin2SRForImageSuperResolution,p.Swin2SRImageProcessor,p.Swin2SRModel,p.Swin2SRPreTrainedModel,p.SwinForImageClassification,p.SwinModel,p.SwinPreTrainedModel,p.T5ForConditionalGeneration,p.T5Model,p.T5PreTrainedModel,p.T5Tokenizer,p.TableTransformerForObjectDetection,p.TableTransformerModel,p.TableTransformerObjectDetectionOutput,p.TableTransformerPreTrainedModel,p.Tensor,p.Text2TextGenerationPipeline,p.TextClassificationPipeline,p.TextGenerationPipeline,p.TextStreamer,p.TextToAudioPipeline,p.TokenClassificationPipeline,p.TokenClassifierOutput,p.TokenizerModel,p.TrOCRForCausalLM,p.TrOCRPreTrainedModel,p.TranslationPipeline,p.UniSpeechForCTC,p.UniSpeechForSequenceClassification,p.UniSpeechModel,p.UniSpeechPreTrainedModel,p.UniSpeechSatForAudioFrameClassification,p.UniSpeechSatForCTC,p.UniSpeechSatForSequenceClassification,p.UniSpeechSatModel,p.UniSpeechSatPreTrainedModel,p.ViTFeatureExtractor,p.ViTForImageClassification,p.ViTImageProcessor,p.ViTModel,p.ViTPreTrainedModel,p.VisionEncoderDecoderModel,p.VitMatteForImageMatting,p.VitMatteImageProcessor,p.VitMattePreTrainedModel,p.VitsModel,p.VitsModelOutput,p.VitsPreTrainedModel,p.VitsTokenizer,p.Wav2Vec2BertForCTC,p.Wav2Vec2BertForSequenceClassification,p.Wav2Vec2BertModel,p.Wav2Vec2BertPreTrainedModel,p.Wav2Vec2CTCTokenizer,p.Wav2Vec2FeatureExtractor,p.Wav2Vec2ForAudioFrameClassification,p.Wav2Vec2ForCTC,p.Wav2Vec2ForSequenceClassification,p.Wav2Vec2Model,p.Wav2Vec2PreTrainedModel,p.Wav2Vec2ProcessorWithLM,p.WavLMForAudioFrameClassification,p.WavLMForCTC,p.WavLMForSequenceClassification,p.WavLMForXVector,p.WavLMModel,p.WavLMPreTrainedModel,p.WeSpeakerFeatureExtractor,p.WeSpeakerResNetModel,p.WeSpeakerResNetPreTrainedModel,p.WhisperFeatureExtractor,p.WhisperForConditionalGeneration,p.WhisperModel,p.WhisperPreTrainedModel,p.WhisperProcessor,p.WhisperTextStreamer,p.WhisperTokenizer,p.XLMForQuestionAnswering,p.XLMForSequenceClassification,p.XLMForTokenClassification,p.XLMModel,p.XLMPreTrainedModel,p.XLMRobertaForMaskedLM,p.XLMRobertaForQuestionAnswering,p.XLMRobertaForSequenceClassification,p.XLMRobertaForTokenClassification,p.XLMRobertaModel,p.XLMRobertaPreTrainedModel,p.XLMRobertaTokenizer,p.XLMTokenizer,p.XLMWithLMHeadModel,p.XVectorOutput,p.YolosFeatureExtractor,p.YolosForObjectDetection,p.YolosModel,p.YolosObjectDetectionOutput,p.YolosPreTrainedModel,p.ZeroShotAudioClassificationPipeline,p.ZeroShotClassificationPipeline,p.ZeroShotImageClassificationPipeline,p.ZeroShotObjectDetectionPipeline,p.bankers_round,p.cat,p.cos_sim,p.dot,p.dynamic_time_warping;var Yh=p.env;p.full,p.full_like,p.getKeyValueShapes,p.hamming,p.hanning,p.interpolate,p.interpolate_4d,p.interpolate_data,p.is_chinese_char,p.layer_norm,p.log_softmax,p.magnitude,p.matmul,p.max,p.mean,p.mean_pooling,p.medianFilter,p.mel_filter_bank,p.min,p.ones,p.ones_like,p.permute,p.permute_data;var Zh=p.pipeline;p.quantize_embeddings,p.read_audio,p.rfft,p.round,p.softmax,p.spectrogram,p.stack,p.std_mean,p.topk,p.window_function,p.zeros,p.zeros_like,Yh.allowLocalModels=!1;class Ou{static async getInstance(me=null){return this.instance===null&&(this.instance=Zh(this.task,this.model,{progress_callback:me,dtype:"fp32",device:navigator.gpu?"webgpu":"wasm"})),this.instance}}xe(Ou,"task","feature-extraction"),xe(Ou,"model","Supabase/gte-small"),xe(Ou,"instance",null),self.addEventListener("message",async $t=>{let l=await(await Ou.getInstance(X=>{self.postMessage(X)}))($t.data.text,{pooling:"mean",normalize:!0});const x=Array.from(l.data);self.postMessage({status:"complete",embedding:x})})})();