diff --git "a/assets/worker-BSsemfC0.js" "b/assets/worker-BSsemfC0.js" new file mode 100644--- /dev/null +++ "b/assets/worker-BSsemfC0.js" @@ -0,0 +1,2630 @@ +var Wv=Object.defineProperty;var Gv=(Ei,cn,Gn)=>cn in Ei?Wv(Ei,cn,{enumerable:!0,configurable:!0,writable:!0,value:Gn}):Ei[cn]=Gn;var De=(Ei,cn,Gn)=>Gv(Ei,typeof cn!="symbol"?cn+"":cn,Gn);(function(){"use strict";var Ei={},cn={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Ft,Te,m)=>{Ft.exports=m.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{Environment:()=>st,Interpreter:()=>bt,Template:()=>Ot,parse:()=>je,tokenize:()=>B});var P=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"}),re=Object.freeze({set:P.Set,for:P.For,in:P.In,is:P.Is,if:P.If,else:P.Else,endif:P.EndIf,elif:P.ElseIf,endfor:P.EndFor,and:P.And,or:P.Or,not:P.Not,"not in":P.NotIn,macro:P.Macro,endmacro:P.EndMacro,true:P.BooleanLiteral,false:P.BooleanLiteral,True:P.BooleanLiteral,False:P.BooleanLiteral}),ke=class{constructor(S,Y){this.value=S,this.type=Y}};function ze(S){return/\w/.test(S)}function Oe(S){return/[0-9]/.test(S)}var V=[["{%",P.OpenStatement],["%}",P.CloseStatement],["{{",P.OpenExpression],["}}",P.CloseExpression],["(",P.OpenParen],[")",P.CloseParen],["{",P.OpenCurlyBracket],["}",P.CloseCurlyBracket],["[",P.OpenSquareBracket],["]",P.CloseSquareBracket],[",",P.Comma],[".",P.Dot],[":",P.Colon],["|",P.Pipe],["<=",P.ComparisonBinaryOperator],[">=",P.ComparisonBinaryOperator],["==",P.ComparisonBinaryOperator],["!=",P.ComparisonBinaryOperator],["<",P.ComparisonBinaryOperator],[">",P.ComparisonBinaryOperator],["+",P.AdditiveBinaryOperator],["-",P.AdditiveBinaryOperator],["*",P.MultiplicativeBinaryOperator],["/",P.MultiplicativeBinaryOperator],["%",P.MultiplicativeBinaryOperator],["=",P.Equals]],A=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function H(S,Y={}){return S.endsWith(` +`)&&(S=S.slice(0,-1)),S=S.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(S=S.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(S=S.replace(/([#%]})\n/g,"$1")),S.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function B(S,Y={}){var ct,Ut,$t;const D=[],ne=H(S,Y);let xe=0;const ut=Ne=>{let z="";for(;Ne(ne[xe]);){if(ne[xe]==="\\"){if(++xe,xe>=ne.length)throw new SyntaxError("Unexpected end of input");const ee=ne[xe++],Ee=A.get(ee);if(Ee===void 0)throw new SyntaxError(`Unexpected escaped character: ${ee}`);z+=Ee;continue}if(z+=ne[xe++],xe>=ne.length)throw new SyntaxError("Unexpected end of input")}return z};e:for(;xe0){D.push(new ke(ee,P.Text));continue}}ut(ee=>/\s/.test(ee));const z=ne[xe];if(z==="-"||z==="+"){const ee=(Ut=D.at(-1))==null?void 0:Ut.type;if(ee===P.Text||ee===void 0)throw new SyntaxError(`Unexpected character: ${z}`);switch(ee){case P.Identifier:case P.NumericLiteral:case P.BooleanLiteral:case P.StringLiteral:case P.CloseParen:case P.CloseSquareBracket:break;default:{++xe;const Ee=ut(Oe);D.push(new ke(`${z}${Ee}`,Ee.length>0?P.NumericLiteral:P.UnaryOperator));continue}}}for(const[ee,Ee]of V)if(ne.slice(xe,xe+ee.length)===ee){D.push(new ke(ee,Ee)),xe+=ee.length;continue e}if(z==="'"||z==='"'){++xe;const ee=ut(Ee=>Ee!==z);D.push(new ke(ee,P.StringLiteral)),++xe;continue}if(Oe(z)){const ee=ut(Oe);D.push(new ke(ee,P.NumericLiteral));continue}if(ze(z)){const ee=ut(ze),Ee=Object.hasOwn(re,ee)?re[ee]:P.Identifier;Ee===P.In&&(($t=D.at(-1))==null?void 0:$t.type)===P.Not?(D.pop(),D.push(new ke("not in",P.NotIn))):D.push(new ke(ee,Ee));continue}throw new SyntaxError(`Unexpected character: ${z}`)}return D}var le=class{constructor(){De(this,"type","Statement")}},de=class extends le{constructor(Y){super();De(this,"type","Program");this.body=Y}},pe=class extends le{constructor(Y,D,ne){super();De(this,"type","If");this.test=Y,this.body=D,this.alternate=ne}},fe=class extends le{constructor(Y,D,ne,xe){super();De(this,"type","For");this.loopvar=Y,this.iterable=D,this.body=ne,this.defaultBlock=xe}},q=class extends le{constructor(Y,D){super();De(this,"type","Set");this.assignee=Y,this.value=D}},ae=class extends le{constructor(Y,D,ne){super();De(this,"type","Macro");this.name=Y,this.args=D,this.body=ne}},he=class extends le{constructor(){super(...arguments);De(this,"type","Expression")}},ye=class extends he{constructor(Y,D,ne){super();De(this,"type","MemberExpression");this.object=Y,this.property=D,this.computed=ne}},ge=class extends he{constructor(Y,D){super();De(this,"type","CallExpression");this.callee=Y,this.args=D}},K=class extends he{constructor(Y){super();De(this,"type","Identifier");this.value=Y}},R=class extends he{constructor(Y){super();De(this,"type","Literal");this.value=Y}},W=class extends R{constructor(){super(...arguments);De(this,"type","NumericLiteral")}},j=class extends R{constructor(){super(...arguments);De(this,"type","StringLiteral")}},Ce=class extends R{constructor(){super(...arguments);De(this,"type","BooleanLiteral")}},Se=class extends R{constructor(){super(...arguments);De(this,"type","ArrayLiteral")}},Be=class extends R{constructor(){super(...arguments);De(this,"type","TupleLiteral")}},Ve=class extends R{constructor(){super(...arguments);De(this,"type","ObjectLiteral")}},Ge=class extends he{constructor(Y,D,ne){super();De(this,"type","BinaryExpression");this.operator=Y,this.left=D,this.right=ne}},pt=class extends he{constructor(Y,D){super();De(this,"type","FilterExpression");this.operand=Y,this.filter=D}},ot=class extends he{constructor(Y,D){super();De(this,"type","SelectExpression");this.iterable=Y,this.test=D}},Tt=class extends he{constructor(Y,D,ne){super();De(this,"type","TestExpression");this.operand=Y,this.negate=D,this.test=ne}},$e=class extends he{constructor(Y,D){super();De(this,"type","UnaryExpression");this.operator=Y,this.argument=D}},X=class extends he{constructor(Y=void 0,D=void 0,ne=void 0){super();De(this,"type","SliceExpression");this.start=Y,this.stop=D,this.step=ne}},Me=class extends he{constructor(Y,D){super();De(this,"type","KeywordArgumentExpression");this.key=Y,this.value=D}};function je(S){const Y=new de([]);let D=0;function ne(dt,Nt){const Ht=S[D++];if(!Ht||Ht.type!==dt)throw new Error(`Parser Error: ${Nt}. ${Ht.type} !== ${dt}.`);return Ht}function xe(){switch(S[D].type){case P.Text:return Ut();case P.OpenStatement:return $t();case P.OpenExpression:return Ne();default:throw new SyntaxError(`Unexpected token type: ${S[D].type}`)}}function ut(...dt){return D+dt.length<=S.length&&dt.some((Nt,Ht)=>Nt!==S[D+Ht].type)}function ct(...dt){return D+dt.length<=S.length&&dt.every((Nt,Ht)=>Nt===S[D+Ht].type)}function Ut(){return new j(ne(P.Text,"Expected text token").value)}function $t(){ne(P.OpenStatement,"Expected opening statement token");let dt;switch(S[D].type){case P.Set:++D,dt=z(),ne(P.CloseStatement,"Expected closing statement token");break;case P.If:++D,dt=ee(),ne(P.OpenStatement,"Expected {% token"),ne(P.EndIf,"Expected endif token"),ne(P.CloseStatement,"Expected %} token");break;case P.Macro:++D,dt=Ee(),ne(P.OpenStatement,"Expected {% token"),ne(P.EndMacro,"Expected endmacro token"),ne(P.CloseStatement,"Expected %} token");break;case P.For:++D,dt=We(),ne(P.OpenStatement,"Expected {% token"),ne(P.EndFor,"Expected endfor token"),ne(P.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${S[D].type}`)}return dt}function Ne(){ne(P.OpenExpression,"Expected opening expression token");const dt=Ze();return ne(P.CloseExpression,"Expected closing expression token"),dt}function z(){const dt=Ze();if(ct(P.Equals)){++D;const Nt=z();return new q(dt,Nt)}return dt}function ee(){var ii,Zi,Gi,Hr,di,Xr,Ri,Rr;const dt=Ze();ne(P.CloseStatement,"Expected closing statement token");const Nt=[],Ht=[];for(;!(((ii=S[D])==null?void 0:ii.type)===P.OpenStatement&&(((Zi=S[D+1])==null?void 0:Zi.type)===P.ElseIf||((Gi=S[D+1])==null?void 0:Gi.type)===P.Else||((Hr=S[D+1])==null?void 0:Hr.type)===P.EndIf));)Nt.push(xe());if(((di=S[D])==null?void 0:di.type)===P.OpenStatement&&((Xr=S[D+1])==null?void 0:Xr.type)!==P.EndIf)if(++D,ct(P.ElseIf))ne(P.ElseIf,"Expected elseif token"),Ht.push(ee());else for(ne(P.Else,"Expected else token"),ne(P.CloseStatement,"Expected closing statement token");!(((Ri=S[D])==null?void 0:Ri.type)===P.OpenStatement&&((Rr=S[D+1])==null?void 0:Rr.type)===P.EndIf);)Ht.push(xe());return new pe(dt,Nt,Ht)}function Ee(){const dt=Br();if(dt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Nt=Yt();ne(P.CloseStatement,"Expected closing statement token");const Ht=[];for(;ut(P.OpenStatement,P.EndMacro);)Ht.push(xe());return new ae(dt,Nt,Ht)}function Xe(dt=!1){const Nt=dt?Br:Ze,Ht=[Nt()],ii=ct(P.Comma);for(;ii&&(++D,Ht.push(Nt()),!!ct(P.Comma)););return ii?new Be(Ht):Ht[0]}function We(){const dt=Xe(!0);if(!(dt instanceof K||dt instanceof Be))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${dt.type} instead`);ne(P.In,"Expected `in` keyword following loop variable");const Nt=Ze();ne(P.CloseStatement,"Expected closing statement token");const Ht=[];for(;ut(P.OpenStatement,P.EndFor)&&ut(P.OpenStatement,P.Else);)Ht.push(xe());const ii=[];if(ct(P.OpenStatement,P.Else))for(++D,++D,ne(P.CloseStatement,"Expected closing statement token");ut(P.OpenStatement,P.EndFor);)ii.push(xe());return new fe(dt,Nt,Ht,ii)}function Ze(){return vt()}function vt(){const dt=_t();if(ct(P.If)){++D;const Nt=_t();if(ct(P.Else)){++D;const Ht=_t();return new pe(Nt,[dt],[Ht])}else return new ot(dt,Nt)}return dt}function _t(){let dt=zt();for(;ct(P.Or);){const Nt=S[D];++D;const Ht=zt();dt=new Ge(Nt,dt,Ht)}return dt}function zt(){let dt=Ct();for(;ct(P.And);){const Nt=S[D];++D;const Ht=Ct();dt=new Ge(Nt,dt,Ht)}return dt}function Ct(){let dt;for(;ct(P.Not);){const Nt=S[D];++D;const Ht=Ct();dt=new $e(Nt,Ht)}return dt??jt()}function jt(){let dt=Qt();for(;ct(P.ComparisonBinaryOperator)||ct(P.In)||ct(P.NotIn);){const Nt=S[D];++D;const Ht=Qt();dt=new Ge(Nt,dt,Ht)}return dt}function Qt(){let dt=rr();for(;ct(P.AdditiveBinaryOperator);){const Nt=S[D];++D;const Ht=rr();dt=new Ge(Nt,dt,Ht)}return dt}function at(){const dt=dr();return ct(P.OpenParen)?Zt(dt):dt}function Zt(dt){let Nt=new ge(dt,Yt());return ct(P.OpenParen)&&(Nt=Zt(Nt)),Nt}function Yt(){ne(P.OpenParen,"Expected opening parenthesis for arguments list");const dt=ir();return ne(P.CloseParen,"Expected closing parenthesis for arguments list"),dt}function ir(){const dt=[];for(;!ct(P.CloseParen);){let Nt=Ze();if(ct(P.Equals)){if(++D,!(Nt instanceof K))throw new SyntaxError("Expected identifier for keyword argument");const Ht=Ze();Nt=new Me(Nt,Ht)}dt.push(Nt),ct(P.Comma)&&++D}return dt}function nr(){const dt=[];let Nt=!1;for(;!ct(P.CloseSquareBracket);)ct(P.Colon)?(dt.push(void 0),++D,Nt=!0):(dt.push(Ze()),ct(P.Colon)&&(++D,Nt=!0));if(dt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Nt){if(dt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new X(...dt)}return dt[0]}function dr(){let dt=Br();for(;ct(P.Dot)||ct(P.OpenSquareBracket);){const Nt=S[D];++D;let Ht;const ii=Nt.type!==P.Dot;if(ii)Ht=nr(),ne(P.CloseSquareBracket,"Expected closing square bracket");else if(Ht=Br(),Ht.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");dt=new ye(dt,Ht,ii)}return dt}function rr(){let dt=Dr();for(;ct(P.MultiplicativeBinaryOperator);){const Nt=S[D];++D;const Ht=Dr();dt=new Ge(Nt,dt,Ht)}return dt}function Dr(){let dt=Jr();for(;ct(P.Is);){++D;const Nt=ct(P.Not);Nt&&++D;let Ht=Br();if(Ht instanceof Ce&&(Ht=new K(Ht.value.toString())),!(Ht instanceof K))throw new SyntaxError("Expected identifier for the test");dt=new Tt(dt,Nt,Ht)}return dt}function Jr(){let dt=at();for(;ct(P.Pipe);){++D;let Nt=Br();if(!(Nt instanceof K))throw new SyntaxError("Expected identifier for the filter");ct(P.OpenParen)&&(Nt=Zt(Nt)),dt=new pt(dt,Nt)}return dt}function Br(){const dt=S[D];switch(dt.type){case P.NumericLiteral:return++D,new W(Number(dt.value));case P.StringLiteral:return++D,new j(dt.value);case P.BooleanLiteral:return++D,new Ce(dt.value.toLowerCase()==="true");case P.Identifier:return++D,new K(dt.value);case P.OpenParen:{++D;const Nt=Xe();if(S[D].type!==P.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${S[D].type} instead`);return++D,Nt}case P.OpenSquareBracket:{++D;const Nt=[];for(;!ct(P.CloseSquareBracket);)Nt.push(Ze()),ct(P.Comma)&&++D;return++D,new Se(Nt)}case P.OpenCurlyBracket:{++D;const Nt=new Map;for(;!ct(P.CloseCurlyBracket);){const Ht=Ze();ne(P.Colon,"Expected colon between key and value in object literal");const ii=Ze();Nt.set(Ht,ii),ct(P.Comma)&&++D}return++D,new Ve(Nt)}default:throw new SyntaxError(`Unexpected token: ${dt.type}`)}}for(;D=0?(Y=(Y??(Y=0))<0?Math.max(S.length+Y,0):Math.min(Y,S.length),D=(D??(D=S.length))<0?Math.max(S.length+D,0):Math.min(D,S.length)):(Y=(Y??(Y=S.length-1))<0?Math.max(S.length+Y,-1):Math.min(Y,S.length-1),D=(D??(D=-1))<-1?Math.max(S.length+D,-1):Math.min(D,S.length-1));const ut=[];for(let ct=Y;xe*ctY.toUpperCase())}var ft=class{constructor(S=void 0){De(this,"type","RuntimeValue");De(this,"value");De(this,"builtins",new Map);this.value=S}__bool__(){return new gt(!!this.value)}},yt=class extends ft{constructor(){super(...arguments);De(this,"type","NumericValue")}},Qe=class extends ft{constructor(){super(...arguments);De(this,"type","StringValue");De(this,"builtins",new Map([["upper",new Je(()=>new Qe(this.value.toUpperCase()))],["lower",new Je(()=>new Qe(this.value.toLowerCase()))],["strip",new Je(()=>new Qe(this.value.trim()))],["title",new Je(()=>new Qe(xt(this.value)))],["length",new yt(this.value.length)]]))}},gt=class extends ft{constructor(){super(...arguments);De(this,"type","BooleanValue")}},Dt=class extends ft{constructor(){super(...arguments);De(this,"type","ObjectValue");De(this,"builtins",new Map([["get",new Je(([Y,D])=>{if(!(Y instanceof Qe))throw new Error(`Object key must be a string: got ${Y.type}`);return this.value.get(Y.value)??D??new rt})],["items",new Je(()=>new ce(Array.from(this.value.entries()).map(([Y,D])=>new ce([new Qe(Y),D]))))]]))}__bool__(){return new gt(this.value.size>0)}},Ke=class extends Dt{constructor(){super(...arguments);De(this,"type","KeywordArgumentsValue")}},ce=class extends ft{constructor(){super(...arguments);De(this,"type","ArrayValue");De(this,"builtins",new Map([["length",new yt(this.value.length)]]))}__bool__(){return new gt(this.value.length>0)}},Re=class extends ce{constructor(){super(...arguments);De(this,"type","TupleValue")}},Je=class extends ft{constructor(){super(...arguments);De(this,"type","FunctionValue")}},rt=class extends ft{constructor(){super(...arguments);De(this,"type","NullValue")}},et=class extends ft{constructor(){super(...arguments);De(this,"type","UndefinedValue")}},st=class{constructor(S){De(this,"variables",new Map([["namespace",new Je(S=>{if(S.length===0)return new Dt(new Map);if(S.length!==1||!(S[0]instanceof Dt))throw new Error("`namespace` expects either zero arguments or a single object argument");return S[0]})]]));De(this,"tests",new Map([["boolean",S=>S.type==="BooleanValue"],["callable",S=>S instanceof Je],["odd",S=>{if(S.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${S.type}`);return S.value%2!==0}],["even",S=>{if(S.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${S.type}`);return S.value%2===0}],["false",S=>S.type==="BooleanValue"&&!S.value],["true",S=>S.type==="BooleanValue"&&S.value],["string",S=>S.type==="StringValue"],["number",S=>S.type==="NumericValue"],["integer",S=>S.type==="NumericValue"&&Number.isInteger(S.value)],["iterable",S=>S instanceof ce||S instanceof Qe],["lower",S=>{const Y=S.value;return S.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",S=>{const Y=S.value;return S.type==="StringValue"&&Y===Y.toUpperCase()}],["none",S=>S.type==="NullValue"],["defined",S=>S.type!=="UndefinedValue"],["undefined",S=>S.type==="UndefinedValue"],["equalto",(S,Y)=>S.value===Y.value],["eq",(S,Y)=>S.value===Y.value]]));this.parent=S}set(S,Y){return this.declareVariable(S,kt(Y))}declareVariable(S,Y){if(this.variables.has(S))throw new SyntaxError(`Variable already declared: ${S}`);return this.variables.set(S,Y),Y}setVariable(S,Y){return this.variables.set(S,Y),Y}resolve(S){if(this.variables.has(S))return this;if(this.parent)return this.parent.resolve(S);throw new Error(`Unknown variable: ${S}`)}lookupVariable(S){try{return this.resolve(S).variables.get(S)??new et}catch{return new et}}},bt=class{constructor(S){De(this,"global");this.global=S??new st}run(S){return this.evaluate(S,this.global)}evaluateBinaryExpression(S,Y){const D=this.evaluate(S.left,Y);switch(S.operator.value){case"and":return D.__bool__().value?this.evaluate(S.right,Y):D;case"or":return D.__bool__().value?D:this.evaluate(S.right,Y)}const ne=this.evaluate(S.right,Y);switch(S.operator.value){case"==":return new gt(D.value==ne.value);case"!=":return new gt(D.value!=ne.value)}if(D instanceof et||ne instanceof et)throw new Error("Cannot perform operation on undefined values");if(D instanceof rt||ne instanceof rt)throw new Error("Cannot perform operation on null values");if(D instanceof yt&&ne instanceof yt)switch(S.operator.value){case"+":return new yt(D.value+ne.value);case"-":return new yt(D.value-ne.value);case"*":return new yt(D.value*ne.value);case"/":return new yt(D.value/ne.value);case"%":return new yt(D.value%ne.value);case"<":return new gt(D.value":return new gt(D.value>ne.value);case">=":return new gt(D.value>=ne.value);case"<=":return new gt(D.value<=ne.value)}else if(D instanceof ce&&ne instanceof ce)switch(S.operator.value){case"+":return new ce(D.value.concat(ne.value))}else if(ne instanceof ce){const xe=ne.value.find(ut=>ut.value===D.value)!==void 0;switch(S.operator.value){case"in":return new gt(xe);case"not in":return new gt(!xe)}}if(D instanceof Qe||ne instanceof Qe)switch(S.operator.value){case"+":return new Qe(D.value.toString()+ne.value.toString())}if(D instanceof Qe&&ne instanceof Qe)switch(S.operator.value){case"in":return new gt(ne.value.includes(D.value));case"not in":return new gt(!ne.value.includes(D.value))}if(D instanceof Qe&&ne instanceof Dt)switch(S.operator.value){case"in":return new gt(ne.value.has(D.value));case"not in":return new gt(!ne.value.has(D.value))}throw new SyntaxError(`Unknown operator "${S.operator.value}" between ${D.type} and ${ne.type}`)}evaluateArguments(S,Y){const D=[],ne=new Map;for(const xe of S)if(xe.type==="KeywordArgumentExpression"){const ut=xe;ne.set(ut.key.value,this.evaluate(ut.value,Y))}else{if(ne.size>0)throw new Error("Positional arguments must come before keyword arguments");D.push(this.evaluate(xe,Y))}return[D,ne]}evaluateFilterExpression(S,Y){const D=this.evaluate(S.operand,Y);if(S.filter.type==="Identifier"){const ne=S.filter;if(ne.value==="tojson")return new Qe(Et(D));if(D instanceof ce)switch(ne.value){case"list":return D;case"first":return D.value[0];case"last":return D.value[D.value.length-1];case"length":return new yt(D.value.length);case"reverse":return new ce(D.value.reverse());case"sort":return new ce(D.value.sort((xe,ut)=>{if(xe.type!==ut.type)throw new Error(`Cannot compare different types: ${xe.type} and ${ut.type}`);switch(xe.type){case"NumericValue":return xe.value-ut.value;case"StringValue":return xe.value.localeCompare(ut.value);default:throw new Error(`Cannot compare type: ${xe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ne.value}`)}else if(D instanceof Qe)switch(ne.value){case"length":return new yt(D.value.length);case"upper":return new Qe(D.value.toUpperCase());case"lower":return new Qe(D.value.toLowerCase());case"title":return new Qe(xt(D.value));case"capitalize":return new Qe(D.value.charAt(0).toUpperCase()+D.value.slice(1));case"trim":return new Qe(D.value.trim());case"indent":return new Qe(D.value.split(` +`).map((xe,ut)=>ut===0||xe.length===0?xe:" "+xe).join(` +`));case"string":return D;default:throw new Error(`Unknown StringValue filter: ${ne.value}`)}else if(D instanceof yt)switch(ne.value){case"abs":return new yt(Math.abs(D.value));default:throw new Error(`Unknown NumericValue filter: ${ne.value}`)}else if(D instanceof Dt)switch(ne.value){case"items":return new ce(Array.from(D.value.entries()).map(([xe,ut])=>new ce([new Qe(xe),ut])));case"length":return new yt(D.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ne.value}`)}throw new Error(`Cannot apply filter "${ne.value}" to type: ${D.type}`)}else if(S.filter.type==="CallExpression"){const ne=S.filter;if(ne.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ne.callee.type}`);const xe=ne.callee.value;if(xe==="tojson"){const[,ut]=this.evaluateArguments(ne.args,Y),ct=ut.get("indent")??new rt;if(!(ct instanceof yt||ct instanceof rt))throw new Error("If set, indent must be a number");return new Qe(Et(D,ct.value))}if(D instanceof ce){switch(xe){case"selectattr":{if(D.value.some(z=>!(z instanceof Dt)))throw new Error("`selectattr` can only be applied to array of objects");if(ne.args.some(z=>z.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[ut,ct,Ut]=ne.args.map(z=>this.evaluate(z,Y));let $t;if(ct){const z=Y.tests.get(ct.value);if(!z)throw new Error(`Unknown test: ${ct.value}`);$t=z}else $t=(...z)=>z[0].__bool__().value;const Ne=D.value.filter(z=>{const ee=z.value.get(ut.value);return ee?$t(ee,Ut):!1});return new ce(Ne)}case"map":{const[,ut]=this.evaluateArguments(ne.args,Y);if(ut.has("attribute")){const ct=ut.get("attribute");if(!(ct instanceof Qe))throw new Error("attribute must be a string");const Ut=ut.get("default"),$t=D.value.map(Ne=>{if(!(Ne instanceof Dt))throw new Error("items in map must be an object");return Ne.value.get(ct.value)??Ut??new et});return new ce($t)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${xe}`)}else if(D instanceof Qe){switch(xe){case"indent":{const[ut,ct]=this.evaluateArguments(ne.args,Y),Ut=ut.at(0)??ct.get("width")??new yt(4);if(!(Ut instanceof yt))throw new Error("width must be a number");const $t=ut.at(1)??ct.get("first")??new gt(!1),Ne=ut.at(2)??ct.get("blank")??new gt(!1),z=D.value.split(` +`),ee=" ".repeat(Ut.value),Ee=z.map((Xe,We)=>!$t.value&&We===0||!Ne.value&&Xe.length===0?Xe:ee+Xe);return new Qe(Ee.join(` +`))}}throw new Error(`Unknown StringValue filter: ${xe}`)}else throw new Error(`Cannot apply filter "${xe}" to type: ${D.type}`)}throw new Error(`Unknown filter: ${S.filter.type}`)}evaluateTestExpression(S,Y){const D=this.evaluate(S.operand,Y),ne=Y.tests.get(S.test.value);if(!ne)throw new Error(`Unknown test: ${S.test.value}`);const xe=ne(D);return new gt(S.negate?!xe:xe)}evaluateUnaryExpression(S,Y){const D=this.evaluate(S.argument,Y);switch(S.operator.value){case"not":return new gt(!D.value);default:throw new SyntaxError(`Unknown operator: ${S.operator.value}`)}}evalProgram(S,Y){return this.evaluateBlock(S.body,Y)}evaluateBlock(S,Y){let D="";for(const ne of S){const xe=this.evaluate(ne,Y);xe.type!=="NullValue"&&xe.type!=="UndefinedValue"&&(D+=xe.value)}return new Qe(D)}evaluateIdentifier(S,Y){return Y.lookupVariable(S.value)}evaluateCallExpression(S,Y){const[D,ne]=this.evaluateArguments(S.args,Y);ne.size>0&&D.push(new Ke(ne));const xe=this.evaluate(S.callee,Y);if(xe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${xe.type}`);return xe.value(D,Y)}evaluateSliceExpression(S,Y,D){if(!(S instanceof ce||S instanceof Qe))throw new Error("Slice object must be an array or string");const ne=this.evaluate(Y.start,D),xe=this.evaluate(Y.stop,D),ut=this.evaluate(Y.step,D);if(!(ne instanceof yt||ne instanceof et))throw new Error("Slice start must be numeric or undefined");if(!(xe instanceof yt||xe instanceof et))throw new Error("Slice stop must be numeric or undefined");if(!(ut instanceof yt||ut instanceof et))throw new Error("Slice step must be numeric or undefined");return S instanceof ce?new ce(nt(S.value,ne.value,xe.value,ut.value)):new Qe(nt(Array.from(S.value),ne.value,xe.value,ut.value).join(""))}evaluateMemberExpression(S,Y){const D=this.evaluate(S.object,Y);let ne;if(S.computed){if(S.property.type==="SliceExpression")return this.evaluateSliceExpression(D,S.property,Y);ne=this.evaluate(S.property,Y)}else ne=new Qe(S.property.value);let xe;if(D instanceof Dt){if(!(ne instanceof Qe))throw new Error(`Cannot access property with non-string: got ${ne.type}`);xe=D.value.get(ne.value)??D.builtins.get(ne.value)}else if(D instanceof ce||D instanceof Qe)if(ne instanceof yt)xe=D.value.at(ne.value),D instanceof Qe&&(xe=new Qe(D.value.at(ne.value)));else if(ne instanceof Qe)xe=D.builtins.get(ne.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ne.type}`);else{if(!(ne instanceof Qe))throw new Error(`Cannot access property with non-string: got ${ne.type}`);xe=D.builtins.get(ne.value)}return xe instanceof ft?xe:new et}evaluateSet(S,Y){const D=this.evaluate(S.value,Y);if(S.assignee.type==="Identifier"){const ne=S.assignee.value;Y.setVariable(ne,D)}else if(S.assignee.type==="MemberExpression"){const ne=S.assignee,xe=this.evaluate(ne.object,Y);if(!(xe instanceof Dt))throw new Error("Cannot assign to member of non-object");if(ne.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");xe.value.set(ne.property.value,D)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(S.assignee)}`);return new rt}evaluateIf(S,Y){const D=this.evaluate(S.test,Y);return this.evaluateBlock(D.__bool__().value?S.body:S.alternate,Y)}evaluateFor(S,Y){const D=new st(Y);let ne,xe;if(S.iterable.type==="SelectExpression"){const Ne=S.iterable;xe=this.evaluate(Ne.iterable,D),ne=Ne.test}else xe=this.evaluate(S.iterable,D);if(!(xe instanceof ce))throw new Error(`Expected iterable type in for loop: got ${xe.type}`);const ut=[],ct=[];for(let Ne=0;NeXe.setVariable(S.loopvar.value,ee);else if(S.loopvar.type==="TupleLiteral"){const Xe=S.loopvar;if(ee.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ee.type}`);const We=ee;if(Xe.value.length!==We.value.length)throw new Error(`Too ${Xe.value.length>We.value.length?"few":"many"} items to unpack`);Ee=Ze=>{for(let vt=0;vt0?ut[Ne-1]:new et],["nextitem",Ne{var ct;const xe=new st(ne);D=D.slice();let ut;((ct=D.at(-1))==null?void 0:ct.type)==="KeywordArgumentsValue"&&(ut=D.pop());for(let Ut=0;Utthis.evaluate(D,Y)));case"TupleLiteral":return new Re(S.value.map(D=>this.evaluate(D,Y)));case"ObjectLiteral":{const D=new Map;for(const[ne,xe]of S.value){const ut=this.evaluate(ne,Y);if(!(ut instanceof Qe))throw new Error(`Object keys must be strings: got ${ut.type}`);D.set(ut.value,this.evaluate(xe,Y))}return new Dt(D)}case"Identifier":return this.evaluateIdentifier(S,Y);case"CallExpression":return this.evaluateCallExpression(S,Y);case"MemberExpression":return this.evaluateMemberExpression(S,Y);case"UnaryExpression":return this.evaluateUnaryExpression(S,Y);case"BinaryExpression":return this.evaluateBinaryExpression(S,Y);case"FilterExpression":return this.evaluateFilterExpression(S,Y);case"TestExpression":return this.evaluateTestExpression(S,Y);default:throw new SyntaxError(`Unknown node type: ${S.type}`)}}};function kt(S){switch(typeof S){case"number":return new yt(S);case"string":return new Qe(S);case"boolean":return new gt(S);case"undefined":return new et;case"object":return S===null?new rt:Array.isArray(S)?new ce(S.map(kt)):new Dt(new Map(Object.entries(S).map(([Y,D])=>[Y,kt(D)])));case"function":return new Je((Y,D)=>{const ne=S(...Y.map(xe=>xe.value))??null;return kt(ne)});default:throw new Error(`Cannot convert to runtime value: ${S}`)}}function Et(S,Y,D){const ne=D??0;switch(S.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(S.value);case"ArrayValue":case"ObjectValue":{const xe=Y?" ".repeat(Y):"",ut=` +`+xe.repeat(ne),ct=ut+xe;if(S.type==="ArrayValue"){const Ut=S.value.map($t=>Et($t,Y,ne+1));return Y?`[${ct}${Ut.join(`,${ct}`)}${ut}]`:`[${Ut.join(", ")}]`}else{const Ut=Array.from(S.value.entries()).map(([$t,Ne])=>{const z=`"${$t}": ${Et(Ne,Y,ne+1)}`;return Y?`${ct}${z}`:z});return Y?`{${Ut.join(",")}${ut}}`:`{${Ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${S.type}`)}}var Ot=class{constructor(S){De(this,"parsed");const Y=B(S,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=je(Y)}render(S){const Y=new st;Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",xe=>{throw new Error(xe)}),Y.set("range",ue);for(const[xe,ut]of Object.entries(S))Y.set(xe,ut);return new bt(Y).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{registerBackend:()=>ke,resolveBackendAndExecutionProviders:()=>Oe});const P=new Map,re=[],ke=(V,A,H)=>{if(A&&typeof A.init=="function"&&typeof A.createInferenceSessionHandler=="function"){const B=P.get(V);if(B===void 0)P.set(V,{backend:A,priority:H});else{if(B.priority>H)return;if(B.priority===H&&B.backend!==A)throw new Error(`cannot register backend "${V}" using priority ${H}`)}if(H>=0){const le=re.indexOf(V);le!==-1&&re.splice(le,1);for(let de=0;de{const A=P.get(V);if(!A)return"backend not found.";if(A.initialized)return A.backend;if(A.aborted)return A.error;{const H=!!A.initPromise;try{return H||(A.initPromise=A.backend.init(V)),await A.initPromise,A.initialized=!0,A.backend}catch(B){return H||(A.error=`${B}`,A.aborted=!0),A.error}finally{delete A.initPromise}}},Oe=async V=>{const A=V.executionProviders||[],H=A.map(q=>typeof q=="string"?q:q.name),B=H.length===0?re:H;let le;const de=[],pe=new Set;for(const q of B){const ae=await ze(q);typeof ae=="string"?de.push({name:q,err:ae}):(le||(le=ae),le===ae&&pe.add(q))}if(!le)throw new Error(`no available backend found. ERR: ${de.map(q=>`[${q.name}] ${q.err}`).join(", ")}`);for(const{name:q,err:ae}of de)H.includes(q)&&console.warn(`removing requested execution provider "${q}" from session options because it is not available: ${ae}`);const fe=A.filter(q=>pe.has(typeof q=="string"?q:q.name));return[le,new Proxy(V,{get:(q,ae)=>ae==="executionProviders"?fe:Reflect.get(q,ae)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{registerBackend:()=>P.registerBackend});var P=m("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{env:()=>ke});var P=m("./node_modules/onnxruntime-common/dist/esm/version.js");let re="warning";const ke={wasm:{},webgl:{},webgpu:{},versions:{common:P.version},set logLevel(ze){if(ze!==void 0){if(typeof ze!="string"||["verbose","info","warning","error","fatal"].indexOf(ze)===-1)throw new Error(`Unsupported logging level: ${ze}`);re=ze}},get logLevel(){return re}};Object.defineProperty(ke,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{env:()=>re});var P=m("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const re=P.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{InferenceSession:()=>ke.InferenceSession,TRACE:()=>Oe.TRACE,TRACE_FUNC_BEGIN:()=>Oe.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Oe.TRACE_FUNC_END,Tensor:()=>ze.Tensor,TrainingSession:()=>V.TrainingSession,env:()=>re.env,registerBackend:()=>P.registerBackend});var P=m("./node_modules/onnxruntime-common/dist/esm/backend.js"),re=m("./node_modules/onnxruntime-common/dist/esm/env.js"),ke=m("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),ze=m("./node_modules/onnxruntime-common/dist/esm/tensor.js");m("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),m("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Oe=m("./node_modules/onnxruntime-common/dist/esm/trace.js");m("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),m("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var V=m("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{InferenceSession:()=>ze});var P=m("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),re=m("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ke=m("./node_modules/onnxruntime-common/dist/esm/trace.js");class ze{constructor(V){this.handler=V}async run(V,A,H){(0,ke.TRACE_FUNC_BEGIN)();const B={};let le={};if(typeof V!="object"||V===null||V instanceof re.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let de=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof re.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");de=!1;for(const q of A){if(typeof q!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(q)===-1)throw new RangeError(`'fetches' contains invalid output name: ${q}.`);B[q]=null}if(typeof H=="object"&&H!==null)le=H;else if(typeof H<"u")throw new TypeError("'options' must be an object.")}else{let q=!1;const ae=Object.getOwnPropertyNames(A);for(const he of this.outputNames)if(ae.indexOf(he)!==-1){const ye=A[he];(ye===null||ye instanceof re.Tensor)&&(q=!0,de=!1,B[he]=ye)}if(q){if(typeof H=="object"&&H!==null)le=H;else if(typeof H<"u")throw new TypeError("'options' must be an object.")}else le=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const q of this.inputNames)if(typeof V[q]>"u")throw new Error(`input '${q}' is missing in 'feeds'.`);if(de)for(const q of this.outputNames)B[q]=null;const pe=await this.handler.run(V,B,le),fe={};for(const q in pe)if(Object.hasOwnProperty.call(pe,q)){const ae=pe[q];ae instanceof re.Tensor?fe[q]=ae:fe[q]=new re.Tensor(ae.type,ae.data,ae.dims)}return(0,ke.TRACE_FUNC_END)(),fe}async release(){return this.handler.dispose()}static async create(V,A,H,B){(0,ke.TRACE_FUNC_BEGIN)();let le,de={};if(typeof V=="string"){if(le=V,typeof A=="object"&&A!==null)de=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(V instanceof Uint8Array){if(le=V,typeof A=="object"&&A!==null)de=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer){const ae=V;let he=0,ye=V.byteLength;if(typeof A=="object"&&A!==null)de=A;else if(typeof A=="number"){if(he=A,!Number.isSafeInteger(he))throw new RangeError("'byteOffset' must be an integer.");if(he<0||he>=ae.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ae.byteLength}).`);if(ye=V.byteLength-he,typeof H=="number"){if(ye=H,!Number.isSafeInteger(ye))throw new RangeError("'byteLength' must be an integer.");if(ye<=0||he+ye>ae.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ae.byteLength-he}].`);if(typeof B=="object"&&B!==null)de=B;else if(typeof B<"u")throw new TypeError("'options' must be an object.")}else if(typeof H<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");le=new Uint8Array(ae,he,ye)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[pe,fe]=await(0,P.resolveBackendAndExecutionProviders)(de),q=await pe.createInferenceSessionHandler(le,fe);return(0,ke.TRACE_FUNC_END)(),new ze(q)}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":(Ft,Te,m)=>{m.r(Te),m.d(Te,{InferenceSession:()=>re});var P=m("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const re=P.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Ft,Te,m)=>{m.r(Te)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Ft,Te,m)=>{m.r(Te)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{tensorToDataURL:()=>P,tensorToImageData:()=>re});const P=(ke,ze)=>{const Oe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Oe.width=ke.dims[3],Oe.height=ke.dims[2];const V=Oe.getContext("2d");if(V!=null){let A,H;(ze==null?void 0:ze.tensorLayout)!==void 0&&ze.tensorLayout==="NHWC"?(A=ke.dims[2],H=ke.dims[3]):(A=ke.dims[3],H=ke.dims[2]);const B=(ze==null?void 0:ze.format)!==void 0?ze.format:"RGB",le=ze==null?void 0:ze.norm;let de,pe;le===void 0||le.mean===void 0?de=[255,255,255,255]:typeof le.mean=="number"?de=[le.mean,le.mean,le.mean,le.mean]:(de=[le.mean[0],le.mean[1],le.mean[2],0],le.mean[3]!==void 0&&(de[3]=le.mean[3])),le===void 0||le.bias===void 0?pe=[0,0,0,0]:typeof le.bias=="number"?pe=[le.bias,le.bias,le.bias,le.bias]:(pe=[le.bias[0],le.bias[1],le.bias[2],0],le.bias[3]!==void 0&&(pe[3]=le.bias[3]));const fe=H*A;let q=0,ae=fe,he=fe*2,ye=-1;B==="RGBA"?(q=0,ae=fe,he=fe*2,ye=fe*3):B==="RGB"?(q=0,ae=fe,he=fe*2):B==="RBG"&&(q=0,he=fe,ae=fe*2);for(let ge=0;ge{const Oe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let V;if(Oe!=null){let A,H,B;(ze==null?void 0:ze.tensorLayout)!==void 0&&ze.tensorLayout==="NHWC"?(A=ke.dims[2],H=ke.dims[1],B=ke.dims[3]):(A=ke.dims[3],H=ke.dims[2],B=ke.dims[1]);const le=ze!==void 0&&ze.format!==void 0?ze.format:"RGB",de=ze==null?void 0:ze.norm;let pe,fe;de===void 0||de.mean===void 0?pe=[255,255,255,255]:typeof de.mean=="number"?pe=[de.mean,de.mean,de.mean,de.mean]:(pe=[de.mean[0],de.mean[1],de.mean[2],255],de.mean[3]!==void 0&&(pe[3]=de.mean[3])),de===void 0||de.bias===void 0?fe=[0,0,0,0]:typeof de.bias=="number"?fe=[de.bias,de.bias,de.bias,de.bias]:(fe=[de.bias[0],de.bias[1],de.bias[2],0],de.bias[3]!==void 0&&(fe[3]=de.bias[3]));const q=H*A;if(ze!==void 0&&(ze.format!==void 0&&B===4&&ze.format!=="RGBA"||B===3&&ze.format!=="RGB"&&ze.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const ae=4;let he=0,ye=1,ge=2,K=3,R=0,W=q,j=q*2,Ce=-1;le==="RGBA"?(R=0,W=q,j=q*2,Ce=q*3):le==="RGB"?(R=0,W=q,j=q*2):le==="RBG"&&(R=0,j=q,W=q*2),V=Oe.createImageData(A,H);for(let Se=0;Se{m.r(Te)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{bufferToTensor:()=>re,tensorFromGpuBuffer:()=>Oe,tensorFromImage:()=>ke,tensorFromPinnedBuffer:()=>V,tensorFromTexture:()=>ze});var P=m("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const re=(A,H)=>{if(A===void 0)throw new Error("Image buffer must be defined");if(H.height===void 0||H.width===void 0)throw new Error("Image height and width must be defined");if(H.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:B,width:le}=H,de=H.norm??{mean:255,bias:0};let pe,fe;typeof de.mean=="number"?pe=[de.mean,de.mean,de.mean,de.mean]:pe=[de.mean[0],de.mean[1],de.mean[2],de.mean[3]??255],typeof de.bias=="number"?fe=[de.bias,de.bias,de.bias,de.bias]:fe=[de.bias[0],de.bias[1],de.bias[2],de.bias[3]??0];const q=H.format!==void 0?H.format:"RGBA",ae=H.tensorFormat!==void 0&&H.tensorFormat!==void 0?H.tensorFormat:"RGB",he=B*le,ye=ae==="RGBA"?new Float32Array(he*4):new Float32Array(he*3);let ge=4,K=0,R=1,W=2,j=3,Ce=0,Se=he,Be=he*2,Ve=-1;q==="RGB"&&(ge=3,K=0,R=1,W=2,j=-1),ae==="RGBA"?Ve=he*3:ae==="RBG"?(Ce=0,Be=he,Se=he*2):ae==="BGR"&&(Be=0,Se=he,Ce=he*2);for(let pt=0;pt{const B=typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement,le=typeof ImageData<"u"&&A instanceof ImageData,de=typeof ImageBitmap<"u"&&A instanceof ImageBitmap,pe=typeof A=="string";let fe,q=H??{};const ae=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},he=ye=>ye instanceof HTMLCanvasElement||ye instanceof OffscreenCanvas?ye.getContext("2d"):null;if(B){const ye=ae();ye.width=A.width,ye.height=A.height;const ge=he(ye);if(ge!=null){let K=A.height,R=A.width;if(H!==void 0&&H.resizedHeight!==void 0&&H.resizedWidth!==void 0&&(K=H.resizedHeight,R=H.resizedWidth),H!==void 0){if(q=H,H.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");q.tensorFormat="RGBA",q.height=K,q.width=R}else q.tensorFormat="RGBA",q.height=K,q.width=R;ge.drawImage(A,0,0),fe=ge.getImageData(0,0,R,K).data}else throw new Error("Can not access image data")}else if(le){let ye,ge;if(H!==void 0&&H.resizedWidth!==void 0&&H.resizedHeight!==void 0?(ye=H.resizedHeight,ge=H.resizedWidth):(ye=A.height,ge=A.width),H!==void 0&&(q=H),q.format="RGBA",q.height=ye,q.width=ge,H!==void 0){const K=ae();K.width=ge,K.height=ye;const R=he(K);if(R!=null)R.putImageData(A,0,0),fe=R.getImageData(0,0,ge,ye).data;else throw new Error("Can not access image data")}else fe=A.data}else if(de){if(H===void 0)throw new Error("Please provide image config with format for Imagebitmap");const ye=ae();ye.width=A.width,ye.height=A.height;const ge=he(ye);if(ge!=null){const K=A.height,R=A.width;return ge.drawImage(A,0,0,R,K),fe=ge.getImageData(0,0,R,K).data,q.height=K,q.width=R,re(fe,q)}else throw new Error("Can not access image data")}else{if(pe)return new Promise((ye,ge)=>{const K=ae(),R=he(K);if(!A||!R)return ge();const W=new Image;W.crossOrigin="Anonymous",W.src=A,W.onload=()=>{K.width=W.width,K.height=W.height,R.drawImage(W,0,0,K.width,K.height);const j=R.getImageData(0,0,K.width,K.height);q.height=K.height,q.width=K.width,ye(re(j.data,q))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(fe!==void 0)return re(fe,q);throw new Error("Input data provided is not supported - aborted tensor creation")},ze=(A,H)=>{const{width:B,height:le,download:de,dispose:pe}=H,fe=[1,le,B,4];return new P.Tensor({location:"texture",type:"float32",texture:A,dims:fe,download:de,dispose:pe})},Oe=(A,H)=>{const{dataType:B,dims:le,download:de,dispose:pe}=H;return new P.Tensor({location:"gpu-buffer",type:B??"float32",gpuBuffer:A,dims:le,download:de,dispose:pe})},V=(A,H,B)=>new P.Tensor({location:"cpu-pinned",type:A,data:H,dims:B??[H.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Ft,Te,m)=>{m.r(Te)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>re,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>P,checkTypedArray:()=>ze});const P=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),re=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ke=!1;const ze=()=>{if(!ke){ke=!0;const Oe=typeof BigInt64Array<"u"&&BigInt64Array.from,V=typeof BigUint64Array<"u"&&BigUint64Array.from,A=typeof Float16Array<"u"&&Float16Array.from;Oe&&(P.set("int64",BigInt64Array),re.set(BigInt64Array,"int64")),V&&(P.set("uint64",BigUint64Array),re.set(BigUint64Array,"uint64")),A?(P.set("float16",Float16Array),re.set(Float16Array,"float16")):P.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{Tensor:()=>Oe});var P=m("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),re=m("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ke=m("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),ze=m("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Oe{constructor(A,H,B){(0,ke.checkTypedArray)();let le,de;if(typeof A=="object"&&"location"in A)switch(this.dataLocation=A.location,le=A.type,de=A.dims,A.location){case"cpu-pinned":{const fe=ke.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(le);if(!fe)throw new TypeError(`unsupported type "${le}" to create tensor from pinned buffer`);if(!(A.data instanceof fe))throw new TypeError(`buffer should be of type ${fe.name}`);this.cpuData=A.data;break}case"texture":{if(le!=="float32")throw new TypeError(`unsupported type "${le}" to create tensor from texture`);this.gpuTextureData=A.texture,this.downloader=A.download,this.disposer=A.dispose;break}case"gpu-buffer":{if(le!=="float32"&&le!=="float16"&&le!=="int32"&&le!=="int64"&&le!=="uint32"&&le!=="uint8"&&le!=="bool")throw new TypeError(`unsupported type "${le}" to create tensor from gpu buffer`);this.gpuBufferData=A.gpuBuffer,this.downloader=A.download,this.disposer=A.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let fe,q;if(typeof A=="string")if(le=A,q=B,A==="string"){if(!Array.isArray(H))throw new TypeError("A string tensor's data must be a string array.");fe=H}else{const ae=ke.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(A);if(ae===void 0)throw new TypeError(`Unsupported tensor type: ${A}.`);if(Array.isArray(H)){if(A==="float16"&&ae===Uint16Array||A==="uint4"||A==="int4")throw new TypeError(`Creating a ${A} tensor from number array is not supported. Please use ${ae.name} as data.`);A==="uint64"||A==="int64"?fe=ae.from(H,BigInt):fe=ae.from(H)}else if(H instanceof ae)fe=H;else throw new TypeError(`A ${le} tensor's data must be type of ${ae}`)}else if(q=H,Array.isArray(A)){if(A.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const ae=typeof A[0];if(ae==="string")le="string",fe=A;else if(ae==="boolean")le="bool",fe=Uint8Array.from(A);else throw new TypeError(`Invalid element type of data array: ${ae}.`)}else{const ae=ke.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(A.constructor);if(ae===void 0)throw new TypeError(`Unsupported type for tensor data: ${A.constructor}.`);le=ae,fe=A}if(q===void 0)q=[fe.length];else if(!Array.isArray(q))throw new TypeError("A tensor's dims must be a number array");de=q,this.cpuData=fe,this.dataLocation="cpu"}const pe=(0,ze.calculateSize)(de);if(this.cpuData&&pe!==this.cpuData.length&&!((le==="uint4"||le==="int4")&&Math.ceil(pe/2)===this.cpuData.length))throw new Error(`Tensor's size(${pe}) does not match data length(${this.cpuData.length}).`);this.type=le,this.dims=de,this.size=pe}static async fromImage(A,H){return(0,re.tensorFromImage)(A,H)}static fromTexture(A,H){return(0,re.tensorFromTexture)(A,H)}static fromGpuBuffer(A,H){return(0,re.tensorFromGpuBuffer)(A,H)}static fromPinnedBuffer(A,H,B){return(0,re.tensorFromPinnedBuffer)(A,H,B)}toDataURL(A){return(0,P.tensorToDataURL)(this,A)}toImageData(A){return(0,P.tensorToImageData)(this,A)}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(A){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 H=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=H,A&&this.disposer&&(this.disposer(),this.disposer=void 0),H}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(A){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,ze.tensorReshape)(this,A)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{calculateSize:()=>re,tensorReshape:()=>ke});var P=m("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const re=ze=>{let Oe=1;for(let V=0;V{switch(ze.location){case"cpu":return new P.Tensor(ze.type,ze.data,Oe);case"cpu-pinned":return new P.Tensor({location:"cpu-pinned",data:ze.data,type:ze.type,dims:Oe});case"texture":return new P.Tensor({location:"texture",texture:ze.texture,type:ze.type,dims:Oe});case"gpu-buffer":return new P.Tensor({location:"gpu-buffer",gpuBuffer:ze.gpuBuffer,type:ze.type,dims:Oe});default:throw new Error(`tensorReshape: tensor location ${ze.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{Tensor:()=>re});var P=m("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const re=P.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{TRACE:()=>re,TRACE_FUNC_BEGIN:()=>ze,TRACE_FUNC_END:()=>Oe});var P=m("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const re=(V,A)=>{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||console.timeStamp(`${V}::ORT::${A}`)},ke=(V,A)=>{var le;const H=((le=new Error().stack)==null?void 0:le.split(/\r\n|\r|\n/g))||[];let B=!1;for(let de=0;de{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||ke("BEGIN",V)},Oe=V=>{(typeof P.env.trace>"u"?!P.env.wasm.trace:!P.env.trace)||ke("END",V)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{TrainingSession:()=>ze});var P=m("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),re=m("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ke="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class ze{constructor(V,A,H){this.handler=V,this.hasOptimizerModel=A,this.hasEvalModel=H}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(V,A){const H=V.evalModel||"",B=V.optimizerModel||"",le=A||{},[de,pe]=await(0,P.resolveBackendAndExecutionProviders)(le);if(de.createTrainingSessionHandler){const fe=await de.createTrainingSessionHandler(V.checkpointState,V.trainModel,H,B,pe);return new ze(fe,!!V.optimizerModel,!!V.evalModel)}else throw new Error(ke)}typeNarrowingForRunStep(V,A,H,B,le){const de={};let pe={};if(typeof H!="object"||H===null||H instanceof re.Tensor||Array.isArray(H))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let fe=!0;if(typeof B=="object"){if(B===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(B instanceof re.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(B)){if(B.length===0)throw new TypeError("'fetches' cannot be an empty array.");fe=!1;for(const q of B){if(typeof q!="string")throw new TypeError("'fetches' must be a string array or an object.");if(A.indexOf(q)===-1)throw new RangeError(`'fetches' contains invalid output name: ${q}.`);de[q]=null}if(typeof le=="object"&&le!==null)pe=le;else if(typeof le<"u")throw new TypeError("'options' must be an object.")}else{let q=!1;const ae=Object.getOwnPropertyNames(B);for(const he of A)if(ae.indexOf(he)!==-1){const ye=B[he];(ye===null||ye instanceof re.Tensor)&&(q=!0,fe=!1,de[he]=ye)}if(q){if(typeof le=="object"&&le!==null)pe=le;else if(typeof le<"u")throw new TypeError("'options' must be an object.")}else pe=B}}else if(typeof B<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const q of V)if(typeof H[q]>"u")throw new Error(`input '${q}' is missing in 'feeds'.`);if(fe)for(const q of A)de[q]=null;return[de,pe]}convertHandlerReturnTypeToMapOfTensors(V){const A={};for(const H in V)if(Object.hasOwnProperty.call(V,H)){const B=V[H];B instanceof re.Tensor?A[H]=B:A[H]=new re.Tensor(B.type,B.data,B.dims)}return A}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(V,A,H){const[B,le]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,V,A,H),de=await this.handler.runTrainStep(V,B,le);return this.convertHandlerReturnTypeToMapOfTensors(de)}async runOptimizerStep(V){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(V||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(V,A,H){if(this.hasEvalModel){const[B,le]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,V,A,H),de=await this.handler.runEvalStep(V,B,le);return this.convertHandlerReturnTypeToMapOfTensors(de)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(V=!0){return this.handler.getParametersSize(V)}async loadParametersBuffer(V,A=!0){const H=await this.getParametersSize(A);if(V.length!==4*H)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(V,A)}async getContiguousParameters(V=!0){return this.handler.getContiguousParameters(V)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{TrainingSession:()=>re});var P=m("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const re=P.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{version:()=>P});const P="1.20.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Ft,Te,m)=>{m.r(Te),m.d(Te,{InferenceSession:()=>Et,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>rt,TRACE_FUNC_END:()=>et,Tensor:()=>Ke,TrainingSession:()=>Ut,default:()=>Jg,env:()=>j,registerBackend:()=>pe});/*! + * ONNX Runtime Web v1.20.0 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var P=Object.defineProperty,re=Object.getOwnPropertyDescriptor,ke=Object.getOwnPropertyNames,ze=Object.prototype.hasOwnProperty,Oe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),V=(e,t)=>()=>(e&&(t=e(e=0)),t),A=(e,t)=>{for(var i in t)P(e,i,{get:t[i],enumerable:!0})},H=(e,t,i,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ke(t))!ze.call(e,u)&&u!==i&&P(e,u,{get:()=>t[u],enumerable:!(a=re(t,u))||a.enumerable});return e},B=e=>H(P({},"__esModule",{value:!0}),e),le,de,pe,fe,q,ae=V(()=>{le=new Map,de=[],pe=(e,t,i)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let a=le.get(e);if(a===void 0)le.set(e,{backend:t,priority:i});else{if(a.priority>i)return;if(a.priority===i&&a.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${i}`)}if(i>=0){let u=de.indexOf(e);u!==-1&&de.splice(u,1);for(let p=0;p{let t=le.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let i=!!t.initPromise;try{return i||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(a){return i||(t.error=`${a}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},q=async e=>{let t=e.executionProviders||[],i=t.map(g=>typeof g=="string"?g:g.name),a=i.length===0?de:i,u,p=[],d=new Set;for(let g of a){let y=await fe(g);typeof y=="string"?p.push({name:g,err:y}):(u||(u=y),u===y&&d.add(g))}if(!u)throw new Error(`no available backend found. ERR: ${p.map(g=>`[${g.name}] ${g.err}`).join(", ")}`);for(let{name:g,err:y}of p)i.includes(g)&&console.warn(`removing requested execution provider "${g}" from session options because it is not available: ${y}`);let _=t.filter(g=>d.has(typeof g=="string"?g:g.name));return[u,new Proxy(e,{get:(g,y)=>y==="executionProviders"?_:Reflect.get(g,y)})]}}),he=V(()=>{ae()}),ye,ge=V(()=>{ye="1.20.0"}),K,R,W=V(()=>{ge(),K="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:ye},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}`);K=e}},get logLevel(){return K}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),j,Ce=V(()=>{W(),j=R}),Se,Be,Ve=V(()=>{Se=(e,t)=>{let i=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);i.width=e.dims[3],i.height=e.dims[2];let a=i.getContext("2d");if(a!=null){let u,p;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],p=e.dims[3]):(u=e.dims[3],p=e.dims[2]);let d=(t==null?void 0:t.format)!==void 0?t.format:"RGB",_=t==null?void 0:t.norm,g,y;_===void 0||_.mean===void 0?g=[255,255,255,255]:typeof _.mean=="number"?g=[_.mean,_.mean,_.mean,_.mean]:(g=[_.mean[0],_.mean[1],_.mean[2],0],_.mean[3]!==void 0&&(g[3]=_.mean[3])),_===void 0||_.bias===void 0?y=[0,0,0,0]:typeof _.bias=="number"?y=[_.bias,_.bias,_.bias,_.bias]:(y=[_.bias[0],_.bias[1],_.bias[2],0],_.bias[3]!==void 0&&(y[3]=_.bias[3]));let C=p*u,k=0,l=C,F=C*2,I=-1;d==="RGBA"?(k=0,l=C,F=C*2,I=C*3):d==="RGB"?(k=0,l=C,F=C*2):d==="RBG"&&(k=0,F=C,l=C*2);for(let L=0;L{let i=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(i!=null){let u,p,d;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],p=e.dims[1],d=e.dims[3]):(u=e.dims[3],p=e.dims[2],d=e.dims[1]);let _=t!==void 0&&t.format!==void 0?t.format:"RGB",g=t==null?void 0:t.norm,y,C;g===void 0||g.mean===void 0?y=[255,255,255,255]:typeof g.mean=="number"?y=[g.mean,g.mean,g.mean,g.mean]:(y=[g.mean[0],g.mean[1],g.mean[2],255],g.mean[3]!==void 0&&(y[3]=g.mean[3])),g===void 0||g.bias===void 0?C=[0,0,0,0]:typeof g.bias=="number"?C=[g.bias,g.bias,g.bias,g.bias]:(C=[g.bias[0],g.bias[1],g.bias[2],0],g.bias[3]!==void 0&&(C[3]=g.bias[3]));let k=p*u;if(t!==void 0&&(t.format!==void 0&&d===4&&t.format!=="RGBA"||d===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,F=0,I=1,L=2,Q=3,Z=0,U=k,we=k*2,te=-1;_==="RGBA"?(Z=0,U=k,we=k*2,te=k*3):_==="RGB"?(Z=0,U=k,we=k*2):_==="RBG"&&(Z=0,we=k,U=k*2),a=i.createImageData(u,p);for(let me=0;me{Dt(),Ge=(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:i,width:a}=t,u=t.norm??{mean:255,bias:0},p,d;typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:p=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let _=t.format!==void 0?t.format:"RGBA",g=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",y=i*a,C=g==="RGBA"?new Float32Array(y*4):new Float32Array(y*3),k=4,l=0,F=1,I=2,L=3,Q=0,Z=y,U=y*2,we=-1;_==="RGB"&&(k=3,l=0,F=1,I=2,L=-1),g==="RGBA"?we=y*3:g==="RBG"?(Q=0,U=y,Z=y*2):g==="BGR"&&(U=0,Z=y,Q=y*2);for(let te=0;te{let i=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,a=typeof ImageData<"u"&&e instanceof ImageData,u=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,p=typeof e=="string",d,_=t??{},g=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},y=C=>C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?C.getContext("2d"):null;if(i){let C=g();C.width=e.width,C.height=e.height;let k=y(C);if(k!=null){let l=e.height,F=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,F=t.resizedWidth),t!==void 0){if(_=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");_.tensorFormat="RGBA",_.height=l,_.width=F}else _.tensorFormat="RGBA",_.height=l,_.width=F;k.drawImage(e,0,0),d=k.getImageData(0,0,F,l).data}else throw new Error("Can not access image data")}else if(a){let C,k;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(C=t.resizedHeight,k=t.resizedWidth):(C=e.height,k=e.width),t!==void 0&&(_=t),_.format="RGBA",_.height=C,_.width=k,t!==void 0){let l=g();l.width=k,l.height=C;let F=y(l);if(F!=null)F.putImageData(e,0,0),d=F.getImageData(0,0,k,C).data;else throw new Error("Can not access image data")}else d=e.data}else if(u){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let C=g();C.width=e.width,C.height=e.height;let k=y(C);if(k!=null){let l=e.height,F=e.width;return k.drawImage(e,0,0,F,l),d=k.getImageData(0,0,F,l).data,_.height=l,_.width=F,Ge(d,_)}else throw new Error("Can not access image data")}else{if(p)return new Promise((C,k)=>{let l=g(),F=y(l);if(!e||!F)return k();let I=new Image;I.crossOrigin="Anonymous",I.src=e,I.onload=()=>{l.width=I.width,l.height=I.height,F.drawImage(I,0,0,l.width,l.height);let L=F.getImageData(0,0,l.width,l.height);_.height=l.height,_.width=l.width,C(Ge(L.data,_))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return Ge(d,_);throw new Error("Input data provided is not supported - aborted tensor creation")},ot=(e,t)=>{let{width:i,height:a,download:u,dispose:p}=t,d=[1,a,i,4];return new gt({location:"texture",type:"float32",texture:e,dims:d,download:u,dispose:p})},Tt=(e,t)=>{let{dataType:i,dims:a,download:u,dispose:p}=t;return new gt({location:"gpu-buffer",type:i??"float32",gpuBuffer:e,dims:a,download:u,dispose:p})},$e=(e,t,i)=>new gt({location:"cpu-pinned",type:e,data:t,dims:i??[t.length]})}),Me,je,ue,nt,xt=V(()=>{Me=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),je=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ue=!1,nt=()=>{if(!ue){ue=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,i=typeof Float16Array<"u"&&Float16Array.from;e&&(Me.set("int64",BigInt64Array),je.set(BigInt64Array,"int64")),t&&(Me.set("uint64",BigUint64Array),je.set(BigUint64Array,"uint64")),i?(Me.set("float16",Float16Array),je.set(Float16Array,"float16")):Me.set("float16",Uint16Array)}}}),ft,yt,Qe=V(()=>{Dt(),ft=e=>{let t=1;for(let i=0;i{switch(e.location){case"cpu":return new gt(e.type,e.data,t);case"cpu-pinned":return new gt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new gt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new gt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),gt,Dt=V(()=>{Ve(),X(),xt(),Qe(),gt=class{constructor(e,t,i){nt();let a,u;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,a=e.type,u=e.dims,e.location){case"cpu-pinned":{let d=Me.get(a);if(!d)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=e.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="uint8"&&a!=="bool")throw new TypeError(`unsupported type "${a}" 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 d,_;if(typeof e=="string")if(a=e,_=i,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");d=t}else{let g=Me.get(e);if(g===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&g===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${g.name} as data.`);e==="uint64"||e==="int64"?d=g.from(t,BigInt):d=g.from(t)}else if(t instanceof g)d=t;else throw new TypeError(`A ${a} tensor's data must be type of ${g}`)}else if(_=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let g=typeof e[0];if(g==="string")a="string",d=e;else if(g==="boolean")a="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${g}.`)}else{let g=je.get(e.constructor);if(g===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);a=g,d=e}if(_===void 0)_=[d.length];else if(!Array.isArray(_))throw new TypeError("A tensor's dims must be a number array");u=_,this.cpuData=d,this.dataLocation="cpu"}let p=ft(u);if(this.cpuData&&p!==this.cpuData.length&&!((a==="uint4"||a==="int4")&&Math.ceil(p/2)===this.cpuData.length))throw new Error(`Tensor's size(${p}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=u,this.size=p}static async fromImage(e,t){return pt(e,t)}static fromTexture(e,t){return ot(e,t)}static fromGpuBuffer(e,t){return Tt(e,t)}static fromPinnedBuffer(e,t,i){return $e(e,t,i)}toDataURL(e){return Se(this,e)}toImageData(e){return Be(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 yt(this,e)}}}),Ke,ce=V(()=>{Dt(),Ke=gt}),Re,Je,rt,et,st=V(()=>{W(),Re=(e,t)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${e}::ORT::${t}`)},Je=(e,t)=>{var u;let i=((u=new Error().stack)==null?void 0:u.split(/\r\n|\r|\n/g))||[],a=!1;for(let p=0;p{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||Je("BEGIN",e)},et=e=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||Je("END",e)}}),bt,kt=V(()=>{ae(),ce(),st(),bt=class Cg{constructor(t){this.handler=t}async run(t,i,a){rt();let u={},p={};if(typeof t!="object"||t===null||t instanceof Ke||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Ke)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let y of i){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);u[y]=null}if(typeof a=="object"&&a!==null)p=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,C=Object.getOwnPropertyNames(i);for(let k of this.outputNames)if(C.indexOf(k)!==-1){let l=i[k];(l===null||l instanceof Ke)&&(y=!0,d=!1,u[k]=l)}if(y){if(typeof a=="object"&&a!==null)p=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else p=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of this.inputNames)if(typeof t[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(d)for(let y of this.outputNames)u[y]=null;let _=await this.handler.run(t,u,p),g={};for(let y in _)if(Object.hasOwnProperty.call(_,y)){let C=_[y];C instanceof Ke?g[y]=C:g[y]=new Ke(C.type,C.data,C.dims)}return et(),g}async release(){return this.handler.dispose()}static async create(t,i,a,u){rt();let p,d={};if(typeof t=="string"){if(p=t,typeof i=="object"&&i!==null)d=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(p=t,typeof i=="object"&&i!==null)d=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let C=t,k=0,l=t.byteLength;if(typeof i=="object"&&i!==null)d=i;else if(typeof i=="number"){if(k=i,!Number.isSafeInteger(k))throw new RangeError("'byteOffset' must be an integer.");if(k<0||k>=C.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${C.byteLength}).`);if(l=t.byteLength-k,typeof a=="number"){if(l=a,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||k+l>C.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${C.byteLength-k}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof i<"u")throw new TypeError("'options' must be an object.");p=new Uint8Array(C,k,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[_,g]=await q(d),y=await _.createInferenceSessionHandler(p,g);return et(),new Cg(y)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Et,Ot=V(()=>{kt(),Et=bt}),S=V(()=>{}),Y=V(()=>{}),D=V(()=>{}),ne=V(()=>{}),xe,ut,ct=V(()=>{ae(),ce(),xe="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ut=class kg{constructor(t,i,a){this.handler=t,this.hasOptimizerModel=i,this.hasEvalModel=a}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,i){let a=t.evalModel||"",u=t.optimizerModel||"",p=i||{},[d,_]=await q(p);if(d.createTrainingSessionHandler){let g=await d.createTrainingSessionHandler(t.checkpointState,t.trainModel,a,u,_);return new kg(g,!!t.optimizerModel,!!t.evalModel)}else throw new Error(xe)}typeNarrowingForRunStep(t,i,a,u,p){let d={},_={};if(typeof a!="object"||a===null||a instanceof Ke||Array.isArray(a))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let g=!0;if(typeof u=="object"){if(u===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(u instanceof Ke)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(u)){if(u.length===0)throw new TypeError("'fetches' cannot be an empty array.");g=!1;for(let y of u){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(i.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);d[y]=null}if(typeof p=="object"&&p!==null)_=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,C=Object.getOwnPropertyNames(u);for(let k of i)if(C.indexOf(k)!==-1){let l=u[k];(l===null||l instanceof Ke)&&(y=!0,g=!1,d[k]=l)}if(y){if(typeof p=="object"&&p!==null)_=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else _=u}}else if(typeof u<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of t)if(typeof a[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(g)for(let y of i)d[y]=null;return[d,_]}convertHandlerReturnTypeToMapOfTensors(t){let i={};for(let a in t)if(Object.hasOwnProperty.call(t,a)){let u=t[a];u instanceof Ke?i[a]=u:i[a]=new Ke(u.type,u.data,u.dims)}return i}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,i,a){let[u,p]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,i,a),d=await this.handler.runTrainStep(t,u,p);return this.convertHandlerReturnTypeToMapOfTensors(d)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,i,a){if(this.hasEvalModel){let[u,p]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,i,a),d=await this.handler.runEvalStep(t,u,p);return this.convertHandlerReturnTypeToMapOfTensors(d)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,i=!0){let a=await this.getParametersSize(i);if(t.length!==4*a)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,i)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),Ut,$t=V(()=>{ct(),Ut=ut}),Ne={};A(Ne,{InferenceSession:()=>Et,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>rt,TRACE_FUNC_END:()=>et,Tensor:()=>Ke,TrainingSession:()=>Ut,env:()=>j,registerBackend:()=>pe});var z=V(()=>{he(),Ce(),Ot(),ce(),S(),Y(),st(),D(),ne(),$t()}),ee=V(()=>{}),Ee={};A(Ee,{default:()=>Ze});var Xe,We,Ze,vt=V(()=>{var e;kp(),di(),Jr(),Xe="ort-wasm-proxy-worker",We=((e=globalThis.self)==null?void 0:e.name)===Xe,We&&(self.onmessage=t=>{let{type:i,in:a}=t.data;try{switch(i){case"init-wasm":Gi(a.wasm).then(()=>{Ud(a).then(()=>{postMessage({type:i})},u=>{postMessage({type:i,err:u})})},u=>{postMessage({type:i,err:u})});break;case"init-ep":{let{epName:u,env:p}=a;Wd(p,u).then(()=>{postMessage({type:i})},d=>{postMessage({type:i,err:d})});break}case"copy-from":{let{buffer:u}=a,p=_d(u);postMessage({type:i,out:p});break}case"create":{let{model:u,options:p}=a;Gd(u,p).then(d=>{postMessage({type:i,out:d})},d=>{postMessage({type:i,err:d})});break}case"release":qd(a),postMessage({type:i});break;case"run":{let{sessionId:u,inputIndices:p,inputs:d,outputIndices:_,options:g}=a;Hd(u,p,d,_,new Array(_.length).fill(null),g).then(y=>{y.some(C=>C[3]!=="cpu")?postMessage({type:i,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:i,out:y},Qd([...d,...y]))},y=>{postMessage({type:i,err:y})});break}case"end-profiling":Xd(a),postMessage({type:i});break;default:}}catch(u){postMessage({type:i,err:u})}}),Ze=We?null:t=>new Worker(t??at,{type:"module",name:Xe})}),_t={};A(_t,{default:()=>jt});var zt,Ct,jt,Qt=V(()=>{var e;Ct=(zt=self.location.href,async function(t={}){function i(){return Bt.buffer!=pr.buffer&&xi(),pr}function a(){return Bt.buffer!=pr.buffer&&xi(),cr}function u(){return Bt.buffer!=pr.buffer&&xi(),lt}function p(){return Bt.buffer!=pr.buffer&&xi(),qt}function d(){return Bt.buffer!=pr.buffer&&xi(),fr}function _(){return Bt.buffer!=pr.buffer&&xi(),Yr}function g(){return Bt.buffer!=pr.buffer&&xi(),ai}function y(){return Bt.buffer!=pr.buffer&&xi(),yd}var C,k,l=t,F=new Promise((r,n)=>{C=r,k=n}),I=typeof window=="object",L=typeof importScripts=="function",Q=L&&self.name=="em-pthread";l.mountExternalData=(r,n)=>{r.startsWith("./")&&(r=r.substring(2)),(l.MountedFiles||(l.MountedFiles=new Map)).set(r,n)},l.unmountExternalData=()=>{delete l.MountedFiles};var Z=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let U=()=>{let r=(s,o,c)=>(...h)=>{let f=ar.currData,w=o==null?void 0:o(),v=s(...h),$=o==null?void 0:o();return w!==$&&(s=$,c(w),c=null,o=null),ar.currData!=f?ar.whenDone():v},n=s=>async(...o)=>{var c;try{if(l.jsepSessionState)throw new Error("Session already started");let h=l.jsepSessionState={sessionHandle:o[0],errors:[]},f=await s(...o);if(l.jsepSessionState!==h)throw new Error("Session mismatch");(c=l.jsepBackend)==null||c.flush();let w=h.errors;if(w.length>0){let v=await Promise.all(w);if(v=v.filter($=>$),v.length>0)throw new Error(v.join(` +`))}return f}finally{l.jsepSessionState=null}};l._OrtCreateSession=r(l._OrtCreateSession,()=>l._OrtCreateSession,s=>l._OrtCreateSession=s),l._OrtRun=n(r(l._OrtRun,()=>l._OrtRun,s=>l._OrtRun=s)),l._OrtRunWithBinding=n(r(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,s=>l._OrtRunWithBinding=s)),l._OrtBindInput=r(l._OrtBindInput,()=>l._OrtBindInput,s=>l._OrtBindInput=s),U=void 0};l.jsepInit=(r,n)=>{if(U==null||U(),r==="webgpu"){[l.jsepBackend,l.jsepAlloc,l.jsepFree,l.jsepCopy,l.jsepCopyAsync,l.jsepCreateKernel,l.jsepReleaseKernel,l.jsepRunKernel,l.jsepCaptureBegin,l.jsepCaptureEnd,l.jsepReplay]=n;let s=l.jsepBackend;l.jsepRegisterBuffer=(o,c,h,f)=>s.registerBuffer(o,c,h,f),l.jsepGetBuffer=o=>s.getBuffer(o),l.jsepCreateDownloader=(o,c,h)=>s.createDownloader(o,c,h),l.jsepOnReleaseSession=o=>{s.onReleaseSession(o)},l.jsepOnRunStart=o=>s.onRunStart(o)}};var we,te,me=Object.assign({},l),it="./this.program",Ye=(r,n)=>{throw n},Mt="";(I||L)&&(L?Mt=self.location.href:typeof document<"u"&&document.currentScript&&(Mt=document.currentScript.src),zt&&(Mt=zt),Mt=Mt.startsWith("blob:")?"":Mt.substr(0,Mt.replace(/[?#].*/,"").lastIndexOf("/")+1),L&&(te=r=>{var n=new XMLHttpRequest;return n.open("GET",r,!1),n.responseType="arraybuffer",n.send(null),new Uint8Array(n.response)}),we=r=>Gp(r)?new Promise((n,s)=>{var o=new XMLHttpRequest;o.open("GET",r,!0),o.responseType="arraybuffer",o.onload=()=>{(o.status==200||o.status==0&&o.response)&&s(o.response),n(o.status)},o.onerror=n,o.send(null)}):fetch(r,{credentials:"same-origin"}).then(n=>n.ok?n.arrayBuffer():Promise.reject(new Error(n.status+" : "+n.url))));var Gt,Bt,gr,Mr=console.log.bind(console),Ur=console.error.bind(console),Ir=Mr,Sr=Ur;if(Object.assign(l,me),me=null,Q){let r=function(...o){var c=o.join(" ");console.error(c)},n=function(...o){var c=o.join(" ");postMessage({cmd:"alert",text:c,threadId:Oa()})},s=function(o){try{var c=o.data,h=c.cmd;if(h==="load"){let f=[];self.onmessage=w=>f.push(w),self.startWorker=w=>{postMessage({cmd:"loaded"});for(let v of f)s(v);self.onmessage=s};for(let w of c.handlers)l[w]&&!l[w].proxy||(l[w]=(...v)=>{postMessage({cmd:"callHandler",handler:w,args:v})},w=="print"&&(Ir=l[w]),w=="printErr"&&(Sr=l[w]));Bt=c.wasmMemory,xi(),ri(c.wasmModule)}else if(h==="run"){fc(c.pthread_ptr,0,0,1,0,0),dc(c.pthread_ptr),rw(),xr.receiveObjectTransfer(c),xr.threadInitTLS(),Kr||(Gh(),Kr=!0);try{iw(c.start_routine,c.arg)}catch(f){if(f!="unwind")throw f}}else h==="cancel"?Oa()&&zd(-1):c.target==="setimmediate"||(h==="checkMailbox"?Kr&&kd():h&&(Sr(`worker: received unknown command ${h}`),Sr(c)))}catch(f){throw qh(),f}};var ri,Kr=!1;Sr=r,self.alert=n,l.instantiateWasm=(o,c)=>new Promise((h,f)=>{ri=w=>{var v=new WebAssembly.Instance(w,Hp());c(v),h()}}),self.onunhandledrejection=o=>{throw o.reason||o},self.onmessage=s}l.wasmBinary&&(Gt=l.wasmBinary);var Wt,pr,cr,lt,qt,fr,Yr,ai,gi,Oi,yd,Wi=!1;function xi(){var r=Bt.buffer;l.HEAP8=pr=new Int8Array(r),l.HEAP16=lt=new Int16Array(r),l.HEAPU8=cr=new Uint8Array(r),l.HEAPU16=qt=new Uint16Array(r),l.HEAP32=fr=new Int32Array(r),l.HEAPU32=Yr=new Uint32Array(r),l.HEAPF32=ai=new Float32Array(r),l.HEAPF64=yd=new Float64Array(r),l.HEAP64=gi=new BigInt64Array(r),l.HEAPU64=Oi=new BigUint64Array(r)}if(!Q){if(!((Bt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof Z))throw Sr("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");xi()}var Du=[],Si=[],Di=[];function Mn(){Q||ic(Si)}var ms=0,_s=null;function Vp(r){ms++}function Up(r){if(--ms==0&&_s){var n=_s;_s=null,n()}}function gs(r){Sr(r="Aborted("+r+")"),Wi=!0,Wt=1,r+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(r);throw k(n),n}var bd,Wp=r=>r.startsWith("data:application/octet-stream;base64,"),Gp=r=>r.startsWith("file://");function qp(r){if(r==bd&&Gt)return new Uint8Array(Gt);if(te)return te(r);throw"both async and sync fetching of the wasm failed"}function Kp(r,n,s){return function(o){return Gt?Promise.resolve().then(()=>qp(o)):we(o).then(c=>new Uint8Array(c),()=>qp(o))}(r).then(o=>WebAssembly.instantiate(o,n)).then(s,o=>{Sr(`failed to asynchronously prepare wasm: ${o}`),gs(o)})}function Hp(){return{a:{Jc:tw,Kc:ew,w:nw,Q:sw,b:ow,n:lw,y:uw,r:dw,Ub:cw,t:pw,gb:hw,Yd:ih,g:aw,Tb:ah,Xd:oh,Wd:uh,Vd:dh,Ud:ch,Td:ph,Sd:hh,Rd:fh,Ic:mh,Qd:_h,Pd:gh,Od:wh,Nd:yh,Id:fw,Fc:_w,Hd:gw,Gd:yw,Ec:vw,Fa:Mw,ca:xw,Dc:Tw,Rb:Aw,Fd:Iw,Ed:Fw,Dd:zw,Cd:Ow,Bd:Dw,Cc:Bw,Ad:dc,zd:jw,yd:Lw,xd:$h,Bc:Rw,Ea:Vw,wd:lc,vd:Uw,ya:qw,ud:Kw,td:Hw,W:Xw,sd:Qw,rd:Yw,fa:Zw,Bb:Jw,qd:ty,pd:ry,Ab:iy,od:ny,nd:oy,md:ly,ld:Ah,kd:Ih,jd:uy,B:dy,Ac:cy,zc:py,yc:hy,zb:fy,id:my,hd:_y,Da:zh,yb:gy,xc:wy,gd:by,fd:vy,ed:My,Md:jh,Ld:Lh,dd:rc,Sb:Rh,Hc:Nh,Kd:Vh,Gc:Uh,xb:d0,cd:Vv,wa:Ob,aa:Av,ea:Pv,ra:cb,qa:l0,bd:Nv,wb:zb,P:U0,z:Ky,c:Py,wc:Wy,pa:Uy,f:Sy,vb:Sv,i:$y,$:_v,j:Dy,ad:Lv,k:Oy,v:zy,s:Xy,p:n0,Xa:h0,Ca:Yb,ja:e0,Qb:R0,bb:W0,Pb:Zb,ub:Rb,vc:wv,uc:_0,tc:Mv,sc:bv,Ob:jv,ha:_b,tb:i0,Wa:mv,sb:Ov,ba:gb,rc:cv,qc:yv,Va:q0,G:Iy,H:E0,Nb:gv,$c:vv,oa:Pb,M:F0,X:P0,U:H0,A:Vy,Mb:kv,pc:xv,oc:lv,nc:ov,Lb:av,_c:Tv,Ua:V0,S:xb,ab:Dv,mc:uv,lc:Bv,Kb:hb,Y:u0,K:Gy,D:v0,Ta:nv,kc:Cv,jc:dv,R:I0,e:Fy,_a:O0,o:Ay,Sa:$v,va:Fb,rb:g0,h:Ey,ic:m0,da:fv,fb:B0,Ba:pb,qb:Nb,eb:y0,d:By,hc:x0,Zc:Jb,l:jy,gc:D0,m:Ry,fc:b0,ec:j0,Yc:Ub,q:Ly,Ra:J0,pb:Z0,Qa:eb,Jb:Bb,C:Jy,F:qy,O:t0,Za:ev,dc:Eb,ob:z0,ua:K0,la:Ny,ta:N0,cc:Gb,xa:r0,Xc:C0,nb:Rv,Aa:Kb,bc:Hb,Pa:qb,Oa:Vb,Wc:zv,Vc:L0,_:ob,na:Ib,Uc:Qb,Tc:Q0,Ib:fb,Na:$b,Ma:Ab,ac:wb,La:jb,Ka:kb,mb,ia:Tb,za:X0,$b:sv,Hb:vb,Gb:Xb,ka:rv,ga:$0,Sc:p0,Rc:tv,T:bb,db:Zy,Ya:hv,_b:Iv,cb:w0,E:a0,N:Qy,Qc:pv,Ja:f0,Pc:iv,V:o0,lb:Lb,sa:Mb,Zb:Db,Yb:Fv,Oc:Yy,u:Hy,L:T0,Nc:Sb,Fb:sb,Xb:Wb,Mc:c0,Eb:ab,Db:yb,$a:G0,Wb:s0,Cb:S0,Ia:Cb,Z:lb,Vb:k0,J:A0,Lc:Ev,kb:M0,ma:db,I:ub,jb:ib,Ha:rb,Ga:Y0,ib:tb,hb:nb,x:Cy,a:Bt,Jd:tc}}}var Xp={1338516:(r,n,s,o)=>{if(l===void 0||!l.MountedFiles)return 1;let c=Ti(r>>>0);c.startsWith("./")&&(c=c.substring(2));let h=l.MountedFiles.get(c);if(!h)return 2;let f=n>>>0,w=s>>>0,v=o>>>0;if(f+w>h.byteLength)return 3;try{return a().set(h.subarray(f,f+w),v>>>0),0}catch{return 4}},1339017:(r,n,s)=>{let o=r,c=n,h=Ti(s),f=new Uint8Array(c);f.set(a().subarray(o>>>0,o+c>>>0));{let w=new File([f],h,{type:"application/octet-stream"}),v=URL.createObjectURL(w);window.open(v,"_blank")}},1339525:()=>{l.jsepCaptureBegin()},1339556:()=>{l.jsepCaptureEnd()},1339585:()=>{l.jsepReplay()},1339610:r=>l.jsepAlloc(r),1339643:r=>l.jsepFree(r),1339675:(r,n,s)=>{l.jsepCopy(r,n,s,!0)},1339714:(r,n,s)=>{l.jsepCopy(r,n,s)},1339747:()=>typeof wasmOffsetConverter<"u",1339804:r=>{l.jsepCreateKernel("Abs",r,void 0)},1339855:r=>{l.jsepCreateKernel("Neg",r,void 0)},1339906:r=>{l.jsepCreateKernel("Floor",r,void 0)},1339959:r=>{l.jsepCreateKernel("Ceil",r,void 0)},1340011:r=>{l.jsepCreateKernel("Reciprocal",r,void 0)},1340069:r=>{l.jsepCreateKernel("Sqrt",r,void 0)},1340121:r=>{l.jsepCreateKernel("Exp",r,void 0)},1340172:r=>{l.jsepCreateKernel("Erf",r,void 0)},1340223:r=>{l.jsepCreateKernel("Sigmoid",r,void 0)},1340278:(r,n,s)=>{l.jsepCreateKernel("HardSigmoid",r,{alpha:n,beta:s})},1340357:r=>{l.jsepCreateKernel("Log",r,void 0)},1340408:r=>{l.jsepCreateKernel("Sin",r,void 0)},1340459:r=>{l.jsepCreateKernel("Cos",r,void 0)},1340510:r=>{l.jsepCreateKernel("Tan",r,void 0)},1340561:r=>{l.jsepCreateKernel("Asin",r,void 0)},1340613:r=>{l.jsepCreateKernel("Acos",r,void 0)},1340665:r=>{l.jsepCreateKernel("Atan",r,void 0)},1340717:r=>{l.jsepCreateKernel("Sinh",r,void 0)},1340769:r=>{l.jsepCreateKernel("Cosh",r,void 0)},1340821:r=>{l.jsepCreateKernel("Asinh",r,void 0)},1340874:r=>{l.jsepCreateKernel("Acosh",r,void 0)},1340927:r=>{l.jsepCreateKernel("Atanh",r,void 0)},1340980:r=>{l.jsepCreateKernel("Tanh",r,void 0)},1341032:r=>{l.jsepCreateKernel("Not",r,void 0)},1341083:(r,n,s)=>{l.jsepCreateKernel("Clip",r,{min:n,max:s})},1341152:r=>{l.jsepCreateKernel("Clip",r,void 0)},1341204:(r,n)=>{l.jsepCreateKernel("Elu",r,{alpha:n})},1341262:r=>{l.jsepCreateKernel("Gelu",r,void 0)},1341314:r=>{l.jsepCreateKernel("Relu",r,void 0)},1341366:(r,n)=>{l.jsepCreateKernel("LeakyRelu",r,{alpha:n})},1341430:(r,n)=>{l.jsepCreateKernel("ThresholdedRelu",r,{alpha:n})},1341500:(r,n)=>{l.jsepCreateKernel("Cast",r,{to:n})},1341558:r=>{l.jsepCreateKernel("Add",r,void 0)},1341609:r=>{l.jsepCreateKernel("Sub",r,void 0)},1341660:r=>{l.jsepCreateKernel("Mul",r,void 0)},1341711:r=>{l.jsepCreateKernel("Div",r,void 0)},1341762:r=>{l.jsepCreateKernel("Pow",r,void 0)},1341813:r=>{l.jsepCreateKernel("Equal",r,void 0)},1341866:r=>{l.jsepCreateKernel("Greater",r,void 0)},1341921:r=>{l.jsepCreateKernel("GreaterOrEqual",r,void 0)},1341983:r=>{l.jsepCreateKernel("Less",r,void 0)},1342035:r=>{l.jsepCreateKernel("LessOrEqual",r,void 0)},1342094:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceMean",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1342253:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceMax",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1342411:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceMin",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1342569:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceProd",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1342728:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceSum",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1342886:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceL1",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1343043:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceL2",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1343200:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceLogSum",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1343361:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceSumSquare",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1343525:(r,n,s,o,c)=>{l.jsepCreateKernel("ReduceLogSumExp",r,{keepDims:!!n,noopWithEmptyAxes:!!s,axes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1343689:r=>{l.jsepCreateKernel("Where",r,void 0)},1343742:(r,n,s)=>{l.jsepCreateKernel("Transpose",r,{perm:n?Array.from(d().subarray(n>>>0,s>>>0)):[]})},1343850:(r,n,s,o)=>{l.jsepCreateKernel("DepthToSpace",r,{blocksize:n,mode:Ti(s),format:o?"NHWC":"NCHW"})},1343983:(r,n,s,o)=>{l.jsepCreateKernel("DepthToSpace",r,{blocksize:n,mode:Ti(s),format:o?"NHWC":"NCHW"})},1344116:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>{l.jsepCreateKernel("ConvTranspose",r,{format:v?"NHWC":"NCHW",autoPad:n,dilations:[s],group:o,kernelShape:[c],pads:[h,f],strides:[w],wIsConst:()=>!!i()[$>>>0],outputPadding:E?Array.from(d().subarray(E>>>0,G>>>0)):[],outputShape:J?Array.from(d().subarray(J>>>0,_e>>>0)):[],activation:Ti(Le)})},1344517:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("ConvTranspose",r,{format:w?"NHWC":"NCHW",autoPad:n,dilations:Array.from(d().subarray(s>>>0,2+(s>>>0)>>>0)),group:o,kernelShape:Array.from(d().subarray(c>>>0,2+(c>>>0)>>>0)),pads:Array.from(d().subarray(h>>>0,4+(h>>>0)>>>0)),strides:Array.from(d().subarray(f>>>0,2+(f>>>0)>>>0)),wIsConst:()=>!!i()[v>>>0],outputPadding:$?Array.from(d().subarray($>>>0,E>>>0)):[],outputShape:G?Array.from(d().subarray(G>>>0,J>>>0)):[],activation:Ti(_e)})},1345082:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>{l.jsepCreateKernel("ConvTranspose",r,{format:v?"NHWC":"NCHW",autoPad:n,dilations:[s],group:o,kernelShape:[c],pads:[h,f],strides:[w],wIsConst:()=>!!i()[$>>>0],outputPadding:E?Array.from(d().subarray(E>>>0,G>>>0)):[],outputShape:J?Array.from(d().subarray(J>>>0,_e>>>0)):[],activation:Ti(Le)})},1345483:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("ConvTranspose",r,{format:w?"NHWC":"NCHW",autoPad:n,dilations:Array.from(d().subarray(s>>>0,2+(s>>>0)>>>0)),group:o,kernelShape:Array.from(d().subarray(c>>>0,2+(c>>>0)>>>0)),pads:Array.from(d().subarray(h>>>0,4+(h>>>0)>>>0)),strides:Array.from(d().subarray(f>>>0,2+(f>>>0)>>>0)),wIsConst:()=>!!i()[v>>>0],outputPadding:$?Array.from(d().subarray($>>>0,E>>>0)):[],outputShape:G?Array.from(d().subarray(G>>>0,J>>>0)):[],activation:Ti(_e)})},1346048:(r,n)=>{l.jsepCreateKernel("GlobalAveragePool",r,{format:n?"NHWC":"NCHW"})},1346139:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("AveragePool",r,{format:_e?"NHWC":"NCHW",auto_pad:n,ceil_mode:s,count_include_pad:o,storage_order:c,dilations:h?Array.from(d().subarray(h>>>0,f>>>0)):[],kernel_shape:w?Array.from(d().subarray(w>>>0,v>>>0)):[],pads:$?Array.from(d().subarray($>>>0,E>>>0)):[],strides:G?Array.from(d().subarray(G>>>0,J>>>0)):[]})},1346554:(r,n)=>{l.jsepCreateKernel("GlobalAveragePool",r,{format:n?"NHWC":"NCHW"})},1346645:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("AveragePool",r,{format:_e?"NHWC":"NCHW",auto_pad:n,ceil_mode:s,count_include_pad:o,storage_order:c,dilations:h?Array.from(d().subarray(h>>>0,f>>>0)):[],kernel_shape:w?Array.from(d().subarray(w>>>0,v>>>0)):[],pads:$?Array.from(d().subarray($>>>0,E>>>0)):[],strides:G?Array.from(d().subarray(G>>>0,J>>>0)):[]})},1347060:(r,n)=>{l.jsepCreateKernel("GlobalMaxPool",r,{format:n?"NHWC":"NCHW"})},1347147:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("MaxPool",r,{format:_e?"NHWC":"NCHW",auto_pad:n,ceil_mode:s,count_include_pad:o,storage_order:c,dilations:h?Array.from(d().subarray(h>>>0,f>>>0)):[],kernel_shape:w?Array.from(d().subarray(w>>>0,v>>>0)):[],pads:$?Array.from(d().subarray($>>>0,E>>>0)):[],strides:G?Array.from(d().subarray(G>>>0,J>>>0)):[]})},1347558:(r,n)=>{l.jsepCreateKernel("GlobalMaxPool",r,{format:n?"NHWC":"NCHW"})},1347645:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>{l.jsepCreateKernel("MaxPool",r,{format:_e?"NHWC":"NCHW",auto_pad:n,ceil_mode:s,count_include_pad:o,storage_order:c,dilations:h?Array.from(d().subarray(h>>>0,f>>>0)):[],kernel_shape:w?Array.from(d().subarray(w>>>0,v>>>0)):[],pads:$?Array.from(d().subarray($>>>0,E>>>0)):[],strides:G?Array.from(d().subarray(G>>>0,J>>>0)):[]})},1348056:(r,n,s,o,c)=>{l.jsepCreateKernel("Gemm",r,{alpha:n,beta:s,transA:o,transB:c})},1348160:r=>{l.jsepCreateKernel("MatMul",r,void 0)},1348214:(r,n,s,o)=>{l.jsepCreateKernel("ArgMax",r,{keepDims:!!n,selectLastIndex:!!s,axis:o})},1348322:(r,n,s,o)=>{l.jsepCreateKernel("ArgMin",r,{keepDims:!!n,selectLastIndex:!!s,axis:o})},1348430:(r,n)=>{l.jsepCreateKernel("Softmax",r,{axis:n})},1348493:(r,n)=>{l.jsepCreateKernel("Concat",r,{axis:n})},1348553:(r,n,s,o,c)=>{l.jsepCreateKernel("Split",r,{axis:n,numOutputs:s,splitSizes:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},1348693:r=>{l.jsepCreateKernel("Expand",r,void 0)},1348747:(r,n)=>{l.jsepCreateKernel("Gather",r,{axis:Number(n)})},1348818:(r,n)=>{l.jsepCreateKernel("GatherElements",r,{axis:Number(n)})},1348897:(r,n,s,o,c,h,f,w,v,$,E)=>{l.jsepCreateKernel("Resize",r,{antialias:n,axes:s?Array.from(d().subarray(s>>>0,o>>>0)):[],coordinateTransformMode:Ti(c),cubicCoeffA:h,excludeOutside:f,extrapolationValue:w,keepAspectRatioPolicy:Ti(v),mode:Ti($),nearestMode:Ti(E)})},1349243:(r,n,s,o,c,h,f)=>{l.jsepCreateKernel("Slice",r,{starts:n?Array.from(d().subarray(n>>>0,s>>>0)):[],ends:o?Array.from(d().subarray(o>>>0,c>>>0)):[],axes:h?Array.from(d().subarray(h>>>0,f>>>0)):[]})},1349459:r=>{l.jsepCreateKernel("Tile",r,void 0)},1349511:(r,n,s)=>{l.jsepCreateKernel("InstanceNormalization",r,{epsilon:n,format:s?"NHWC":"NCHW"})},1349625:(r,n,s)=>{l.jsepCreateKernel("InstanceNormalization",r,{epsilon:n,format:s?"NHWC":"NCHW"})},1349739:r=>{l.jsepCreateKernel("Range",r,void 0)},1349792:(r,n)=>{l.jsepCreateKernel("Einsum",r,{equation:Ti(n)})},1349873:(r,n,s,o,c)=>{l.jsepCreateKernel("Pad",r,{mode:n,value:s,pads:o?Array.from(d().subarray(o>>>0,c>>>0)):[]})},135e4:(r,n,s,o,c,h)=>{l.jsepCreateKernel("BatchNormalization",r,{epsilon:n,momentum:s,spatial:!!c,trainingMode:!!o,format:h?"NHWC":"NCHW"})},1350169:(r,n,s,o,c,h)=>{l.jsepCreateKernel("BatchNormalization",r,{epsilon:n,momentum:s,spatial:!!c,trainingMode:!!o,format:h?"NHWC":"NCHW"})},1350338:(r,n,s)=>{l.jsepCreateKernel("CumSum",r,{exclusive:Number(n),reverse:Number(s)})},1350435:(r,n,s)=>{l.jsepCreateKernel("DequantizeLinear",r,{axis:n,blockSize:s})},1350525:(r,n,s,o,c,h,f,w,v)=>{l.jsepCreateKernel("Attention",r,{numHeads:n,isUnidirectional:s,maskFilterValue:o,scale:c,doRotary:h,qkvHiddenSizes:f?Array.from(d().subarray(Number(w)>>>0,Number(w)+f>>>0)):[],pastPresentShareBuffer:!!v})},1350797:r=>{l.jsepCreateKernel("BiasAdd",r,void 0)},1350852:r=>{l.jsepCreateKernel("BiasSplitGelu",r,void 0)},1350913:r=>{l.jsepCreateKernel("FastGelu",r,void 0)},1350969:(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)=>{l.jsepCreateKernel("Conv",r,{format:G?"NHWC":"NCHW",auto_pad:n,dilations:s?Array.from(d().subarray(s>>>0,o>>>0)):[],group:c,kernel_shape:h?Array.from(d().subarray(h>>>0,f>>>0)):[],pads:w?Array.from(d().subarray(w>>>0,v>>>0)):[],strides:$?Array.from(d().subarray($>>>0,E>>>0)):[],w_is_const:()=>!!i()[J>>>0],activation:Ti(_e),activation_params:Le?Array.from(g().subarray(Le>>>0,ht>>>0)):[]})},1351465:r=>{l.jsepCreateKernel("Gelu",r,void 0)},1351517:(r,n,s,o)=>{l.jsepCreateKernel("GroupQueryAttention",r,{numHeads:n,kvNumHeads:s,scale:o})},1351630:(r,n,s,o)=>{l.jsepCreateKernel("LayerNormalization",r,{axis:n,epsilon:s,simplified:!!o})},1351741:(r,n,s,o)=>{l.jsepCreateKernel("LayerNormalization",r,{axis:n,epsilon:s,simplified:!!o})},1351852:(r,n,s,o,c,h)=>{l.jsepCreateKernel("MatMulNBits",r,{k:n,n:s,accuracyLevel:o,bits:c,blockSize:h})},1351979:(r,n,s,o,c,h)=>{l.jsepCreateKernel("MultiHeadAttention",r,{numHeads:n,isUnidirectional:s,maskFilterValue:o,scale:c,doRotary:h})},1352138:(r,n)=>{l.jsepCreateKernel("QuickGelu",r,{alpha:n})},1352202:(r,n,s,o,c)=>{l.jsepCreateKernel("RotaryEmbedding",r,{interleaved:!!n,numHeads:s,rotaryEmbeddingDim:o,scale:c})},1352341:(r,n,s)=>{l.jsepCreateKernel("SkipLayerNormalization",r,{epsilon:n,simplified:!!s})},1352443:r=>{l.jsepReleaseKernel(r)},1352477:(r,n)=>l.jsepRunKernel(r,n,l.jsepSessionState.sessionHandle,l.jsepSessionState.errors),1352589:(r,n,s)=>{l.jsepCreateKernel("SkipLayerNormalization",r,{epsilon:n,simplified:!!s})}};function ew(r,n,s){return ar.handleAsync(async()=>{await l.jsepCopyAsync(r,n,s)})}function tw(){return typeof wasmOffsetConverter<"u"}function Qp(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var Jd=r=>{r.terminate(),r.onmessage=n=>{}},Yp=r=>{var n=xr.pthreads[r];xr.returnWorkerToPool(n)},Zp=r=>{var n=xr.getNewWorker();if(!n)return 6;xr.runningWorkers.push(n),xr.pthreads[r.pthread_ptr]=n,n.pthread_ptr=r.pthread_ptr;var s={cmd:"run",start_routine:r.startRoutine,arg:r.arg,pthread_ptr:r.pthread_ptr};return n.postMessage(s,r.transferList),0},vd=0,ec=()=>vd>0,Ie=()=>Jh(),Pe=r=>Yh(r),Jp=r=>Zh(r),Bu=r=>r<-9007199254740992||r>9007199254740992?NaN:Number(r),ei=(r,n,s,...o)=>{for(var c=2*o.length,h=Ie(),f=Jp(8*c),w=f>>>3,v=0;v>>0]=$)}var E=Kh(r,n,c,f,s);return Pe(h),E};function tc(r){if(Q)return ei(0,0,1,r);Wt=r,ec()||(xr.terminateAllThreads(),Wi=!0),Ye(r,new Qp(r))}var eh=r=>{if(r instanceof Qp||r=="unwind")return Wt;Ye(1,r)};function th(r){if(Q)return ei(1,0,0,r);rc(r)}var rc=(r,n)=>{if(Wt=r,Q)throw th(r),"unwind";tc(r)},xr={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){Q?xr.initWorker():xr.initMainThread()},initMainThread(){for(var r,n=l.numThreads-1;n--;)xr.allocateUnusedWorker();r=()=>{Vp(),xr.loadWasmModuleToAllWorkers(()=>Up())},Du.unshift(r)},initWorker(){},setExitStatus:r=>Wt=r,terminateAllThreads__deps:["$terminateWorker"],terminateAllThreads:()=>{for(var r of xr.runningWorkers)Jd(r);for(var r of xr.unusedWorkers)Jd(r);xr.unusedWorkers=[],xr.runningWorkers=[],xr.pthreads=[]},returnWorkerToPool:r=>{var n=r.pthread_ptr;delete xr.pthreads[n],xr.unusedWorkers.push(r),xr.runningWorkers.splice(xr.runningWorkers.indexOf(r),1),r.pthread_ptr=0,mc(n)},receiveObjectTransfer(r){},threadInitTLS(){xr.tlsInitFunctions.forEach(r=>r())},loadWasmModuleToWorker:r=>new Promise(n=>{r.onmessage=c=>{var h=c.data,f=h.cmd;if(h.targetThread&&h.targetThread!=Oa()){var w=xr.pthreads[h.targetThread];w?w.postMessage(h,h.transferList):Sr(`Internal error! Worker sent a message "${f}" to target pthread ${h.targetThread}, but that thread no longer exists!`)}else{var v;f==="checkMailbox"?kd():f==="spawnThread"?Zp(h):f==="cleanupThread"?Yp(h.thread):f==="killThread"?($=>{var E=xr.pthreads[$];delete xr.pthreads[$],Jd(E),mc($),xr.runningWorkers.splice(xr.runningWorkers.indexOf(E),1),E.pthread_ptr=0})(h.thread):f==="cancelThread"?(v=h.thread,xr.pthreads[v].postMessage({cmd:"cancel"})):f==="loaded"?(r.loaded=!0,n(r)):f==="alert"?alert(`Thread ${h.threadId}: ${h.text}`):h.target==="setimmediate"?r.postMessage(h):f==="callHandler"?l[h.handler](...h.args):f&&Sr(`worker sent an unknown command ${f}`)}},r.onerror=c=>{throw Sr(`worker sent an error! ${c.filename}:${c.lineno}: ${c.message}`),c};var s=[];for(var o of[])l.propertyIsEnumerable(o)&&s.push(o);r.postMessage({cmd:"load",handlers:s,wasmMemory:Bt,wasmModule:gr})}),loadWasmModuleToAllWorkers(r){if(Q)return r();Promise.all(xr.unusedWorkers.map(xr.loadWasmModuleToWorker)).then(r)},allocateUnusedWorker(){var r;r=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"}),xr.unusedWorkers.push(r)},getNewWorker:()=>(xr.unusedWorkers.length==0&&(xr.allocateUnusedWorker(),xr.loadWasmModuleToWorker(xr.unusedWorkers[0])),xr.unusedWorkers.pop())},ic=r=>{for(;r.length>0;)r.shift()(l)},rw=()=>{var r=Oa(),n=_()[r+52>>>2>>>0],s=_()[r+56>>>2>>>0];Qh(n,n-s),Pe(n)},iw=(r,n)=>{var s;vd=0,s=_c(r,n),ec()?xr.setExitStatus(s):zd(s)},Md=[],xd=0;function nw(r){var n=new nc(r>>>=0);return n.get_caught()||(n.set_caught(!0),xd--),n.set_rethrown(!1),Md.push(n),tf(n.excPtr),n.get_exception_ptr()}var ws=0,sw=()=>{Fe(0,0);var r=Md.pop();ef(r.excPtr),ws=0};class nc{constructor(n){this.excPtr=n,this.ptr=n-24}set_type(n){_()[this.ptr+4>>>2>>>0]=n}get_type(){return _()[this.ptr+4>>>2>>>0]}set_destructor(n){_()[this.ptr+8>>>2>>>0]=n}get_destructor(){return _()[this.ptr+8>>>2>>>0]}set_caught(n){n=n?1:0,i()[this.ptr+12>>>0]=n}get_caught(){return i()[this.ptr+12>>>0]!=0}set_rethrown(n){n=n?1:0,i()[this.ptr+13>>>0]=n}get_rethrown(){return i()[this.ptr+13>>>0]!=0}init(n,s){this.set_adjusted_ptr(0),this.set_type(n),this.set_destructor(s)}set_adjusted_ptr(n){_()[this.ptr+16>>>2>>>0]=n}get_adjusted_ptr(){return _()[this.ptr+16>>>2>>>0]}get_exception_ptr(){if(nf(this.get_type()))return _()[this.excPtr>>>2>>>0];var n=this.get_adjusted_ptr();return n!==0?n:this.excPtr}}function aw(r){throw ws||(ws=r>>>=0),ws}var Td=r=>Xh(r),Cd=r=>{var n=ws;if(!n)return Td(0),0;var s=new nc(n);s.set_adjusted_ptr(n);var o=s.get_type();if(!o)return Td(0),n;for(var c of r){if(c===0||c===o)break;var h=s.ptr+16;if(rf(c,o,h))return Td(c),n}return Td(o),n};function ow(){return Cd([])}function lw(r){return Cd([r>>>=0])}function uw(r,n){return Cd([r>>>=0,n>>>=0])}function dw(r,n,s){return Cd([r>>>=0,n>>>=0,s>>>=0])}var cw=()=>{var r=Md.pop();r||gs("no exception to throw");var n=r.excPtr;throw r.get_rethrown()||(Md.push(r),r.set_rethrown(!0),r.set_caught(!1),xd++),ws=n};function pw(r,n,s){throw n>>>=0,s>>>=0,new nc(r>>>=0).init(n,s),xd++,ws=r}var hw=()=>xd;function rh(r,n,s,o){return Q?ei(2,0,1,r,n,s,o):ih(r,n,s,o)}function ih(r,n,s,o){if(r>>>=0,n>>>=0,s>>>=0,o>>>=0,Z===void 0)return Sr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var c=[];if(Q&&c.length===0)return rh(r,n,s,o);var h={startRoutine:s,pthread_ptr:r,arg:o,transferList:c};return Q?(h.cmd="spawnThread",postMessage(h,c),0):Zp(h)}var nh=typeof TextDecoder<"u"?new TextDecoder:void 0,sh=(r,n,s)=>{for(var o=(n>>>=0)+s,c=n;r[c]&&!(c>=o);)++c;if(c-n>16&&r.buffer&&nh)return nh.decode(r.buffer instanceof Z?r.slice(n,c):r.subarray(n,c));for(var h="";n>10,56320|1023&$)}}else h+=String.fromCharCode((31&f)<<6|w)}else h+=String.fromCharCode(f)}return h},Ti=(r,n)=>(r>>>=0)?sh(a(),r,n):"";function ah(r,n,s){return Q?ei(3,0,1,r,n,s):(s>>>=0,0)}function oh(r,n){if(Q)return ei(4,0,1,r,n);n>>>=0}var lh=r=>{for(var n=0,s=0;s=55296&&o<=57343?(n+=4,++s):n+=3}return n},za=(r,n,s)=>((o,c,h,f)=>{if(!(f>0))return 0;for(var w=h>>>=0,v=h+f-1,$=0;$=55296&&E<=57343&&(E=65536+((1023&E)<<10)|1023&o.charCodeAt(++$)),E<=127){if(h>=v)break;c[h++>>>0]=E}else if(E<=2047){if(h+1>=v)break;c[h++>>>0]=192|E>>6,c[h++>>>0]=128|63&E}else if(E<=65535){if(h+2>=v)break;c[h++>>>0]=224|E>>12,c[h++>>>0]=128|E>>6&63,c[h++>>>0]=128|63&E}else{if(h+3>=v)break;c[h++>>>0]=240|E>>18,c[h++>>>0]=128|E>>12&63,c[h++>>>0]=128|E>>6&63,c[h++>>>0]=128|63&E}}return c[h>>>0]=0,h-w})(r,a(),n,s);function uh(r,n){if(Q)return ei(5,0,1,r,n);r>>>=0,n>>>=0}function dh(r,n,s){if(Q)return ei(6,0,1,r,n,s);n>>>=0,s>>>=0}function ch(r,n,s){return Q?ei(7,0,1,r,n,s):(s>>>=0,0)}function ph(r,n){if(Q)return ei(8,0,1,r,n);r>>>=0,n>>>=0}function hh(r,n,s){if(Q)return ei(9,0,1,r,n,s);n>>>=0}function fh(r,n,s,o){if(Q)return ei(10,0,1,r,n,s,o);n>>>=0,s>>>=0}function mh(r,n,s,o){if(Q)return ei(11,0,1,r,n,s,o);n>>>=0,o>>>=0}function _h(r,n,s,o){if(Q)return ei(12,0,1,r,n,s,o);n>>>=0,s>>>=0,o>>>=0}function gh(r){if(Q)return ei(13,0,1,r);r>>>=0}function wh(r,n){if(Q)return ei(14,0,1,r,n);r>>>=0,n>>>=0}function yh(r,n,s){if(Q)return ei(15,0,1,r,n,s);n>>>=0}var bh,vh,fw=()=>{gs("")},mw=r=>{if(r===null)return"null";var n=typeof r;return n==="object"||n==="array"||n==="function"?r.toString():""+r},un=r=>{for(var n="",s=r;a()[s>>>0];)n+=bh[a()[s++>>>0]];return n},sc={},ac={},ys=r=>{throw new vh(r)};function xn(r,n,s={}){if(!("argPackAdvance"in n))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(o,c,h={}){var f=c.name;if(o||ys(`type "${f}" must have a positive integer typeid pointer`),ac.hasOwnProperty(o)){if(h.ignoreDuplicateRegistrations)return;ys(`Cannot register type '${f}' twice`)}if(ac[o]=c,sc.hasOwnProperty(o)){var w=sc[o];delete sc[o],w.forEach(v=>v())}}(r,n,s)}var Mh=(r,n,s)=>{switch(n){case 1:return s?o=>i()[o>>>0]:o=>a()[o>>>0];case 2:return s?o=>u()[o>>>1>>>0]:o=>p()[o>>>1>>>0];case 4:return s?o=>d()[o>>>2>>>0]:o=>_()[o>>>2>>>0];case 8:return s?o=>gi[o>>>3]:o=>Oi[o>>>3];default:throw new TypeError(`invalid integer width (${n}): ${r}`)}};function _w(r,n,s,o,c){r>>>=0,s>>>=0;var h=(n=un(n>>>=0)).indexOf("u")!=-1;xn(r,{name:n,fromWireType:f=>f,toWireType:function(f,w){if(typeof w!="bigint"&&typeof w!="number")throw new TypeError(`Cannot convert "${mw(w)}" to ${this.name}`);return typeof w=="number"&&(w=BigInt(w)),w},argPackAdvance:Wn,readValueFromPointer:Mh(n,s,!h),destructorFunction:null})}var Wn=8;function gw(r,n,s,o){xn(r>>>=0,{name:n=un(n>>>=0),fromWireType:function(c){return!!c},toWireType:function(c,h){return h?s:o},argPackAdvance:Wn,readValueFromPointer:function(c){return this.fromWireType(a()[c>>>0])},destructorFunction:null})}var oc=[],Tn=[];function lc(r){(r>>>=0)>9&&--Tn[r+1]==0&&(Tn[r]=void 0,oc.push(r))}var ti={toValue:r=>(r||ys("Cannot use deleted val. handle = "+r),Tn[r]),toHandle:r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let n=oc.pop()||Tn.length;return Tn[n]=r,Tn[n+1]=1,n}}}};function uc(r){return this.fromWireType(_()[r>>>2>>>0])}var ww={name:"emscripten::val",fromWireType:r=>{var n=ti.toValue(r);return lc(r),n},toWireType:(r,n)=>ti.toHandle(n),argPackAdvance:Wn,readValueFromPointer:uc,destructorFunction:null};function yw(r){return xn(r>>>=0,ww)}var bw=(r,n)=>{switch(n){case 4:return function(s){return this.fromWireType(g()[s>>>2>>>0])};case 8:return function(s){return this.fromWireType(y()[s>>>3>>>0])};default:throw new TypeError(`invalid float width (${n}): ${r}`)}},vw=function(r,n,s){s>>>=0,xn(r>>>=0,{name:n=un(n>>>=0),fromWireType:o=>o,toWireType:(o,c)=>c,argPackAdvance:Wn,readValueFromPointer:bw(n,s),destructorFunction:null})};function Mw(r,n,s,o,c){r>>>=0,s>>>=0,n=un(n>>>=0);var h=v=>v;if(o===0){var f=32-8*s;h=v=>v<>>f}var w=n.includes("unsigned");xn(r,{name:n,fromWireType:h,toWireType:w?function(v,$){return this.name,$>>>0}:function(v,$){return this.name,$},argPackAdvance:Wn,readValueFromPointer:Mh(n,s,o!==0),destructorFunction:null})}function xw(r,n,s){s>>>=0;var o=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][n];function c(h){var f=_()[h>>>2>>>0],w=_()[h+4>>>2>>>0];return new o(i().buffer,w,f)}xn(r>>>=0,{name:s=un(s),fromWireType:c,argPackAdvance:Wn,readValueFromPointer:c},{ignoreDuplicateRegistrations:!0})}function Tw(r,n){r>>>=0;var s=(n=un(n>>>=0))==="std::string";xn(r,{name:n,fromWireType(o){var c,h=_()[o>>>2>>>0],f=o+4;if(s)for(var w=f,v=0;v<=h;++v){var $=f+v;if(v==h||a()[$>>>0]==0){var E=Ti(w,$-w);c===void 0?c=E:(c+="\0",c+=E),w=$+1}}else{var G=new Array(h);for(v=0;v>>0]);c=G.join("")}return dn(o),c},toWireType(o,c){var h;c instanceof ArrayBuffer&&(c=new Uint8Array(c));var f=typeof c=="string";f||c instanceof Uint8Array||c instanceof Uint8ClampedArray||c instanceof Int8Array||ys("Cannot pass non-string to std::string"),h=s&&f?lh(c):c.length;var w=Fd(4+h+1),v=w+4;if(_()[w>>>2>>>0]=h,s&&f)za(c,v,h+1);else if(f)for(var $=0;$255&&(dn(v),ys("String has UTF-16 code units that do not fit in 8 bits")),a()[v+$>>>0]=E}else for($=0;$>>0]=c[$];return o!==null&&o.push(dn,w),w},argPackAdvance:Wn,readValueFromPointer:uc,destructorFunction(o){dn(o)}})}var xh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Cw=(r,n)=>{for(var s=r,o=s>>1,c=o+n/2;!(o>=c)&&p()[o>>>0];)++o;if((s=o<<1)-r>32&&xh)return xh.decode(a().slice(r,s));for(var h="",f=0;!(f>=n/2);++f){var w=u()[r+2*f>>>1>>>0];if(w==0)break;h+=String.fromCharCode(w)}return h},kw=(r,n,s)=>{if(s??(s=2147483647),s<2)return 0;for(var o=n,c=(s-=2)<2*r.length?s/2:r.length,h=0;h>>1>>>0]=f,n+=2}return u()[n>>>1>>>0]=0,n-o},$w=r=>2*r.length,Sw=(r,n)=>{for(var s=0,o="";!(s>=n/4);){var c=d()[r+4*s>>>2>>>0];if(c==0)break;if(++s,c>=65536){var h=c-65536;o+=String.fromCharCode(55296|h>>10,56320|1023&h)}else o+=String.fromCharCode(c)}return o},Ew=(r,n,s)=>{if(n>>>=0,s??(s=2147483647),s<4)return 0;for(var o=n,c=o+s-4,h=0;h=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&r.charCodeAt(++h)),d()[n>>>2>>>0]=f,(n+=4)+4>c)break}return d()[n>>>2>>>0]=0,n-o},Pw=r=>{for(var n=0,s=0;s=55296&&o<=57343&&++s,n+=4}return n},Aw=function(r,n,s){var o,c,h,f;r>>>=0,n>>>=0,s=un(s>>>=0),n===2?(o=Cw,c=kw,f=$w,h=w=>p()[w>>>1>>>0]):n===4&&(o=Sw,c=Ew,f=Pw,h=w=>_()[w>>>2>>>0]),xn(r,{name:s,fromWireType:w=>{for(var v,$=_()[w>>>2>>>0],E=w+4,G=0;G<=$;++G){var J=w+4+G*n;if(G==$||h(J)==0){var _e=o(E,J-E);v===void 0?v=_e:(v+="\0",v+=_e),E=J+n}}return dn(w),v},toWireType:(w,v)=>{typeof v!="string"&&ys(`Cannot pass non-string to C++ string type ${s}`);var $=f(v),E=Fd(4+$+n);return _()[E>>>2>>>0]=$/n,c(v,E+4,$+n),w!==null&&w.push(dn,E),E},argPackAdvance:Wn,readValueFromPointer:uc,destructorFunction(w){dn(w)}})},Iw=function(r,n){xn(r>>>=0,{isVoid:!0,name:n=un(n>>>=0),argPackAdvance:0,fromWireType:()=>{},toWireType:(s,o)=>{}})},Fw=()=>1;function zw(r){fc(r>>>=0,!L,1,!I,131072,!1),xr.threadInitTLS()}var Th=r=>{if(!Wi)try{r(),(()=>{if(!ec())try{Q?zd(Wt):rc(Wt)}catch(n){eh(n)}})()}catch(n){eh(n)}};function dc(r){if(r>>>=0,typeof Atomics.waitAsync=="function"){Atomics.waitAsync(d(),r>>>2,r).value.then(kd);var n=r+128;Atomics.store(d(),n>>>2,1)}}var kd=()=>{var r=Oa();r&&(dc(r),Th(Hh))};function Ow(r,n,s){if((r>>>=0)==(n>>>=0))setTimeout(kd);else if(Q)postMessage({targetThread:r,cmd:"checkMailbox"});else{var o=xr.pthreads[r];if(!o)return;o.postMessage({cmd:"checkMailbox"})}}var $d=[];function Dw(r,n,s,o,c){n>>>=0,s>>>=0,c>>>=0,o/=2,$d.length=o;for(var h=c>>>3,f=0;f>>0];var w=n?Xp[n]:ky[r];xr.currentProxiedOperationCallerThread=s;var v=w(...$d);return xr.currentProxiedOperationCallerThread=0,v}function Bw(r){r>>>=0,Q?postMessage({cmd:"cleanupThread",thread:r}):Yp(r)}function jw(r){}var cc=(r,n)=>{var s,o,c,h=ac[r];return h===void 0&&ys(`${n} has unknown type ${s=r,o=Wh(s),c=un(o),dn(o),c}`),h},Ch=(r,n,s)=>{var o=[],c=r.toWireType(o,s);return o.length&&(_()[n>>>2>>>0]=ti.toHandle(o)),c};function Lw(r,n,s){return r>>>=0,n>>>=0,s>>>=0,r=ti.toValue(r),n=cc(n,"emval::as"),Ch(n,s,r)}var Sd=r=>{try{return r()}catch(n){gs(n)}},kh=()=>{vd+=1},ar={instrumentWasmImports(r){var n=/^(invoke_.*|__asyncjs__.*)$/;for(let[s,o]of Object.entries(r))typeof o=="function"&&(o.isAsync||n.test(s))},instrumentWasmExports(r){var n={};for(let[s,o]of Object.entries(r))n[s]=typeof o=="function"?(...c)=>{ar.exportCallStack.push(s);try{return o(...c)}finally{Wi||(ar.exportCallStack.pop(),ar.maybeStopUnwind())}}:o;return n},State:{Normal:0,Unwinding:1,Rewinding:2,Disabled:3},state:0,StackSize:65536,currData:null,handleSleepReturnValue:0,exportCallStack:[],callStackNameToId:{},callStackIdToName:{},callStackId:0,asyncPromiseHandlers:null,sleepCallbacks:[],getCallStackId(r){var n=ar.callStackNameToId[r];return n===void 0&&(n=ar.callStackId++,ar.callStackNameToId[r]=n,ar.callStackIdToName[n]=r),n},maybeStopUnwind(){ar.currData&&ar.state===ar.State.Unwinding&&ar.exportCallStack.length===0&&(ar.state=ar.State.Normal,kh(),Sd(vg),typeof Fibers<"u"&&Fibers.trampoline())},whenDone:()=>new Promise((r,n)=>{ar.asyncPromiseHandlers={resolve:r,reject:n}}),allocateData(){var r=Fd(12+ar.StackSize);return ar.setDataHeader(r,r+12,ar.StackSize),ar.setDataRewindFunc(r),r},setDataHeader(r,n,s){_()[r>>>2>>>0]=n,_()[r+4>>>2>>>0]=n+s},setDataRewindFunc(r){var n=ar.exportCallStack[0],s=ar.getCallStackId(n);d()[r+8>>>2>>>0]=s},getDataRewindFuncName(r){var n=d()[r+8>>>2>>>0];return ar.callStackIdToName[n]},getDataRewindFunc:r=>oe[r],doRewind(r){var n=ar.getDataRewindFuncName(r),s=ar.getDataRewindFunc(n);return vd-=1,s()},handleSleep(r){if(!Wi){if(ar.state===ar.State.Normal){var n=!1,s=!1;r((o=0)=>{if(!Wi&&(ar.handleSleepReturnValue=o,n=!0,s)){ar.state=ar.State.Rewinding,Sd(()=>Mg(ar.currData)),typeof Browser<"u"&&Browser.mainLoop.func&&Browser.mainLoop.resume();var c,h=!1;try{c=ar.doRewind(ar.currData)}catch(v){c=v,h=!0}var f=!1;if(!ar.currData){var w=ar.asyncPromiseHandlers;w&&(ar.asyncPromiseHandlers=null,(h?w.reject:w.resolve)(c),f=!0)}if(h&&!f)throw c}}),s=!0,n||(ar.state=ar.State.Unwinding,ar.currData=ar.allocateData(),typeof Browser<"u"&&Browser.mainLoop.func&&Browser.mainLoop.pause(),Sd(()=>bg(ar.currData)))}else ar.state===ar.State.Rewinding?(ar.state=ar.State.Normal,Sd(xg),dn(ar.currData),ar.currData=null,ar.sleepCallbacks.forEach(Th)):gs(`invalid state: ${ar.state}`);return ar.handleSleepReturnValue}},handleAsync:r=>ar.handleSleep(n=>{r().then(n)})},$h=function(r){return r>>>=0,ar.handleAsync(()=>(r=ti.toValue(r)).then(ti.toHandle))};$h.isAsync=!0;var Ed=[];function Rw(r,n,s,o){return n>>>=0,s>>>=0,o>>>=0,(r=Ed[r>>>=0])(null,n=ti.toValue(n),s,o)}var Nw={},Pd=r=>{var n=Nw[r];return n===void 0?un(r):n};function Vw(r,n,s,o,c){return n>>>=0,s>>>=0,o>>>=0,c>>>=0,(r=Ed[r>>>=0])(n=ti.toValue(n),n[s=Pd(s)],o,c)}var Sh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Uw(r){return(r>>>=0)==0?ti.toHandle(Sh()):(r=Pd(r),ti.toHandle(Sh()[r]))}var Ww=r=>{var n=Ed.length;return Ed.push(r),n},Gw=(r,n)=>{for(var s=new Array(r),o=0;o>>2>>>0],"parameter "+o);return s},Eh=(r,n)=>Object.defineProperty(n,"name",{value:r});function qw(r,n,s){var o=Gw(r,n>>>=0),c=o.shift();r--;var h=`return function (obj, func, destructorsRef, args) { +`,f=0,w=[];s===0&&w.push("obj");for(var v=["retType"],$=[c],E=0;E_e.name).join(", ")}) => ${c.name}>`;return Ww(Eh(J,G))}function Kw(r){return r=Pd(r>>>=0),ti.toHandle(l[r])}function Hw(r,n){return r>>>=0,n>>>=0,r=ti.toValue(r),n=ti.toValue(n),ti.toHandle(r[n])}function Xw(r){(r>>>=0)>9&&(Tn[r+1]+=1)}function Qw(){return ti.toHandle([])}function Yw(r){r>>>=0,r=ti.toValue(r);for(var n=new Array(r.length),s=0;s>>=0,ti.toHandle(Pd(r))}function Jw(){return ti.toHandle({})}var ey=r=>{for(;r.length;){var n=r.pop();r.pop()(n)}};function ty(r){r>>>=0;var n=ti.toValue(r);ey(n),lc(r)}function ry(r,n,s){r>>>=0,n>>>=0,s>>>=0,r=ti.toValue(r),n=ti.toValue(n),s=ti.toValue(s),r[n]=s}function iy(r,n){n>>>=0;var s=(r=cc(r>>>=0,"_emval_take_value")).readValueFromPointer(n);return ti.toHandle(s)}function ny(r,n){r=Bu(r),n>>>=0;var s=new Date(1e3*r);d()[n>>>2>>>0]=s.getUTCSeconds(),d()[n+4>>>2>>>0]=s.getUTCMinutes(),d()[n+8>>>2>>>0]=s.getUTCHours(),d()[n+12>>>2>>>0]=s.getUTCDate(),d()[n+16>>>2>>>0]=s.getUTCMonth(),d()[n+20>>>2>>>0]=s.getUTCFullYear()-1900,d()[n+24>>>2>>>0]=s.getUTCDay();var o=Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0),c=(s.getTime()-o)/864e5|0;d()[n+28>>>2>>>0]=c}var sy=[0,31,60,91,121,152,182,213,244,274,305,335],ay=[0,31,59,90,120,151,181,212,243,273,304,334],Ph=r=>{var n;return((n=r.getFullYear())%4!=0||n%100==0&&n%400!=0?ay:sy)[r.getMonth()]+r.getDate()-1};function oy(r,n){r=Bu(r),n>>>=0;var s=new Date(1e3*r);d()[n>>>2>>>0]=s.getSeconds(),d()[n+4>>>2>>>0]=s.getMinutes(),d()[n+8>>>2>>>0]=s.getHours(),d()[n+12>>>2>>>0]=s.getDate(),d()[n+16>>>2>>>0]=s.getMonth(),d()[n+20>>>2>>>0]=s.getFullYear()-1900,d()[n+24>>>2>>>0]=s.getDay();var o=0|Ph(s);d()[n+28>>>2>>>0]=o,d()[n+36>>>2>>>0]=-60*s.getTimezoneOffset();var c=new Date(s.getFullYear(),0,1),h=new Date(s.getFullYear(),6,1).getTimezoneOffset(),f=c.getTimezoneOffset(),w=0|(h!=f&&s.getTimezoneOffset()==Math.min(f,h));d()[n+32>>>2>>>0]=w}var ly=function(r){r>>>=0;var n=(()=>{var s=new Date(d()[r+20>>>2>>>0]+1900,d()[r+16>>>2>>>0],d()[r+12>>>2>>>0],d()[r+8>>>2>>>0],d()[r+4>>>2>>>0],d()[r>>>2>>>0],0),o=d()[r+32>>>2>>>0],c=s.getTimezoneOffset(),h=new Date(s.getFullYear(),0,1),f=new Date(s.getFullYear(),6,1).getTimezoneOffset(),w=h.getTimezoneOffset(),v=Math.min(w,f);if(o<0)d()[r+32>>>2>>>0]=+(f!=w&&v==c);else if(o>0!=(v==c)){var $=Math.max(w,f),E=o>0?v:$;s.setTime(s.getTime()+6e4*(E-c))}d()[r+24>>>2>>>0]=s.getDay();var G=0|Ph(s);d()[r+28>>>2>>>0]=G,d()[r>>>2>>>0]=s.getSeconds(),d()[r+4>>>2>>>0]=s.getMinutes(),d()[r+8>>>2>>>0]=s.getHours(),d()[r+12>>>2>>>0]=s.getDate(),d()[r+16>>>2>>>0]=s.getMonth(),d()[r+20>>>2>>>0]=s.getYear();var J=s.getTime();return isNaN(J)?-1:J/1e3})();return BigInt(n)};function Ah(r,n,s,o,c,h,f){return Q?ei(16,0,1,r,n,s,o,c,h,f):(r>>>=0,c=Bu(c),h>>>=0,f>>>=0,-52)}function Ih(r,n,s,o,c,h){if(Q)return ei(17,0,1,r,n,s,o,c,h);r>>>=0,n>>>=0,h=Bu(h)}var uy=function(r,n,s,o){r>>>=0,n>>>=0,s>>>=0,o>>>=0;var c=new Date().getFullYear(),h=new Date(c,0,1),f=new Date(c,6,1),w=h.getTimezoneOffset(),v=f.getTimezoneOffset(),$=Math.max(w,v);_()[r>>>2>>>0]=60*$,d()[n>>>2>>>0]=+(w!=v);var E=_e=>_e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],G=E(h),J=E(f);v{var o=((c,h)=>{var f;for(pc.length=0;f=a()[c++>>>0];){var w=f!=105;h+=(w&=f!=112)&&h%8?4:0,pc.push(f==112?_()[h>>>2>>>0]:f==106?gi[h>>>3]:f==105?d()[h>>>2>>>0]:y()[h>>>3>>>0]),h+=w?8:4}return pc})(n,s);return Xp[r](...o)};function dy(r,n,s){return Fh(r>>>=0,n>>>=0,s>>>=0)}function cy(r,n,s){return Fh(r>>>=0,n>>>=0,s>>>=0)}var py=()=>{},hy=()=>Date.now();function fy(r,n){return Sr(Ti(r>>>=0,n>>>=0))}var zh,my=()=>{throw kh(),"unwind"},Oh=()=>4294901760;function _y(){return Oh()}zh=()=>performance.timeOrigin+performance.now();var gy=()=>navigator.hardwareConcurrency;function wy(r){return gs("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}var yy=r=>{var n=(r-Bt.buffer.byteLength+65535)/65536;try{return Bt.grow(n),xi(),1}catch{}};function by(r){r>>>=0;var n=a().length;if(r<=n)return!1;var s=Oh();if(r>s)return!1;for(var o,c=1;c<=4;c*=2){var h=n*(1+.2/c);h=Math.min(h,r+100663296);var f=Math.min(s,(o=Math.max(r,h))+(65536-o%65536)%65536);if(yy(f))return!0}return!1}var Ad=r=>(gs("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),ju={},Dh=r=>{r.forEach(n=>{Ad()})};function Bh(){return new Error().stack.toString()}function vy(){var r=Bh().split(` +`);return r[0]=="Error"&&r.shift(),Dh(r),ju.last_addr=Ad(r[3]),ju.last_stack=r,ju.last_addr}function My(r,n,s){var o;r>>>=0,n>>>=0,ju.last_addr==r?o=ju.last_stack:((o=Bh().split(` +`))[0]=="Error"&&o.shift(),Dh(o));for(var c=3;o[c]&&Ad(o[c])!=r;)++c;for(var h=0;h>>2>>>0]=Ad(o[h+c]);return h}var hc={},Lu=()=>{if(!Lu.strings){var r={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",_:it};for(var n in hc)hc[n]===void 0?delete r[n]:r[n]=hc[n];var s=[];for(var n in r)s.push(`${n}=${r[n]}`);Lu.strings=s}return Lu.strings},jh=function(r,n){if(Q)return ei(18,0,1,r,n);r>>>=0,n>>>=0;var s=0;return Lu().forEach((o,c)=>{var h=n+s;_()[r+4*c>>>2>>>0]=h,((f,w)=>{for(var v=0;v>>0]=f.charCodeAt(v);i()[w>>>0]=0})(o,h),s+=o.length+1}),0},Lh=function(r,n){if(Q)return ei(19,0,1,r,n);r>>>=0,n>>>=0;var s=Lu();_()[r>>>2>>>0]=s.length;var o=0;return s.forEach(c=>o+=c.length+1),_()[n>>>2>>>0]=o,0};function Rh(r){return Q?ei(20,0,1,r):52}function Nh(r,n,s,o){return Q?ei(21,0,1,r,n,s,o):(n>>>=0,s>>>=0,o>>>=0,52)}function Vh(r,n,s,o){return Q?ei(22,0,1,r,n,s,o):(n=Bu(n),o>>>=0,70)}var xy=[null,[],[]],Ty=(r,n)=>{var s=xy[r];n===0||n===10?((r===1?Ir:Sr)(sh(s,0)),s.length=0):s.push(n)};function Uh(r,n,s,o){if(Q)return ei(23,0,1,r,n,s,o);n>>>=0,s>>>=0,o>>>=0;for(var c=0,h=0;h>>2>>>0],w=_()[n+4>>>2>>>0];n+=8;for(var v=0;v>>0]);c+=w}return _()[o>>>2>>>0]=c,0}function Cy(r){return r>>>0}xr.init(),(()=>{for(var r=new Array(256),n=0;n<256;++n)r[n]=String.fromCharCode(n);bh=r})(),vh=l.BindingError=class extends Error{constructor(r){super(r),this.name="BindingError"}},l.InternalError=class extends Error{constructor(r){super(r),this.name="InternalError"}},Tn.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Tn.length/2-5-oc.length;var Id,ky=[tc,th,rh,ah,oh,uh,dh,ch,ph,hh,fh,mh,_h,gh,wh,yh,Ah,Ih,jh,Lh,Rh,Nh,Vh,Uh],oe=function(){var r,n,s,o,c=Hp();function h(f,w){var v,$;return oe=f.exports,oe=function(E){var G=_e=>Le=>_e(Le)>>>0,J=_e=>()=>_e()>>>0;return(E=Object.assign({},E))._d=G(E._d),E.De=J(E.De),E.Ee=G(E.Ee),E.emscripten_main_runtime_thread_id=J(E.emscripten_main_runtime_thread_id),E.Se=G(E.Se),E.Te=J(E.Te),E}(oe=ar.instrumentWasmExports(oe)),$=oe.Ge,xr.tlsInitFunctions.push($),oe.He,v=oe.Zd,Si.unshift(v),gr=w,Up(),oe}if(Vp(),l.instantiateWasm)try{return l.instantiateWasm(c,h)}catch(f){Sr(`Module.instantiateWasm callback failed with error: ${f}`),k(f)}return bd||(bd=function(){if(l.locateFile){var f="ort-wasm-simd-threaded.jsep.wasm";return Wp(f)?f:(w=f,l.locateFile?l.locateFile(w,Mt):Mt+w)}var w;return new URL(m("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),m.b).href}()),(r=Gt,n=bd,s=c,o=function(f){h(f.instance,f.module)},r||typeof WebAssembly.instantiateStreaming!="function"||Wp(n)||Gp(n)||typeof fetch!="function"?Kp(n,s,o):fetch(n,{credentials:"same-origin"}).then(f=>WebAssembly.instantiateStreaming(f,s).then(o,function(w){return Sr(`wasm streaming compile failed: ${w}`),Sr("falling back to ArrayBuffer instantiation"),Kp(n,s,o)}))).catch(k),{}}(),Wh=r=>(Wh=oe._d)(r),Gh=()=>(Gh=oe.$d)(),Oa=(l._OrtInit=(r,n)=>(l._OrtInit=oe.ae)(r,n),l._OrtGetLastError=(r,n)=>(l._OrtGetLastError=oe.be)(r,n),l._OrtCreateSessionOptions=(r,n,s,o,c,h,f,w,v,$)=>(l._OrtCreateSessionOptions=oe.ce)(r,n,s,o,c,h,f,w,v,$),l._OrtAppendExecutionProvider=(r,n)=>(l._OrtAppendExecutionProvider=oe.de)(r,n),l._OrtAddFreeDimensionOverride=(r,n,s)=>(l._OrtAddFreeDimensionOverride=oe.ee)(r,n,s),l._OrtAddSessionConfigEntry=(r,n,s)=>(l._OrtAddSessionConfigEntry=oe.fe)(r,n,s),l._OrtReleaseSessionOptions=r=>(l._OrtReleaseSessionOptions=oe.ge)(r),l._OrtCreateSession=(r,n,s)=>(l._OrtCreateSession=oe.he)(r,n,s),l._OrtReleaseSession=r=>(l._OrtReleaseSession=oe.ie)(r),l._OrtGetInputOutputCount=(r,n,s)=>(l._OrtGetInputOutputCount=oe.je)(r,n,s),l._OrtGetInputName=(r,n)=>(l._OrtGetInputName=oe.ke)(r,n),l._OrtGetOutputName=(r,n)=>(l._OrtGetOutputName=oe.le)(r,n),l._OrtFree=r=>(l._OrtFree=oe.me)(r),l._OrtCreateTensor=(r,n,s,o,c,h)=>(l._OrtCreateTensor=oe.ne)(r,n,s,o,c,h),l._OrtGetTensorData=(r,n,s,o,c)=>(l._OrtGetTensorData=oe.oe)(r,n,s,o,c),l._OrtReleaseTensor=r=>(l._OrtReleaseTensor=oe.pe)(r),l._OrtCreateRunOptions=(r,n,s,o)=>(l._OrtCreateRunOptions=oe.qe)(r,n,s,o),l._OrtAddRunConfigEntry=(r,n,s)=>(l._OrtAddRunConfigEntry=oe.re)(r,n,s),l._OrtReleaseRunOptions=r=>(l._OrtReleaseRunOptions=oe.se)(r),l._OrtCreateBinding=r=>(l._OrtCreateBinding=oe.te)(r),l._OrtBindInput=(r,n,s)=>(l._OrtBindInput=oe.ue)(r,n,s),l._OrtBindOutput=(r,n,s,o)=>(l._OrtBindOutput=oe.ve)(r,n,s,o),l._OrtClearBoundOutputs=r=>(l._OrtClearBoundOutputs=oe.we)(r),l._OrtReleaseBinding=r=>(l._OrtReleaseBinding=oe.xe)(r),l._OrtRunWithBinding=(r,n,s,o,c)=>(l._OrtRunWithBinding=oe.ye)(r,n,s,o,c),l._OrtRun=(r,n,s,o,c,h,f,w)=>(l._OrtRun=oe.ze)(r,n,s,o,c,h,f,w),l._OrtEndProfiling=r=>(l._OrtEndProfiling=oe.Ae)(r),l._JsepOutput=(r,n,s)=>(l._JsepOutput=oe.Be)(r,n,s),l._JsepGetNodeName=r=>(l._JsepGetNodeName=oe.Ce)(r),()=>(Oa=oe.De)()),Fd=l._malloc=r=>(Fd=l._malloc=oe.Ee)(r),dn=l._free=r=>(dn=l._free=oe.Fe)(r),fc=(r,n,s,o,c,h)=>(fc=oe.Ie)(r,n,s,o,c,h),qh=()=>(qh=oe.Je)(),Kh=(r,n,s,o,c)=>(Kh=oe.Ke)(r,n,s,o,c),mc=r=>(mc=oe.Le)(r),zd=r=>(zd=oe.Me)(r),Hh=()=>(Hh=oe.Ne)(),Fe=(r,n)=>(Fe=oe.Oe)(r,n),Xh=r=>(Xh=oe.Pe)(r),Qh=(r,n)=>(Qh=oe.Qe)(r,n),Yh=r=>(Yh=oe.Re)(r),Zh=r=>(Zh=oe.Se)(r),Jh=()=>(Jh=oe.Te)(),ef=r=>(ef=oe.Ue)(r),tf=r=>(tf=oe.Ve)(r),rf=(r,n,s)=>(rf=oe.We)(r,n,s),nf=r=>(nf=oe.Xe)(r),sf=l.dynCall_vii=(r,n,s)=>(sf=l.dynCall_vii=oe.Ye)(r,n,s),af=l.dynCall_iiii=(r,n,s,o)=>(af=l.dynCall_iiii=oe.Ze)(r,n,s,o),of=l.dynCall_iii=(r,n,s)=>(of=l.dynCall_iii=oe._e)(r,n,s),_c=l.dynCall_ii=(r,n)=>(_c=l.dynCall_ii=oe.$e)(r,n),lf=l.dynCall_iiiiiii=(r,n,s,o,c,h,f)=>(lf=l.dynCall_iiiiiii=oe.af)(r,n,s,o,c,h,f),uf=l.dynCall_vi=(r,n)=>(uf=l.dynCall_vi=oe.bf)(r,n),df=l.dynCall_v=r=>(df=l.dynCall_v=oe.cf)(r),cf=l.dynCall_iiiiii=(r,n,s,o,c,h)=>(cf=l.dynCall_iiiiii=oe.df)(r,n,s,o,c,h),pf=l.dynCall_iiij=(r,n,s,o)=>(pf=l.dynCall_iiij=oe.ef)(r,n,s,o),hf=l.dynCall_iiiii=(r,n,s,o,c)=>(hf=l.dynCall_iiiii=oe.ff)(r,n,s,o,c),ff=l.dynCall_viii=(r,n,s,o)=>(ff=l.dynCall_viii=oe.gf)(r,n,s,o),mf=l.dynCall_viiiii=(r,n,s,o,c,h)=>(mf=l.dynCall_viiiii=oe.hf)(r,n,s,o,c,h),_f=l.dynCall_viiii=(r,n,s,o,c)=>(_f=l.dynCall_viiii=oe.jf)(r,n,s,o,c),gf=l.dynCall_viiiiii=(r,n,s,o,c,h,f)=>(gf=l.dynCall_viiiiii=oe.kf)(r,n,s,o,c,h,f),wf=l.dynCall_viiji=(r,n,s,o,c)=>(wf=l.dynCall_viiji=oe.lf)(r,n,s,o,c),yf=l.dynCall_viiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(yf=l.dynCall_viiiiiiiiiii=oe.mf)(r,n,s,o,c,h,f,w,v,$,E,G),bf=l.dynCall_viiijjjii=(r,n,s,o,c,h,f,w,v)=>(bf=l.dynCall_viiijjjii=oe.nf)(r,n,s,o,c,h,f,w,v),vf=l.dynCall_iij=(r,n,s)=>(vf=l.dynCall_iij=oe.of)(r,n,s),Mf=l.dynCall_iif=(r,n,s)=>(Mf=l.dynCall_iif=oe.pf)(r,n,s),xf=l.dynCall_iid=(r,n,s)=>(xf=l.dynCall_iid=oe.qf)(r,n,s),Tf=l.dynCall_jii=(r,n,s)=>(Tf=l.dynCall_jii=oe.rf)(r,n,s),Cf=l.dynCall_i=r=>(Cf=l.dynCall_i=oe.sf)(r),kf=l.dynCall_viiiiiiii=(r,n,s,o,c,h,f,w,v)=>(kf=l.dynCall_viiiiiiii=oe.tf)(r,n,s,o,c,h,f,w,v),$f=l.dynCall_ji=(r,n)=>($f=l.dynCall_ji=oe.uf)(r,n),Sf=l.dynCall_viij=(r,n,s,o)=>(Sf=l.dynCall_viij=oe.vf)(r,n,s,o),Ef=l.dynCall_iiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(Ef=l.dynCall_iiiiiiiiiiii=oe.wf)(r,n,s,o,c,h,f,w,v,$,E,G),Pf=l.dynCall_viiiiiiiii=(r,n,s,o,c,h,f,w,v,$)=>(Pf=l.dynCall_viiiiiiiii=oe.xf)(r,n,s,o,c,h,f,w,v,$),Af=l.dynCall_ij=(r,n)=>(Af=l.dynCall_ij=oe.yf)(r,n),If=l.dynCall_iiiiij=(r,n,s,o,c,h)=>(If=l.dynCall_iiiiij=oe.zf)(r,n,s,o,c,h),Ff=l.dynCall_j=r=>(Ff=l.dynCall_j=oe.Af)(r),zf=l.dynCall_vij=(r,n,s)=>(zf=l.dynCall_vij=oe.Bf)(r,n,s),Of=l.dynCall_iiiiiiii=(r,n,s,o,c,h,f,w)=>(Of=l.dynCall_iiiiiiii=oe.Cf)(r,n,s,o,c,h,f,w),Df=l.dynCall_viijjjiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(Df=l.dynCall_viijjjiiiiii=oe.Df)(r,n,s,o,c,h,f,w,v,$,E,G),Bf=l.dynCall_viiijiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(Bf=l.dynCall_viiijiiiiiii=oe.Ef)(r,n,s,o,c,h,f,w,v,$,E,G),jf=l.dynCall_viiiiiii=(r,n,s,o,c,h,f,w)=>(jf=l.dynCall_viiiiiii=oe.Ff)(r,n,s,o,c,h,f,w),Lf=l.dynCall_iiiiiiiij=(r,n,s,o,c,h,f,w,v)=>(Lf=l.dynCall_iiiiiiiij=oe.Gf)(r,n,s,o,c,h,f,w,v),Rf=l.dynCall_viiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>(Rf=l.dynCall_viiiiiiiiiiiiii=oe.Hf)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le),Nf=l.dynCall_iiiiiiiii=(r,n,s,o,c,h,f,w,v)=>(Nf=l.dynCall_iiiiiiiii=oe.If)(r,n,s,o,c,h,f,w,v),Vf=l.dynCall_iiiiijiiiii=(r,n,s,o,c,h,f,w,v,$,E)=>(Vf=l.dynCall_iiiiijiiiii=oe.Jf)(r,n,s,o,c,h,f,w,v,$,E),Uf=l.dynCall_vijjjiiij=(r,n,s,o,c,h,f,w,v)=>(Uf=l.dynCall_vijjjiiij=oe.Kf)(r,n,s,o,c,h,f,w,v),Wf=l.dynCall_viijj=(r,n,s,o,c)=>(Wf=l.dynCall_viijj=oe.Lf)(r,n,s,o,c),Gf=l.dynCall_fi=(r,n)=>(Gf=l.dynCall_fi=oe.Mf)(r,n),qf=l.dynCall_fii=(r,n,s)=>(qf=l.dynCall_fii=oe.Nf)(r,n,s),Kf=l.dynCall_di=(r,n)=>(Kf=l.dynCall_di=oe.Of)(r,n),Hf=l.dynCall_dii=(r,n,s)=>(Hf=l.dynCall_dii=oe.Pf)(r,n,s),Xf=l.dynCall_vijj=(r,n,s,o)=>(Xf=l.dynCall_vijj=oe.Qf)(r,n,s,o),Qf=l.dynCall_iiiiiiiiii=(r,n,s,o,c,h,f,w,v,$)=>(Qf=l.dynCall_iiiiiiiiii=oe.Rf)(r,n,s,o,c,h,f,w,v,$),Yf=l.dynCall_viijiii=(r,n,s,o,c,h,f)=>(Yf=l.dynCall_viijiii=oe.Sf)(r,n,s,o,c,h,f),Zf=l.dynCall_viid=(r,n,s,o)=>(Zf=l.dynCall_viid=oe.Tf)(r,n,s,o),Jf=l.dynCall_viffiii=(r,n,s,o,c,h,f)=>(Jf=l.dynCall_viffiii=oe.Uf)(r,n,s,o,c,h,f),em=l.dynCall_viifiii=(r,n,s,o,c,h,f)=>(em=l.dynCall_viifiii=oe.Vf)(r,n,s,o,c,h,f),tm=l.dynCall_viiiiidiidi=(r,n,s,o,c,h,f,w,v,$,E)=>(tm=l.dynCall_viiiiidiidi=oe.Wf)(r,n,s,o,c,h,f,w,v,$,E),rm=l.dynCall_viiiiiiiiidi=(r,n,s,o,c,h,f,w,v,$,E,G)=>(rm=l.dynCall_viiiiiiiiidi=oe.Xf)(r,n,s,o,c,h,f,w,v,$,E,G),im=l.dynCall_jiii=(r,n,s,o)=>(im=l.dynCall_jiii=oe.Yf)(r,n,s,o),nm=l.dynCall_vjiiiiii=(r,n,s,o,c,h,f,w)=>(nm=l.dynCall_vjiiiiii=oe.Zf)(r,n,s,o,c,h,f,w),sm=l.dynCall_viiid=(r,n,s,o,c)=>(sm=l.dynCall_viiid=oe._f)(r,n,s,o,c),am=l.dynCall_viiiiiiiiiji=(r,n,s,o,c,h,f,w,v,$,E,G)=>(am=l.dynCall_viiiiiiiiiji=oe.$f)(r,n,s,o,c,h,f,w,v,$,E,G),om=l.dynCall_viji=(r,n,s,o)=>(om=l.dynCall_viji=oe.ag)(r,n,s,o),lm=l.dynCall_viiiiiiiiiiiiiifi=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)=>(lm=l.dynCall_viiiiiiiiiiiiiifi=oe.bg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It),um=l.dynCall_ijii=(r,n,s,o)=>(um=l.dynCall_ijii=oe.cg)(r,n,s,o),dm=l.dynCall_vijjjjjjjjjjjjji=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)=>(dm=l.dynCall_vijjjjjjjjjjjjji=oe.dg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht),cm=l.dynCall_viiiji=(r,n,s,o,c,h)=>(cm=l.dynCall_viiiji=oe.eg)(r,n,s,o,c,h),pm=l.dynCall_vijjjiiji=(r,n,s,o,c,h,f,w,v)=>(pm=l.dynCall_vijjjiiji=oe.fg)(r,n,s,o,c,h,f,w,v),hm=l.dynCall_iiiji=(r,n,s,o,c)=>(hm=l.dynCall_iiiji=oe.gg)(r,n,s,o,c),fm=l.dynCall_iiijiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(fm=l.dynCall_iiijiiiiiiiiii=oe.hg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),mm=l.dynCall_vj=(r,n)=>(mm=l.dynCall_vj=oe.ig)(r,n),_m=l.dynCall_jjj=(r,n,s)=>(_m=l.dynCall_jjj=oe.jg)(r,n,s),gm=l.dynCall_iiijiiiiii=(r,n,s,o,c,h,f,w,v,$)=>(gm=l.dynCall_iiijiiiiii=oe.kg)(r,n,s,o,c,h,f,w,v,$),wm=l.dynCall_vfiii=(r,n,s,o,c)=>(wm=l.dynCall_vfiii=oe.lg)(r,n,s,o,c),ym=l.dynCall_viiiiff=(r,n,s,o,c,h,f)=>(ym=l.dynCall_viiiiff=oe.mg)(r,n,s,o,c,h,f),bm=l.dynCall_viiiiiff=(r,n,s,o,c,h,f,w)=>(bm=l.dynCall_viiiiiff=oe.ng)(r,n,s,o,c,h,f,w),vm=l.dynCall_viiff=(r,n,s,o,c)=>(vm=l.dynCall_viiff=oe.og)(r,n,s,o,c),Mm=l.dynCall_viiiiiiiiifiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>(Mm=l.dynCall_viiiiiiiiifiiii=oe.pg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le),xm=l.dynCall_viiiiiiiijj=(r,n,s,o,c,h,f,w,v,$,E)=>(xm=l.dynCall_viiiiiiiijj=oe.qg)(r,n,s,o,c,h,f,w,v,$,E),Tm=l.dynCall_iiiiiiiiiiiiiifii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)=>(Tm=l.dynCall_iiiiiiiiiiiiiifii=oe.rg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It),Cm=l.dynCall_viiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(Cm=l.dynCall_viiiiiiiiiiii=oe.sg)(r,n,s,o,c,h,f,w,v,$,E,G,J),km=l.dynCall_iiiiiiiiiiiiiiiiifii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)=>(km=l.dynCall_iiiiiiiiiiiiiiiiifii=oe.tg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er),$m=l.dynCall_vijjiiiiii=(r,n,s,o,c,h,f,w,v,$)=>($m=l.dynCall_vijjiiiiii=oe.ug)(r,n,s,o,c,h,f,w,v,$),Sm=l.dynCall_iiiijjj=(r,n,s,o,c,h,f)=>(Sm=l.dynCall_iiiijjj=oe.vg)(r,n,s,o,c,h,f),Em=l.dynCall_viiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E)=>(Em=l.dynCall_viiiiiiiiii=oe.wg)(r,n,s,o,c,h,f,w,v,$,E),Pm=l.dynCall_iiijjj=(r,n,s,o,c,h)=>(Pm=l.dynCall_iiijjj=oe.xg)(r,n,s,o,c,h),Am=l.dynCall_fffffff=(r,n,s,o,c,h,f)=>(Am=l.dynCall_fffffff=oe.yg)(r,n,s,o,c,h,f),Im=l.dynCall_viiiij=(r,n,s,o,c,h)=>(Im=l.dynCall_viiiij=oe.zg)(r,n,s,o,c,h),Fm=l.dynCall_viiiiiijiifiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(Fm=l.dynCall_viiiiiijiifiii=oe.Ag)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),zm=l.dynCall_vjjjjjjffjifiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt)=>(zm=l.dynCall_vjjjjjjffjifiiiiii=oe.Bg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt),Om=l.dynCall_viiiiiiffjifiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)=>(Om=l.dynCall_viiiiiiffjifiiiii=oe.Cg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It),Dm=l.dynCall_viiiiiiffjfiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)=>(Dm=l.dynCall_viiiiiiffjfiiiii=oe.Dg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht),Bm=l.dynCall_viiiiiiffjiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>(Bm=l.dynCall_viiiiiiffjiiiii=oe.Eg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le),jm=l.dynCall_vjjjjjjjjfffiiifiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)=>(jm=l.dynCall_vjjjjjjjjfffiiifiiiii=oe.Fg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr),Lm=l.dynCall_vjjjjjjfffifijiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or)=>(Lm=l.dynCall_vjjjjjjfffifijiiiii=oe.Gg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or),Rm=l.dynCall_vjjjjjjfffifiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt)=>(Rm=l.dynCall_vjjjjjjfffifiiiiii=oe.Hg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt),Nm=l.dynCall_vjjjjjjjjfffjifiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)=>(Nm=l.dynCall_vjjjjjjjjfffjifiiiiii=oe.Ig)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr),Vm=l.dynCall_vijiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(Vm=l.dynCall_vijiiiiiiiiii=oe.Jg)(r,n,s,o,c,h,f,w,v,$,E,G,J),Um=l.dynCall_vijjfffiii=(r,n,s,o,c,h,f,w,v,$)=>(Um=l.dynCall_vijjfffiii=oe.Kg)(r,n,s,o,c,h,f,w,v,$),Wm=l.dynCall_viiiiiiijiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(Wm=l.dynCall_viiiiiiijiiii=oe.Lg)(r,n,s,o,c,h,f,w,v,$,E,G,J),Gm=l.dynCall_vijjjjjjifiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>(Gm=l.dynCall_vijjjjjjifiiiii=oe.Mg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le),qm=l.dynCall_viifi=(r,n,s,o,c)=>(qm=l.dynCall_viifi=oe.Ng)(r,n,s,o,c),Km=l.dynCall_vjjjjjiiii=(r,n,s,o,c,h,f,w,v,$)=>(Km=l.dynCall_vjjjjjiiii=oe.Og)(r,n,s,o,c,h,f,w,v,$),Hm=l.dynCall_vjjjjfiii=(r,n,s,o,c,h,f,w,v)=>(Hm=l.dynCall_vjjjjfiii=oe.Pg)(r,n,s,o,c,h,f,w,v),Xm=l.dynCall_viiiiiijiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(Xm=l.dynCall_viiiiiijiiiiii=oe.Qg)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),Qm=l.dynCall_vijjii=(r,n,s,o,c,h)=>(Qm=l.dynCall_vijjii=oe.Rg)(r,n,s,o,c,h),Ym=l.dynCall_viiiiijjiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(Ym=l.dynCall_viiiiijjiiiii=oe.Sg)(r,n,s,o,c,h,f,w,v,$,E,G,J),Zm=l.dynCall_iiiiiji=(r,n,s,o,c,h,f)=>(Zm=l.dynCall_iiiiiji=oe.Tg)(r,n,s,o,c,h,f),Jm=l.dynCall_iiiiji=(r,n,s,o,c,h)=>(Jm=l.dynCall_iiiiji=oe.Ug)(r,n,s,o,c,h),e_=l.dynCall_viiiiijiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(e_=l.dynCall_viiiiijiiiiii=oe.Vg)(r,n,s,o,c,h,f,w,v,$,E,G,J),t_=l.dynCall_viiijiiiiii=(r,n,s,o,c,h,f,w,v,$,E)=>(t_=l.dynCall_viiijiiiiii=oe.Wg)(r,n,s,o,c,h,f,w,v,$,E),r_=l.dynCall_viiiijii=(r,n,s,o,c,h,f,w)=>(r_=l.dynCall_viiiijii=oe.Xg)(r,n,s,o,c,h,f,w),i_=l.dynCall_viijjiii=(r,n,s,o,c,h,f,w)=>(i_=l.dynCall_viijjiii=oe.Yg)(r,n,s,o,c,h,f,w),n_=l.dynCall_viiiiijjji=(r,n,s,o,c,h,f,w,v,$)=>(n_=l.dynCall_viiiiijjji=oe.Zg)(r,n,s,o,c,h,f,w,v,$),s_=l.dynCall_vijjjjiij=(r,n,s,o,c,h,f,w,v)=>(s_=l.dynCall_vijjjjiij=oe._g)(r,n,s,o,c,h,f,w,v),a_=l.dynCall_viiiiijij=(r,n,s,o,c,h,f,w,v)=>(a_=l.dynCall_viiiiijij=oe.$g)(r,n,s,o,c,h,f,w,v),o_=l.dynCall_viiiiiijij=(r,n,s,o,c,h,f,w,v,$)=>(o_=l.dynCall_viiiiiijij=oe.ah)(r,n,s,o,c,h,f,w,v,$),l_=l.dynCall_vijiii=(r,n,s,o,c,h)=>(l_=l.dynCall_vijiii=oe.bh)(r,n,s,o,c,h),u_=l.dynCall_viiiiiiiiifi=(r,n,s,o,c,h,f,w,v,$,E,G)=>(u_=l.dynCall_viiiiiiiiifi=oe.ch)(r,n,s,o,c,h,f,w,v,$,E,G),d_=l.dynCall_viiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(d_=l.dynCall_viiiiiiiiiiiii=oe.dh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),c_=l.dynCall_iiijiiii=(r,n,s,o,c,h,f,w)=>(c_=l.dynCall_iiijiiii=oe.eh)(r,n,s,o,c,h,f,w),p_=l.dynCall_viiiiiijjiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(p_=l.dynCall_viiiiiijjiiiii=oe.fh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),h_=l.dynCall_viiiiiiijiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)=>(h_=l.dynCall_viiiiiiijiiiiii=oe.gh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le),f_=l.dynCall_vif=(r,n,s)=>(f_=l.dynCall_vif=oe.hh)(r,n,s),m_=l.dynCall_viif=(r,n,s,o)=>(m_=l.dynCall_viif=oe.ih)(r,n,s,o),__=l.dynCall_fiii=(r,n,s,o)=>(__=l.dynCall_fiii=oe.jh)(r,n,s,o),g_=l.dynCall_diii=(r,n,s,o)=>(g_=l.dynCall_diii=oe.kh)(r,n,s,o),w_=l.dynCall_viijjiiii=(r,n,s,o,c,h,f,w,v)=>(w_=l.dynCall_viijjiiii=oe.lh)(r,n,s,o,c,h,f,w,v),y_=l.dynCall_viiiiiifiii=(r,n,s,o,c,h,f,w,v,$,E)=>(y_=l.dynCall_viiiiiifiii=oe.mh)(r,n,s,o,c,h,f,w,v,$,E),b_=l.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr,li,Bi,gc,wc,yc)=>(b_=l.dynCall_viiiiijiiiiiiiiiiiiiiiiiii=oe.nh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr,li,Bi,gc,wc,yc),v_=l.dynCall_viijji=(r,n,s,o,c,h)=>(v_=l.dynCall_viijji=oe.oh)(r,n,s,o,c,h),M_=l.dynCall_iiiiiiiiiiiji=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(M_=l.dynCall_iiiiiiiiiiiji=oe.ph)(r,n,s,o,c,h,f,w,v,$,E,G,J),x_=l.dynCall_viifiifijjjii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(x_=l.dynCall_viifiifijjjii=oe.qh)(r,n,s,o,c,h,f,w,v,$,E,G,J),T_=l.dynCall_viiiiiiiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)=>(T_=l.dynCall_viiiiiiiiiiiiiiiiiiii=oe.rh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr),C_=l.dynCall_viiiiifiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(C_=l.dynCall_viiiiifiiiiii=oe.sh)(r,n,s,o,c,h,f,w,v,$,E,G,J),k_=l.dynCall_vijiiiiiiijjii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(k_=l.dynCall_vijiiiiiiijjii=oe.th)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),$_=l.dynCall_viiiiiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or)=>($_=l.dynCall_viiiiiiiiiiiiiiiiii=oe.uh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or),S_=l.dynCall_viiiiiiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)=>(S_=l.dynCall_viiiiiiiiiiiiiiiiiii=oe.vh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er),E_=l.dynCall_viiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)=>(E_=l.dynCall_viiiiiiiiiiiiiii=oe.wh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht),P_=l.dynCall_viiiiiiiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)=>(P_=l.dynCall_viiiiiiiiiiiiiiii=oe.xh)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It),A_=l.dynCall_viiiijjj=(r,n,s,o,c,h,f,w)=>(A_=l.dynCall_viiiijjj=oe.yh)(r,n,s,o,c,h,f,w),I_=l.dynCall_iiiiid=(r,n,s,o,c,h)=>(I_=l.dynCall_iiiiid=oe.zh)(r,n,s,o,c,h),F_=l.dynCall_viiiiiiijjj=(r,n,s,o,c,h,f,w,v,$,E)=>(F_=l.dynCall_viiiiiiijjj=oe.Ah)(r,n,s,o,c,h,f,w,v,$,E),z_=l.dynCall_iiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E)=>(z_=l.dynCall_iiiiiiiiiii=oe.Bh)(r,n,s,o,c,h,f,w,v,$,E),O_=l.dynCall_iiiiiiiiiiiiiiiiiifi=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)=>(O_=l.dynCall_iiiiiiiiiiiiiiiiiifi=oe.Ch)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er),D_=l.dynCall_viiif=(r,n,s,o,c)=>(D_=l.dynCall_viiif=oe.Dh)(r,n,s,o,c),B_=l.dynCall_viiijiiiii=(r,n,s,o,c,h,f,w,v,$)=>(B_=l.dynCall_viiijiiiii=oe.Eh)(r,n,s,o,c,h,f,w,v,$),j_=l.dynCall_jj=(r,n)=>(j_=l.dynCall_jj=oe.Fh)(r,n),L_=l.dynCall_viiij=(r,n,s,o,c)=>(L_=l.dynCall_viiij=oe.Gh)(r,n,s,o,c),R_=l.dynCall_iiiijii=(r,n,s,o,c,h,f)=>(R_=l.dynCall_iiiijii=oe.Hh)(r,n,s,o,c,h,f),N_=l.dynCall_viiiiji=(r,n,s,o,c,h,f)=>(N_=l.dynCall_viiiiji=oe.Ih)(r,n,s,o,c,h,f),V_=l.dynCall_iijjji=(r,n,s,o,c,h)=>(V_=l.dynCall_iijjji=oe.Jh)(r,n,s,o,c,h),U_=l.dynCall_ijijji=(r,n,s,o,c,h)=>(U_=l.dynCall_ijijji=oe.Kh)(r,n,s,o,c,h),W_=l.dynCall_iijijijijiji=(r,n,s,o,c,h,f,w,v,$,E,G)=>(W_=l.dynCall_iijijijijiji=oe.Lh)(r,n,s,o,c,h,f,w,v,$,E,G),G_=l.dynCall_iijijiji=(r,n,s,o,c,h,f,w)=>(G_=l.dynCall_iijijiji=oe.Mh)(r,n,s,o,c,h,f,w),q_=l.dynCall_viiijjiii=(r,n,s,o,c,h,f,w,v)=>(q_=l.dynCall_viiijjiii=oe.Nh)(r,n,s,o,c,h,f,w,v),K_=l.dynCall_viijii=(r,n,s,o,c,h)=>(K_=l.dynCall_viijii=oe.Oh)(r,n,s,o,c,h),H_=l.dynCall_iiiiijji=(r,n,s,o,c,h,f,w)=>(H_=l.dynCall_iiiiijji=oe.Ph)(r,n,s,o,c,h,f,w),X_=l.dynCall_iiiifi=(r,n,s,o,c,h)=>(X_=l.dynCall_iiiifi=oe.Qh)(r,n,s,o,c,h),Q_=l.dynCall_iiijii=(r,n,s,o,c,h)=>(Q_=l.dynCall_iiijii=oe.Rh)(r,n,s,o,c,h),Y_=l.dynCall_iiiiiiiiijii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(Y_=l.dynCall_iiiiiiiiijii=oe.Sh)(r,n,s,o,c,h,f,w,v,$,E,G),Z_=l.dynCall_iiiijjii=(r,n,s,o,c,h,f,w)=>(Z_=l.dynCall_iiiijjii=oe.Th)(r,n,s,o,c,h,f,w),J_=l.dynCall_iiiiiijjjii=(r,n,s,o,c,h,f,w,v,$,E)=>(J_=l.dynCall_iiiiiijjjii=oe.Uh)(r,n,s,o,c,h,f,w,v,$,E),eg=l.dynCall_iiijiii=(r,n,s,o,c,h,f)=>(eg=l.dynCall_iiijiii=oe.Vh)(r,n,s,o,c,h,f),tg=l.dynCall_iiiiiiiijjjfi=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(tg=l.dynCall_iiiiiiiijjjfi=oe.Wh)(r,n,s,o,c,h,f,w,v,$,E,G,J),rg=l.dynCall_iijiiii=(r,n,s,o,c,h,f)=>(rg=l.dynCall_iijiiii=oe.Xh)(r,n,s,o,c,h,f),ig=l.dynCall_iijjjii=(r,n,s,o,c,h,f)=>(ig=l.dynCall_iijjjii=oe.Yh)(r,n,s,o,c,h,f),ng=l.dynCall_jij=(r,n,s)=>(ng=l.dynCall_jij=oe.Zh)(r,n,s),sg=l.dynCall_iiji=(r,n,s,o)=>(sg=l.dynCall_iiji=oe._h)(r,n,s,o),ag=l.dynCall_iiif=(r,n,s,o)=>(ag=l.dynCall_iiif=oe.$h)(r,n,s,o),og=l.dynCall_vidi=(r,n,s,o)=>(og=l.dynCall_vidi=oe.ai)(r,n,s,o),lg=l.dynCall_vjiii=(r,n,s,o,c)=>(lg=l.dynCall_vjiii=oe.bi)(r,n,s,o,c),ug=l.dynCall_diiiii=(r,n,s,o,c,h)=>(ug=l.dynCall_diiiii=oe.ci)(r,n,s,o,c,h),dg=l.dynCall_diiii=(r,n,s,o,c)=>(dg=l.dynCall_diiii=oe.di)(r,n,s,o,c),cg=l.dynCall_viiijjiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G)=>(cg=l.dynCall_viiijjiiiiii=oe.ei)(r,n,s,o,c,h,f,w,v,$,E,G),pg=l.dynCall_viijjijjjjiii=(r,n,s,o,c,h,f,w,v,$,E,G,J)=>(pg=l.dynCall_viijjijjjjiii=oe.fi)(r,n,s,o,c,h,f,w,v,$,E,G,J),hg=l.dynCall_ijiij=(r,n,s,o,c)=>(hg=l.dynCall_ijiij=oe.gi)(r,n,s,o,c),fg=l.dynCall_iiiij=(r,n,s,o,c)=>(fg=l.dynCall_iiiij=oe.hi)(r,n,s,o,c),mg=l.dynCall_viiijii=(r,n,s,o,c,h,f)=>(mg=l.dynCall_viiijii=oe.ii)(r,n,s,o,c,h,f),_g=l.dynCall_viijiiiiiiiiii=(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)=>(_g=l.dynCall_viijiiiiiiiiii=oe.ji)(r,n,s,o,c,h,f,w,v,$,E,G,J,_e),gg=l.dynCall_fiiii=(r,n,s,o,c)=>(gg=l.dynCall_fiiii=oe.ki)(r,n,s,o,c),wg=l.dynCall_jfi=(r,n,s)=>(wg=l.dynCall_jfi=oe.li)(r,n,s),yg=l.dynCall_jiij=(r,n,s,o)=>(yg=l.dynCall_jiij=oe.mi)(r,n,s,o),bg=r=>(bg=oe.ni)(r),vg=()=>(vg=oe.oi)(),Mg=r=>(Mg=oe.pi)(r),xg=()=>(xg=oe.qi)();function $y(r,n,s,o){var c=Ie();try{return af(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Sy(r,n,s){var o=Ie();try{return of(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Ey(r,n,s){var o=Ie();try{sf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Py(r,n){var s=Ie();try{return _c(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function Ay(r,n){var s=Ie();try{uf(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function Iy(r,n,s,o){var c=Ie();try{return pf(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Fy(r){var n=Ie();try{df(r)}catch(s){if(Pe(n),s!==s+0)throw s;Fe(1,0)}}function zy(r,n,s,o,c,h,f){var w=Ie();try{return lf(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function Oy(r,n,s,o,c,h){var f=Ie();try{return cf(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Dy(r,n,s,o,c){var h=Ie();try{return hf(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function By(r,n,s,o){var c=Ie();try{ff(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function jy(r,n,s,o,c){var h=Ie();try{_f(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Ly(r,n,s,o,c,h,f){var w=Ie();try{gf(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function Ry(r,n,s,o,c,h){var f=Ie();try{mf(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Ny(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{yf(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Vy(r,n,s){var o=Ie();try{return vf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Uy(r,n,s){var o=Ie();try{return Mf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Wy(r,n,s){var o=Ie();try{return xf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Gy(r,n,s){var o=Ie();try{return Tf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;return Fe(1,0),0n}}function qy(r,n,s,o,c,h,f,w,v){var $=Ie();try{kf(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function Ky(r){var n=Ie();try{return Cf(r)}catch(s){if(Pe(n),s!==s+0)throw s;Fe(1,0)}}function Hy(r,n,s){var o=Ie();try{zf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Xy(r,n,s,o,c,h,f,w){var v=Ie();try{return Of(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function Qy(r,n,s,o,c){var h=Ie();try{wf(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Yy(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{Df(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Zy(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{Bf(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Jy(r,n,s,o,c,h,f,w){var v=Ie();try{jf(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function e0(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{return Ef(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function t0(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{Pf(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function r0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le){var ht=Ie();try{Rf(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)}catch(It){if(Pe(ht),It!==It+0)throw It;Fe(1,0)}}function i0(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{return Vf(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function n0(r,n,s,o,c,h,f,w,v){var $=Ie();try{return Nf(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function s0(r,n,s,o,c,h,f,w,v){var $=Ie();try{Uf(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function a0(r,n,s,o){var c=Ie();try{Sf(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function o0(r,n,s,o,c){var h=Ie();try{Wf(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function l0(r,n){var s=Ie();try{return Gf(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function u0(r,n){var s=Ie();try{return $f(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;return Fe(1,0),0n}}function d0(r,n){var s=Ie();try{return Kf(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function c0(r,n,s,o){var c=Ie();try{Xf(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function p0(r,n,s,o,c,h,f){var w=Ie();try{mg(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function h0(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{return Qf(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function f0(r,n,s,o,c,h,f){var w=Ie();try{Yf(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function m0(r,n,s,o){var c=Ie();try{Zf(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function _0(r,n,s,o,c,h,f,w,v){var $=Ie();try{return Lf(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function g0(r,n,s,o,c,h,f){var w=Ie();try{Jf(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function w0(r,n,s,o,c,h,f,w,v){var $=Ie();try{bf(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function y0(r,n,s,o,c,h,f){var w=Ie();try{em(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function b0(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{tm(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function v0(r,n,s,o){var c=Ie();try{return im(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;return Fe(1,0),0n}}function M0(r,n,s,o,c,h,f,w){var v=Ie();try{nm(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function x0(r,n,s,o,c){var h=Ie();try{sm(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function T0(r,n,s,o){var c=Ie();try{om(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function C0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It){var Xt=Ie();try{lm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)}catch(or){if(Pe(Xt),or!==or+0)throw or;Fe(1,0)}}function k0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht){var It=Ie();try{dm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)}catch(Xt){if(Pe(It),Xt!==Xt+0)throw Xt;Fe(1,0)}}function $0(r,n,s,o,c,h){var f=Ie();try{cm(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function S0(r,n,s,o,c,h,f,w,v){var $=Ie();try{pm(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function E0(r,n,s,o,c){var h=Ie();try{return hm(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function P0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{return fm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function A0(r,n){var s=Ie();try{mm(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function I0(r,n,s){var o=Ie();try{return _m(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;return Fe(1,0),0n}}function F0(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{return gm(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function z0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le){var ht=Ie();try{Mm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)}catch(It){if(Pe(ht),It!==It+0)throw It;Fe(1,0)}}function O0(r,n,s,o,c){var h=Ie();try{wm(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function D0(r,n,s,o,c,h,f){var w=Ie();try{ym(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function B0(r,n,s,o,c){var h=Ie();try{vm(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function j0(r,n,s,o,c,h,f,w){var v=Ie();try{bm(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function L0(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{xm(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function R0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It){var Xt=Ie();try{return Tm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)}catch(or){if(Pe(Xt),or!==or+0)throw or;Fe(1,0)}}function N0(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{Cm(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function V0(r,n){var s=Ie();try{return Af(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;Fe(1,0)}}function U0(r,n,s,o,c){var h=Ie();try{return gg(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function W0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er){var Gr=Ie();try{return km(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)}catch(li){if(Pe(Gr),li!==li+0)throw li;Fe(1,0)}}function G0(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{$m(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function q0(r,n,s,o,c,h,f){var w=Ie();try{return Sm(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function K0(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{Em(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function H0(r,n,s,o,c,h){var f=Ie();try{return Pm(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function X0(r,n,s,o,c,h){var f=Ie();try{Im(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Q0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{Fm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function Y0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt){var or=Ie();try{zm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt)}catch(Er){if(Pe(or),Er!==Er+0)throw Er;Fe(1,0)}}function Z0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It){var Xt=Ie();try{Om(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)}catch(or){if(Pe(Xt),or!==or+0)throw or;Fe(1,0)}}function J0(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht){var It=Ie();try{Dm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)}catch(Xt){if(Pe(It),Xt!==Xt+0)throw Xt;Fe(1,0)}}function eb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le){var ht=Ie();try{Bm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)}catch(It){if(Pe(ht),It!==It+0)throw It;Fe(1,0)}}function tb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr){var li=Ie();try{jm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)}catch(Bi){if(Pe(li),Bi!==Bi+0)throw Bi;Fe(1,0)}}function rb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or){var Er=Ie();try{Lm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or)}catch(Gr){if(Pe(Er),Gr!==Gr+0)throw Gr;Fe(1,0)}}function ib(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt){var or=Ie();try{Rm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt)}catch(Er){if(Pe(or),Er!==Er+0)throw Er;Fe(1,0)}}function nb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr){var li=Ie();try{Nm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)}catch(Bi){if(Pe(li),Bi!==Bi+0)throw Bi;Fe(1,0)}}function sb(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{Vm(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function ab(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{Um(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function ob(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{Wm(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function lb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le){var ht=Ie();try{Gm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)}catch(It){if(Pe(ht),It!==It+0)throw It;Fe(1,0)}}function ub(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{Km(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function db(r,n,s,o,c,h,f,w,v){var $=Ie();try{Hm(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function cb(r,n,s,o,c,h,f){var w=Ie();try{return Am(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function pb(r,n,s,o,c){var h=Ie();try{qm(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function hb(r,n,s){var o=Ie();try{return wg(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;return Fe(1,0),0n}}function fb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{Xm(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function mb(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{Ym(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function _b(r,n,s,o,c,h,f){var w=Ie();try{return Zm(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function gb(r,n,s,o,c,h){var f=Ie();try{return Jm(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function wb(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{e_(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function yb(r,n,s,o,c,h){var f=Ie();try{Qm(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function bb(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{t_(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function vb(r,n,s,o,c,h,f,w){var v=Ie();try{r_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function Mb(r,n,s,o,c,h,f,w){var v=Ie();try{i_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function xb(r,n,s,o){var c=Ie();try{return um(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Tb(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{n_(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function Cb(r,n,s,o,c,h,f,w,v){var $=Ie();try{s_(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function kb(r,n,s,o,c,h,f,w,v){var $=Ie();try{a_(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function $b(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{o_(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function Sb(r,n,s,o,c,h){var f=Ie();try{l_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Eb(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{u_(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Pb(r,n,s,o,c,h,f,w){var v=Ie();try{return c_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function Ab(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{p_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function Ib(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le){var ht=Ie();try{h_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le)}catch(It){if(Pe(ht),It!==It+0)throw It;Fe(1,0)}}function Fb(r,n,s){var o=Ie();try{f_(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function zb(r,n,s,o){var c=Ie();try{return __(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Ob(r,n,s,o){var c=Ie();try{return g_(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Db(r,n,s,o,c,h,f,w,v){var $=Ie();try{w_(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function Bb(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{y_(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function jb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr,li,Bi,gc,wc,yc){var Uv=Ie();try{b_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr,li,Bi,gc,wc,yc)}catch(bc){if(Pe(Uv),bc!==bc+0)throw bc;Fe(1,0)}}function Lb(r,n,s,o,c,h){var f=Ie();try{v_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Rb(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{return M_(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function Nb(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{x_(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function Vb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr){var li=Ie();try{T_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er,Gr)}catch(Bi){if(Pe(li),Bi!==Bi+0)throw Bi;Fe(1,0)}}function Ub(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{C_(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function Wb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{k_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function Gb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{d_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function qb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er){var Gr=Ie();try{S_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)}catch(li){if(Pe(Gr),li!==li+0)throw li;Fe(1,0)}}function Kb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It){var Xt=Ie();try{P_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It)}catch(or){if(Pe(Xt),or!==or+0)throw or;Fe(1,0)}}function Hb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or){var Er=Ie();try{$_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or)}catch(Gr){if(Pe(Er),Gr!==Gr+0)throw Gr;Fe(1,0)}}function Xb(r,n,s,o,c,h,f,w){var v=Ie();try{A_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function Qb(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{F_(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function Yb(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{return z_(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function Zb(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er){var Gr=Ie();try{return O_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht,It,Xt,or,Er)}catch(li){if(Pe(Gr),li!==li+0)throw li;Fe(1,0)}}function Jb(r,n,s,o,c){var h=Ie();try{D_(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function ev(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{rm(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function tv(r,n,s,o,c,h,f,w,v,$){var E=Ie();try{B_(r,n,s,o,c,h,f,w,v,$)}catch(G){if(Pe(E),G!==G+0)throw G;Fe(1,0)}}function rv(r,n,s,o,c){var h=Ie();try{L_(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function iv(r,n,s,o,c,h,f,w,v,$,E,G,J,_e){var Le=Ie();try{_g(r,n,s,o,c,h,f,w,v,$,E,G,J,_e)}catch(ht){if(Pe(Le),ht!==ht+0)throw ht;Fe(1,0)}}function nv(r,n,s,o){var c=Ie();try{return yg(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;return Fe(1,0),0n}}function sv(r,n,s,o,c,h,f){var w=Ie();try{N_(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function av(r,n,s,o,c,h){var f=Ie();try{return V_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function ov(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{return W_(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function lv(r,n,s,o,c,h,f,w){var v=Ie();try{return G_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function uv(r,n,s,o,c,h){var f=Ie();try{return U_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function dv(r,n){var s=Ie();try{return j_(r,n)}catch(o){if(Pe(s),o!==o+0)throw o;return Fe(1,0),0n}}function cv(r,n,s,o,c,h,f){var w=Ie();try{return R_(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function pv(r,n,s,o,c,h){var f=Ie();try{K_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function hv(r,n,s,o,c,h,f,w,v){var $=Ie();try{q_(r,n,s,o,c,h,f,w,v)}catch(E){if(Pe($),E!==E+0)throw E;Fe(1,0)}}function fv(r,n,s,o){var c=Ie();try{m_(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function mv(r,n,s,o,c,h,f,w){var v=Ie();try{return H_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function _v(r,n,s,o,c,h){var f=Ie();try{return X_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function gv(r,n,s,o,c,h){var f=Ie();try{return Q_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function wv(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{return Y_(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function yv(r,n,s,o,c,h,f,w){var v=Ie();try{return Z_(r,n,s,o,c,h,f,w)}catch($){if(Pe(v),$!==$+0)throw $;Fe(1,0)}}function bv(r,n,s,o,c,h,f,w,v,$,E){var G=Ie();try{return J_(r,n,s,o,c,h,f,w,v,$,E)}catch(J){if(Pe(G),J!==J+0)throw J;Fe(1,0)}}function vv(r,n,s,o,c,h,f){var w=Ie();try{return eg(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function Mv(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{return tg(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function xv(r,n,s,o,c,h,f){var w=Ie();try{return rg(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function Tv(r,n,s,o,c,h,f){var w=Ie();try{return ig(r,n,s,o,c,h,f)}catch(v){if(Pe(w),v!==v+0)throw v;Fe(1,0)}}function Cv(r,n,s){var o=Ie();try{return ng(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;return Fe(1,0),0n}}function kv(r,n,s,o){var c=Ie();try{return sg(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function $v(r,n,s,o){var c=Ie();try{og(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Sv(r,n,s,o){var c=Ie();try{return ag(r,n,s,o)}catch(h){if(Pe(c),h!==h+0)throw h;Fe(1,0)}}function Ev(r,n,s,o,c){var h=Ie();try{lg(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Pv(r,n,s,o,c,h){var f=Ie();try{return ug(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Av(r,n,s,o,c){var h=Ie();try{return dg(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Iv(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{cg(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Fv(r,n,s,o,c,h,f,w,v,$,E,G,J){var _e=Ie();try{pg(r,n,s,o,c,h,f,w,v,$,E,G,J)}catch(Le){if(Pe(_e),Le!==Le+0)throw Le;Fe(1,0)}}function zv(r,n,s,o,c,h,f,w,v,$,E,G){var J=Ie();try{am(r,n,s,o,c,h,f,w,v,$,E,G)}catch(_e){if(Pe(J),_e!==_e+0)throw _e;Fe(1,0)}}function Ov(r,n,s,o,c){var h=Ie();try{return fg(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Dv(r,n,s,o,c){var h=Ie();try{return hg(r,n,s,o,c)}catch(f){if(Pe(h),f!==f+0)throw f;Fe(1,0)}}function Bv(r){var n=Ie();try{return Ff(r)}catch(s){if(Pe(n),s!==s+0)throw s;return Fe(1,0),0n}}function jv(r,n,s,o,c,h){var f=Ie();try{return If(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Lv(r,n,s,o,c,h){var f=Ie();try{return I_(r,n,s,o,c,h)}catch(w){if(Pe(f),w!==w+0)throw w;Fe(1,0)}}function Rv(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht){var It=Ie();try{E_(r,n,s,o,c,h,f,w,v,$,E,G,J,_e,Le,ht)}catch(Xt){if(Pe(It),Xt!==Xt+0)throw Xt;Fe(1,0)}}function Nv(r,n,s){var o=Ie();try{return qf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Vv(r,n,s){var o=Ie();try{return Hf(r,n,s)}catch(c){if(Pe(o),c!==c+0)throw c;Fe(1,0)}}function Tg(){if(!(ms>0)){if(Q)return C(l),Mn(),void startWorker(l);ic(Du),ms>0||Id||(Id=!0,l.calledRun=!0,Wi||(Mn(),C(l),Q||ic(Di)))}}return l.stackSave=Ie,l.stackRestore=Pe,l.stackAlloc=Jp,l.UTF8ToString=Ti,l.stringToUTF8=za,l.lengthBytesUTF8=lh,_s=function r(){Id||Tg(),Id||(_s=r)},Tg(),F}),jt=Ct,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Ct()}),at,Zt,Yt,ir,nr,dr,rr,Dr,Jr=V(()=>{var e,t;ee(),at=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),Zt=typeof location>"u"?void 0:location.origin,Yt=(i,a)=>{try{let u=a??at;return(u?new URL(i,u):new URL(i)).origin===Zt}catch{return!1}},ir=async i=>{let a=await(await fetch(i,{credentials:"same-origin"})).blob();return URL.createObjectURL(a)},nr=(vt(),B(Ee)).default,dr=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Yt(at))return[void 0,nr()];let i=await ir(at);return[i,nr(i)]},rr=(Qt(),B(_t)).default,Dr=async(i,a,u)=>[void 0,rr]}),Br,dt,Nt,Ht,ii,Zi,Gi,Hr,di=V(()=>{Jr(),dt=!1,Nt=!1,Ht=!1,ii=()=>{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}},Zi=()=>{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}},Gi=async e=>{if(dt)return Promise.resolve();if(Nt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ht)throw new Error("previous call to 'initializeWebAssembly()' failed.");Nt=!0;let t=e.initTimeout,i=e.numThreads;if(!Zi())throw new Error("WebAssembly SIMD is not supported in the current environment.");let a=ii();i>1&&!a&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+i+", 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=i=1);let u=e.wasmPaths,p=typeof u=="string"?u:void 0,d=u==null?void 0:u.mjs,_=(d==null?void 0:d.href)??d,g=u==null?void 0:u.wasm,y=(g==null?void 0:g.href)??g,C=e.wasmBinary,[k,l]=await Dr(_,p,i>1),F=!1,I=[];if(t>0&&I.push(new Promise(L=>{setTimeout(()=>{F=!0,L()},t)})),I.push(new Promise((L,Q)=>{let Z={numThreads:i};C?Z.wasmBinary=C:(y||p)&&(Z.locateFile=(U,we)=>y??(p??we)+U),l(Z).then(U=>{Nt=!1,dt=!0,Br=U,L(),k&&URL.revokeObjectURL(k)},U=>{Nt=!1,Ht=!0,Q(U)})})),await Promise.race(I),F)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Hr=()=>{if(dt&&Br)return Br;throw new Error("WebAssembly is not initialized yet.")}}),Xr,Ri,Rr,Ji=V(()=>{di(),Xr=(e,t)=>{let i=Hr(),a=i.lengthBytesUTF8(e)+1,u=i._malloc(a);return i.stringToUTF8(e,u,a),t.push(u),u},Ri=(e,t,i,a)=>{if(typeof e=="object"&&e!==null){if(i.has(e))throw new Error("Circular reference in options");i.add(e)}Object.entries(e).forEach(([u,p])=>{let d=t?t+u:u;if(typeof p=="object")Ri(p,d+".",i,a);else if(typeof p=="string"||typeof p=="number")a(d,p.toString());else if(typeof p=="boolean")a(d,p?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof p}`)})},Rr=e=>{let t=Hr(),i=t.stackSave();try{let a=t.stackAlloc(8);t._OrtGetLastError(a,a+4);let u=t.HEAP32[a/4],p=t.HEAPU32[a/4+1],d=p?t.UTF8ToString(p):"";throw new Error(`${e} ERROR_CODE: ${u}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(i)}}}),qi,qn=V(()=>{di(),Ji(),qi=e=>{let t=Hr(),i=0,a=[],u=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)u.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)u.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&&(u.terminate=!1);let p=0;return(e==null?void 0:e.tag)!==void 0&&(p=Xr(e.tag,a)),i=t._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,p),i===0&&Rr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Ri(e.extra,"",new WeakSet,(d,_)=>{let g=Xr(d,a),y=Xr(_,a);t._OrtAddRunConfigEntry(i,g,y)!==0&&Rr(`Can't set a run config entry: ${d} - ${_}.`)}),[i,a]}catch(p){throw i!==0&&t._OrtReleaseRunOptions(i),a.forEach(d=>t._free(d)),p}}}),Cn,kn,$n,Sn,en,Kn=V(()=>{di(),Ji(),Cn=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}`)}},kn=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},$n=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(i=>(typeof i=="string"?i:i.name)==="webgpu")&&(e.enableMemPattern=!1)},Sn=(e,t,i)=>{for(let a of t){let u=typeof a=="string"?a:a.name;switch(u){case"webnn":if(u="WEBNN",typeof a!="string"){let d=a==null?void 0:a.deviceType;if(d){let _=Xr("deviceType",i),g=Xr(d,i);Hr()._OrtAddSessionConfigEntry(e,_,g)!==0&&Rr(`Can't set a session config entry: 'deviceType' - ${d}.`)}}break;case"webgpu":if(u="JS",typeof a!="string"){let d=a;if(d!=null&&d.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);let _=Xr("preferredLayout",i),g=Xr(d.preferredLayout,i);Hr()._OrtAddSessionConfigEntry(e,_,g)!==0&&Rr(`Can't set a session config entry: 'preferredLayout' - ${d.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${u}`)}let p=Xr(u,i);Hr()._OrtAppendExecutionProvider(e,p)!==0&&Rr(`Can't append execution provider: ${u}.`)}},en=e=>{let t=Hr(),i=0,a=[],u=e||{};$n(u);try{let p=Cn(u.graphOptimizationLevel??"all"),d=kn(u.executionMode??"sequential"),_=typeof u.logId=="string"?Xr(u.logId,a):0,g=u.logSeverityLevel??2;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log serverity level is not valid: ${g}`);let y=u.logVerbosityLevel??0;if(!Number.isInteger(y)||y<0||y>4)throw new Error(`log verbosity level is not valid: ${y}`);let C=typeof u.optimizedModelFilePath=="string"?Xr(u.optimizedModelFilePath,a):0;if(i=t._OrtCreateSessionOptions(p,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,_,g,y,C),i===0&&Rr("Can't create session options."),u.executionProviders&&Sn(i,u.executionProviders,a),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);let k=Xr("enableGraphCapture",a),l=Xr(u.enableGraphCapture.toString(),a);t._OrtAddSessionConfigEntry(i,k,l)!==0&&Rr(`Can't set a session config entry: 'enableGraphCapture' - ${u.enableGraphCapture}.`)}if(u.freeDimensionOverrides)for(let[k,l]of Object.entries(u.freeDimensionOverrides)){if(typeof k!="string")throw new Error(`free dimension override name must be a string: ${k}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let F=Xr(k,a);t._OrtAddFreeDimensionOverride(i,F,l)!==0&&Rr(`Can't set a free dimension override: ${k} - ${l}.`)}return u.extra!==void 0&&Ri(u.extra,"",new WeakSet,(k,l)=>{let F=Xr(k,a),I=Xr(l,a);t._OrtAddSessionConfigEntry(i,F,I)!==0&&Rr(`Can't set a session config entry: ${k} - ${l}.`)}),[i,a]}catch(p){throw i!==0&&t._OrtReleaseSessionOptions(i),a.forEach(d=>t._free(d)),p}}}),pn,Ni,Ki,Hi,an,hn,fn,sr=V(()=>{pn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Ni=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Ki=(e,t)=>{let i=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],a=typeof t=="number"?t:t.reduce((u,p)=>u*p,1);return i>0?Math.ceil(a*i):void 0},Hi=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}`)}},an=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}`)}},hn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",fn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}}),on,En=V(()=>{ee(),on=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 i=t.headers.get("Content-Length"),a=i?parseInt(i,10):0;if(a<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let u=t.body.getReader(),p;try{p=new ArrayBuffer(a)}catch(_){if(_ instanceof RangeError){let g=Math.ceil(a/65536);p=new WebAssembly.Memory({initial:g,maximum:g}).buffer}else throw _}let d=0;for(;;){let{done:_,value:g}=await u.read();if(_)break;let y=g.byteLength;new Uint8Array(p,d,y).set(g),d+=y}return new Uint8Array(p,0,a)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Pn,mn,An,In,_n,Fn,qr,Ci=V(()=>{sr(),Pn=["V","I","W","E","F"],mn=(e,t)=>{console.log(`[${Pn[e]},${new Date().toISOString()}]${t}`)},_n=(e,t)=>{An=e,In=t},Fn=(e,t)=>{let i=an(e),a=an(An);i>=a&&mn(i,typeof t=="function"?t():t)},qr=(...e)=>{In&&Fn(...e)}}),Ae,x=V(()=>{sr(),Ae=(e,t)=>new(Hi(t))(e)}),N=V(()=>{}),se,be,ve,qe,St,At,Pt,Vt,ur,jr=V(()=>{Ci(),N(),se=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]]),be=[],ve=e=>Math.ceil(e/16)*16,qe=e=>{for(let t=0;tSt++,Pt=async(e,t,i,a)=>{let u=ve(i),p=e.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=e.getCommandEncoder();e.endComputePass(),d.copyBufferToBuffer(t,0,p,0,u),e.flush(),await p.mapAsync(GPUMapMode.READ);let _=p.getMappedRange();if(a){let g=a();return g.set(new Uint8Array(_,0,i)),g}else return new Uint8Array(_.slice(0,i))}finally{p.destroy()}},Vt=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 se)be.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let i=t.buffer,a=t.byteOffset,u=t.byteLength,p=ve(u),d=this.storageCache.get(e);if(!d)throw new Error("gpu data for uploading does not exist");if(d.originalSize!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);let _=this.backend.device.createBuffer({mappedAtCreation:!0,size:p,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),g=_.getMappedRange();new Uint8Array(g).set(new Uint8Array(i,a,u)),_.unmap();let y=this.backend.getCommandEncoder();this.backend.endComputePass(),y.copyBufferToBuffer(_,0,d.gpuData.buffer,0,p),qr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(_)}memcpy(e,t){let i=this.storageCache.get(e);if(!i)throw new Error("source gpu data for memcpy does not exist");let a=this.storageCache.get(t);if(!a)throw new Error("destination gpu data for memcpy does not exist");if(i.originalSize!==a.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=ve(i.originalSize),p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(i.gpuData.buffer,0,a.gpuData.buffer,0,u)}registerExternalBuffer(e,t,i){let a;if(i){if(a=this.externalBuffers.get(i),a===void 0)throw new Error("previous buffer is not registered");if(e===i)return qr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${a}, buffer is the same, skip.`),a;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(i)}else a=At();return this.storageCache.set(a,{gpuData:{id:a,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,a),qr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${a}, registered.`),a}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),qr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let i=qe(e),a,u=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,p=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||p){let _=(u?this.freeBuffers:this.freeUniformBuffers).get(i);_?_.length>0?a=_.pop():a=this.backend.device.createBuffer({size:i,usage:t}):a=this.backend.device.createBuffer({size:i,usage:t})}else a=this.backend.device.createBuffer({size:i,usage:t});let d={id:At(),type:0,buffer:a};return this.storageCache.set(d.id,{gpuData:d,originalSize:e}),qr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${d.id}`),d}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 qr("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 i=this.storageCache.get(e);if(!i)throw new Error("data does not exist");await Pt(this.backend,i.gpuData.buffer,i.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=se.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let i=this.freeBuffers.get(e.size)||[];t===void 0||i.length>=t?e.destroy():i.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let i=this.freeUniformBuffers.get(e.size)||[];t===void 0||i.length>=t?e.destroy():i.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(i=>{i.destroy()}),this.capturedPendingBuffers.delete(e))}},ur=(...e)=>new Vt(...e)}),hr,tr,Tr=V(()=>{hr=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}},tr=e=>new hr(e)}),wi,ui,tt,Pi,Fr,ni,vi,lr=V(()=>{wi=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ui=class{static calcShape(e,t,i=!1){let a=e.length,u=t.length;if(a===0)return t;if(u===0)return e;let p=Math.max(e.length,t.length),d=new Array(p);if(i){if(a<2||u<2)return;let _=wi.calcMatMulShape([e[a-2],e[a-1]],[t[u-2],t[u-1]]);if(_===void 0)return;[d[p-2],d[p-1]]=_}for(let _=i?3:1;_<=p;_++){let g=a-_<0?1:e[a-_],y=u-_<0?1:t[u-_];if(g!==y&&g>1&&y>1)return;let C=Math.max(g,y);if(g&&y)d[p-_]=Math.max(g,y);else{if(C>1)return;d[p-_]=0}}return d}static isValidBroadcast(e,t){let i=e.length,a=t.length;if(i>a)return!1;for(let u=1;u<=i;u++)if(e[i-u]!==1&&e[i-u]!==t[a-u])return!1;return!0}},tt=class Od{static size(t){return Od.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,i=4){let a=t.length;if(a===0)return[];let u=new Array(a),p=a-1;for(;p>=0;){if(t[p]%i===0){u[p]=t[p]/i;break}if(i%t[p]!==0)throw new Error("cannot convert shape");u[p]=1,i/=t[p],p--}for(p--;p>=0;p--)u[p]=t[p];return u}static sizeFromDimension(t,i){if(i<0||i>t.length)throw new Error(`invalid dimension of ${i} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Od.getSizeFromDimensionRange(t,i,t.length)}static sizeToDimension(t,i){if(i<0||i>t.length)throw new Error(`invalid dimension of ${i} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Od.getSizeFromDimensionRange(t,0,i)}static getSizeFromDimensionRange(t,i,a){let u=1;for(let p=i;p=0;--u)a[u]=a[u+1]*t[u+1];return a}static normalizeAxis(t,i){if(t<-i&&t>=i)throw new Error("unsupported axis for this operation.");return t<0?t+i:t}static normalizeAxes(t,i){return t.map(a=>this.normalizeAxis(a,i??t.length))}static sortBasedOnPerm(t,i){return i?i.map(a=>t[a]):t.slice().reverse()}static padShape(t,i){let a=t.length;return t.map((u,p)=>u+i[p]+i[p+a])}static areEqual(t,i){return t.length!==i.length?!1:t.every((a,u)=>a===i[u])}},Pi=class Ru{static adjustPoolAttributes(t,i,a,u,p,d){if(!t&&a.length!==i.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let _=0;_=a.length?a.push(i[_+2]):a[_]=i[_+2];for(let _=0;_=a[_]||d[_+a.length]>=a[_])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,i,a,u,p,d,_){if(_){if(p.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let g=0;g{sr(),lr(),ki=64,ci=(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}`)}},zr=(e,t=1)=>{let i=ci(e,t);return typeof i=="string"?i:i[0]},Or=(e,t=1)=>{let i=ci(e,t);return typeof i=="string"?i:i[1]},Rt=(...e)=>{let t=[];return e.forEach(i=>{i.length!==0&&t.push({type:12,data:i},{type:12,data:tt.computeStrides(i)})}),t},$r=e=>e%4===0?4:e%2===0?2:1,Nr=(e="f32",t,i="0")=>!t||t===1?`${e}(${i})`:`vec${t}<${e}>(${i})`,Qr=(e,t,i)=>e==="f32"?i:t===1?`f32(${i})`:`vec${t}(${i})`,$i=(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,Kt=(e,t,i,a)=>e.startsWith("uniforms.")&&i>4?typeof t=="string"?a==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:a==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:i>1?`${e}[${t}]`:e,Hn=(e,t,i,a,u)=>{let p=typeof i=="number",d=p?i:i.length,_=[...new Array(d).keys()],g=d<2?"u32":d<=4?`vec${d}`:`array`,y=ci(t,u),C=typeof y=="string"?y:y[1],k=typeof y=="string"?y:y[0],l={indices:g,value:C,storage:k,tensor:t},F=lt=>typeof lt=="string"?lt:`${lt}u`,I={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},L=p?"uniforms.":"",Q=`${L}${e}_shape`,Z=`${L}${e}_strides`,U="";for(let lt=0;lt ${l.indices} { + var indices: ${l.indices}; + var current = offset; + ${U} + return indices; + }`,te=lt=>(I.offsetToIndices=!0,d<2?lt:`o2i_${e}(${lt})`),me=[];if(d>=2)for(let lt=d-1;lt>=0;lt--)me.push(`${Kt(Z,lt,d)} * (indices[${lt}])`);let it=d<2?"":` + fn i2o_${e}(indices: ${l.indices}) -> u32 { + return ${me.join("+")}; + }`,Ye=lt=>(I.indicesToOffset=!0,d<2?lt:`i2o_${e}(${lt})`),Mt=(...lt)=>d===0?"0u":`${l.indices}(${lt.map(F).join(",")})`,Gt=(lt,qt)=>d<2?`${lt}`:`${Kt(lt,qt,d)}`,Bt=(lt,qt,fr)=>d<2?`${lt}=${fr};`:`${Kt(lt,qt,d)}=${fr};`,gr={},Mr=(lt,qt)=>{I.broadcastedIndicesToOffset=!0;let fr=`${qt.name}broadcastedIndicesTo${e}Offset`;if(fr in gr)return`${fr}(${lt})`;let Yr=[];for(let ai=d-1;ai>=0;ai--){let gi=qt.indicesGet("outputIndices",ai+qt.rank-d);Yr.push(`${Gt(Z,ai)} * (${gi} % ${Gt(Q,ai)})`)}return gr[fr]=`fn ${fr}(outputIndices: ${qt.type.indices}) -> u32 { + return ${Yr.length>0?Yr.join("+"):"0u"}; + }`,`${fr}(${lt})`},Ur=(lt,qt)=>(()=>{if(l.storage===l.value)return`${e}[${lt}]=${qt};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${lt}]=vec2(u32(${qt}), select(0u, 0xFFFFFFFFu, ${qt} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${lt}]=vec2(u32(${qt}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${lt}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${qt}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Ir=lt=>(()=>{if(l.storage===l.value)return`${e}[${lt}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${lt}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${lt}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${lt}] & 0xFFu), bool(${e}[${lt}] & 0xFF00u), bool(${e}[${lt}] & 0xFF0000u), bool(${e}[${lt}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Sr=d<2?"":` + fn get_${e}ByIndices(indices: ${l.indices}) -> ${C} { + return ${Ir(`i2o_${e}(indices)`)}; + }`,ri=d<2?"":(()=>{let lt=_.map(fr=>`d${fr}: u32`).join(", "),qt=_.map(fr=>`d${fr}`).join(", ");return` + fn get_${e}(${lt}) -> ${C} { + return get_${e}ByIndices(${Mt(qt)}); + }`})(),Kr=(...lt)=>{if(lt.length!==d)throw new Error(`indices length must be ${d}`);let qt=lt.map(F).join(",");return d===0?Ir("0u"):d===1?Ir(qt[0]):(I.get=!0,I.getByIndices=!0,I.indicesToOffset=!0,`get_${e}(${qt})`)},Wt=lt=>d<2?Ir(lt):(I.getByIndices=!0,I.indicesToOffset=!0,`get_${e}ByIndices(${lt})`),pr=d<2?"":` + fn set_${e}ByIndices(indices: ${l.indices}, value: ${C}) { + ${Ur(`i2o_${e}(indices)`,"value")} + }`,cr=d<2?"":(()=>{let lt=_.map(fr=>`d${fr}: u32`).join(", "),qt=_.map(fr=>`d${fr}`).join(", ");return` + fn set_${e}(${lt}, value: ${C}) { + set_${e}ByIndices(${Mt(qt)}, value); + }`})();return{impl:()=>{let lt=[],qt=!1;return I.offsetToIndices&&(lt.push(we),qt=!0),I.indicesToOffset&&(lt.push(it),qt=!0),I.broadcastedIndicesToOffset&&(Object.values(gr).forEach(fr=>lt.push(fr)),qt=!0),I.set&&(lt.push(cr),qt=!0),I.setByIndices&&(lt.push(pr),qt=!0),I.get&&(lt.push(ri),qt=!0),I.getByIndices&&(lt.push(Sr),qt=!0),!p&&qt&<.unshift(`const ${Q} = ${l.indices}(${i.join(",")});`,`const ${Z} = ${l.indices}(${tt.computeStrides(i).join(",")});`),lt.join(` +`)},type:l,offsetToIndices:te,indicesToOffset:Ye,broadcastedIndicesToOffset:Mr,indices:Mt,indicesGet:Gt,indicesSet:Bt,set:(...lt)=>{if(lt.length!==d+1)throw new Error(`indices length must be ${d}`);let qt=lt[d];if(typeof qt!="string")throw new Error("value must be string");let fr=lt.slice(0,d).map(F).join(",");return d===0?Ur("0u",qt):d===1?Ur(fr[0],qt):(I.set=!0,I.setByIndices=!0,I.indicesToOffset=!0,`set_${e}(${fr}, ${qt})`)},setByOffset:Ur,setByIndices:(lt,qt)=>d<2?Ur(lt,qt):(I.setByIndices=!0,I.indicesToOffset=!0,`set_${e}ByIndices(${lt}, ${qt});`),get:Kr,getByOffset:Ir,getByIndices:Wt,usage:a,name:e,strides:Z,shape:Q,rank:d}},mt=(e,t,i,a=1)=>Hn(e,t,i,"input",a),Jt=(e,t,i,a=1)=>Hn(e,t,i,"output",a),bs=(e,t,i,a=1)=>Hn(e,t,i,"internal",a),vs=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=ki){let t=typeof e=="number"?e:e[0],i=typeof e=="number"?1:e[1],a=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||i>this.limits.maxComputeWorkgroupSizeY||a>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${i}, ${a}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*i*a>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${i}, ${a}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,p=u?`@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`,d=u?"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*i*a}u + local_idx;`;return`@compute @workgroup_size(${t}, ${i}, ${a}) + fn main(${p}) { + ${d} + `}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 i=e.usage==="input"?"read":"read_write",a=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${a}>;`}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,i=1){return this.uniforms.push({name:e,type:t,length:i}),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:i,length:a}of this.uniforms)if(a&&a>4)i==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(a/8)}>`):e.push(`${t}:array, ${Math.ceil(a/4)}>`);else{let u=a==null||a===1?i:`vec${a}<${i}>`;e.push(`${t}:${u}`)}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])}},Da=(e,t)=>new vs(e,t),gn=(e,t)=>{let i=e.length,a=[];for(let u=0;u1&&d===1&&a.unshift(p)}return a}}),Ba,Ms,zn,ja,Vi,La,xs,wn=V(()=>{sr(),lr(),Tr(),mr(),Ba=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Ms=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,zn=(e,t)=>tt.sortBasedOnPerm(e,Ms(e.length,t)),ja=(e,t,i,a)=>{let u=[];u.push(`fn perm(i: ${a.type.indices}) -> ${i.type.indices} { + var a: ${i.type.indices};`);for(let p=0;p{let i=e.dataType,a=e.dims.length,u=Ms(a,t),p=zn(e.dims,u),d=Jt("output",i,p.length),_=mt("a",i,a),g;if(u.length===2&&u[0]===1&&u[1]===0){let y=d.type.value,C=[16,16,1];g=k=>` + ${k.registerUniform("output_size","u32").declareVariables(_,d)} + var tile : array, ${C[0]}>; + ${k.mainStart(C)} + var x = workgroup_id.x * ${C[0]}u + local_id.x; + var y = workgroup_id.y * ${C[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] = ${_.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${C[0]}u + local_id.x; + y = workgroup_id.x * ${C[0]}u + local_id.y; + if (x < height && y < width) { + ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else g=y=>` + ${y.registerUniform("output_size","u32").declareVariables(_,d)} + + ${ja(u,a,_,d)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${d.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:y=>{let C=tt.size(p);return{outputs:[{dims:p,dataType:y[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Rt(y[0].dims,p)]}},getShaderSource:g}},La=(e,t)=>{Ba(e.inputs),e.compute(Vi(e.inputs[0],t.perm))},xs=e=>tr({perm:e.perm})}),Ra,Na,Va,Ua,Ts,Wa,Ga,Cs,qa,Ka,Ai,Ha,Xa,ks,Qa,Ya,$s,Za,Ja,Ss,eo,Vu=V(()=>{sr(),lr(),mr(),Os(),wn(),Ra={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"},Na={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"},Va={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ua={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ts=(e,t)=>{let i=[];for(let a=t-e;a{let i=[],a=e.length;for(let p=0;pe[p]);return[i,u]},Ga=(e,t)=>{let i=e.length+t.length,a=[],u=0;for(let p=0;p{for(let i=0;i{let i=[];if(!Cs(e,t)){for(let a=0;ai.push(a))}return i},Ka=(e,t,i,a,u,p,d)=>{let _=i[0].dims,g=tt.size(p),y=tt.size(d),C=mt("_A",i[0].dataType,_),k=Jt("output",u,p),l=32,F=` + var aBestValues : array; + `;return{name:e,shaderCache:t,getShaderSource:I=>` + ${I.registerUniform("reduceSize","u32").declareVariables(C,k)} + ${F} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${I.mainStart(l)} + + let outputIndex = global_idx / ${l}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Va[a]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${l}) { + let candidate = f32(${C.getByOffset("offset + k")}); + bestValue = ${Ra[a]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${l}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 = ${Na[a]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${k.setByOffset("outputIndex",`${a==="mean"?`${k.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${k.type.storage}(${Ua[a]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:g},programUniforms:[{type:12,data:y}]})}},Ai=(e,t,i,a)=>{let u=e.inputs.length===1?i:Qn(e.inputs,i),p=u.axes;p.length===0&&!u.noopWithEmptyAxes&&(p=e.inputs[0].dims.map((F,I)=>I));let d=tt.normalizeAxes(p,e.inputs[0].dims.length),_=d,g=e.inputs[0],y=qa(_,e.inputs[0].dims.length);y.length>0&&(g=e.compute(Vi(e.inputs[0],y),{inputs:[0],outputs:[-1]})[0],_=Ts(_.length,g.dims.length));let[C,k]=Wa(g.dims,_),l=C;u.keepDims&&(l=Ga(C,d)),e.compute(Ka(t,{hint:u.cacheKey,inputDependencies:["type"]},[g],a,e.inputs[0].dataType,l,k),{inputs:[g]})},Ha=(e,t)=>{Ai(e,"ReduceMeanShared",t,"mean")},Xa=(e,t)=>{Ai(e,"ReduceL1Shared",t,"l1")},ks=(e,t)=>{Ai(e,"ReduceL2Shared",t,"l2")},Qa=(e,t)=>{Ai(e,"ReduceLogSumExpShared",t,"logSumExp")},Ya=(e,t)=>{Ai(e,"ReduceMaxShared",t,"max")},$s=(e,t)=>{Ai(e,"ReduceMinShared",t,"min")},Za=(e,t)=>{Ai(e,"ReduceProdShared",t,"prod")},Ja=(e,t)=>{Ai(e,"ReduceSumShared",t,"sum")},Ss=(e,t)=>{Ai(e,"ReduceSumSquareShared",t,"sumSquare")},eo=(e,t)=>{Ai(e,"ReduceLogSumShared",t,"logSum")}}),Ii,to,Xn,Qn,ji,ro,Es,io,no,Ps,so,ao,As,oo,lo,Fi,uo,co,Is,po,ho,Fs,fo,mo,zs,_o,Os=V(()=>{sr(),lr(),Tr(),mr(),Vu(),Ii=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.")},to=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Xn=(e,t,i,a,u,p,d=!1,_=!1)=>{let g=[],y=i[0].dims,C=y.length,k=tt.normalizeAxes(u,C),l=!_&&k.length===0;y.forEach((L,Q)=>{l||k.indexOf(Q)>=0?d&&g.push(1):g.push(L)});let F=g.length,I=tt.size(g);return{name:e,shaderCache:t,getShaderSource:L=>{let Q=[],Z=mt("_A",i[0].dataType,C),U=Jt("output",p,F),we=a(Z,U,k),te=we[2];for(let me=0,it=0;me=0?(d&&it++,te=`for(var j${me}: u32 = 0; j${me} < ${y[me]}; j${me}++) { + ${we[2].includes("last_index")?`let last_index = j${me};`:""} + ${Z.indicesSet("input_indices",me,`j${me}`)} + ${te} + }`):(Q.push(`${Z.indicesSet("input_indices",me,U.indicesGet("output_indices",it))};`),it++);return` + + ${L.registerUniform("output_size","u32").declareVariables(Z,U)} + + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${Z.type.indices}; + let output_indices = ${U.offsetToIndices("global_idx")}; + + ${Q.join(` +`)} + ${we[0]} // init ops for reduce max/min + ${we[1]} + ${te} + ${we[3]} + ${we.length===4?U.setByOffset("global_idx","value"):we.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:g,dataType:p}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:[{type:12,data:I},...Rt(y,g)]})}},Qn=(e,t)=>{let i=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(a=>i.push(Number(a))),tr({axes:i,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},ji=(e,t,i,a)=>{let u=e.inputs,p=u.length===1?i:Qn(u,i);e.compute(Xn(t,{hint:p.cacheKey,inputDependencies:["rank"]},[u[0]],p.noopWithEmptyAxes&&p.axes.length===0?to:a,p.axes,u[0].dataType,p.keepDims,p.noopWithEmptyAxes),{inputs:[0]})},ro=(e,t)=>{Ii(e.inputs),ji(e,"ReduceLogSum",t,(i,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${i.getByIndices("input_indices")};`,"value = log(value);"])},Es=(e,t)=>{Ii(e.inputs),ji(e,"ReduceL1",t,(i,a)=>[`var value = ${a.type.storage}(0);`,"",`value += abs(${i.getByIndices("input_indices")});`,""])},io=(e,t)=>{Ii(e.inputs),ji(e,"ReduceL2",t,(i,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${i.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},no=(e,t)=>{Ii(e.inputs),ji(e,"ReduceLogSumExp",t,(i,a)=>[`var value = ${a.type.storage}(0);`,"",`value += exp(${i.getByIndices("input_indices")});`,"value = log(value);"])},Ps=(e,t)=>{Ii(e.inputs),ji(e,"ReduceMax",t,(i,a,u)=>{let p=[];for(let d=0;d=0||u.length===0)&&p.push(i.indicesSet("input_indices",d,0));return[`${p.join(` +`)}`,`var value = ${i.getByIndices("input_indices")};`,`value = max(value, ${i.getByIndices("input_indices")});`,""]})},so=(e,t)=>{Ii(e.inputs),ji(e,"ReduceMean",t,(i,a,u)=>{let p=1;for(let d=0;d=0||u.length===0)&&(p*=e.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${i.getByIndices("input_indices")});`,`let value = ${a.type.value}(sum / ${p});`]})},ao=(e,t)=>{Ii(e.inputs),ji(e,"ReduceMin",t,(i,a,u)=>{let p=[];for(let d=0;d=0||u.length===0)&&p.push(`input_indices[${d}] = 0;`);return[`${p.join(` +`)}`,`var value = ${i.getByIndices("input_indices")};`,`value = min(value, ${i.getByIndices("input_indices")});`,""]})},As=(e,t)=>{Ii(e.inputs),ji(e,"ReduceProd",t,(i,a)=>[`var value = ${a.type.storage}(1);`,"",`value *= ${i.getByIndices("input_indices")};`,""])},oo=(e,t)=>{Ii(e.inputs),ji(e,"ReduceSum",t,(i,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${i.getByIndices("input_indices")};`,""])},lo=(e,t)=>{Ii(e.inputs),ji(e,"ReduceSumSquare",t,(i,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${i.getByIndices("input_indices")}; value += t * t;`,""])},Fi=(e,t,i)=>{if(t.length===0)return i;let a=1,u=1;for(let p=0;p1024},uo=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?so(e,t):Ha(e,t)},co=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Es(e,t):Xa(e,t)},Is=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?io(e,t):ks(e,t)},po=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?no(e,t):Qa(e,t)},ho=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ps(e,t):Ya(e,t)},Fs=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ao(e,t):$s(e,t)},fo=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?As(e,t):Za(e,t)},mo=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?oo(e,t):Ja(e,t)},zs=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?lo(e,t):Ss(e,t)},_o=(e,t)=>{Fi(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):eo(e,t)}}),Yn,go,wo,Zn,Uu=V(()=>{sr(),Tr(),Os(),Yn=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.")},go=(e,t)=>{Yn(e.inputs);let i=(a,u,p)=>{let d=[];for(let _=0;_=0||p.length===0)&&d.push(`input_indices[${_}] = 0;`);return[`${d.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Xn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],i,[t.axis],7,t.keepDims),{inputs:[0]})},wo=(e,t)=>{Yn(e.inputs);let i=(a,u,p)=>{let d=[];for(let _=0;_=0||p.length===0)&&d.push(`input_indices[${_}] = 0;`);return[`${d.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Xn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],i,[t.axis],7,t.keepDims),{inputs:[0]})},Zn=e=>tr(e)}),yo,Ds,bo,vo,yn,Mo,xo,Jn=V(()=>{sr(),N(),mr(),yo=(e,t)=>{let i=e[0],a=e[1],u=e[2],p=e[3],d=e[4],_=e[5];if(d&&_)throw new Error("Attention cannot have both past and relative_position_bias");if(i.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let g=i.dims[0],y=i.dims[1],C=i.dims[2];if(u.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(a.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(a.dims[0]!==C)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(u.dims[0]!==a.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let k=u.dims[0]/3,l=k,F=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let we of t.qkvHiddenSizes)if(we%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");k=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],F=t.qkvHiddenSizes[2]}let I=y;if(k!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(u.dims[0]!==k+l+F)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let L=0;if(d){if(l!==F)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(d.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(d.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(d.dims[1]!==g)throw new Error('Input "past" second dimension must be batch_size');if(d.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(d.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(L=d.dims[3])}let Q=I+L,Z=-1,U=0;if(p)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");return{batchSize:g,sequenceLength:y,pastSequenceLength:L,kvSequenceLength:I,totalSequenceLength:Q,maxSequenceLength:Z,inputHiddenSize:C,hiddenSize:k,vHiddenSize:F,headSize:Math.floor(k/t.numHeads),vHeadSize:Math.floor(F/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:U,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ds=(e,t,i,a)=>{let u=$r(a),p=64,d=a/u;d{let F=Jt("x",t.dataType,t.dims,u),I=Or(t.dataType),L=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${l.registerUniforms(L).declareVariables(F)} + ${l.mainStart([p,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${p}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${C}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${C}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${p}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${C}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${C}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${p}; 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] = ${F.type.value}(${I}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${C}(x[offset + i]); + x[offset + i] = ${F.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${y};${u}`},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:i},programUniforms:g})}},bo=(e,t,i,a,u,p,d,_)=>{let g=_+p.kvSequenceLength,y=[p.batchSize,p.numHeads,p.sequenceLength,g],C=p.kvNumHeads===void 0&&e.outputCount>1,k=C?[p.batchSize,p.numHeads,g,p.headSize]:void 0,l=d.scale===0?1/Math.sqrt(p.headSize):d.scale,F=$r(p.headSize),I=p.headSize/F,L=12,Q={x:Math.ceil(g/L),y:Math.ceil(p.sequenceLength/L),z:p.batchSize*p.numHeads},Z=[{type:12,data:p.sequenceLength},{type:12,data:I},{type:12,data:g},{type:12,data:p.numHeads},{type:1,data:l},{type:12,data:_},{type:12,data:p.kvSequenceLength}],U=["type","type"];a&&U.push("type"),u&&U.push("type");let we=[{dims:y,dataType:t.dataType,gpuDataType:0}];C&&we.push({dims:k,dataType:t.dataType,gpuDataType:0});let te=me=>{let it=mt("q",t.dataType,t.dims,F),Ye=mt("key",i.dataType,i.dims,F),Mt=[it,Ye];if(a){let Ur=mt("past_key",a.dataType,a.dims,F);Mt.push(Ur)}u&&Mt.push(mt("relative_position_bias",u.dataType,u.dims));let Gt=Jt("output",t.dataType,y),Bt=[Gt];C&&Bt.push(Jt("present_key",t.dataType,k,F));let gr=Or(1,F),Mr=[{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 = ${L}u; + + var tileQ: array<${it.type.storage}, ${L*L}>; + var tileK: array<${it.type.storage}, ${L*L}>; + ${me.registerUniforms(Mr).declareVariables(...Mt,...Bt)} + ${me.mainStart([L,L,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; + ${a&&C?` + 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;`} + ${C?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${gr}(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; + ${a&&C?` + 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];"} + ${C?"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 += ${gr}(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(F){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: ${F}`)}})()}; + output[outputIdx] = ${Gt.type.value} (sum * uniforms.alpha) + ${u?"relative_position_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${F};${u!==void 0};${a!==void 0};${e.outputCount}`,inputDependencies:U},getRunData:()=>({outputs:we,dispatchGroup:Q,programUniforms:Z}),getShaderSource:te}},vo=(e,t,i,a,u,p)=>{let d=p+u.kvSequenceLength,_=u.nReps?u.nReps:1,g=u.vHiddenSize*_,y=u.kvNumHeads==null&&e.outputCount>1,C=y?[u.batchSize,u.numHeads,d,u.headSize]:void 0,k=[u.batchSize,u.sequenceLength,g],l=12,F={x:Math.ceil(u.vHeadSize/l),y:Math.ceil(u.sequenceLength/l),z:u.batchSize*u.numHeads},I=[{type:12,data:u.sequenceLength},{type:12,data:d},{type:12,data:u.vHeadSize},{type:12,data:u.numHeads},{type:12,data:g},{type:12,data:p},{type:12,data:u.kvSequenceLength}],L=a?["type","type","type"]:["type","type"],Q=[{dims:k,dataType:t.dataType,gpuDataType:0}];y&&Q.push({dims:C,dataType:t.dataType,gpuDataType:0});let Z=U=>{let we=mt("probs",t.dataType,t.dims),te=mt("v",i.dataType,i.dims),me=[we,te];a&&me.push(mt("past_value",a.dataType,a.dims));let it=[Jt("output",t.dataType,k)];y&&it.push(Jt("present_value",t.dataType,C));let Ye=[{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 = ${l}u; + var tileQ: array<${we.type.value}, ${l*l}>; + var tileK: array<${we.type.value}, ${l*l}>; + ${U.registerUniforms(Ye).declareVariables(...me,...it)} + ${U.mainStart([l,l,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; + ${a&&y?` + 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; + `} + ${y?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${we.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; + ${a&&y?` + 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]; + `} + ${y?"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:`${a!==void 0};${e.outputCount}`,inputDependencies:L},getRunData:()=>({outputs:Q,dispatchGroup:F,programUniforms:I}),getShaderSource:Z}},yn=(e,t,i,a,u,p,d,_,g,y,C)=>{let k=y.kvNumHeads!==void 0||e.outputCount>1?y.pastSequenceLength:0,l=k+y.kvSequenceLength;if(y.kvNumHeads===void 0){let Z=[y.batchSize,y.numHeads,l,y.headSize];e.output(1,Z)===0&&(e.outputCount=1)}let F=e.outputCount,I=y.kvNumHeads===void 0&&F>1&&d?[t,i,d]:[t,i];g&&I.push(g);let L=e.compute(bo(e,t,i,F>1?d:void 0,g,y,C,k),{inputs:I,outputs:y.kvNumHeads===void 0&&F>1?[-1,1]:[-1]})[0];e.compute(Ds(e,L,y.batchSize*y.numHeads*y.sequenceLength,l),{inputs:[L],outputs:[]});let Q=y.kvNumHeads===void 0&&F>1&&_?[L,a,_]:[L,a];e.compute(vo(e,L,a,F>1&&_?_:void 0,y,k),{inputs:Q,outputs:y.kvNumHeads===void 0&&F>1?[0,2]:[0]})},Mo=(e,t)=>{let i=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],a=t.sequenceLength,u=t.inputHiddenSize,p=t.headSize,d=12,_={x:Math.ceil(t.headSize/d),y:Math.ceil(t.sequenceLength/d),z:t.batchSize*t.numHeads},g=[e.inputs[0],e.inputs[1],e.inputs[2]],y=[{type:12,data:a},{type:12,data:u},{type:12,data:p},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],C=k=>{let l=Jt("output_q",g[0].dataType,i),F=Jt("output_k",g[0].dataType,i),I=Jt("output_v",g[0].dataType,i),L=mt("input",g[0].dataType,g[0].dims),Q=mt("weight",g[1].dataType,g[1].dims),Z=mt("bias",g[2].dataType,g[2].dims),U=L.type.storage,we=[{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 = ${d}u; + var tileInput: array<${U}, ${d*d}>; + var tileWeightQ: array<${U}, ${d*d}>; + var tileWeightK: array<${U}, ${d*d}>; + var tileWeightV: array<${U}, ${d*d}>; + ${k.registerUniforms(we).declareVariables(L,Q,Z,l,F,I)} + ${k.mainStart([d,d,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 = ${U}(0); + var valueK = ${U}(0); + var valueV = ${U}(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:i,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:i,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:i,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:_,programUniforms:y}),getShaderSource:C},{inputs:g,outputs:[-1,-1,-1]})},xo=(e,t)=>{let i=yo(e.inputs,t),[a,u,p]=Mo(e,i);return yn(e,a,u,p,e.inputs[4],void 0,void 0,void 0,e.inputs[5],i,t)}}),To,Co,ko,$o,So=V(()=>{z(),sr(),lr(),Tr(),mr(),To=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let i=(a,u,p)=>{let d=u.length;if(d!==a.length)throw new Error(`${p}: num dimensions != ${d}`);u.forEach((_,g)=>{if(_!==a[g])throw new Error(`${p}: dim[${g}] do not match`)})};if(e[0].dims.length>1){let a=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);i(e[1].dims,a,"Invalid input scale"),i(e[2].dims,a,"Invalid input B"),i(e[3].dims,a,"Invalid input mean"),i(e[4].dims,a,"Invalid input var")}else i(e[1].dims,[1],"Invalid input scale"),i(e[2].dims,[1],"Invalid input B"),i(e[3].dims,[1],"Invalid input mean"),i(e[4].dims,[1],"Invalid input var")},Co=(e,t)=>{let{epsilon:i,spatial:a,format:u}=t,p=e[0].dims,d=a?$r(p[p.length-1]):1,_=u==="NHWC"&&p.length>1?d:1,g=tt.size(p)/d,y=a,C=y?p.length:p,k=mt("x",e[0].dataType,e[0].dims,d),l=mt("scale",e[1].dataType,e[1].dims,_),F=mt("bias",e[2].dataType,e[2].dims,_),I=mt("inputMean",e[3].dataType,e[3].dims,_),L=mt("inputVar",e[4].dataType,e[4].dims,_),Q=Jt("y",e[0].dataType,C,d),Z=()=>{let we="";if(a)we=`let cOffset = ${p.length===1?"0u":u==="NHWC"?`outputIndices[${p.length-1}] / ${d}`:"outputIndices[1]"};`;else if(u==="NCHW")we=` + ${Q.indicesSet("outputIndices","0","0")} + let cOffset = ${Q.indicesToOffset("outputIndices")};`;else{we=`var cIndices = ${l.type.indices}(0); + cIndices[0] = outputIndices[${p.length-1}];`;for(let te=1;te` + const epsilon = ${i}; + ${we.registerUniform("outputSize","u32").declareVariables(k,l,F,I,L,Q)} + ${we.mainStart()} + ${we.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${Q.offsetToIndices(`global_idx * ${d}`)}; + ${Z()} + let scale = ${l.getByOffset("cOffset")}; + let bias = ${F.getByOffset("cOffset")}; + let inputMean = ${I.getByOffset("cOffset")}; + let inputVar = ${L.getByOffset("cOffset")}; + let x = ${k.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${Q.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${a}_${d}`,inputDependencies:y?["rank","type","type","type","type"]:void 0},getShaderSource:U,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y?[{type:12,data:g},...Rt(p)]:[{type:12,data:g}]})}},ko=e=>tr(e),$o=(e,t)=>{let{inputs:i,outputCount:a}=e,u=ko({...t,outputCount:a});if(j.webgpu.validateInputContent&&To(i,u),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Co(i,u))}}),Eo,Po,Bs,Wu=V(()=>{lr(),mr(),Eo=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")},Po=e=>{let t=e[0].dims,i=e[0].dims[2],a=tt.size(t)/4,u=e[0].dataType,p=mt("input",u,t,4),d=mt("bias",u,[i],4),_=mt("residual",u,t,4),g=Jt("output",u,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:y=>` + const channels = ${i}u / 4; + ${y.declareVariables(p,d,_,g)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let value = ${p.getByOffset("global_idx")} + + ${d.getByOffset("global_idx % channels")} + ${_.getByOffset("global_idx")}; + ${g.setByOffset("global_idx","value")} + }`}},Bs=e=>{Eo(e.inputs),e.compute(Po(e.inputs))}}),Ao,Pr,Io,Fo,js,zo,Oo,Ls,Do,Bo,es,jo,Lo,Ro,Rs,No,bn,Vo,ts,Uo,Ns,Wo,Go,qo,Vs,Ko,Ho,Us,Xo,Qo,Ws,Yo,Zo,Gs,Jo,qs,Ks,Hs,Xs,el,tl,Qs,rl,il,nl,Ys=V(()=>{sr(),lr(),Tr(),mr(),Ao=(e,t,i,a,u,p)=>{let d=Math.ceil(t/4),_="";typeof u=="string"?_=`${u}(a)`:_=u("a");let g=mt("inputData",i,[d],4),y=Jt("outputData",a,[d],4);return` + ${e.registerUniform("vec_size","u32").declareVariables(g,y)} + + ${p??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${g.getByOffset("global_idx")}; + ${y.setByOffset("global_idx",_)} + }`},Pr=(e,t,i,a,u,p=e.dataType)=>({name:t,shaderCache:{hint:u,inputDependencies:["type"]},getShaderSource:d=>Ao(d,tt.size(e.dims),e.dataType,p,i,a),getRunData:d=>({outputs:[{dims:e.dims,dataType:p}],dispatchGroup:{x:Math.ceil(tt.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(tt.size(e.dims)/4)}]})}),Io=e=>{e.compute(Pr(e.inputs[0],"Abs","abs"))},Fo=e=>{e.compute(Pr(e.inputs[0],"Acos","acos"))},js=e=>{e.compute(Pr(e.inputs[0],"Acosh","acosh"))},zo=e=>{e.compute(Pr(e.inputs[0],"Asin","asin"))},Oo=e=>{e.compute(Pr(e.inputs[0],"Asinh","asinh"))},Ls=e=>{e.compute(Pr(e.inputs[0],"Atan","atan"))},Do=e=>{e.compute(Pr(e.inputs[0],"Atanh","atanh"))},Bo=e=>tr(e),es=(e,t)=>{let i;switch(t.to){case 10:i="vec4";break;case 1:i="vec4";break;case 12:i="vec4";break;case 6:i="vec4";break;case 9:i="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Pr(e.inputs[0],"Cast",i,void 0,t.cacheKey,t.to))},jo=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:ni,i=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:vi;return tr({min:t,max:i})},Lo=(e,t)=>{let i=e.inputs.length===1?t:jo(e.inputs),a=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"Clip",u=>`clamp(${u}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${a}> = vec4(${a}(${i.min})); + const clip_max_: vec4<${a}> = vec4(${a}(${i.max})); +`,i.cacheKey),{inputs:[0]})},Ro=e=>{e.compute(Pr(e.inputs[0],"Ceil","ceil"))},Rs=e=>{e.compute(Pr(e.inputs[0],"Cos","cos"))},No=e=>{e.compute(Pr(e.inputs[0],"Cosh","cosh"))},bn=e=>tr(e),Vo=(e,t)=>{let i=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"Elu",a=>`elu_vf32(${a})`,` + const elu_alpha_ = ${i}(${t.alpha}); + + fn elu_f32(a: ${i}) -> ${i} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${i}>) -> vec4<${i}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},ts=(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)); +}`,Uo=e=>{let t=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"Erf",i=>`erf_vf32(${i})`,ts(t)))},Ns=e=>{e.compute(Pr(e.inputs[0],"Exp","exp"))},Wo=e=>{e.compute(Pr(e.inputs[0],"Floor","floor"))},Go=e=>{let t=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"Gelu",i=>`0.5 * ${i} * (1.0 + erf_vf32(${i} * 0.7071067811865475))`,ts(t)))},qo=(e,t)=>{let i=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"LeakyRelu",a=>`select(leaky_relu_alpha_ * ${a}, ${a}, ${a} >= vec4<${i}>(0.0))`,`const leaky_relu_alpha_ = ${i}(${t.alpha});`,t.cacheKey))},Vs=e=>{e.compute(Pr(e.inputs[0],"Not",t=>`!${t}`))},Ko=e=>{e.compute(Pr(e.inputs[0],"Neg",t=>`-${t}`))},Ho=e=>{e.compute(Pr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Us=e=>{let t=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"Relu",i=>`select(vec4<${t}>(0.0), ${i}, ${i} > vec4<${t}>(0.0))`))},Xo=e=>{e.compute(Pr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Qo=e=>tr(e),Ws=(e,t)=>{let i=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"HardSigmoid",a=>`max(vec4<${i}>(0.0), min(vec4<${i}>(1.0), ${t.alpha} * ${a} + vec4<${i}>(${t.beta})))`,void 0,t.cacheKey))},Yo=e=>{e.compute(Pr(e.inputs[0],"Sin","sin"))},Zo=e=>{e.compute(Pr(e.inputs[0],"Sinh","sinh"))},Gs=e=>{e.compute(Pr(e.inputs[0],"Sqrt","sqrt"))},Jo=e=>{e.compute(Pr(e.inputs[0],"Tan","tan"))},qs=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ks=e=>{e.compute(Pr(e.inputs[0],"Tanh",qs))},Hs=(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 ${qs("v")}; +} +`,Xs=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,el=e=>{let t=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"FastGelu",Xs,Hs(t),void 0,e.inputs[0].dataType))},tl=(e,t)=>{let i=Or(e.inputs[0].dataType);return e.compute(Pr(e.inputs[0],"ThresholdedRelu",a=>`select(vec4<${i}>(0.0), ${a}, ${a} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${i}>(${t.alpha});`,t.cacheKey)),0},Qs=e=>{e.compute(Pr(e.inputs[0],"Log","log"))},rl=(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; +} +`,il=e=>`quick_gelu_impl(${e})`,nl=(e,t)=>{let i=Or(e.inputs[0].dataType);e.compute(Pr(e.inputs[0],"QuickGelu",il,rl(i,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Zs,sl,al,ol=V(()=>{lr(),mr(),Ys(),Zs=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")},sl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let i=mt("input",e[0].dataType,e[0].dims,4),a=mt("bias",e[0].dataType,[e[0].dims[2]],4),u=Jt("output",e[0].dataType,t,4),p=tt.size(t)/4,d=zr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)}}),getShaderSource:_=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${_.declareVariables(i,a,u)} + + ${ts(d)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes(p)} + 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); + + ${u.setByOffset("global_idx","valueLeft * geluRight")} + }`}},al=e=>{Zs(e.inputs),e.compute(sl(e.inputs))}}),ll,ul,zi,dl,cl,Js,pl,hl,fl,ml,_l,gl,ea,Gu=V(()=>{sr(),lr(),mr(),ll=(e,t,i,a,u,p,d,_,g,y,C,k)=>{let l,F;typeof _=="string"?l=F=(U,we)=>`${_}((${U}),(${we}))`:typeof _=="function"?l=F=_:(l=_.scalar,F=_.vector);let I=Jt("outputData",C,a.length,4),L=mt("aData",g,t.length,4),Q=mt("bData",y,i.length,4),Z;if(u)if(p){let U=tt.size(t)===1,we=tt.size(i)===1,te=t.length>0&&t[t.length-1]%4===0,me=i.length>0&&i[i.length-1]%4===0;U||we?Z=I.setByOffset("global_idx",F(U?`${L.type.value}(${L.getByOffset("0")}.x)`:L.getByOffset("global_idx"),we?`${Q.type.value}(${Q.getByOffset("0")}.x)`:Q.getByOffset("global_idx"))):Z=` + let outputIndices = ${I.offsetToIndices("global_idx * 4u")}; + let offsetA = ${L.broadcastedIndicesToOffset("outputIndices",I)}; + let offsetB = ${Q.broadcastedIndicesToOffset("outputIndices",I)}; + ${I.setByOffset("global_idx",F(d||te?L.getByOffset("offsetA / 4u"):`${L.type.value}(${L.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||me?Q.getByOffset("offsetB / 4u"):`${Q.type.value}(${Q.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else Z=I.setByOffset("global_idx",F(L.getByOffset("global_idx"),Q.getByOffset("global_idx")));else{if(!p)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let U=(we,te,me="")=>{let it=`aData[indexA${te}][componentA${te}]`,Ye=`bData[indexB${te}][componentB${te}]`;return` + let outputIndices${te} = ${I.offsetToIndices(`global_idx * 4u + ${te}u`)}; + let offsetA${te} = ${L.broadcastedIndicesToOffset(`outputIndices${te}`,I)}; + let offsetB${te} = ${Q.broadcastedIndicesToOffset(`outputIndices${te}`,I)}; + let indexA${te} = offsetA${te} / 4u; + let indexB${te} = offsetB${te} / 4u; + let componentA${te} = offsetA${te} % 4u; + let componentB${te} = offsetB${te} % 4u; + ${we}[${te}] = ${me}(${l(it,Ye)}); + `};C===9?Z=` + var data = vec4(0); + ${U("data",0,"u32")} + ${U("data",1,"u32")} + ${U("data",2,"u32")} + ${U("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:Z=` + ${U("outputData[global_idx]",0)} + ${U("outputData[global_idx]",1)} + ${U("outputData[global_idx]",2)} + ${U("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(L,Q,I)} + + ${k??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${Z} + }`},ul=(e,t,i,a,u,p,d=i.dataType)=>{let _=!tt.areEqual(i.dims,a.dims),g=i.dims,y=tt.size(i.dims),C=!1,k=!1,l=[_];if(_){let F=ui.calcShape(i.dims,a.dims,!1);if(!F)throw new Error("Can't perform binary op on the given tensors");g=F,y=tt.size(g);let I=tt.size(i.dims)===1,L=tt.size(a.dims)===1,Q=i.dims.length>0&&i.dims[i.dims.length-1]%4===0,Z=a.dims.length>0&&a.dims[a.dims.length-1]%4===0;l.push(I),l.push(L),l.push(Q),l.push(Z);let U=1;for(let we=1;weF.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:F=>ll(F,i.dims,a.dims,g,C,_,k,u,i.dataType,a.dataType,d,p),getRunData:()=>({outputs:[{dims:g,dataType:d}],dispatchGroup:{x:Math.ceil(y/64/4)},programUniforms:[{type:12,data:Math.ceil(tt.size(g)/4)},...Rt(i.dims,a.dims,g)]})}},zi=(e,t,i,a,u,p)=>{e.compute(ul(t,u??"",e.inputs[0],e.inputs[1],i,a,p))},dl=e=>{zi(e,"Add",(t,i)=>`${t}+${i}`)},cl=e=>{zi(e,"Div",(t,i)=>`${t}/${i}`)},Js=e=>{zi(e,"Equal",{scalar:(t,i)=>`u32(${t}==${i})`,vector:(t,i)=>`vec4(${t}==${i})`},void 0,void 0,9)},pl=e=>{zi(e,"Mul",(t,i)=>`${t}*${i}`)},hl=e=>{let t=mt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;zi(e,"Pow",{scalar:(i,a)=>`pow_custom(${i},${a})`,vector:(i,a)=>`pow_vector_custom(${i},${a})`},` + 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)); + } + `)},fl=e=>{zi(e,"Sub",(t,i)=>`${t}-${i}`)},ml=e=>{zi(e,"Greater",{scalar:(t,i)=>`u32(${t}>${i})`,vector:(t,i)=>`vec4(${t}>${i})`},void 0,void 0,9)},_l=e=>{zi(e,"Less",{scalar:(t,i)=>`u32(${t}<${i})`,vector:(t,i)=>`vec4(${t}<${i})`},void 0,void 0,9)},gl=e=>{zi(e,"GreaterOrEqual",{scalar:(t,i)=>`u32(${t}>=${i})`,vector:(t,i)=>`vec4(${t}>=${i})`},void 0,void 0,9)},ea=e=>{zi(e,"LessOrEqual",{scalar:(t,i)=>`u32(${t}<=${i})`,vector:(t,i)=>`vec4(${t}<=${i})`},void 0,void 0,9)}}),wl,ta,yl,bl,tn,vl,qu=V(()=>{sr(),lr(),Tr(),mr(),wl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let i=0,a=e[i],u=a.dataType,p=a.dims.length;e.forEach((d,_)=>{if(_!==i){if(d.dataType!==u)throw new Error("input tensors should be one type");if(d.dims.length!==p)throw new Error("input tensors should have the same shape");d.dims.forEach((g,y)=>{if(y!==t&&g!==a.dims[y])throw new Error("non concat dimensions must match")})}})},ta=(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; + }`,yl=(e,t)=>{let i=e.length,a=[];for(let u=0;u{let u=tt.size(i),p=new Array(e.length),d=new Array(e.length),_=0,g=[],y=[],C=[{type:12,data:u}];for(let L=0;L`uniforms.sizeInConcatAxis${L}`).join(","),I=L=>` + + ${(()=>{L.registerUniform("outputSize","u32");for(let Q=0;Q(${F}); + ${l} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${yl(d,k)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:C}),getShaderSource:I}},tn=(e,t)=>{let i=e.inputs,a=i[0].dims,u=tt.normalizeAxis(t.axis,a.length);wl(i,u);let p=a.slice();p[u]=i.reduce((_,g)=>_+(g.dims.length>u?g.dims[u]:0),0);let d=i.filter(_=>tt.size(_.dims)>0);e.compute(bl(d,u,p,i[0].dataType),{inputs:d})},vl=e=>tr({axis:e.axis})}),rn,nn,Xi,ra,sn=V(()=>{sr(),lr(),rn=(e,t,i="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}(${i}(uniforms.clip_min)), ${t}(${i}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${i}(uniforms.alpha) * value + ${i}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${i}(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}`)}},nn=(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})},Xi=(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"})},ra=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[i,a]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:i,beta:a}}else if(t==="Clip"){let[i,a]=(e==null?void 0:e.activation_params)||[ni,vi];return{activation:t,clipMax:a,clipMin:i}}else if(t==="LeakyRelu"){let[i]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:i}}return{activation:t}}}),pi,ia,vn=V(()=>{pi=(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.`)}},ia=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),na,Ml=V(()=>{na=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)); +} +`}),xl,On,rs,sa,Tl,is,ns,aa,ss=V(()=>{sr(),lr(),mr(),sn(),vn(),xl=(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":""}); + `,On=(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];"} + }`,rs=(e,t,i="f32",a,u=!1,p=32,d=!1,_=32)=>{let g=t[1]*e[1],y=t[0]*e[0],C=u?g:p,k=u?p:g,l=C/t[0],F=p/t[1];if(!((u&&l===4&&e[1]===4||!u&&(l===3||l===4))&&C%t[0]===0&&p%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${u} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${l} must be 3 or 4. + tileAWidth ${C} must be divisible by workgroupSize[0]${t[0]}. tileInner ${p} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${C/l}>, ${k}>; +var mm_Bsub: array, ${y/e[0]}>, ${p}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${l}; +const tileInner = ${p}; + +@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 = ${d?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${g}; + + let num_tiles = ${d?`${Math.ceil(_/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${_}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${F}; + 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; + ${xl(u,a)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${F}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${a?", 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]; + ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${On(u,l)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},sa=(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":""}); + `,Tl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",is=(e,t,i="f32",a,u=!1,p=32,d=!1,_=32,g=!1)=>{let y=e[1]*t[1],C=e[0]*t[0],k=u?y:p,l=u?p:y;if(!(l%t[1]===0&&k%t[0]===0&&p%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}, tileInner ${p} must be divisible by workgroupSize[1]${t[1]}`);let F=l/t[1],I=k/t[0],L=p/t[1],Q=g?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${y}; + let globalColStart = i32(workgroupId.x) * ${C}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + ${sa(u,a)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${C}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${a?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${i}, 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 = ${u?`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) * ${y}; + +let tileRowA = i32(localId.y) * ${F}; +let tileColA = i32(localId.x) * ${I}; +let tileRowB = i32(localId.y) * ${L}; +// 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 < ${F}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${I}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${sa(u,a)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${L}; 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${a?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${i}, 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) { + ${Tl(u)} + 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, ${l}>; + var mm_Bsub : array, ${p}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${p}; + +@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 = ${d?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${d?`${Math.ceil(_/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${_}`:"0"}; + + var acc : array, rowPerThread>; + ${Q} + } +`},ns=(e,t,i,a,u,p=!1)=>{let[d,_,g]=u,[y,C,k,l]=a,F=gn(d,g),I=gn(_,g),L=zr(a[0].type.tensor),Q=()=>{let U=C.rank,we=y.rank,te=`var aIndices: ${C.type.indices};`;for(let me=U-2-1,it=we-1;me>=0;me--,it--)te+=` +aIndices[${me}] = ${we>1?`batchIndices[${it}]`:"batchIndices"};`;return F.forEach(me=>{te+=` +aIndices[${me}] = 0;`}),te+=` +aIndices[${U-2}] = u32(row); + aIndices[${U-1}] = u32(colIn);`,te},Z=()=>{let U=k.rank,we=y.rank,te=`var bIndices: ${k.type.indices};`;for(let me=U-2-1,it=we-1;me>=0;me--,it--)te+=` +bIndices[${me}] = ${we>1?`batchIndices[${it}]`:"batchIndices"};`;return I.forEach(me=>{te+=` +bIndices[${me}] = 0;`}),te+=` +bIndices[${U-2}] = u32(row); + bIndices[${U-1}] = u32(colIn);`,te};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${pi(e,L)} { + var value = ${pi(e,L)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${Q()} + value = ${C.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${pi(e,L)} { + var value = ${pi(e,L)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${Z()} + value = ${k.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${pi(e,L)}) { + 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 + ${p?"bias[colIn]":`${pi(e,L)}(bias[row])`};`:""} + ${i} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},aa=(e,t,i,a,u=!1)=>{let p=e[0].dims,d=e[1].dims,_=p.slice(0,-2),g=d.slice(0,-2),y=a?a.slice(0,-2):i.slice(0,-2),C=tt.size(y),k=p[p.length-2],l=p[p.length-1],F=d[d.length-1],I=l%4===0&&F%4===0,L=k<=8?[4,1,1]:[4,4,1],Q=[8,8,1],Z=[Math.ceil(F/Q[0]/L[0]),Math.ceil(k/Q[1]/L[1]),Math.ceil(C/Q[2]/L[2])],U=I?4:1,we=[..._,k,l/U],te=we.length,me=[...g,l,F/U],it=me.length,Ye=[C,k,F/U],Mt=[{type:6,data:k},{type:6,data:F},{type:6,data:l}];nn(t,Mt),Mt.push(...Rt(y,we,me));let Gt=["rank","rank"],Bt=e.length>2;Bt&&(Mt.push(...Rt(e[2].dims)),Gt.push("rank")),Mt.push(...Rt(Ye));let gr=Mr=>{let Ur=y.length,Ir=bs("batchDims",e[0].dataType,Ur,1),Sr=zr(e[0].dataType),ri=mt("a",e[0].dataType,te,U),Kr=mt("b",e[1].dataType,it,U),Wt=Jt("result",e[0].dataType,Ye.length,U),pr=[ri,Kr];if(Bt){let Yr=u?U:1;pr.push(mt("bias",e[2].dataType,e[2].dims.length,Yr))}let cr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Xi(t,cr);let lt=zr(Wt.type.tensor),qt=rn(t,Wt.type.value,lt),fr=ns(U,Bt,qt,[Ir,ri,Kr,Wt],[_,g,y],u);return` + ${Mr.registerUniforms(cr).registerInternalVariables(Ir).declareVariables(...pr,Wt)} + ${fr} + ${I?rs(L,Q,Sr,Ir):is(L,Q,Sr,Ir)} + `};return{name:"MatMul",shaderCache:{hint:`${L};${t.activation};${I};${u}`,inputDependencies:Gt},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Z[0],y:Z[1],z:Z[2]},programUniforms:Mt}),getShaderSource:gr}}}),Cl,Ku,Hu=V(()=>{sr(),Ci(),mr(),sn(),vn(),Ml(),ss(),Cl=(e,t,i,a,u=!1,p,d=4,_=4,g=4,y="f32")=>{let C=Gt=>{switch(Gt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${y}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Gt} is not supported.`)}},k=Gt=>{switch(Gt){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 ${Gt} is not supported.`)}},l=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,F=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,I=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",L=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Q=e?"row":"col",Z=e?"col":"row",U=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${Q} / outWidth; + let outCol = ${Q} % outWidth; + + let WRow = ${Z} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${Z} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${Z} % inChannels; + var resData = ${pi(d,y)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${I} && xCol >= 0 && xCol < ${L}) { + ${l} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${C(d)} + } + return resData;`,we=e?t&&a?` + let col = colIn * ${d}; + ${U}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${U} + } + return ${pi(d,y)}(0.0);`:a&&i?` + let col = colIn * ${d}; + ${U}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${U} + } + return ${pi(d,y)}(0.0);`,te=`${k(_)}`,me=pi(g,y),it=pi(e?d:_,y),Ye=pi(e?_:d,y),Mt=rn(p,me,y);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${it} { + ${e?we:te} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ye} { + ${e?te:we} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${me}) { + let col = colIn * ${g}; + 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])"}; + ${F} + ${ia(u)} + ${Mt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Ku=(e,t,i,a,u,p,d,_)=>{let g=t.format==="NHWC",y=g?e[0].dims[3]:e[0].dims[1],C=i[0],k=g?i[2]:i[3],l=g?i[1]:i[2],F=g?i[3]:i[1],I=g&&(y%4===0||y%3===0)&&F%4===0,L=g?F:k*l,Q=g?k*l:F,Z=[8,8,1],U=a<=8?[4,1,1]:[4,4,1],we=[Math.ceil(L/Z[0]/U[0]),Math.ceil(Q/Z[1]/U[1]),Math.ceil(C/Z[2]/U[2])];qr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${we}`);let te=I?g&&y%4!==0?3:4:1,me=Z[1]*U[1],it=Z[0]*U[0],Ye=Math.max(Z[0]*te,Z[1]),Mt=a%me===0,Gt=u%it===0,Bt=p%Ye===0,gr=I?[te,4,4]:[1,1,1],Mr=[{type:6,data:a},{type:6,data:u},{type:6,data:p},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];nn(t,Mr),Mr.push(...Rt(e[0].dims,e[1].dims));let Ur=["rank","rank"];d&&(Mr.push(...Rt(e[2].dims)),Ur.push("rank")),Mr.push(...Rt(i));let Ir=Sr=>{let ri=[{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}];Xi(t,ri);let Kr=I?4:1,Wt=zr(e[0].dataType),pr=` + fn setOutputAtIndex(flatIndex : i32, value : ${I?`vec4<${Wt}>`:Wt}) { + result[flatIndex] = ${I?`vec4<${Wt}>`:Wt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${I?`vec4<${Wt}>`:Wt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${I?"/ 4":""}, value); + }`,cr=mt("x",e[0].dataType,e[0].dims.length,te===3?1:te),lt=mt("w",e[1].dataType,e[1].dims.length,Kr),qt=[cr,lt],fr=Jt("result",e[0].dataType,i.length,Kr);if(d){let Yr=mt("bias",e[2].dataType,e[2].dims.length,Kr);qt.push(Yr),pr+=` + fn getBiasByOutputCoords(coords : vec4) -> ${I?`vec4<${Wt}>`:Wt} { + return bias[coords.${g?"w":"y"}${I?"/ 4":""}]; + }`}return` + ${na("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 }; + ${Sr.registerUniforms(ri).declareVariables(...qt,fr)} + ${pr} + ${Cl(g,Mt,Gt,Bt,d,t,gr[0],gr[1],gr[2],Wt)} + ${I?rs(U,Z,Wt,void 0,!g,Ye):is(U,Z,Wt,void 0,!g,Ye,!1,void 0,_)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${te};${I};${Mt};${Gt};${Bt};${me};${it};${Ye}`,inputDependencies:Ur},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:we[0],y:we[1],z:we[2]},programUniforms:Mr}),getShaderSource:Ir}}}),kl,oa,Qi,$l,la,Sl,El,Pl,ua=V(()=>{sr(),Ci(),lr(),mr(),sn(),vn(),kl=e=>{let t=1;for(let i=0;itypeof e=="number"?[e,e,e]:e,Qi=(e,t)=>t<=1?e:e+(e-1)*(t-1),$l=(e,t,i,a=1)=>{let u=Qi(t,a);return Math.floor((e[0]*(i-1)-i+u)/2)},la=(e,t,i,a,u)=>{u==null&&(u=$l(e,t[0],a[0]));let p=[0,0,0,i];for(let d=0;d<3;d++)e[d]+2*u>=t[d]&&(p[d]=Math.trunc((e[d]-t[d]+2*u)/a[d]+1));return p},Sl=(e,t,i,a,u,p,d,_,g,y)=>{let C,k,l,F;if(e==="VALID"&&(e=0),typeof e=="number"){C={top:e,bottom:e,left:e,right:e,front:e,back:e};let I=la([t,i,a,1],[_,g,y],1,[u,p,d],e);k=I[0],l=I[1],F=I[2]}else if(Array.isArray(e)){if(!e.every((L,Q,Z)=>L===Z[0]))throw Error(`Unsupported padding parameter: ${e}`);C={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let I=la([t,i,a,1],[_,g,y],1,[u,p,d],e[0]);k=I[0],l=I[1],F=I[2]}else if(e==="SAME_UPPER"){k=Math.ceil(t/u),l=Math.ceil(i/p),F=Math.ceil(a/d);let I=(k-1)*u+_-t,L=(l-1)*p+g-i,Q=(F-1)*d+y-a,Z=Math.floor(I/2),U=I-Z,we=Math.floor(L/2),te=L-we,me=Math.floor(Q/2),it=Q-me;C={top:we,bottom:te,left:me,right:it,front:Z,back:U}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:C,outDepth:k,outHeight:l,outWidth:F}},El=(e,t,i,a,u,p=!1,d="channelsLast")=>{let _,g,y,C,k;if(d==="channelsLast")[_,g,y,C,k]=e;else if(d==="channelsFirst")[_,k,g,y,C]=e;else throw new Error(`Unknown dataFormat ${d}`);let[l,,F,I,L]=t,[Q,Z,U]=oa(i),[we,te,me]=oa(a),it=Qi(F,we),Ye=Qi(I,te),Mt=Qi(L,me),{padInfo:Gt,outDepth:Bt,outHeight:gr,outWidth:Mr}=Sl(u,g,y,C,Q,Z,U,it,Ye,Mt),Ur=p?l*k:l,Ir=[0,0,0,0,0];return d==="channelsFirst"?Ir=[_,Ur,Bt,gr,Mr]:d==="channelsLast"&&(Ir=[_,Bt,gr,Mr,Ur]),{batchSize:_,dataFormat:d,inDepth:g,inHeight:y,inWidth:C,inChannels:k,outDepth:Bt,outHeight:gr,outWidth:Mr,outChannels:Ur,padInfo:Gt,strideDepth:Q,strideHeight:Z,strideWidth:U,filterDepth:F,filterHeight:I,filterWidth:L,effectiveFilterDepth:it,effectiveFilterHeight:Ye,effectiveFilterWidth:Mt,dilationDepth:we,dilationHeight:te,dilationWidth:me,inShape:e,outShape:Ir,filterShape:t}},Pl=(e,t,i,a,u,p)=>{let d=p==="channelsLast";d?e[0].dims[3]:e[0].dims[1];let _=[64,1,1],g={x:i.map((Q,Z)=>Z)},y=[Math.ceil(kl(g.x.map(Q=>i[Q]))/_[0]),1,1];qr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${y}`);let C=1,k=tt.size(i),l=[{type:12,data:k},{type:12,data:a},{type:12,data:u},{type:12,data:t.strides},{type:12,data:t.dilations}];nn(t,l),l.push(...Rt(e[0].dims,e[1].dims));let F=["rank","rank"],I=e.length===3;I&&(l.push(...Rt(e[2].dims)),F.push("rank")),l.push(...Rt(i));let L=Q=>{let Z=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:a.length},{name:"pads",type:"u32",length:u.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Xi(t,Z);let U=1,we=zr(e[0].dataType),te=mt("x",e[0].dataType,e[0].dims.length,C),me=mt("W",e[1].dataType,e[1].dims.length,U),it=[te,me],Ye=Jt("result",e[0].dataType,i.length,U),Mt="";if(I){let gr=mt("bias",e[2].dataType,e[2].dims.length,U);it.push(gr),Mt+=` + fn getBiasByOutputCoords(coords : array) -> ${we} { + return bias[${d?Kt("coords",4,5):Kt("coords",1,5)}]; + }`}let Gt=pi(C,we),Bt=rn(t,Gt,we);return` + ${Mt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${te.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${me.getByIndices("aIndices")}; + } + ${Q.registerUniforms(Z).declareVariables(...it,Ye)} + ${Q.mainStart()} + ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ye.offsetToIndices("global_idx")}; + let batch = ${Kt("coords",0,te.rank)}; + let d2 = ${d?Kt("coords",te.rank-1,te.rank):Kt("coords",1,te.rank)}; + let xFRCCorner = vec3(${d?Kt("coords",1,te.rank):Kt("coords",2,te.rank)}, + ${d?Kt("coords",2,te.rank):Kt("coords",3,te.rank)}, + ${d?Kt("coords",3,te.rank):Kt("coords",4,te.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?Kt("uniforms.x_shape",1,te.rank):Kt("uniforms.x_shape",2,te.rank)}; + let xShapeZ = ${d?Kt("uniforms.x_shape",2,te.rank):Kt("uniforms.x_shape",3,te.rank)}; + let xShapeW = ${d?Kt("uniforms.x_shape",3,te.rank):Kt("uniforms.x_shape",4,te.rank)}; + let xShapeU = ${d?Kt("uniforms.x_shape",4,te.rank):Kt("uniforms.x_shape",1,te.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) { + ${d?`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) { + ${d?`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) { + ${d?`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) { + ${d?`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); + } + } + } + } + ${I?"value = value + getBiasByOutputCoords(coords)":""}; + ${Bt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${d};${C};${I}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:l}),getShaderSource:L}}}),Al,Il,Xu=V(()=>{sr(),lr(),mr(),Bl(),sn(),Al=(e,t,i)=>{let a=e.length>2,u=a?"value += b[output_channel];":"",p=e[0].dims,d=e[1].dims,_=d[0]/t.group,g=t.format==="NHWC",y=as(p,d,t.dilations,t.pads,t.strides,g),C=tt.size(y),k=[{type:12,data:C},{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:_}];nn(t,k),k.push(...Rt(p,d));let l=["rank","rank"];a&&(k.push(...Rt(e[2].dims)),l.push("rank")),k.push(...Rt(y));let F=I=>{let L=Jt("output",e[0].dataType,y.length),Q=zr(L.type.tensor),Z=rn(t,L.type.value,Q),U=mt("x",e[0].dataType,p.length),we=mt("w",e[1].dataType,d.length),te=[U,we];a&&te.push(mt("b",e[2].dataType,e[2].dims.length));let me=[{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 Xi(t,me),` + ${I.registerUniforms(me).declareVariables(...te,L)} + + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${L.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${g?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${g?1:2}], outputIndices[${g?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${L.type.value} = ${L.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[${g?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[${g?2:3}]) { + continue; + } + + let xVal = ${g?U.get("batch","xHeight","xWidth","input_channel"):U.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${we.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${u} + ${Z} + ${L.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:l},getRunData:()=>({outputs:[{dims:i?i(y):y,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:k}),getShaderSource:F}},Il=(e,t,i)=>{let a=e.length>2,u=$r(i[3]),p=$r(i[2]),d=tt.size(i)/u/p,_=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/u],g=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/u],y=[i[0],i[1],i[2],i[3]/u],C=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];nn(t,C),C.push(...Rt(_,g,y));let k=(p-1)*t.strides[1]+g[1],l=F=>{let I=Jt("output",e[0].dataType,y.length,u),L=zr(I.type.tensor),Q=rn(t,I.type.value,L),Z=mt("x",e[0].dataType,_.length,u),U=mt("w",e[1].dataType,g.length,u),we=[Z,U];a&&we.push(mt("b",e[2].dataType,e[2].dims,u));let te=a?"value += b[output_channel];":"",me=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Xi(t,me),` + ${F.registerUniforms(me).declareVariables(...we,I)} + ${F.mainStart()} + ${F.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] / ${p}u; + let col = (index1 % width1) * ${p}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<${Z.type.value}, ${k}>; + var values: array<${I.type.value}, ${p}>; + 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 < ${g[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${k}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${Z.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${Z.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${g[1]}; w_width++) { + let w_val = ${U.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${p}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${p}u; i++) { + var value = values[i]; + ${te} + ${Q} + ${I.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${u};${p};${k};${g[0]};${g[1]}`,inputDependencies:a?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:C}),getShaderSource:l}}}),da,Fl,zl,ca=V(()=>{sr(),lr(),ss(),mr(),sn(),da=(e,t,i,a,u=!1)=>{let p=e[0].dims,d=e[1].dims,_=p[p.length-2],g=d[d.length-1],y=p[p.length-1],C=$r(g),k=$r(y),l=$r(_),F=tt.size(i)/C/l,I=e.length>2,L=a?a.slice(0,-2):i.slice(0,-2),Q=[tt.size(L),_,g],Z=[{type:12,data:F},{type:12,data:_},{type:12,data:g},{type:12,data:y}];nn(t,Z),Z.push(...Rt(L,p,d)),I&&Z.push(...Rt(e[2].dims)),Z.push(...Rt(Q));let U=we=>{let te=bs("batch_dims",e[0].dataType,L.length),me=mt("a",e[0].dataType,p.length,k),it=mt("b",e[1].dataType,d.length,C),Ye=Jt("output",e[0].dataType,Q.length,C),Mt=zr(Ye.type.tensor),Gt=rn(t,Ye.type.value,Mt),Bt=[me,it],gr="";if(I){let pr=u?C:1;Bt.push(mt("bias",e[2].dataType,e[2].dims.length,pr)),gr=`${u?`value += bias[col / ${pr}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let Mr=p.slice(0,-2),Ur=d.slice(0,-2),Ir=gn(Mr,L),Sr=gn(Ur,L),ri=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Xi(t,ri);let Kr=(pr,cr)=>{let lt=pr.rank,qt=pr.name;if(lt===2)return`var ${qt}_indices = ${pr.type.indices}(0u, 0u);`;let fr=te.rank,Yr=`var ${qt}_indices: ${pr.type.indices};`;for(let ai=lt-2-1,gi=fr-1;ai>=0;ai--,gi--)Yr+=` +${qt}_indices[${ai}] = ${fr>1?`batch_indices[${gi}]`:"batch_indices"};`;return cr.forEach(ai=>{Yr+=` +${qt}_indices[${ai}] = 0;`}),Yr+=`${qt}_indices[${lt-2}] = 0u; + ${qt}_indices[${lt-1}] = 0u;`,Yr},Wt=()=>{let pr=`var a_data: ${me.type.value};`;for(let cr=0;cr; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${k}) { + ${Wt()} + } + for (var i = 0u; i < ${l}u; i++) { + var value = values[i]; + ${gr} + ${Gt} + let cur_indices = ${Ye.type.indices}(batch, row + i, col); + let offset = ${Ye.indicesToOffset("cur_indices")}; + ${Ye.setByOffset(`offset / ${C}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${C};${k};${l};${u}`,inputDependencies:I?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:Z}),getShaderSource:U}},Fl=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.")},zl=e=>{Fl(e.inputs);let t=ui.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let i=t[t.length-1],a=e.inputs[0].dims[e.inputs[0].dims.length-1];i<8&&a<8?e.compute(da(e.inputs,{activation:""},t)):e.compute(aa(e.inputs,{activation:""},t))}}),as,os,pa,ls,ha,fa,Ol,Dl,Dn,Bl=V(()=>{lr(),Hu(),ua(),ss(),Xu(),sn(),ca(),wn(),as=(e,t,i,a,u,p)=>{let d=e[0],_=e.slice(p?1:2,p?3:4),g=_.length,y=t[0],C=t.slice(2).map((l,F)=>l+(l-1)*(i[F]-1)),k=_.map((l,F)=>l+a[F]+a[F+g]).map((l,F)=>Math.floor((l-C[F]+u[F])/u[F]));return k.splice(0,0,d),k.splice(p?3:1,0,y),k},os=[2,3,1,0],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>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 i=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],a=e[1].dims[1]*t.group;if(i!==a)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 u=e[0].dims.length-2;if(t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ls=(e,t)=>{let i=e.kernelShape.slice();for(let p=2;p{let t=ra(e),i=e.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],u=e.dilations,p=e.group,d=e.kernel_shape,_=e.pads,g=e.strides,y=e.w_is_const();return{autoPad:a,format:i,dilations:u,group:p,kernelShape:d,pads:_,strides:g,wIsConst:y,...t,cacheKey:`${e.format};${t.activation};`}},fa=(e,t,i)=>{let a=ls(i,t),u=i.format==="NHWC";if(i.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&u&&t[1].dims[0]===i.group&&t[1].dims[1]===1&&i.dilations[0]===1&&i.dilations[1]===1){let it=as(t[0].dims,t[1].dims,i.dilations,a.pads,i.strides,u),Ye=e.kernelCustomData.wT??e.compute(Vi(t[1],os),{inputs:[1],outputs:[i.wIsConst?-2:-1]})[0];i.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ye);let Mt=[t[0],Ye];t.length===3&&Mt.push(t[2]),e.compute(Il(Mt,a,it),{inputs:Mt})}else e.compute(Al(t,a));return}let p=t.length===3,d=t[0].dims[u?1:2],_=t[0].dims[u?2:3],g=t[0].dims[u?3:1],y=t[1].dims[2],C=t[1].dims[3],k=as(t[0].dims,t[1].dims,i.dilations,a.pads,i.strides,u),l=k[u?1:2],F=k[u?2:3],I=k[u?3:1],L=u&&y===d&&C===_&&i.pads[0]===0&&i.pads[1]===0;if(L||y===1&&C===1&&i.dilations[0]===1&&i.dilations[1]===1&&i.strides[0]===1&&i.strides[1]===1&&i.pads[0]===0&&i.pads[1]===0){let it=k[0],Ye,Mt,Gt,Bt=[];if(u){let Ur=e.kernelCustomData.wT??e.compute(Vi(t[1],os),{inputs:[1],outputs:[i.wIsConst?-2:-1]})[0];if(i.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ur),L){let Ir=d*_*g;Ye=t[0].reshape([1,it,Ir]),Mt=Ur.reshape([1,Ir,I]),Gt=[1,it,I]}else Ye=t[0].reshape([it,d*_,g]),Mt=Ur.reshape([1,g,I]),Gt=[it,l*F,I];Bt.push(Ye),Bt.push(Mt)}else Ye=t[0].reshape([it,g,d*_]),Mt=t[1].reshape([1,I,g]),Gt=[it,I,l*F],Bt.push(Mt),Bt.push(Ye);p&&Bt.push(t[2]);let gr=Gt[2],Mr=Bt[0].dims[Bt[0].dims.length-1];gr<8&&Mr<8?e.compute(da(Bt,a,k,Gt,u),{inputs:Bt}):e.compute(aa(Bt,a,k,Gt,u),{inputs:Bt});return}let Q=!0,Z=e.kernelCustomData.wT??e.compute(Vi(t[1],os),{inputs:[1],outputs:[i.wIsConst?-2:-1]})[0];i.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Z);let U=[t[0],Z];p&&U.push(t[2]);let we=u?l*F:I,te=u?I:l*F,me=y*C*g;e.compute(Ku(U,a,k,we,te,me,p,Q),{inputs:U})},Ol=(e,t)=>{let i=t.format==="NHWC",a=[e.inputs[0].reshape(i?[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&&a.push(e.inputs[2]);let u=[0,t.pads[0],0,t.pads[1]],p=[1].concat(t.strides),d=[1].concat(t.dilations),_=[1].concat(t.kernelShape),g=ls({...t,pads:u,strides:p,dilations:d,kernelShape:_},a);e.compute(Al(a,g,y=>i?[y[0],y[2],y[3]]:[]))},Dl=(e,t,i)=>{let a=i.format==="NHWC"?"channelsLast":"channelsFirst",u=ls(i,t),p=i.autoPad==="NOTSET"?i.pads:i.autoPad,d=El(t[0].dims,t[1].dims,i.strides,i.dilations,p,!1,a);e.compute(Pl(t,u,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],a))},Dn=(e,t)=>{pa(e.inputs,t),e.inputs[0].dims.length===3?Ol(e,t):e.inputs[0].dims.length===5?Dl(e,e.inputs,t):fa(e,e.inputs,t)}}),jl,Ll,Qu=V(()=>{sr(),Ci(),mr(),sn(),vn(),Ml(),ss(),jl=(e,t=!1,i,a,u=4)=>{let p=Q=>{switch(Q){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 ${a}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${Q} is not supported.`)}},d=e?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,_=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,g=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",C=e?"row":"col",k=e?"col":"row",l=` + 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 = ${C} / outWidth; + let outCol = ${C} % outWidth; + + let WRow = ${k} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${k} / 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(${g}) || fract(xR) > 0.0) { + return ${a}(0.0); + } + if (xC < 0.0 || xC >= f32(${y}) || fract(xC) > 0.0) { + return ${a}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${k} % inChannels; + ${d} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${u}];`,F=e?` + let col = colIn * ${u}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${l} + } + return ${a}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${l} + } + return ${a}(0.0);`,I=` + let col = colIn * ${u}; + 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); + ${p(u)} + } + return ${a}(0.0); + `,L=rn(i,a);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${a} { + ${e?F:I} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${a} { + ${e?I:F} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${a}) { + let col = colIn * ${u}; + 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])"}; + ${_} + ${ia(t)} + ${L} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${u}] = value; + } + }`},Ll=(e,t,i,a,u,p,d,_)=>{let g=t.format==="NHWC",y=g?e[0].dims[3]:e[0].dims[1],C=i[0],k=g?i[2]:i[3],l=g?i[1]:i[2],F=g?i[3]:i[1],I=g&&y%4===0&&y%3&&F%4===0,L=g?F:k*l,Q=g?k*l:F,Z=[8,8,1],U=a<=8?[4,1,1]:[4,4,1],we=[Math.ceil(L/Z[0]/U[0]),Math.ceil(Q/Z[1]/U[1]),Math.ceil(C/Z[2]/U[2])];qr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${we}`);let te=I?4:1,me=Math.max(Z[0]*te,Z[1]),it=I?4:1,Ye=[t.kernelShape[g?1:2],t.kernelShape[g?2:3]],Mt=[Ye[0]+(t.dilations[0]<=1?0:(Ye[0]-1)*(t.dilations[0]-1)),Ye[1]+(t.dilations[1]<=1?0:(Ye[1]-1)*(t.dilations[1]-1))],Gt=[Mt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),Mt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Bt=[{type:6,data:a},{type:6,data:u},{type:6,data:p},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Ye},{type:6,data:Gt}];nn(t,Bt),Bt.push(...Rt(e[0].dims,e[1].dims));let gr=["rank","rank"];d&&(Bt.push(...Rt(e[2].dims)),gr.push("rank")),Bt.push(...Rt(i));let Mr=Ur=>{let Ir=mt("x",e[0].dataType,e[0].dims.length,it),Sr=mt("w",e[1].dataType,e[1].dims.length,1),ri=Jt("result",e[0].dataType,i.length,it),Kr=[Ir,Sr],Wt="";if(d){let lt=mt("bias",e[2].dataType,e[2].dims.length,it);Kr.push(lt),Wt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${lt.type.value} { + return bias[coords.${g?"w":"y"}${I?"/ 4":""}]; + }`}let pr=[{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:Ye.length},{name:"pads",type:"i32",length:Gt.length}];Xi(t,pr);let cr=zr(e[0].dataType,1);if(cr!=="f16"&&cr!=="f32")throw new Error(`elemType ${cr} is not supported.`);return` + ${na("uniforms.result_strides")} + ${Ur.registerUniforms(pr).declareVariables(...Kr,ri)}; + ${Wt} + ${jl(g,d,t,Ir.type.value,te)} + ${I?rs(U,Z,cr,void 0,!g,me):is(U,Z,cr,void 0,!g,me,!1,void 0,_)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${U};${Z};${I}`,inputDependencies:gr},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:we[0],y:we[1],z:we[2]},programUniforms:Bt}),getShaderSource:Mr}}}),ma,Bn,Dd=V(()=>{sr(),Ci(),lr(),mr(),ma=(e,t,i,a,u,p=!1,d,_,g=!1)=>{let y=g?1:2,C=g?2:3,k=g?3:1,l=p?2:1,F=` + fn setOutputAtIndex(flatIndex : u32, value : ${p?`vec4<${d}>`:d}) { + result[flatIndex] = ${p?`vec4<${d}>`:d}(value); + }`;a&&(F+=` + fn getBiasByOutputCoords(coords : vec4) -> ${p?`vec4<${d}>`:d} { + return bias[coords.${g?"w":"y"}${p?"/ 4":""}]; + }`);let I=p?4:1,L=mt("W",t[1].dataType,t[1].dims.length,I),Q=mt("Dy",t[0].dataType,t[0].dims.length,I),Z=[Q,L];a&&Z.push(mt("bias",t[2].dataType,[i[k]].length,I));let U=Jt("result",t[0].dataType,i.length,I),we=`{ + let batch: u32 = ${u?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${u?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${u?"global_id.y":"workgroup_id.y"} * ${l}; + let d1: u32 = ${u?"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, ${l}>; + for (var i = 0; i < ${l}; i++) { + dotProd[i] = vec4<${d}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${d}(dyCorner.x) + ${d}(wR)) / ${d}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${d}(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 = (${d}(dyCorner.y) + ${d}(wC)) / ${d}(uniforms.strides.y); + let dyC2 = (${d}(dyCorner.y) + 1.0 + ${d}(wC)) / ${d}(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 >= ${d}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${d}(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 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${Q.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${Q.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${k}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${Q.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(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 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${L.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${Q.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${l}; i = i + 1) { + let value = dotProd[i] + ${a?"bias[c+i]":`vec4<${d}>(0.0)`}; + ${U.set("batch","r","c + i","d1","value")}; + } + }`,te=` + let outputIndices = ${U.offsetToIndices("global_idx")}; + let batch = ${U.indicesGet("outputIndices",0)}; + let d1 = ${U.indicesGet("outputIndices",k)}; + let r = ${U.indicesGet("outputIndices",y)}; + let c = ${U.indicesGet("outputIndices",C)}; + 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 = ${d}(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 = (${d}(dyRCorner) + ${d}(wR)) / ${d}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${d}(uniforms.Dy_shape[${y}]) || 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 = (${d}(dyCCorner) + ${d}(wC)) / ${d}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${d}(uniforms.Dy_shape[${C}]) || + 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 = ${g?Q.get("batch","idyR","idyC","inputChannel"):Q.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${L.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${a?"bias[d1]":`${d}(0.0)`}; + ${U.setByOffset("global_idx","value")}; + `;return` + ${e.registerUniforms(_).declareVariables(...Z,U)} + ${F} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${p?we:te}}`},Bn=(e,t,i)=>{let a=e.length>2,u=t.outputShape,p=tt.size(u),d=[Math.ceil(p/64),1,1];qr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let _=t.format==="NHWC",g=["rank","rank"],y=[t.strides[0],t.strides[1]],C=[t.kernelShape[_?1:2],t.kernelShape[_?2:3]],k=[t.dilations[0],t.dilations[1]],l=[C[0]+(t.dilations[0]<=1?0:(t.kernelShape[_?1:2]-1)*(t.dilations[0]-1)),C[1]+(t.dilations[1]<=1?0:(t.kernelShape[_?2:3]-1)*(t.dilations[1]-1))],F=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],I=!1,L=t.group,Q=e[1].dims,Z=Q[0]/L,U=Q[1],we=[{type:12,data:p},{type:12,data:y},{type:12,data:C},{type:12,data:k},{type:12,data:l},{type:6,data:F},{type:12,data:Z},{type:12,data:U},...Rt(e[0].dims,e[1].dims)];a&&(we.push(...Rt(e[2].dims)),g.push("rank")),we.push(...Rt(u));let te=d[1]===1&&d[2]===1,me=it=>{let Ye=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:y.length},{name:"filter_dims",type:"u32",length:C.length},{name:"dilations",type:"u32",length:C.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:F.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Mt=zr(e[0].dataType);return`${ma(it,e,u,a,te,I,Mt,Ye,_)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:i?i(u):u,dataType:e[0].dataType}],programUniforms:we}),getShaderSource:me}}}),Rl,Nl,_a,ga,Vl,wa,Ul,Wl,ya,Yu,Bd=V(()=>{Qu(),Dd(),sn(),wn(),Rl=(e,t,i,a,u,p)=>(e-1)*t+i+(a-1)*u+1-p,Nl=(e,t,i,a,u)=>{let p=Math.floor(e/2);t==="SAME_UPPER"?(i[a]=p,i[u]=e-p):t==="SAME_LOWER"&&(i[a]=e-p,i[u]=p)},_a=(e,t,i,a,u,p,d,_,g,y)=>{let C=e.length-2,k=y.length===0;if(g.length===0)for(let I=0;I{let i=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((k,l)=>k*l,1)===0){i.length=0;for(let k=2;kk+l,0)===0){let k=t[0].dims.length-2;g=new Array(k).fill(1)}let y=e.strides.slice();if(y.reduce((k,l)=>k+l,0)===0){let k=t[0].dims.length-2;y=new Array(k).fill(1)}_a(_,i,g,e.autoPad,e.group,u,y,a,d,p);let C=Object.assign({},e);return Object.assign(C,{kernelShape:i,pads:u,outputPadding:d,outputShape:p,dilations:g,strides:y}),C},Vl=e=>{let t=ra(e),i=e.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],u=e.dilations,p=e.group,d=e.kernelShape,_=e.pads,g=e.strides,y=e.wIsConst(),C=e.outputPadding,k=e.outputShape;return{autoPad:a,format:i,dilations:u,group:p,kernelShape:d,outputPadding:C,outputShape:k,pads:_,strides:g,wIsConst:y,...t,cacheKey:`${e.format};${t.activation};`}},wa=(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 i=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],a=e[1].dims[0];if(i!==a)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==u))throw new Error("invalid bias");let p=e[0].dims.length-2;if(t.dilations.reduce((d,_)=>d+_,0)>0&&t.dilations.length!==p)throw new Error(`dilations should be ${p}D`);if(t.strides.reduce((d,_)=>d+_,0)>0&&t.strides.length!==p)throw new Error(`strides should be ${p}D`);if(t.pads.reduce((d,_)=>d+_,0)>0&&t.pads.length!==p*2)throw new Error(`pads should be ${p*2}D`);if(t.outputPadding.length!==p&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${p}D`);if(t.kernelShape.reduce((d,_)=>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")},Ul=[2,3,1,0],Wl=(e,t,i)=>{let a=ga(i,t),u=i.format==="NHWC",p=a.outputShape,d=p[u?3:1],_=t[0].dims[u?3:1];if(a.group!==1||d===1&&_===1){e.compute(Bn(t,a));return}let g=p[u?1:2],y=p[u?2:3],C=t[1].dims[2],k=t[1].dims[3],l=u?g*y:d,F=u?d:g*y,I=C*k*_,L=!0,Q=e.kernelCustomData.wT??e.compute(Vi(t[1],Ul),{inputs:[1],outputs:[i.wIsConst?-2:-1]})[0];i.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Q);let Z=[t[0],Q],U=t.length===3;U&&(!u&&t[2].dims.length===1?Z.push(t[2].reshape([t[2].dims[0],1,1])):Z.push(t[2])),e.compute(Ll(Z,a,p,l,F,I,U,L),{inputs:Z})},ya=(e,t)=>{let i=t.format==="NHWC",a=[e.inputs[0].reshape(i?[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&&a.push(e.inputs[2]);let u=t.kernelShape;(u.length===0||u[0]===0)&&(u=[e.inputs[1].dims[2]]);let p=t.dilations;(p.length===0||p[0]===0)&&(p=[1]);let d=t.strides;(d.length===0||d[0]===0)&&(d=[1]);let _=t.pads;_.length===0&&(_=[0,0]),_=[0,_[0],0,_[1]],d=[1].concat(d),p=[1].concat(p),u=[1].concat(u);let g=ga({...t,pads:_,strides:d,dilations:p,kernelShape:u},a);e.compute(Bn(a,g,y=>i?[y[0],y[2],y[3]]:[y[0],y[1],y[3]]))},Yu=(e,t)=>{wa(e.inputs,t),e.inputs[0].dims.length===3?ya(e,t):Wl(e,e.inputs,t)}}),ba,va,Gl,Zu=V(()=>{sr(),lr(),Tr(),mr(),ba=(e,t,i,a)=>{let u=tt.size(t),p=t.length,d=mt("input",e,p),_=Jt("output",e,p),g=i.dataType===6?i.getInt32Array()[0]:Number(i.getBigInt64Array()[0]),y=tt.normalizeAxis(g,p),C=k=>{let l=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,F=Kt("uniforms.input_shape","uniforms.axis",p),I=a.reverse?l+(a.exclusive?" + 1":""):"0",L=a.reverse?F:l+(a.exclusive?"":" + 1");return` + ${k.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,_)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${_.offsetToIndices("global_idx")}; + var sum = ${_.type.value}(0); + let first : i32 = ${I}; + let last : i32 = ${L}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${_.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:a.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:12,data:y},...Rt(t,t)]}),getShaderSource:C}},va=(e,t)=>{let i=e.inputs[0].dims,a=e.inputs[0].dataType,u=e.inputs[1];e.compute(ba(a,i,u,t),{inputs:[0]})},Gl=e=>{let t=e.exclusive===1,i=e.reverse===1;return tr({exclusive:t,reverse:i})}}),Ma,ql,Kl,xa,Hl,Ju=V(()=>{sr(),lr(),Tr(),mr(),Ma=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.")},ql=(e,t,i,a)=>{let u=[];u.push(`fn perm(i: ${a.type.indices}) -> ${i.type.indices} { + var a: ${i.type.indices};`);for(let p=0;p{let i,a,u,p,d,_,g=t.format==="NHWC",y=t.blocksize,C=t.mode==="DCR";g?([i,a,u,p]=e.dims,d=C?[i,a,u,y,y,p/y**2]:[i,a,u,p/y**2,y,y],_=C?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([i,a,u,p]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],d=C?[i,y,y,p/y**2,a,u]:[i,p/y**2,y,y,a,u],_=C?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let k=e.reshape(d),l=k.dims.length,F=e.dataType,I=mt("a",F,l),L=Jt("output",F,l),Q=Z=>` + ${Z.registerUniform("output_size","u32").declareVariables(I,L)} + + ${ql(_,l,I,L)} + + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${L.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${L.setByOffset("global_idx",I.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:Z=>{let U=g?[i,a*y,u*y,p/y**2]:[i,p/y**2,a*y,u*y],we=tt.size(U),te=k.dims,me=tt.sortBasedOnPerm(te,_);return{outputs:[{dims:U,dataType:Z[0].dataType}],dispatchGroup:{x:Math.ceil(we/64)},programUniforms:[{type:12,data:we},...Rt(te,me)]}},getShaderSource:Q}},xa=(e,t)=>{Ma(e.inputs),e.compute(Kl(e.inputs[0],t))},Hl=e=>tr({blocksize:e.blocksize,mode:e.mode,format:e.format})}),jn,Ln,Ta,Vr,ed,td,rd,us,Xl,Ql,Yl,id=V(()=>{sr(),lr(),Tr(),mr(),jn="[a-zA-Z]|\\.\\.\\.",Ln="("+jn+")+",Ta="^"+Ln+"$",Vr="("+Ln+",)*"+Ln,ed="^"+Vr+"$",td=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let i=this.symbolToIndices.get(e);i===void 0?i=[t]:i.push(t),this.symbolToIndices.set(e,i)}},rd=class{constructor(e,t){var u;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[i,a]=t.includes("->")?t.split("->",2):[t,""];if(!i.match(RegExp(ed)))throw new Error("Invalid LHS term");if(i.split(",").forEach((p,d)=>{let _=e[d].dims.slice();if(!p.match(RegExp(Ta)))throw new Error("Invalid LHS term");let g=this.processTerm(p,!0,_,d);this.lhs.push(g)}),a==="")a+=[...this.symbolToInfo.entries()].filter(([p,d])=>d.count===1||p==="...").map(([p])=>p).join("");else if(!a.match(RegExp(Ln)))throw new Error("Invalid RHS");(u=a.match(RegExp(jn,"g")))==null||u.forEach(p=>{if(p==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(p);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(a,!1,this.outputDims)}addSymbol(e,t,i){let a=this.symbolToInfo.get(e);if(a!==void 0){if(a.dimValue!==t&&a.count!==1)throw new Error("Dimension mismatch");a.count++,a.inputIndices.push(i)}else a={count:1,dimValue:t,inputIndices:[i]};this.symbolToInfo.set(e,a)}processTerm(e,t,i,a=-1){let u=i.length,p=!1,d=[],_=0;if(!e.match(RegExp(Ta))&&!t&&e!=="")throw new Error("Invalid LHS term");let g=e.match(RegExp(jn,"g")),y=new td(a);return g==null||g.forEach((C,k)=>{if(C==="..."){if(p)throw new Error("Only one ellipsis is allowed per input term");p=!0;let l=u-g.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(d=i.slice(_,_+l),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let F=0;Fe+"_max",Xl=(e,t,i,a)=>{let u=e.map(y=>y.length).map((y,C)=>mt(`input${C}`,t,y)),p=tt.size(a),d=Jt("output",t,a.length),_=[...i.symbolToInfo.keys()].filter(y=>!i.rhs.symbolToIndices.has(y)),g=y=>{let C=[],k="var prod = 1.0;",l="var sum = 0.0;",F="sum += prod;",I=[],L=[],Q=[],Z=[],U=i.symbolToInfo.size===i.rhs.symbolToIndices.size;i.symbolToInfo.forEach((te,me)=>{var it;if(i.rhs.symbolToIndices.has(me)){let Ye=(it=i.rhs.symbolToIndices.get(me))==null?void 0:it[0];Ye!==void 0&&i.lhs.forEach((Mt,Gt)=>{if(te.inputIndices.includes(Gt)){let Bt=Mt.symbolToIndices.get(me);if(Bt===void 0)throw new Error("Invalid symbol error");Bt.forEach(gr=>{C.push(`${u[Gt].indicesSet(`input${Gt}Indices`,gr,d.indicesGet("outputIndices",Ye))}`)})}})}else i.lhs.forEach((Ye,Mt)=>{if(te.inputIndices.includes(Mt)){let Gt=Ye.symbolToIndices.get(me);if(Gt===void 0)throw new Error("Invalid symbol error");Gt.forEach(Bt=>{I.push(`${u[Mt].indicesSet(`input${Mt}Indices`,Bt,`${me}`)}`)}),Z.push(`prod *= ${u[Mt].getByIndices(`input${Mt}Indices`)};`)}}),L.push(`for(var ${me}: u32 = 0; ${me} < uniforms.${us(me)}; ${me}++) {`),Q.push("}")});let we=U?[...C,`let sum = ${u.map((te,me)=>te.getByIndices(`input${me}Indices`)).join(" * ")};`]:[...C,l,...L,...I,k,...Z,F,...Q];return` + ${y.registerUniforms(_.map(te=>({name:`${us(te)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,d)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${d.offsetToIndices("global_idx")}; + ${u.map((te,me)=>`var input${me}Indices: ${u[me].type.indices};`).join(` +`)} + ${we.join(` +`)}; + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:i.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let y=_.filter(k=>i.symbolToInfo.has(k)).map(k=>{var l;return{type:12,data:((l=i.symbolToInfo.get(k))==null?void 0:l.dimValue)||0}});y.push({type:12,data:p});let C=e.map((k,l)=>[...Rt(k)]).reduce((k,l)=>k.concat(l),y);return C.push(...Rt(a)),{outputs:[{dims:a,dataType:t}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:C}},getShaderSource:g}},Ql=(e,t)=>{let i=new rd(e.inputs,t.equation),a=i.outputDims,u=e.inputs.map((p,d)=>p.dims);e.compute(Xl(u,e.inputs[0].dataType,i,a))},Yl=e=>{let t=e.equation.replace(/\s+/g,"");return tr({equation:t})}}),Ca,ds,Zl,Jl,ka,jd=V(()=>{sr(),lr(),mr(),Ca=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,i=Array.from(e[1].getBigInt64Array(),Number),a=i.length{let i=e.length-t.length,a=[];for(let u=0;ue.length>t.length?ds(e,t):ds(t,e),Jl=e=>{let t=e[0].dims,i=Array.from(e[1].getBigInt64Array(),Number),a=Zl(t,i),u=e[0].dataType,p=u===9?4:1,d=Math.ceil(tt.size(a)/p),_=y=>{let C=mt("input",u,t.length,p),k=Jt("output",u,a.length,p),l;if(u===9){let F=(I,L,Q="")=>` + let outputIndices${L} = ${k.offsetToIndices(`outputOffset + ${L}u`)}; + let offset${L} = ${C.broadcastedIndicesToOffset(`outputIndices${L}`,k)}; + let index${L} = offset${L} / 4u; + let component${L} = offset${L} % 4u; + ${I}[${L}] = ${Q}(${C.getByOffset(`index${L}`)}[component${L}]); + `;l=` + let outputOffset = global_idx * ${p}; + var data = vec4(0); + ${F("data",0,"u32")} + ${F("data",1,"u32")} + ${F("data",2,"u32")} + ${F("data",3,"u32")} + ${k.setByOffset("global_idx","data")} + }`}else l=` + let outputIndices = ${k.offsetToIndices("global_idx")}; + let inputOffset = ${C.broadcastedIndicesToOffset("outputIndices",k)}; + ${k.setByOffset("global_idx",C.getByOffset("inputOffset"))} + }`;return` + ${y.registerUniform("vec_size","u32").declareVariables(C,k)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${l}`},g=[{type:12,data:d},...Rt(t,a)];return{name:"Expand",shaderCache:{hint:`${a.length}`,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:g})}},ka=e=>{Ca(e.inputs),e.compute(Jl(e.inputs),{inputs:[0]})}}),nd,eu,sd=V(()=>{sr(),lr(),mr(),Ys(),nd=e=>{let t=e[0].dataType,i=tt.size(e[0].dims),a=tt.size(e[1].dims),u=a%4===0,p=d=>{let _=mt("x",t,[1],4),g=mt("bias",t,[1],4),y=Jt("y",t,[1],4),C=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],k=F=>` + let bias${F}_offset: u32 = (global_idx * 4 + ${F}) % uniforms.bias_size; + let bias${F} = ${g.getByOffset(`bias${F}_offset / 4`)}[bias${F}_offset % 4];`,l=u?` + let bias = ${g.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${k(0)}${k(1)}${k(2)}${k(3)} + let bias = ${_.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(C).declareVariables(_,g,y)} + + ${Hs(Or(t))} + + ${d.mainStart(ki)} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${_.getByOffset("global_idx")}; + ${l} + let x_in = x + bias; + ${y.setByOffset("global_idx",Xs("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getShaderSource:p,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(i/4)},{type:12,data:a}],dispatchGroup:{x:Math.ceil(i/ki/4)}})}},eu=e=>{e.inputs.length<2||tt.size(e.inputs[1].dims)===0?el(e):e.compute(nd(e.inputs))}}),tu,ru,iu,nu,ad=V(()=>{sr(),lr(),Tr(),mr(),tu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},ru=(e,t)=>{let i=e[0].dims,a=e[1].dims,u=i.length,p=tt.normalizeAxis(t.axis,u),d=i.slice(0);d.splice(p,1,...a);let _=i[p],g=e[0].dataType===9?4:1,y=Math.ceil(tt.size(d)/g),C=[{type:12,data:y},{type:6,data:_},{type:12,data:p},...Rt(e[0].dims,e[1].dims,d)],k=l=>{let F=mt("data",e[0].dataType,e[0].dims.length,g),I=mt("inputIndices",e[1].dataType,e[1].dims.length),L=Jt("output",e[0].dataType,d.length,g),Q=U=>{let we=a.length,te=`var indicesIndices${U} = ${I.type.indices}(0);`;for(let me=0;me1?`indicesIndices${U}[${me}]`:`indicesIndices${U}`} = ${d.length>1?`outputIndices${U}[uniforms.axis + ${me}]`:`outputIndices${U}`};`;te+=` + var idx${U} = ${I.getByIndices(`indicesIndices${U}`)}; + if (idx${U} < 0) { + idx${U} = idx${U} + uniforms.axisDimLimit; + } + var dataIndices${U} : ${F.type.indices}; + `;for(let me=0,it=0;me1?`dataIndices${U}[${me}]`:`dataIndices${U}`} = u32(idx${U});`,it+=we):(te+=`${u>1?`dataIndices${U}[${me}]`:`dataIndices${U}`} = ${d.length>1?`outputIndices${U}[${it}]`:`outputIndices${U}`};`,it++);return te},Z;if(e[0].dataType===9){let U=(we,te,me="")=>` + let outputIndices${te} = ${L.offsetToIndices(`outputOffset + ${te}u`)}; + ${Q(te)}; + let offset${te} = ${F.indicesToOffset(`dataIndices${te}`)}; + let index${te} = offset${te} / 4u; + let component${te} = offset${te} % 4u; + ${we}[${te}] = ${me}(${F.getByOffset(`index${te}`)}[component${te}]); + `;Z=` + let outputOffset = global_idx * ${g}; + var value = vec4(0); + ${U("value",0,"u32")} + ${U("value",1,"u32")} + ${U("value",2,"u32")} + ${U("value",3,"u32")} + ${L.setByOffset("global_idx","value")} + `}else Z=` + let outputIndices = ${L.offsetToIndices("global_idx")}; + ${Q("")}; + let value = ${F.getByIndices("dataIndices")}; + ${L.setByOffset("global_idx","value")}; + `;return` + ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(F,I,L)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${Z} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:C}),getShaderSource:k}},iu=e=>tr({axis:e.axis}),nu=(e,t)=>{let i=e.inputs;tu(i),e.compute(ru(e.inputs,t))}}),su,au,ou,lu,od=V(()=>{sr(),lr(),Tr(),mr(),su=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.`)},au=(e,t)=>{let i=e[0].dims,a=e[0].dataType,u=i.length,p=e[1].dims,d=e[1].dataType,_=tt.normalizeAxis(t.axis,u),g=i[_],y=p.slice(0),C=tt.size(y),k=mt("input",a,u),l=mt("indicesInput",d,p.length),F=Jt("output",a,y.length),I=[{type:12,data:C},{type:6,data:g},{type:12,data:_}];return I.push(...Rt(i,p,y)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:I}),getShaderSource:L=>` + ${L.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,l,F)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${F.offsetToIndices("global_idx")}; + + var idx = ${l.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${k.type.indices}(outputIndices); + ${k.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${k.getByIndices("inputIndices")}; + + ${F.setByOffset("global_idx","value")}; + }`}},ou=e=>tr({axis:e.axis}),lu=(e,t)=>{let i=e.inputs;su(i),e.compute(au(e.inputs,t))}}),uu,du,cu,ld,pu=V(()=>{sr(),lr(),mr(),uu=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")},du=(e,t)=>{let i=e[0].dims.slice(),a=e[1].dims.slice(),[u,p,d]=Fr.getShapeOfGemmResult(i,t.transA,a,t.transB,e.length===3?e[2].dims:void 0),_=[u,p];if(!_)throw new Error("Can't use gemm on the given tensors");let g=tt.size(_),y=[{type:12,data:g},{type:12,data:u},{type:12,data:p},{type:12,data:d},{type:1,data:t.alpha},{type:1,data:t.beta}],C=["type","type"];e.length===3&&(y.push(...Rt(e[2].dims)),C.push("rank")),y.push(...Rt(_));let k=l=>{let F="";t.transA&&t.transB?F="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?F="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?F="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(F="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let I=t.alpha===1?"":"value *= uniforms.alpha;",L=mt("a",e[0].dataType,e[0].dims),Q=mt("b",e[1].dataType,e[1].dims),Z=L.type.value,U=null,we=[L,Q];e.length===3&&(U=mt("c",e[2].dataType,e[2].dims.length),we.push(U));let te=Jt("output",e[0].dataType,_.length);we.push(te);let me=[{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` + ${l.registerUniforms(me).declareVariables(...we)} + + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Z}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${F} + } + + ${I} + ${U!=null?`let cOffset = ${U.broadcastedIndicesToOffset("vec2(m, n)",te)}; value += ${Z}(uniforms.beta) * ${U.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:_,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y}),getShaderSource:k}},cu=e=>{let t=e.transA,i=e.transB,a=e.alpha,u=e.beta;return{transA:t,transB:i,alpha:a,beta:u,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},ld=(e,t)=>{uu(e.inputs),e.compute(du(e.inputs,t))}}),yi,hu,fu,$a,mu,Rn,_u,gu=V(()=>{sr(),lr(),Tr(),N(),Jn(),mr(),wn(),yi=(e,t)=>e.length>t&&e[t].dims.length>0&&tt.size(e[t].dims)>0?e[t]:void 0,hu=(e,t)=>{let i=e[0],a=yi(e,1),u=yi(e,2),p=yi(e,3),d=yi(e,4),_=yi(e,5),g=yi(e,6),y=yi(e,7);if(i.dims.length!==3&&i.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let C=!1,k=i.dims[0],l=i.dims[1],F=i.dims.length===3?C?i.dims[2]/3:i.dims[2]:t.numHeads*i.dims[4],I=l,L=0,Q=0,Z=Math.floor(F/t.numHeads);if(g&&y){if(g.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(g.dims[0]!==k||g.dims[1]!==t.numHeads||g.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(y.dims[0]!==k||y.dims[1]!==t.numHeads||y.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(g.dims[2]!==y.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(y.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');L=g.dims[2],Q=g.dims[2]}else if(g||y)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U;if(a){if(i.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(a.dims.length<3||a.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(i.dims[0]!==a.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(a.dims.length===3){if(a.dims[2]!==i.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');U=2,I=a.dims[1]}else if(a.dims.length===5){if(a.dims[2]!==t.numHeads||a.dims[3]!==2||a.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');U=5,I=a.dims[1]}else{if(a.dims[1]!==t.numHeads||a.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');U=0,I=a.dims[2]}}else{if(i.dims.length!==3&&i.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(i.dims.length===5&&(i.dims[2]!==t.numHeads||i.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');U=3}if(p){if(p.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(u&&i.dims.length===5&&i.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let we=0;if(d){we=8;let Mt=d.dims;throw Mt.length===1?Mt[0]===k?we=1:Mt[0]===3*k+2&&(we=3):Mt.length===2&&Mt[0]===k&&Mt[1]===I&&(we=5),we===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let te=!1,me=F;if(u){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(i.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(I!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=u.dims[2]}else{if(I!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=u.dims[1]*u.dims[3],te=!0}}let it=L+I,Ye=!1;if(d)throw new Error("Key padding mask is not supported");if(_){if(_.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(_.dims[0]!==k&&_.dims[0]!==1||_.dims[1]!==t.numHeads||_.dims[2]!==l||_.dims[3]!==it)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:k,sequenceLength:l,pastSequenceLength:L,kvSequenceLength:I,totalSequenceLength:it,maxSequenceLength:Q,inputHiddenSize:0,hiddenSize:F,vHiddenSize:me,headSize:Z,vHeadSize:Math.floor(me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:we,scale:t.scale,broadcastResPosBias:Ye,passPastInKv:te,qkvFormat:U}},fu=e=>tr({...e}),$a=tr({perm:[0,2,1,3]}),mu=(e,t,i,a,u,p,d)=>{let _=[a,u,p],g=tt.size(_),y=[{type:12,data:g},{type:12,data:d},{type:12,data:p}],C=k=>{let l=Jt("qkv_with_bias",t.dataType,_),F=mt("qkv",t.dataType,_),I=mt("bias",i.dataType,_),L=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${k.registerUniforms(L).declareVariables(F,I,l)} + ${k.mainStart()} + ${k.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:_,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y}),getShaderSource:C},{inputs:[t,i],outputs:[-1]})[0]},Rn=(e,t,i,a,u,p,d,_)=>{let g=p;if(d){if(a===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return g=mu(e,p,d,t,a,i*u,_),g=g.reshape([t,a,i,u]),e.compute(Vi(g,$a.perm),{inputs:[g],outputs:[-1]})[0]}else return p.dims.length===3&&(g=p.reshape([t,a,i,u])),e.compute(Vi(g,$a.perm),{inputs:[g],outputs:[-1]})[0]},_u=(e,t)=>{let i=hu(e.inputs,t),a=e.inputs[0],u=yi(e.inputs,1),p=yi(e.inputs,2),d=yi(e.inputs,3),_=yi(e.inputs,4),g=yi(e.inputs,5),y=yi(e.inputs,6),C=yi(e.inputs,7);if(a.dims.length===5)throw new Error("Packed QKV is not implemented");if((u==null?void 0:u.dims.length)===5)throw new Error("Packed KV is not implemented");let k=u&&p&&u.dims.length===4&&p.dims.length===4,l=Rn(e,i.batchSize,i.numHeads,i.sequenceLength,i.headSize,a,d,0);if(k)return yn(e,l,u,p,_,void 0,y,C,g,i,t);if(!u||!p)throw new Error("key and value must be provided");let F=Rn(e,i.batchSize,i.numHeads,i.kvSequenceLength,i.headSize,u,d,i.hiddenSize),I=Rn(e,i.batchSize,i.numHeads,i.kvSequenceLength,i.vHeadSize,p,d,2*i.hiddenSize);yn(e,l,F,I,_,void 0,y,C,g,i,t)}}),Sa,wu,yu,Ea,bu,vu=V(()=>{sr(),lr(),mr(),Sa=e=>Array.from(e.getBigInt64Array(),Number),wu=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(Sa(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")},yu=(e,t)=>{let i=[];for(let a=0;a{let i=e[0].dims,a=t??Sa(e[1]),u=yu(i,a),p=tt.size(u),d=e[0].dataType,_=mt("input",d,i.length),g=Jt("output",d,u.length),y=C=>` + const inputShape = ${_.indices(...i)}; + ${C.registerUniform("output_size","u32").declareVariables(_,g)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${g.offsetToIndices("global_idx")}; + var input_indices: ${_.type.indices}; + for (var i = 0; i < ${i.length}; i++) { + let input_dim_i = ${_.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${g.indicesGet("output_indices","i")} % input_dim_i; + + ${_.indicesSet("input_indices","i","input_dim_value")} + } + ${g.setByOffset("global_idx",_.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${a}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...Rt(e[0].dims,u)]}),getShaderSource:y}},bu=e=>{wu(e.inputs),e.compute(Ea(e.inputs),{inputs:[0]})}}),Mu,Pa,xu,Tu,Aa,Cu,ud=V(()=>{sr(),lr(),Tr(),Jn(),mr(),gu(),vu(),wn(),Mu=(e,t)=>{let i=e[0],a=e[1],u=e[2],p=e[3],d=e[4];if(i.dims.length!==3&&i.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let _=!1,g=i.dims[0],y=i.dims[1],C=i.dims.length===3?_?i.dims[2]/3:i.dims[2]:t.numHeads*i.dims[4],k=y,l=0,F=0,I=Math.floor(C/t.numHeads),L=p&&p.dims.length!==0,Q=d&&d.dims.length!==0,Z=!0;if(L&&Q){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=p.dims[1],F=p.dims[1]}else if(L||Q)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let U;if(a){if(i.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(a.dims.length<3||a.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(i.dims[0]!==a.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(a.dims.length===3){if(i.dims[2]%a.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');U=2,k=a.dims[1]}else if(a.dims.length===5){if(a.dims[2]!==t.numHeads||a.dims[3]!==2||a.dims[4]!==I)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');U=5,k=a.dims[1]}else{if(a.dims[1]!==t.numHeads||a.dims[3]!==I)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');U=0,k=a.dims[2]}}else{if(i.dims.length!==3&&i.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(i.dims.length===5&&(i.dims[2]!==t.numHeads||i.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');U=3}let we=0,te=!1,me=C;if(u){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(i.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(k!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=u.dims[2]}else{if(k!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=u.dims[1]*u.dims[3],te=!0}}let it=l+k;return{batchSize:g,sequenceLength:y,pastSequenceLength:l,kvSequenceLength:k,totalSequenceLength:it,maxSequenceLength:F,inputHiddenSize:0,hiddenSize:C,vHiddenSize:me,headSize:I,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:we,scale:t.scale,broadcastResPosBias:!1,passPastInKv:te,qkvFormat:U,isPastkvBSNH:Z}},Pa=(e,t,i,a)=>{let u=[a.batchSize,a.totalSequenceLength,a.kvNumHeads,a.headSize],p=4,d=tt.size(u)/p,_=a.totalSequenceLength,g=Jt("present_kv",i,u.length,p),y=mt("new_kv",e.dataType,e.dims.length,p),C=t?mt("past_kv",t.dataType,t.dims.length,p):void 0,k=Math.ceil(a.headSize/p),l={x:_,y:e.dims[0],z:1},F=t?["rank","rank"]:["rank"],I=[{type:12,data:d},{type:12,data:a.pastSequenceLength},{type:12,data:a.kvSequenceLength},{type:12,data:a.totalSequenceLength}],L=[y];C?(I.push(...Rt(e.dims),...Rt(t.dims),...Rt(u)),L.push(C)):I.push(...Rt(e.dims),...Rt(u));let Q=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],Z=` 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];`,U=` 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];`,we=t?`if (s < past_seqlen) { + ${Z} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${U} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${U} + }`,te=me=>` + + ${me.registerUniforms(Q).declareVariables(...L,g)} + ${me.mainStart([k,a.kvNumHeads,1])} + ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${g.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 = ${a.kvNumHeads}u; + let H = ${k}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${a.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; + ${we} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${a.kvNumHeads}${k}${!!t}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:u,dataType:i}],dispatchGroup:l,programUniforms:I}),getShaderSource:te}},xu=e=>tr({...e}),Tu=tr({perm:[0,2,1,3]}),Aa=(e,t,i,a,u)=>{let p=t,d=a.kvNumHeads,_=a.nReps;return t.dims.length===3&&a.kvSequenceLength!==0&&(p=t.reshape([a.batchSize,a.kvSequenceLength,d,a.headSize])),i?p=e.compute(Pa(p,i,p.dataType,a),{inputs:[p,i],outputs:[a.isPastkvBSNH?u:-1]})[0]:p=e.compute(Pa(p,void 0,p.dataType,a),{inputs:[p],outputs:[a.isPastkvBSNH?u:-1]})[0],_!==1&&(p=e.compute(Ea([p],[1,1,1,_]),{inputs:[p],outputs:[-1]})[0],p=p.reshape([a.batchSize,a.totalSequenceLength,d*_,a.headSize])),e.compute(Vi(p,Tu.perm),{inputs:[p],outputs:[-1]})[0]},Cu=(e,t)=>{var g;let i=Mu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((g=e.inputs[1])==null?void 0:g.dims.length)===5)throw new Error("Packed KV is not implemented");let a=Rn(e,i.batchSize,i.numHeads,i.sequenceLength,i.headSize,e.inputs[0],void 0,0),u=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,p=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=Aa(e,e.inputs[1],u,i,1),_=Aa(e,e.inputs[2],p,i,2);yn(e,a,d,_,void 0,void 0,void 0,void 0,void 0,i,t)}}),ku,$u,Su,Eu,Ld=V(()=>{sr(),lr(),mr(),ku=(e,t)=>{let i=e[0].dims,a=i,u=2,p=tt.sizeToDimension(i,u),d=tt.sizeFromDimension(i,u),_=$r(d),g=d/_,y=[i[0],i[1],g],C=["rank","type","type"],k=[{type:12,data:d},{type:12,data:g}];k.push(...Rt(y,y));let l=F=>{let I=mt("x",e[0].dataType,y.length,_),L=mt("scale",e[1].dataType,e[1].dims),Q=mt("bias",e[2].dataType,e[2].dims),Z=Jt("output",e[0].dataType,y.length,_),U=[I,L,Q,Z],we=I.type.value,te=_===1?"f32":`vec${_}`,me=64,it=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${te}, ${me}>; + const workgroupSize = ${me}u; + ${F.registerUniforms(it).declareVariables(...U)} + ${F.mainStart(me)} + 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 = ${te}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${te}(${I.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 = ${$i("workgroupShared[0]",_)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${te}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${te}(${I.get("batch","channel","h")}) - ${te}(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 = ${$i("workgroupShared[0]",_)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); + let channelScale = invStdDev * f32(${L.getByOffset("channel")}); + let channelShift = f32(${Q.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${I.get("batch","channel","h")} * ${we}(${te}(channelScale)) + ${we}(${te}(channelShift)); + ${Z.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${_}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:p},programUniforms:k}),getShaderSource:l}},$u=(e,t,i,a,u,p,d,_)=>{let g=$r(d),y=64,C=g===1?"vec2f":`mat2x${g}f`,k=g===1?"f32":`vec${g}f`,l=(it,Ye)=>`${C}(${it}, ${Ye})`,F=u*d/g,I=Math.ceil(p/y),L=["type"],Q=[{type:12,data:I},{type:12,data:p},{type:12,data:Math.floor(d/g)},{type:12,data:Math.floor(p*d/g)}],Z=it=>{let Ye=mt("input",t.dataType,t.dims,g);return` + ${it.declareVariables(Ye)} + @group(0) @binding(1) var output : array<${C}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${it.mainStart(y)} + let currentImageNumber = global_idx / ${y} / uniforms.C; + let currentChannelNumber = (global_idx / ${y}) % 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 = ${Nr("f32",g)}; + var squaredSum = ${Nr("f32",g)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${k}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${l("sum","squaredSum")}; + }`},U=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${g}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:[u,d,y,2],dataType:1}],dispatchGroup:{x:u*d/g},programUniforms:Q}),getShaderSource:Z},{inputs:[t],outputs:[-1]})[0],we=[{type:12,data:F},{type:12,data:p},{type:12,data:Math.floor(d/g)},{type:12,data:Math.floor(y*d/g)}],te=["type","type","type"],me=it=>{let Ye=mt("scale",i.dataType,i.dims,g),Mt=mt("bias",a.dataType,a.dims,g);return` + @group(0) @binding(0) var input : array<${C}>; + @group(0) @binding(1) var scale : array<${Ye.type.storage}>; + @group(0) @binding(2) var bias : array<${Mt.type.storage}>; + @group(0) @binding(3) var output : array<${C}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${it.mainStart()} + ${it.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 = ${Nr("f32",g)}; + var squaredSum = ${Nr("f32",g)}; + for (var i: u32 = 0; i < min(${y}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${y}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${_})); + let channelScale = invStdDev * ${k}(scale[currentChannelNumber]); + let channelShift = ${k}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${l("channelScale","channelShift")}; + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${g};${_}`,inputDependencies:te},getRunData:()=>({outputs:[{dims:[u,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:we}),getShaderSource:me},{inputs:[U,i,a],outputs:[-1]})[0]},Su=(e,t,i)=>{let a=t[0].dims,u=a,p=a[0],d=a[a.length-1],_=tt.sizeFromDimension(a,1)/d,g=$r(d),y=tt.size(u)/g,C=[{type:12,data:_},{type:12,data:Math.floor(d/g)}],k=["type","type"],l=$u(e,t[0],t[1],t[2],p,_,d,i.epsilon),F=I=>{let L=zr(t[0].dataType),Q=g===1?"vec2f":`mat2x${g}f`,Z=g===1?L:`vec${g}<${L}>`,U=mt("input",t[0].dataType,t[0].dims,g),we=Jt("output",t[0].dataType,u,g);return` + @group(0) @binding(0) var input : array<${U.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${Q}>; + @group(0) @binding(2) var output : array<${we.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${I.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], ${Z}(scale[0]), ${Z}(scale[1])); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${g}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:C}),getShaderSource:F},{inputs:[t[0],l]})},Eu=(e,t)=>{t.format==="NHWC"?Su(e,e.inputs,t):e.compute(ku(e.inputs,t))}}),wr,Pu,oi,hi=V(()=>{sr(),lr(),mr(),wr=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Pu=(e,t,i)=>{let a=t.simplified,u=e[0].dims,p=e[1],d=!a&&e[2],_=u,g=tt.normalizeAxis(t.axis,u.length),y=tt.sizeToDimension(u,g),C=tt.sizeFromDimension(u,g),k=tt.size(p.dims),l=d?tt.size(d.dims):0;if(k!==C||d&&l!==C)throw new Error(`Size of X.shape()[axis:] == ${C}. + Size of scale and bias (if provided) must match this. + Got scale size of ${k} and bias size of ${l}`);let F=[];for(let me=0;me1,U=i>2,we=me=>{let it=zr(e[0].dataType),Ye=[mt("x",e[0].dataType,e[0].dims,I),mt("scale",p.dataType,p.dims,I)];d&&Ye.push(mt("bias",d.dataType,d.dims,I)),Ye.push(Jt("output",e[0].dataType,_,I)),Z&&Ye.push(Jt("mean_data_output",1,F)),U&&Ye.push(Jt("inv_std_output",1,F));let Mt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${me.registerUniforms(Mt).declareVariables(...Ye)} + ${me.mainStart()} + ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Nr("f32",I)}; + var mean_square_vector = ${Nr("f32",I)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Qr(it,I,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${$i("mean_vector",I)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${$i("mean_square_vector",I)} / uniforms.norm_size ${a?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Qr(it,I,"x[j + offset]")}; + let f32scale = ${Qr(it,I,"scale[j]")}; + output[j + offset] = ${Ye[0].type.value}((f32input ${a?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Qr(it,I,"bias[j]")}`:""} + ); + } + + ${Z?"mean_data_output[global_idx] = mean":""}; + ${U?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},te=[{dims:_,dataType:e[0].dataType}];return Z&&te.push({dims:F,dataType:1}),U&&te.push({dims:F,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${I};${i};${a}`,inputDependencies:L},getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(y/64)},programUniforms:Q}),getShaderSource:we}},oi=(e,t)=>{wr(e.inputs),e.compute(Pu(e.inputs,t,e.outputCount))}}),fi,ln,dd,Au,cd=V(()=>{sr(),lr(),Tr(),mr(),fi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let i=e[0],a=i.dims.length;if(i.dims[a-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let u=Math.floor((t.k+t.blockSize-1)/t.blockSize),p=t.blockSize/8*t.bits,d=e[1];if(!tt.areEqual(d.dims,[t.n,u,p]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let _=e[2].dims;if(tt.size(_)!==t.n*u)throw new Error("scales input size error.");if(e.length===4){let g=e[3].dims,y=t.bits>4?t.n*u:t.n*Math.floor((u+1)/2);if(tt.size(g)!==y)throw new Error("zeroPoints input size error.")}},ln=(e,t,i,a)=>{let u=e[0].dims,p=u.length,d=Math.floor((t.k+t.blockSize-1)/t.blockSize),_=u[p-2],g=t.k,y=t.n,C=u.slice(0,p-2),k=tt.size(C),l=t.blockSize/8*t.bits/4,F=e[0].dataType,I=$r(_),L=$r(t.k),Q=$r(l),Z=Ki(F,_*d),U=Math.floor(a/Z),we=d<=i[0]&&U>0,te=!we||U>=4?$r(y):U>=2&&$r(y)>=2?2:1,me=C.concat([_,y]),it=tt.size(me)/te/I,Ye=we?[]:[{type:12,data:it},{type:12,data:t.blockSize}],Mt=[k,_,g/L],Gt=tt.convertShape(e[1].dims).slice();Gt.splice(-1,1,l/Q),Ye.push(...Rt(Mt)),Ye.push(...Rt(Gt)),Ye.push(...Rt(e[2].dims)),e.length===4&&Ye.push(...Rt(tt.convertShape(e[3].dims)));let Bt=[k,_,y/te];Ye.push(...Rt(Bt));let gr=Mr=>{let Ur=Mt.length,Ir=mt("a",e[0].dataType,Ur,L),Sr=mt("b",12,Gt.length,Q),ri=mt("scales",e[2].dataType,e[2].dims.length),Kr=[Ir,Sr,ri],Wt=e.length===4?mt("zero_points",12,e[3].dims.length):void 0;Wt&&Kr.push(Wt);let pr=Bt.length,cr=Jt("output",e[0].dataType,pr,te),lt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],qt=zr(e[0].dataType),fr=(()=>{switch(L){case 1:return`array<${qt}, 8>`;case 2:return`mat4x2<${qt}>`;case 4:return`mat2x4<${qt}>`;default:throw new Error(`${L}-component is not supported.`)}})(),Yr=` + for (var word: u32 = 0; word < ${l}; word += ${Q}) { + ${Sr.indicesSet("b_indices","2","word")}; + let b_data = ${Sr.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${Q}; i++) { + let b_value: u32 = ${Q===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 = ${fr}(${Array.from({length:4},(gi,Oi)=>`${qt}(b_value_lower[${Oi}]), ${qt}(b_value_upper[${Oi}])`).join(", ")}); + let b_dequantized_values = ${L===1?`${fr}(${Array.from({length:8},(gi,Oi)=>`(b_quantized_values[${Oi}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${fr}(${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 < ${we?_:I}u; m++) { + ${Ir.indicesSet("a_indices",Ur-2,we?"m":`row * ${I} + m`)}; + ${Ir.indicesSet("a_indices",Ur-1,"word_offset")}; + var input_offset = ${Ir.indicesToOffset("a_indices")}; + var a_data: ${fr}; + for (var j: u32 = 0; j < ${8/L}; j++) { + a_data[j] = ${Ir.getByOffset("input_offset")}; + input_offset++; + } + ${we?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${te>1?"[c]":""} += ${Array.from({length:8/L},(gi,Oi)=>`${L===1?`a_data[${Oi}] * b_dequantized_values[${Oi}]`:`dot(a_data[${Oi}], b_dequantized_values[${Oi}])`}`).join(" + ")}; + } + word_offset += ${8/L}; + } + }`,ai=Wt?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${Wt.getByOffset("zero_point_index")}; + }`:"";return we?` + var workgroup_shared: array<${cr.type.value}, ${_*d}>; + ${Mr.declareVariables(...Kr,cr)} + ${Mr.mainStart([d,1,1])} + var a_indices: ${Ir.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${Ir.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${te}; c++) { + let col_times_components_plus_c = col * ${te} + c; + ${Wt?` + var zero_point_bytes_per_col: u32 = (${d} + 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 = ${Wt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${Sr.type.indices}; + ${Sr.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 * ${d} + block; + let scale = ${ri.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${qt}(${Wt?"(zero_point_word) & 0xFu":8}); + ${Sr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${t.blockSize/L}; + var workgroup_shared_offset: u32 = block * ${_}; + ${Yr} + } + workgroupBarrier(); + var output_indices: ${cr.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(_/d)}; + ${cr.indicesSet("output_indices","0","batch")}; + ${cr.indicesSet("output_indices",pr-1,"col")}; + ${cr.indicesSet("output_indices",pr-2,"local_id.x * elements_per_thread")}; + var output_offset = ${cr.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${_}) { + var output_value: ${cr.type.value} = ${cr.type.value}(0); + var workgroup_shared_offset: u32 = row; + for (var b: u32 = 0u; b < ${d}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${_}; + } + ${cr.setByOffset("output_offset","output_value")}; + output_offset += ${y/te}; + } + } + }`:` + ${Mr.registerUniforms(lt).declareVariables(...Kr,cr)} + ${Mr.mainStart()} + ${Mr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${cr.type.value}, ${I}>; + var output_indices = ${cr.offsetToIndices("global_idx")}; + var col = ${cr.indicesGet("output_indices",pr-1)}; + var row = ${cr.indicesGet("output_indices",pr-2)}; + var a_indices: ${Ir.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 + ${Wt?` + var zero_point_abs_offset = col * ${te} * ((${d} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${Wt.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${d*te}; + var b_indices: ${Sr.type.indices}; + for (var c: u32 = 0; c < ${te}; c++) { + ${Sr.indicesSet("b_indices","0",`col * ${te} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${d}; block++) { + // The scale and zero points are computed per block. + let scale = ${ri.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${qt}(${Wt?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${Sr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Yr} + scale_index++; + ${ai} + block_offset += uniforms.block_size / ${L}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${Wt?`if (zero_point_offset % 8 > 0) { + ${ai} + }`:""} + } + for (var k: u32 = 0u; k < ${I}u; k++) { + ${cr.indicesSet("output_indices",pr-2,`${I} * row + k`)}; + ${cr.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:we?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${_};${F};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:me,dataType:F}],name:we?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:we?{x:1,y:Math.ceil(y/te),z:k}:{x:Math.ceil(it/64)},programUniforms:Ye}),getShaderSource:gr}},dd=(e,t)=>{fi(e.inputs,t);let i=e.getMaxComputeWorkgroupSizes(),a=e.getMaxComputeWorkgroupStoragesize();e.compute(ln(e.inputs,t,i,a))},Au=e=>tr(e)}),M,T,O,ie,Ue,He,wt,Lt,er,yr=V(()=>{sr(),lr(),mr(),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].")}},T=(e,t,i)=>{let a="";for(let u=t-1;u>=0;--u)a+=` + k = i32(${e.indicesGet("indices",u)}) - ${Kt("uniforms.pads",u,i)}; + if (k < 0) { + break; + } + if (k >= i32(${Kt("uniforms.x_shape",u,t)})) { + break; + } + offset += k * i32(${Kt("uniforms.x_strides",u,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + } + `},O=(e,t,i)=>{let a="";for(let u=t-1;u>=0;--u)a+=` + k = i32(${e.indicesGet("indices",u)}) - ${Kt("uniforms.pads",u,i)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Kt("uniforms.x_shape",u,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Kt("uniforms.x_shape",u,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Kt("uniforms.x_strides",u,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},ie=(e,t,i)=>{let a="";for(let u=t-1;u>=0;--u)a+=` + k = i32(${e.indicesGet("indices",u)}) - ${Kt("uniforms.pads",u,i)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Kt("uniforms.x_shape",u,t)})) { + k = i32(${Kt("uniforms.x_shape",u,t)}) - 1; + } + offset += k * i32(${Kt("uniforms.x_strides",u,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},Ue=(e,t,i)=>{let a="";for(let u=t-1;u>=0;--u)a+=` + k = i32(${e.indicesGet("indices",u)}) - ${Kt("uniforms.pads",u,i)}; + if (k < 0) { + k += i32(${Kt("uniforms.x_shape",u,t)}]); + } + if (k >= i32(${Kt("uniforms.x_shape",u,t)})) { + k -= i32(${Kt("uniforms.x_shape",u,t)}); + } + offset += k * i32(${Kt("uniforms.x_strides",u,t)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},He=(e,t,i)=>{switch(i.mode){case 0:return T(e,t,i.pads.length);case 1:return O(e,t,i.pads.length);case 2:return ie(e,t,i.pads.length);case 3:return Ue(e,t,i.pads.length);default:throw new Error("Invalid mode")}},wt=(e,t)=>{let i=tt.padShape(e[0].dims.slice(),t.pads),a=e[0].dims,u=tt.size(i),p=[{type:12,data:u},{type:6,data:t.pads}];t.mode===0&&p.push({type:e[0].dataType,data:t.value}),p.push(...Rt(e[0].dims,i));let d=["rank"],_=g=>{let y=Jt("output",e[0].dataType,i.length),C=mt("x",e[0].dataType,a.length),k=C.type.value,l=He(y,a.length,t),F=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&F.push({name:"constant_value",type:k}),` + ${g.registerUniforms(F).declareVariables(C,y)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${y.offsetToIndices("global_idx")}; + + var value = ${k}(0); + ${l} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(tt.size(i)/64)},programUniforms:p}),getShaderSource:_}},Lt=(e,t)=>{if(e.length>1){let i=e[1].getBigInt64Array(),a=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,u=e[0].dims.length,p=new Int32Array(2*u).fill(0);if(e.length>=4){let _=e[3].getBigInt64Array();for(let g=0;g<_.length;g++)p[Number(_[g])]=Number(i[g]),p[Number(_[g])+u]=Number(i[g+_.length])}else i.forEach((_,g)=>p[Number(g)]=Number(_));let d=[];return p.forEach(_=>d.push(_)),{mode:t.mode,value:a,pads:d}}else return t},er=(e,t)=>{M(e.inputs);let i=Lt(e.inputs,t);e.compute(wt(e.inputs,i),{inputs:[0]})}}),_r,Lr,br,kr,vr,Cr,Ar,Wr,bi,Mi,Yi,mi,si,_i,cs,ps,Ia,Rd,Ui,Nn=V(()=>{z(),sr(),lr(),mr(),_r=e=>{if(j.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Lr=(e,t,i)=>{let a=t.format==="NHWC",u=e.dims.slice();a&&u.splice(1,0,u.pop());let p=Object.hasOwnProperty.call(t,"dilations"),d=t.kernelShape.slice(),_=t.strides.slice(),g=p?t.dilations.slice():[],y=t.pads.slice();Pi.adjustPoolAttributes(i,u,d,_,g,y);let C=Pi.computePoolOutputShape(i,u,_,g,d,y,t.autoPad),k=Object.assign({},t);p?Object.assign(k,{kernelShape:d,strides:_,pads:y,dilations:g,cacheKey:t.cacheKey}):Object.assign(k,{kernelShape:d,strides:_,pads:y,cacheKey:t.cacheKey});let l=C.slice();return l.push(l.splice(1,1)[0]),[k,a?l:C]},br=(e,t)=>{let i=t.format==="NHWC",a=tt.size(e),u=tt.size(t.kernelShape),p=[{type:12,data:a},{type:12,data:u}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let _=t.kernelShape[t.kernelShape.length-1],g=t.strides[t.strides.length-1],y=t.pads[t.pads.length/2-1],C=t.pads[t.pads.length-1],k=!!(y+C);p.push({type:12,data:_},{type:12,data:g},{type:12,data:y},{type:12,data:C}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let F=t.kernelShape[t.kernelShape.length-2],I=t.strides[t.strides.length-2],L=t.pads[t.pads.length/2-2],Q=t.pads[t.pads.length-2];l=!!(L+Q),p.push({type:12,data:F},{type:12,data:I},{type:12,data:L},{type:12,data:Q}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[p,d,!0,k,l]}else{if(i)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let _=tt.computeStrides(t.kernelShape);p.push({type:12,data:_},{type:12,data:t.pads},{type:12,data:t.strides}),d.push({name:"kernelStrides",type:"u32",length:_.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let g=t.pads.reduce((y,C)=>y+C);return[p,d,!!g,!1,!1]}},kr=(e,t,i,a,u,p,d,_,g,y,C,k)=>{let l=u.format==="NHWC",F=t.type.value,I=Jt("output",t.type.tensor,a);if(u.kernelShape.length<=2){let L="",Q="",Z="",U=i-(l?2:1);if(C?L=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${U}] = indices[${U}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${U}] < 0 || xIndices[${U}] + >= uniforms.x_shape[${U}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${p} + }`:L=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${U}] = indices[${U}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${p} + }`,u.kernelShape.length===2){let we=i-(l?3:2);k?Q=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${we}] = indices[${we}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${we}] < 0 || xIndices[${we}] >= uniforms.x_shape[${we}]) { + pad += i32(uniforms.kw); + continue; + } + `:Q=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${we}] = indices[${we}] * uniforms.sh - uniforms.phStart + j; + `,Z=` + } + `}return` + ${e.registerUniforms(g).declareVariables(t,I)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${I.offsetToIndices("global_idx")}; + var xIndices = ${I.offsetToIndices("global_idx")}; + + var value = ${F}(${_}); + var pad = 0; + ${Q} + ${L} + ${Z} + ${d} + + output[global_idx] = value; + }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let L=u.kernelShape.length,Q=u.pads.length,Z="";return y?Z=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${p} + }`:Z=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${p} + `,` + ${e.registerUniforms(g).declareVariables(t,I)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${I.offsetToIndices("global_idx")}; + var xIndices = ${I.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${F}(${_}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${L-1}u; j++) { + offsets[j] = offset / ${Kt("uniforms.kernelStrides","j",L)}; + offset -= offsets[j] * ${Kt("uniforms.kernelStrides","j",L)}; + } + offsets[${L-1}] = offset; + + isPad = false; + for (var j = ${i-L}u; j < ${i}u; j++) { + xIndices[j] = indices[j] * ${Kt("uniforms.strides",`j - ${i-L}u`,L)} + + offsets[j - ${i-L}u] - ${Kt("uniforms.pads","j - 2u",Q)}; + ${Z} + } + ${d} + + output[global_idx] = value; + }`}},vr=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Cr=e=>`${vr(e)};${e.countIncludePad}`,Ar=e=>`${vr(e)};${e.storageOrder};${e.dilations}`,Wr=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}),bi=(e,t,i,a)=>{let[u,p]=Lr(t,a,i),d=mt("x",t.dataType,t.dims.length),_=d.type.value,g="value += x_val;",y="";u.countIncludePad?y+=`value /= ${_}(uniforms.kernelSize);`:y+=`value /= ${_}(i32(uniforms.kernelSize) - pad);`;let[C,k,l,F,I]=br(p,u);C.push(...Rt(t.dims,p));let L=["rank"];return{name:e,shaderCache:{hint:`${a.cacheKey};${l};${F};${I}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(tt.size(p)/64)},programUniforms:C}),getShaderSource:Q=>kr(Q,d,t.dims.length,p.length,u,g,y,0,k,l,F,I)}},Mi=e=>{let t=e.count_include_pad!==0,i=Wr(e);if(i.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let a={countIncludePad:t,...i,cacheKey:""};return{...a,cacheKey:Cr(a)}},Yi=(e,t)=>{_r(e.inputs),e.compute(bi("AveragePool",e.inputs[0],!1,t))},mi={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},si=e=>{let t=e.format;return{format:t,...mi,cacheKey:t}},_i=(e,t)=>{_r(e.inputs),e.compute(bi("GlobalAveragePool",e.inputs[0],!0,t))},cs=(e,t,i,a)=>{let[u,p]=Lr(t,a,i),d=` + value = max(x_val, value); + `,_="",g=mt("x",t.dataType,t.dims.length),y=["rank"],[C,k,l,F,I]=br(p,u);return C.push(...Rt(t.dims,p)),{name:e,shaderCache:{hint:`${a.cacheKey};${l};${F};${I}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(tt.size(p)/64)},programUniforms:C}),getShaderSource:L=>kr(L,g,t.dims.length,p.length,u,d,_,t.dataType===10?-65504:-1e5,k,l,F,I)}},ps=(e,t)=>{_r(e.inputs),e.compute(cs("MaxPool",e.inputs[0],!1,t))},Ia=e=>{let t=e.storage_order,i=e.dilations,a=Wr(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(a.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let u={storageOrder:t,dilations:i,...a,cacheKey:""};return{...u,cacheKey:Ar(u)}},Rd=e=>{let t=e.format;return{format:t,...mi,cacheKey:t}},Ui=(e,t)=>{_r(e.inputs),e.compute(cs("GlobalMaxPool",e.inputs[0],!0,t))}}),pd,hd,fd,Iu,Dg=V(()=>{sr(),lr(),Tr(),mr(),pd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((i,a)=>i===e[2].dims[a]).reduce((i,a)=>i&&a,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((u,p)=>p===t.axis||u===e[0].dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let i=e[0].dims[t.axis],a=e[1].dims[t.axis];if(t.blockSizeMath.ceil(i/(a-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},hd=(e,t)=>{let i=tt.normalizeAxis(t.axis,e[0].dims.length),a=e[0].dataType,u=a===3,p=e[0].dims,d=e[1].dataType,_=tt.size(p),g=a===3||a===2,y=g?[Math.ceil(tt.size(e[0].dims)/4)]:e[0].dims,C=e[1].dims,k=e.length>2?e[2]:void 0,l=k?g?[Math.ceil(tt.size(k.dims)/4)]:k.dims:void 0,F=C.length===0||C.length===1&&C[0]===1,I=F===!1&&C.length===1,L=$r(_),Q=F&&(!g||L===4),Z=Q?L:1,U=Q&&!g?L:1,we=mt("input",g?12:a,y.length,U),te=mt("scale",d,C.length),me=k?mt("zero_point",g?12:a,l.length):void 0,it=Jt("output",d,p.length,Z),Ye=[we,te];me&&Ye.push(me);let Mt=[y,C];k&&Mt.push(l);let Gt=[{type:12,data:_/Z},{type:12,data:i},{type:12,data:t.blockSize},...Rt(...Mt,p)],Bt=gr=>{let Mr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${gr.registerUniforms(Mr).declareVariables(...Ye,it)} + ${gr.mainStart()} + ${gr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${it.offsetToIndices("global_idx")}; + + // Set input x + ${g?` + let input = ${we.getByOffset("global_idx / 4")}; + let x_vec = ${u?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${Z===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${we.getByOffset("global_idx")};`}; + + // Set scale input + ${F?`let scale_value= ${te.getByOffset("0")}`:I?` + let scale_index = ${it.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${te.getByOffset("scale_index")};`:` + var scale_indices: ${te.type.indices} = output_indices; + let index = ${te.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${te.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${te.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${me?F?g?` + let zero_point_input = ${me.getByOffset("0")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${me.getByOffset("0")}`:I?g?` + let zero_point_index = ${it.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${me.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${it.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${me.getByOffset("zero_point_index")};`:g?` + let zero_point_offset = ${te.indicesToOffset("scale_indices")}; + let zero_point_input = ${me.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${me.getByIndices("scale_indices")};`:`let zero_point_value = ${g?u?"i32":"u32":we.type.value}(0);`}; + // Compute and write output + ${it.setByOffset("global_idx",`${it.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Bt,getRunData:()=>({outputs:[{dims:p,dataType:d}],dispatchGroup:{x:Math.ceil(_/Z/64),y:1,z:1},programUniforms:Gt})}},fd=(e,t)=>{pd(e.inputs,t),e.compute(hd(e.inputs,t))},Iu=e=>tr({axis:e.axis,blockSize:e.blockSize})}),Mc,xc,Tc,Bg=V(()=>{z(),sr(),mr(),Mc=(e,t,i)=>{let a=e===t,u=et&&i>0;if(a||u||p)throw new Error("Range these inputs' contents are invalid.")},xc=(e,t,i,a)=>{let u=Math.abs(Math.ceil((t-e)/i)),p=[u],d=u,_=[{type:12,data:d},{type:a,data:e},{type:a,data:i},...Rt(p)],g=y=>{let C=Jt("output",a,p.length),k=C.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:k},{name:"delta",type:k}];return` + ${y.registerUniforms(l).declareVariables(C)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${k}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${a}`},getShaderSource:g,getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_})}},Tc=e=>{let t=0,i=0,a=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],i=e.inputs[1].getInt32Array()[0],a=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],i=e.inputs[1].getFloat32Array()[0],a=e.inputs[2].getFloat32Array()[0]),j.webgpu.validateInputContent&&Mc(t,i,a),e.compute(xc(t,i,a,e.inputs[0].dataType),{inputs:[]})}}),Cc,kc,$c,Sc,Ec,Pc,Ac,Ic,Fc,zc,Oc,Nd,Dc,Bc,jc,Lc,Rc,Nc,Vc,jg=V(()=>{sr(),lr(),Tr(),mr(),Cc=(e,t)=>{if(e.every(i=>i>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")}},kc=(e,t,i)=>{t.every(u=>u>=0&&u{throw new Error("Resize requires axes input values to be positive and less than rank")}));let a=new Array(i).fill(1);return t.forEach((u,p)=>a[u]=e[p]),a},$c=(e,t,i,a,u,p)=>{let[d,_,g]=i>10?[1,2,3]:[-1,e.length>1?1:-1,-1],y=e[0].dims.length;if(d>0&&e.length>d&&e[d].dims.length>0)e[d].getFloat32Array().forEach(C=>p.push(C));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(_>0&&e.length>_&&e[_].dims.length>0){if(e[_].getFloat32Array().forEach(C=>a.push(C)),a.length!==0&&a.length!==y&&i>=18&&a.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");Cc(a,t),t.axes.length>0&&kc(a,t.axes,y).forEach((C,k)=>a[k]=C)}if(g>0&&e.length>g&&(e[g].getBigInt64Array().forEach(C=>u.push(Number(C))),u.length!==y||i>=18&&u.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(a.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(u.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 a<"u"&&typeof u<"u"&&a.length>0&&u.length>y)throw new Error("Resize requires only of scales or sizes to be specified")},Sc=(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`)}})()+"}",Ec=(e,t,i)=>`fn getNearestPixelFromOriginal(xOriginal: ${i}, isDownSample: bool) -> ${i} {`+(()=>{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`)}})()+"}",Pc=(e,t,i)=>{let a=new Array(i).fill(0).concat(new Array(i).fill(1)),u=e.length===0?a:e.slice();return t.length>0?(t.forEach((p,d)=>{a[p]=u[d],a[d+i]=u[t.length+d]}),a):u},Ac=(e,t,i,a)=>{let u=[];if(i.length>0)if(a.length>0){if(e.forEach(p=>u.push(p)),Math.max(...a)>e.length)throw new Error("axes is out of bound");a.forEach((p,d)=>u[p]=i[d])}else i.forEach(p=>u.push(p));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");u=e.map((p,d)=>Math.round(p*t[d]))}return u},Ic=(e,t,i)=>{let a=(()=>{switch(i.keepAspectRatioPolicy){case"not_larger":return i.axes.length>0?Math.min(...i.axes.map(p=>t[p]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return i.axes.length>0?Math.max(...i.axes.map(p=>t[p]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${i.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let u=e.slice();return i.axes.length>0?(i.axes.forEach(p=>t[p]=a),i.axes.forEach(p=>u[p]=Math.round(e[p]*t[p]))):(t.fill(a,0,t.length),u.forEach((p,d)=>u[d]=Math.round(p*t[d]))),u},Fc=(e,t,i,a,u)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${i.length}> { + var original_indices: array<${e.type.value}, ${i.length}>; + for (var i:u32 = 0; i < ${i.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Kt("uniforms.scales","i",a)}; + var roi_low = ${Kt("uniforms.roi","i",u)}; + var roi_hi = ${Kt("uniforms.roi",`i + ${t.length}`,u)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Kt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Kt("uniforms.output_shape","i",i.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,zc=(e,t,i,a,u,p,d)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${a.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Kt("uniforms.scales","i",u)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Kt("uniforms.roi","i",p)}; + var roi_hi = ${Kt("uniforms.roi",`i + ${i.length}`,p)}; + var input_shape_i = ${Kt("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${Kt("uniforms.output_shape","i",a.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${d} || (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; + }`,Oc=(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 >= ${Kt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Nd=(e,t,i,a)=>e.rank>a?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",i,"batch")}; +`:"",Dc=(e,t,i,a,u)=>{let[p,d,_,g]=i.length===2?[-1,0,1,-1]:[0,2,3,1],y=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${y} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",d,`max(0, min(row, ${i[d]} - 1))`)}; + ${e.indicesSet("input_indices",_,`max(0, min(col, ${i[_]} - 1))`)}; + ${Nd(e,g,p,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${y} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${y} = originalIndices[${d}]; + var col:${y} = originalIndices[${_}]; + ${a?`if (row < 0 || row > (${i[d]} - 1) || col < 0 || col > (${i[_]} - 1)) { + return ${u}; + }`:""}; + row = max(0, min(row, ${i[d]} - 1)); + col = max(0, min(col, ${i[_]} - 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 = ${i.length>2?`u32(originalIndices[${g}])`:"0"}; + var batch: u32 = ${i.length>2?`u32(originalIndices[${p}])`:"0"}; + var x11: ${y} = getInputValue(batch, channel, row1, col1); + var x12: ${y} = getInputValue(batch, channel, row1, col2); + var x21: ${y} = getInputValue(batch, channel, row2, col1); + var x22: ${y} = getInputValue(batch, channel, row2, col2); + var dx1: ${y} = abs(row - ${y}(row1)); + var dx2: ${y} = abs(${y}(row2) - row); + var dy1: ${y} = abs(col - ${y}(col1)); + var dy2: ${y} = abs(${y}(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); + }`},Bc=(e,t,i,a,u,p,d,_,g,y)=>{let C=i.length===2,[k,l]=C?[0,1]:[2,3],F=e.type.value,I=L=>{let Q=L===k?"row":"col";return` + fn ${Q}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${F} { + var output_index = ${t.indicesGet("output_indices",L)}; + var originalIdx: ${F} = getOriginalCoordinateFromResizedCoordinate(output_index, ${u[L]}, + ${a[L]}, ${i[L]}, ${p[L]}, ${p[L]} + ${i.length}); + var fractOriginalIdx: ${F} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${_} && (originalIdx < 0 || originalIdx > (${i[L]} - 1))) { + return ${g}; + } + var data: array<${F}, 4> = array<${F}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${Q}: ${F} = originalIdx + ${F}(i); + if (${Q} < 0 || ${Q} >= ${i[L]}) { + ${y?`coefs[i + 1] = 0.0; + continue;`:_?`return ${g};`:`${Q} = max(0, min(${Q}, ${i[L]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",L,`u32(${Q})`)}; + data[i + 1] = ${L===k?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${I(k)}; + ${I(l)}; + fn getCubicInterpolationCoefs(s: ${F}) -> array<${F}, 4> { + var absS = abs(s); + var coeffs: array<${F}, 4> = array<${F}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${F} = 1.0 - absS; + var twoMinusAbsS: ${F} = 2.0 - absS; + var onePlusAbsS: ${F} = 1.0 + absS; + coeffs[0] = ((${d} * onePlusAbsS - 5 * ${d}) * onePlusAbsS + 8 * ${d}) * onePlusAbsS - 4 * ${d}; + coeffs[1] = ((${d} + 2) * absS - (${d} + 3)) * absS * absS + 1; + coeffs[2] = ((${d} + 2) * oneMinusAbsS - (${d} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${d} * twoMinusAbsS - 5 * ${d}) * twoMinusAbsS + 8 * ${d}) * twoMinusAbsS - 4 * ${d}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${F}, 4>, coefs: array<${F}, 4>) -> ${F} { + var coefsSum: ${F} = 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}) -> ${F} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},jc=(e,t,i,a,u)=>{let[p,d,_,g,y]=i.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],C=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${C} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",d,`max(0, min(depth, ${i[d]} - 1))`)}; + ${e.indicesSet("input_indices",_,`max(0, min(height, ${i[_]} - 1))`)}; + ${e.indicesSet("input_indices",g,`max(0, min(width, ${i[g]} - 1))`)}; + ${Nd(e,y,p,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${C} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${C} = originalIndices[${d}]; + var height:${C} = originalIndices[${_}]; + var width:${C} = originalIndices[${g}]; + ${a?`if (depth < 0 || depth > (${i[d]} - 1) || height < 0 || height > (${i[_]} - 1) || width < 0 || (width > ${i[g]} - 1)) { + return ${u}; + }`:""}; + + depth = max(0, min(depth, ${i[d]} - 1)); + height = max(0, min(height, ${i[_]} - 1)); + width = max(0, min(width, ${i[g]} - 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 = ${i.length>3?`u32(originalIndices[${y}])`:"0"}; + var batch: u32 = ${i.length>3?`u32(originalIndices[${p}])`:"0"}; + + var x111: ${C} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${C} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${C} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${C} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${C} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${C} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${C} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${C} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${C} = abs(depth - ${C}(depth1)); + var dx2: ${C} = abs(${C}(depth2) - depth); + var dy1: ${C} = abs(height - ${C}(height1)); + var dy2: ${C} = abs(${C}(height2) - height); + var dz1: ${C} = abs(width - ${C}(width1)); + var dz2: ${C} = abs(${C}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},Lc=(e,t,i,a,u,p)=>{let d=e.dims,_=Pc(p,t.axes,d.length),g=Ac(d,a,u,t.axes),y=a.slice();a.length===0&&(y=d.map((U,we)=>U===0?1:g[we]/U),t.keepAspectRatioPolicy!=="stretch"&&(g=Ic(d,y,t)));let C=Jt("output",e.dataType,g.length),k=mt("input",e.dataType,d.length),l=tt.size(g),F=d.length===g.length&&d.every((U,we)=>U===g[we]),I=t.coordinateTransformMode==="tf_crop_and_resize",L=t.extrapolationValue,Q=k.type.value,Z=U=>` + ${F?"":` + ${Sc(t.coordinateTransformMode,Q)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${Oc(k,d)}; + ${Ec(t.nearestMode,i,Q)}; + ${zc(k,C,d,g,y.length,_.length,I)}; + `;case"linear":return` + ${Fc(C,d,g,y.length,_.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${Dc(k,C,d,I,L)}`;if(d.length===3||d.length===5)return`${jc(k,C,d,I,L)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(d.length===2||d.length===4)return`${Bc(k,C,d,g,y,_,t.cubicCoeffA,I,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")}})()}; + `} + ${U.registerUniform("output_size","u32").registerUniform("scales","f32",y.length).registerUniform("roi","f32",_.length).declareVariables(k,C)} + ${U.mainStart()} + ${U.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${F?"output[global_idx] = input[global_idx];":` + let output_indices = ${C.offsetToIndices("global_idx")}; + var input_indices: ${k.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${k.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${d.length===2||d.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}|${i}|${y.length>0?y:""}|${u.length>0?u:""}|${_.length>0?_:""}|${F}|${d}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[{dims:g,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:y},{type:1,data:_},...Rt(d,g)]})}},Rc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Nc=(e,t)=>{let i=[],a=[],u=[],p=Rc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");$c(e.inputs,t,p,i,a,u),e.compute(Lc(e.inputs[0],t,p,i,a,u),{inputs:[0]})},Vc=e=>{let t=e.antialias,i=e.axes,a=e.coordinateTransformMode,u=e.cubicCoeffA,p=e.excludeOutside!==0,d=e.extrapolationValue,_=e.keepAspectRatioPolicy,g=e.mode,y=e.nearestMode===""?"simple":e.nearestMode;return tr({antialias:t,axes:i,coordinateTransformMode:a,cubicCoeffA:u,excludeOutside:p,extrapolationValue:d,keepAspectRatioPolicy:_,mode:g,nearestMode:y})}}),Uc,Wc,Gc,Lg=V(()=>{sr(),lr(),Tr(),mr(),Uc=(e,t)=>{let[i,a,u,p]=e,{numHeads:d,rotaryEmbeddingDim:_}=t;if(i.dims.length!==3&&i.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${i.dims.length}`);if(!tt.areEqual(a.dims,[])&&!tt.areEqual(a.dims,[1])&&a.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${a.dims.length}`);if(u.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${u.dims.length}`);if(p.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${p.dims.length}`);if(!tt.areEqual(u.dims,p.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(_>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let g=i.dims[0],y=i.dims[i.dims.length-2],C=u.dims[0],k=tt.sizeFromDimension(i.dims,1)/y,l=_===0?u.dims[1]*2:k/d;if(_>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(a.dims.length===2){if(g!==a.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${a.dims[0]}`);if(y!==a.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${a.dims[1]}`)}if(l/2!==u.dims[1]&&_/2!==u.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${u.dims[1]}`);if(y>C)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Wc=(e,t)=>{let{interleaved:i,numHeads:a,rotaryEmbeddingDim:u,scale:p}=t,d=e[0].dims[0],_=tt.sizeFromDimension(e[0].dims,1),g=e[0].dims[e[0].dims.length-2],y=_/g,C=e[2].dims[1],k=u===0?C*2:y/a,l=new Array(d,g,y/k,k-C),F=tt.computeStrides(l),I=[{type:1,data:p},{type:12,data:l},{type:12,data:F},...e[0].dims.length===3?new Array({type:12,data:[_,y,k,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[_,k,g*k,1]}):[],...Rt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],L=Q=>{let Z=mt("input",e[0].dataType,e[0].dims.length),U=mt("position_ids",e[1].dataType,e[1].dims.length),we=mt("cos_cache",e[2].dataType,e[2].dims.length),te=mt("sin_cache",e[3].dataType,e[3].dims.length),me=Jt("output",e[0].dataType,e[0].dims.length);return Q.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:F.length},{name:"input_output_strides",type:"u32",length:F.length}]),` + ${Q.declareVariables(Z,U,we,te,me)} + + ${Q.mainStart(ki)} + let half_rotary_emb_dim = uniforms.${we.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${Q.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${U.broadcastedIndicesToOffset("bsnh.xy",Jt("",U.type.tensor,2))}; + let position_id = + u32(${U.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${i}); + let j = i + select(half_rotary_emb_dim, 1, ${i}); + let re = ${Z.getByOffset("i")} * ${we.get("position_id","bsnh[3]")} - + ${Z.getByOffset("j")} * ${te.get("position_id","bsnh[3]")}; + ${me.setByOffset("i","re")} + let im = ${Z.getByOffset("i")} * ${te.get("position_id","bsnh[3]")} + + ${Z.getByOffset("j")} * ${we.get("position_id","bsnh[3]")}; + ${me.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${me.setByOffset("k",Z.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:tr({interleaved:i}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(tt.size(l)/ki)},programUniforms:I})}},Gc=(e,t)=>{Uc(e.inputs,t),e.compute(Wc(e.inputs,t))}}),qc,Kc,Hc,Rg=V(()=>{sr(),lr(),mr(),qc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],i=e[1],a=e[2];if(t.dataType!==i.dataType||t.dataType!==a.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(i.dims.length!==3&&i.dims.length!==2)throw new Error("Skip must be 2D or 3D");let u=t.dims[t.dims.length-1],p=t.dims[t.dims.length-2];if(i.dims[i.dims.length-1]!==u)throw new Error("Skip must have the same hidden size as input");if(i.dims[i.dims.length-2]!==p)throw new Error("Skip must have the same sequence length as input");if(a.dims.length!==1)throw new Error("Gamma must be 1D");if(a.dims[a.dims.length-1]!==u)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let d=e[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let d=e[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Bias must have the same hidden size as input")}},Kc=(e,t,i,a)=>{let u=t.simplified,p=e[0].dims,d=tt.size(p),_=p,g=d,y=p.slice(-1)[0],C=a?p.slice(0,-1).concat(1):[],k=!u&&e.length>3,l=e.length>4,F=a&&i>1,I=a&&i>2,L=i>3,Q=64,Z=$r(y),U=[{type:12,data:g},{type:12,data:Z},{type:12,data:y},{type:1,data:t.epsilon}],we=me=>{let it=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ye=[mt("x",e[0].dataType,e[0].dims,Z),mt("skip",e[1].dataType,e[1].dims,Z),mt("gamma",e[2].dataType,e[2].dims,Z)];k&&Ye.push(mt("beta",e[3].dataType,e[3].dims,Z)),l&&Ye.push(mt("bias",e[4].dataType,e[4].dims,Z)),Ye.push(Jt("output",e[0].dataType,_,Z)),F&&Ye.push(Jt("mean_output",1,C)),I&&Ye.push(Jt("inv_std_output",1,C)),L&&Ye.push(Jt("input_skip_bias_sum",e[0].dataType,_,Z));let Mt=zr(e[0].dataType),Gt=zr(1,Z);return` + + ${me.registerUniforms(it).declareVariables(...Ye)} + var sum_shared : array<${Gt}, ${Q}>; + var sum_squared_shared : array<${Gt}, ${Q}>; + + ${me.mainStart([Q,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${Q}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${Q}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${Q-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${l?"bias[offset1d + i]":Mt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${L?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Qr(Mt,Z,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${Q}; + 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 = ${$i("sum",Z)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${$i("square_sum",Z)} / f32(uniforms.hidden_size) ${u?"":"- mean * mean"} + uniforms.epsilon); + ${F?"mean_output[global_idx] = mean;":""} + ${I?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${u?"":`- ${Mt}(mean)`}) * + ${Mt}(inv_std_dev) * gamma[offset1d + i] + ${k?"+ beta[offset1d + i]":""}; + } + }`},te=[{dims:_,dataType:e[0].dataType}];return i>1&&te.push({dims:C,dataType:1}),i>2&&te.push({dims:C,dataType:1}),i>3&&te.push({dims:p,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${Z};${F};${I};${L}`,inputDependencies:e.map((me,it)=>"type")},getShaderSource:we,getRunData:()=>({outputs:te,dispatchGroup:{x:Math.ceil(g/y)},programUniforms:U})}},Hc=(e,t)=>{qc(e.inputs);let i=[0];e.outputCount>1&&i.push(-3),e.outputCount>2&&i.push(-3),e.outputCount>3&&i.push(3),e.compute(Kc(e.inputs,t,e.outputCount,!1),{outputs:i})}}),Xc,Fu,Qc,Vd,Yc,Zc,Jc,ep,Ng=V(()=>{sr(),lr(),Tr(),mr(),Xc=(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((i,a)=>{if(e[a+1].dataType!==6&&e[a+1].dataType!==7)throw new Error(`Input ${a} must be an array of int32 or int64`)})},Fu=(e,t)=>{let i=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(a=>i.push(Number(a)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(a=>i.push(Number(a)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return i},Qc=(e,t)=>{if(e.length>1){let i=Fu(e,1),a=Fu(e,2),u=Fu(e,3);return u.length===0&&(u=[...Array(e[0].dims.length).keys()]),tr({starts:i,ends:a,axes:u})}else return t},Vd=(e,t,i,a,u)=>{let p=e;return e<0&&(p+=i[a[t]]),u[t]<0?Math.max(0,Math.min(p,i[a[t]]-1)):Math.max(0,Math.min(p,i[a[t]]))},Yc=(e,t,i)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${i.length}; i >= 0; i--) { + let input_shape_i = ${Kt("uniforms.input_shape","i",i.length)}; + let steps_i = ${Kt("uniforms.steps","i",i.length)}; + let signs_i = ${Kt("uniforms.signs","i",i.length)}; + let starts_i = ${Kt("uniforms.starts","i",i.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; + }`,Zc=(e,t)=>{let i=e[0].dims,a=tt.size(i),u=t.axes.length>0?tt.normalizeAxes(t.axes,i.length):[...Array(i.length).keys()],p=Fu(e,4);p.forEach(Z=>Z!==0||(()=>{throw new Error("step cannot be 0")})),p.length===0&&(p=Array(u.length).fill(1));let d=t.starts.map((Z,U)=>Vd(Z,U,i,u,p)),_=t.ends.map((Z,U)=>Vd(Z,U,i,u,p));if(u.length!==d.length||u.length!==_.length)throw new Error("start, ends and axes should have the same number of elements");if(u.length!==i.length)for(let Z=0;ZMath.sign(Z));p.forEach((Z,U,we)=>{if(Z<0){let te=(_[U]-d[U])/Z,me=d[U],it=me+te*p[U];d[U]=it,_[U]=me,we[U]=-Z}});let y=i.slice(0);u.forEach((Z,U)=>{y[Z]=Math.ceil((_[Z]-d[Z])/p[Z])});let C={dims:y,dataType:e[0].dataType},k=Jt("output",e[0].dataType,y.length),l=mt("input",e[0].dataType,e[0].dims.length),F=tt.size(y),I=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:g.length},{name:"steps",type:"u32",length:p.length}],L=[{type:12,data:F},{type:12,data:d},{type:6,data:g},{type:12,data:p},...Rt(e[0].dims,y)],Q=Z=>` + ${Z.registerUniforms(I).declareVariables(l,k)} + ${Yc(l,k,i)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${k.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${k.setByOffset("global_idx",l.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${g.length}_${d.length}_${p.length}`,inputDependencies:["rank"]},getShaderSource:Q,getRunData:()=>({outputs:[C],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:L})}},Jc=(e,t)=>{Xc(e.inputs,t);let i=Qc(e.inputs,t);e.compute(Zc(e.inputs,i),{inputs:[0]})},ep=e=>{let t=e.starts,i=e.ends,a=e.axes;return tr({starts:t,ends:i,axes:a})}}),tp,rp,ip,np,Vg=V(()=>{sr(),lr(),Tr(),mr(),tp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},rp=(e,t)=>{let i=e.dims,a=tt.size(i),u=64,p=t.axis;if(p<0&&(p=i.length+p),pZ===4?`max(max(${Q}.x, ${Q}.y), max(${Q}.z, ${Q}.w))`:Z===2?`max(${Q}.x, ${Q}.y)`:Z===3?`max(max(${Q}.x, ${Q}.y), ${Q}.z)`:Q,k=mt("x",e.dataType,e.dims,g),l=Jt("result",e.dataType,e.dims,g),F=k.type.value,I=zr(e.dataType)==="f32"?`var threadMax = ${F}(-3.402823e+38f);`:`var threadMax = ${F}(-65504.0h);`,L=Q=>` + var rowMaxShared : ${F}; + var rowSumShared : ${F}; + var threadShared : array<${F}, ${u}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${F} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${F}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Q.registerUniform("packedCols","i32").declareVariables(k,l)} + ${Q.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${u}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${I} + 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 = ${F}(${C("threadShared[0]",g)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${F}(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 = ${F}(${$i("threadShared[0]",g)}); + } + 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:`${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:_},programUniforms:[{type:6,data:y}]}),getShaderSource:L}},ip=(e,t)=>{tp(e.inputs),e.compute(rp(e.inputs[0],t))},np=e=>tr({axis:e.axis})}),sp,ap,op,lp,up,dp,cp,Ug=V(()=>{sr(),lr(),Tr(),mr(),sp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ap=(e,t)=>{let i=[],a=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(u=>i.push(Number(u))),a=i.length),tr({numOutputs:a,axis:t.axis,splitSizes:i})},op=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Kt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,lp=e=>{let t=e.length,i=[];for(let a=0;a{let i=e[0].dims,a=tt.size(i),u=e[0].dataType,p=tt.normalizeAxis(t.axis,i.length),d=new Array(t.numOutputs),_=mt("input",u,i.length),g=new Array(t.numOutputs),y=[],C=[],k=0,l=[{type:12,data:a}];for(let I=0;I` + ${I.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",g.length).declareVariables(_,...d)} + ${op(g.length)} + ${lp(d)} + + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${_.offsetToIndices("global_idx")}; + var index = ${_.indicesGet("indices",p)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Kt("uniforms.size_in_split_axis","output_number - 1u",g.length)}; + ${_.indicesSet("indices",p,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:F,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},dp=(e,t)=>{sp(e.inputs);let i=e.inputs.length===1?t:ap(e.inputs,t);e.compute(up(e.inputs,i),{inputs:[0]})},cp=e=>{let t=e.axis,i=e.splitSizes,a=e.numOutputs<0?i.length:e.numOutputs;if(a!==i.length)throw new Error("numOutputs and splitSizes lengh must be equal");return tr({axis:t,numOutputs:a,splitSizes:i})}}),pp,hp,fp,Wg=V(()=>{sr(),lr(),mr(),pp=(e,t,i,a,u)=>{let p=Jt("output_data",u,i.length,4),d=mt("a_data",t[1].dataType,t[1].dims.length,4),_=mt("b_data",t[2].dataType,t[2].dims.length,4),g=mt("c_data",t[0].dataType,t[0].dims.length,4),y,C=(k,l,F)=>`select(${l}, ${k}, ${F})`;if(!a)y=p.setByOffset("global_idx",C(d.getByOffset("global_idx"),_.getByOffset("global_idx"),g.getByOffset("global_idx")));else{let k=(l,F,I="")=>{let L=`a_data[index_a${F}][component_a${F}]`,Q=`b_data[index_b${F}][component_b${F}]`,Z=`bool(c_data[index_c${F}] & (0xffu << (component_c${F} * 8)))`;return` + let output_indices${F} = ${p.offsetToIndices(`global_idx * 4u + ${F}u`)}; + let offset_a${F} = ${d.broadcastedIndicesToOffset(`output_indices${F}`,p)}; + let offset_b${F} = ${_.broadcastedIndicesToOffset(`output_indices${F}`,p)}; + let offset_c${F} = ${g.broadcastedIndicesToOffset(`output_indices${F}`,p)}; + let index_a${F} = offset_a${F} / 4u; + let index_b${F} = offset_b${F} / 4u; + let index_c${F} = offset_c${F} / 4u; + let component_a${F} = offset_a${F} % 4u; + let component_b${F} = offset_b${F} % 4u; + let component_c${F} = offset_c${F} % 4u; + ${l}[${F}] = ${I}(${C(L,Q,Z)}); + `};u===9?y=` + var data = vec4(0); + ${k("data",0,"u32")} + ${k("data",1,"u32")} + ${k("data",2,"u32")} + ${k("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:y=` + ${k("output_data[global_idx]",0)} + ${k("output_data[global_idx]",1)} + ${k("output_data[global_idx]",2)} + ${k("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(g,d,_,p)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${y} + }`},hp=e=>{let t=e[1].dims,i=e[2].dims,a=e[0].dims,u=e[1].dataType,p=!(tt.areEqual(t,i)&&tt.areEqual(i,a)),d=t,_=tt.size(t);if(p){let y=ui.calcShape(ui.calcShape(t,i,!1),a,!1);if(!y)throw new Error("Can't perform where op on the given tensors");d=y,_=tt.size(d)}let g=Math.ceil(_/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:y=>pp(y,e,d,p,u),getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:g},...Rt(a,t,i,d)]})}},fp=e=>{e.compute(hp(e.inputs))}}),mp,Gg=V(()=>{Uu(),Jn(),So(),Wu(),ol(),Gu(),qu(),Bl(),Bd(),Zu(),Ju(),id(),jd(),sd(),ad(),od(),pu(),ud(),Ld(),hi(),ca(),cd(),gu(),yr(),Nn(),Dg(),Bg(),Os(),jg(),Lg(),Rg(),Ng(),Vg(),Ug(),vu(),wn(),Ys(),Wg(),mp=new Map([["Abs",[Io]],["Acos",[Fo]],["Acosh",[js]],["Add",[dl]],["ArgMax",[wo,Zn]],["ArgMin",[go,Zn]],["Asin",[zo]],["Asinh",[Oo]],["Atan",[Ls]],["Atanh",[Do]],["Attention",[xo]],["AveragePool",[Yi,Mi]],["BatchNormalization",[$o]],["BiasAdd",[Bs]],["BiasSplitGelu",[al]],["Cast",[es,Bo]],["Ceil",[Ro]],["Clip",[Lo]],["Concat",[tn,vl]],["Conv",[Dn,ha]],["ConvTranspose",[Yu,Vl]],["Cos",[Rs]],["Cosh",[No]],["CumSum",[va,Gl]],["DepthToSpace",[xa,Hl]],["DequantizeLinear",[fd,Iu]],["Div",[cl]],["Einsum",[Ql,Yl]],["Elu",[Vo,bn]],["Equal",[Js]],["Erf",[Uo]],["Exp",[Ns]],["Expand",[ka]],["FastGelu",[eu]],["Floor",[Wo]],["FusedConv",[Dn,ha]],["Gather",[nu,iu]],["GatherElements",[lu,ou]],["Gelu",[Go]],["Gemm",[ld,cu]],["GlobalAveragePool",[_i,si]],["GlobalMaxPool",[Ui,Rd]],["Greater",[ml]],["GreaterOrEqual",[gl]],["GroupQueryAttention",[Cu,xu]],["HardSigmoid",[Ws,Qo]],["InstanceNormalization",[Eu]],["LayerNormalization",[oi]],["LeakyRelu",[qo,bn]],["Less",[_l]],["LessOrEqual",[ea]],["Log",[Qs]],["MatMul",[zl]],["MatMulNBits",[dd,Au]],["MaxPool",[ps,Ia]],["Mul",[pl]],["MultiHeadAttention",[_u,fu]],["Neg",[Ko]],["Not",[Vs]],["Pad",[er]],["Pow",[hl]],["QuickGelu",[nl,bn]],["Range",[Tc]],["Reciprocal",[Ho]],["ReduceMin",[Fs]],["ReduceMean",[uo]],["ReduceMax",[ho]],["ReduceSum",[mo]],["ReduceProd",[fo]],["ReduceL1",[co]],["ReduceL2",[Is]],["ReduceLogSum",[_o]],["ReduceLogSumExp",[po]],["ReduceSumSquare",[zs]],["Relu",[Us]],["Resize",[Nc,Vc]],["RotaryEmbedding",[Gc]],["Sigmoid",[Xo]],["Sin",[Yo]],["Sinh",[Zo]],["Slice",[Jc,ep]],["SkipLayerNormalization",[Hc]],["Split",[dp,cp]],["Sqrt",[Gs]],["Softmax",[ip,np]],["Sub",[fl]],["Tan",[Jo]],["Tanh",[Ks]],["ThresholdedRelu",[tl,bn]],["Tile",[bu]],["Transpose",[La,xs]],["Where",[fp]]])}),_p,qg=V(()=>{z(),Ci(),mr(),_p=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,i,a,u){rt(e.programInfo.name);let p=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let _=[];for(let y of t)_.push({binding:_.length,resource:{buffer:y.buffer}});for(let y of i)_.push({binding:_.length,resource:{buffer:y.buffer}});u&&_.push({binding:_.length,resource:u});let g=p.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:_,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let y={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:g,dispatchGroup:a};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(y)}d.setPipeline(e.computePipeline),d.setBindGroup(0,g),d.dispatchWorkgroups(...a),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(),et(e.programInfo.name)}dispose(){}build(e,t){rt(e.name);let i=this.backend.device,a=[];i.features.has("shader-f16")&&a.push("enable f16;");let u=Da(t,this.backend.device.limits),p=e.getShaderSource(u),d=`${a.join(` +`)} +${u.additionalImplementations} +${p}`,_=i.createShaderModule({code:d,label:e.name});qr("verbose",()=>`[WebGPU] ${e.name} shader code: ${d}`);let g=i.createComputePipeline({compute:{module:_,entryPoint:"main"},layout:"auto",label:e.name});return et(e.name),{programInfo:e,computePipeline:g,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,i=typeof e=="number"?1:e.y||1,a=typeof e=="number"?1:e.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=u&&i<=u&&a<=u)return[t,i,a];let p=t*i*a,d=Math.ceil(Math.sqrt(p));if(d>u){if(d=Math.ceil(Math.cbrt(p)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),gp,wp,yp,bp,Kg=V(()=>{z(),sr(),Ci(),x(),jr(),Gg(),qg(),gp=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let i=[];for(let a=0;a{var u,p;let a=e.name;return(u=e.shaderCache)!=null&&u.hint&&(a+="["+e.shaderCache.hint+"]"),a+=":"+i+`:${gp(t,((p=e.shaderCache)==null?void 0:p.inputDependencies)??new Array(t.length).fill("dims"))}`,a},yp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},bp=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 i=[],a={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:i};t.features.has("chromium-experimental-timestamp-query-inside-passes")?i.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&i.push("timestamp-query"),t.features.has("shader-f16")&&i.push("shader-f16"),this.device=await t.requestDevice(a),this.adapterInfo=new yp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ur(this),this.programManager=new _p(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,_n(e.logLevel,!!e.debug),this.device.onuncapturederror=u=>{u.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${u.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;rt(),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 a;let t=new BigUint64Array(e.getMappedRange()),i=this.pendingQueries.get(e);for(let u=0;u"u"&&(this.queryTimeBase=F);let L=Number(F-this.queryTimeBase),Q=Number(I-this.queryTimeBase);if(!Number.isSafeInteger(L)||!Number.isSafeInteger(Q))throw new RangeError("incorrect timestamp range");if((a=this.env.webgpu.profiling)!=null&&a.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:k.map(Z=>({dims:Z.dims,dataType:Ni(Z.dataType)})),outputsMetadata:l.map(Z=>({dims:Z.dims,dataType:Ni(Z.dataType)})),kernelId:d,kernelType:g,kernelName:y,programName:C,startTime:L,endTime:Q});else{let Z="";k.forEach((we,te)=>{Z+=`input[${te}]: [${we.dims}] | ${Ni(we.dataType)}, `});let U="";l.forEach((we,te)=>{U+=`output[${te}]: [${we.dims}] | ${Ni(we.dataType)}, `}),console.log(`[profiling] kernel "${d}|${g}|${y}|${C}" ${Z}${U}execution time: ${Q-L} ns`)}Re("GPU",`${C}::${F}::${I}`)}e.unmap(),this.pendingQueries.delete(e)}),et()}run(e,t,i,a,u,p){rt(e.name);let d=[];for(let U=0;Uwe):i;if(C.length!==_.length)throw new Error(`Output size ${C.length} must be equal to ${_.length}.`);let k=[],l=[];for(let U=0;U<_.length;++U){if(!Number.isInteger(C[U])||C[U]<-3||C[U]>=p)throw new Error(`Invalid output index: ${C[U]}`);if(C[U]===-3)continue;let we=C[U]===-1,te=C[U]===-2,me=we||te?u(_[U].dataType,_[U].dims):a(C[U],_[U].dataType,_[U].dims);if(k.push(me),me.data===0)continue;let it=this.gpuDataManager.get(me.data);if(!it)throw new Error(`no GPU data for output: ${me.data}`);if(we&&this.temporaryData.push(it),te){let Ye=this.kernelPersistentData.get(this.currentKernelId);Ye||(Ye=[],this.kernelPersistentData.set(this.currentKernelId,Ye)),Ye.push(it)}l.push(it)}if(d.length!==t.length||l.length!==k.length){if(l.length===0)return et(e.name),k;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let F;if(y){let U=0,we=[];y.forEach(Ye=>{let Mt=typeof Ye.data=="number"?[Ye.data]:Ye.data;if(Mt.length===0)return;let Gt=Ye.type===10?2:4,Bt,gr;Ye.type===10?(gr=Mt.length>4?16:Mt.length>2?8:Mt.length*Gt,Bt=Mt.length>4?16:Gt*Mt.length):(gr=Mt.length<=2?Mt.length*Gt:16,Bt=16),U=Math.ceil(U/gr)*gr,we.push(U);let Mr=Ye.type===10?8:4;U+=Mt.length>4?Math.ceil(Mt.length/Mr)*Bt:Mt.length*Gt});let te=16;U=Math.ceil(U/te)*te;let me=new ArrayBuffer(U);y.forEach((Ye,Mt)=>{let Gt=we[Mt],Bt=typeof Ye.data=="number"?[Ye.data]:Ye.data;if(Ye.type===6)new Int32Array(me,Gt,Bt.length).set(Bt);else if(Ye.type===12)new Uint32Array(me,Gt,Bt.length).set(Bt);else if(Ye.type===10)new Uint16Array(me,Gt,Bt.length).set(Bt);else if(Ye.type===1)new Float32Array(me,Gt,Bt.length).set(Bt);else throw new Error(`Unsupported uniform type: ${Ni(Ye.type)}`)});let it=this.gpuDataManager.create(U,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(it.buffer,0,me,0,U),this.gpuDataManager.release(it.id),F={offset:0,size:U,buffer:it.buffer}}let I=this.programManager.normalizeDispatchGroupSize(g),L=I[1]===1&&I[2]===1,Q=wp(e,t,L),Z=this.programManager.getArtifact(Q);if(Z||(Z=this.programManager.build(e,I),this.programManager.setArtifact(Q,Z),qr("info",()=>`[artifact] key: ${Q}, programName: ${e.name}`)),y&&Z.uniformVariablesInfo){if(y.length!==Z.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${Z.uniformVariablesInfo.length}, got ${y.length} in program "${Z.programInfo.name}".`);for(let U=0;U`[ProgramManager] run "${e.name}" (key=${Q}) with ${I[0]}x${I[1]}x${I[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let U={kernelId:this.currentKernelId,programName:Z.programInfo.name,inputTensorViews:t,outputTensorViews:k};this.pendingKernels.push(U),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(U)}return this.programManager.run(Z,d,l,I,F),et(e.name),k}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,i,a){let u=mp.get(e);if(!u)throw new Error(`kernel not implemented: ${e}`);let p={kernelType:e,kernelName:a,kernelEntry:u[0],attributes:[u[1],i]};this.kernels.set(t,p)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let i of t)this.gpuDataManager.release(i.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,i){let a=this.kernels.get(e);if(!a)throw new Error(`kernel not created: ${e}`);let u=a.kernelType,p=a.kernelName,d=a.kernelEntry,_=a.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${p}" is not allowed to be called recursively`);this.currentKernelId=e,_[0]&&(_[1]=_[0](_[1]),_[0]=void 0),qr("info",()=>`[WebGPU] Start to run kernel "[${u}] ${p}"...`);let g=this.env.debug;this.temporaryData=[];try{return g&&this.device.pushErrorScope("validation"),d(t,_[1]),0}catch(y){return i.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${p}" failed. ${y}`)),1}finally{g&&i.push(this.device.popErrorScope().then(y=>y?`GPU validation error for kernel "[${u}] ${p}": ${y.message}`:null));for(let y of this.temporaryData)this.gpuDataManager.release(y.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,i,a){let u=this.sessionExternalDataMapping.get(e);u||(u=new Map,this.sessionExternalDataMapping.set(e,u));let p=u.get(t),d=this.gpuDataManager.registerExternalBuffer(i,a,p==null?void 0:p[1]);return u.set(t,[d,i]),d}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(i=>this.gpuDataManager.unregisterExternalBuffer(i[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,i){return async()=>{let a=await Pt(this,e,t);return Ae(a.buffer,i)}}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(){qr("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(){qr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){qr("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),i=e.length;this.pendingKernels=[];for(let a=0;a=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()}}}),vp={};A(vp,{init:()=>xp});var md,Mp,xp,Hg=V(()=>{sr(),Kg(),Ci(),lr(),md=class $g{constructor(t,i,a,u){this.module=t,this.dataType=i,this.data=a,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=tt.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=tt.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=tt.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(tt.size(t)!==tt.size(this.dims))throw new Error("Invalid new shape");return new $g(this.module,this.dataType,this.data,t)}},Mp=class{constructor(e,t,i){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let a=e.HEAPU32,u=i>>>2;this.opKernelContext=a[u++];let p=a[u++];this.outputCount=a[u++],this.customDataOffset=a[u++],this.customDataSize=a[u++];let d=[];for(let _=0;_typeof _=="number"?this.inputs[_]:_))??this.inputs,a=(t==null?void 0:t.outputs)??[],u=(_,g,y)=>new md(this.module,g,this.output(_,y),y),p=(_,g)=>{let y=Ki(_,g);if(!y)throw new Error(`Unsupported data type: ${_}`);let C=y>0?this.backend.gpuDataManager.create(y).id:0;return new md(this.module,_,C,g)};return this.backend.run(e,i,a,u,p,this.outputCount)}output(e,t){let i=this.module.stackSave();try{let a=this.module.stackAlloc((1+t.length)*4),u=a>>2;this.module.HEAPU32[u++]=t.length;for(let p=0;p{let u=t.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let p=new bp;await p.initialize(i,a),u("webgpu",[p,d=>p.alloc(d),d=>p.free(d),(d,_,g,y=!1)=>{if(y)qr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${_}, size=${g}`),p.memcpy(d,_);else{qr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${_}, size=${g}`);let C=t.HEAPU8.subarray(d>>>0,(d>>>0)+g);p.upload(_,C)}},async(d,_,g)=>{qr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${_}, size=${g}`),await p.download(d,()=>t.HEAPU8.subarray(_>>>0,(_>>>0)+g))},(d,_,g)=>p.createKernel(d,_,g,t.UTF8ToString(t._JsepGetNodeName(_))),d=>p.releaseKernel(d),(d,_,g,y)=>{qr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${g}, kernel=${d}, contextDataOffset=${_}`);let C=new Mp(t,p,_);return p.computeKernel(d,C,y)},()=>p.captureBegin(),()=>p.captureEnd(),()=>p.replay()])}else u("webnn")}}),Tp,Ud,Wd,Vn,Cp,_d,Gd,qd,Kd,Hd,Xd,Qd,kp=V(()=>{qn(),Kn(),sr(),di(),Ji(),En(),Tp=(e,t)=>{Hr()._OrtInit(e,t)!==0&&Rr("Can't initialize onnxruntime.")},Ud=async e=>{Tp(e.wasm.numThreads,an(e.logLevel))},Wd=async(e,t)=>{{let i=(Hg(),B(vp)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let a=e.webgpu.adapter;if(a){if(typeof a.limits!="object"||typeof a.features!="object"||typeof a.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let u=e.webgpu.powerPreference;if(u!==void 0&&u!=="low-power"&&u!=="high-performance")throw new Error(`Invalid powerPreference setting: "${u}"`);let p=e.webgpu.forceFallbackAdapter;if(p!==void 0&&typeof p!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${p}"`);if(a=await navigator.gpu.requestAdapter({powerPreference:u,forceFallbackAdapter:p}),!a)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await i("webgpu",Hr(),e,a)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await i("webnn",Hr(),e)}}},Vn=new Map,Cp=e=>{let t=Hr(),i=t.stackSave();try{let a=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,a,a+4)!==0&&Rr("Can't get session input/output count."),[t.HEAP32[a/4],t.HEAP32[a/4+1]]}finally{t.stackRestore(i)}},_d=e=>{let t=Hr(),i=t._malloc(e.byteLength);if(i===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,i),[i,e.byteLength]},Gd=async(e,t)=>{var k,l;let i,a,u=Hr();Array.isArray(e)?[i,a]=e:e.buffer===u.HEAPU8.buffer?[i,a]=[e.byteOffset,e.byteLength]:[i,a]=_d(e);let p=0,d=0,_=0,g=[],y=[],C=[];try{if([d,g]=en(t),(t==null?void 0:t.externalData)&&u.mountExternalData){let te=[];for(let me of t.externalData){let it=typeof me=="string"?me:me.path;te.push(on(typeof me=="string"?me:me.data).then(Ye=>{u.mountExternalData(it,Ye)}))}await Promise.all(te)}for(let te of(t==null?void 0:t.executionProviders)??[])if((typeof te=="string"?te:te.name)==="webnn"){if(u.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof te!="string"){let me=te,it=me==null?void 0:me.context,Ye=me==null?void 0:me.gpuDevice,Mt=me==null?void 0:me.deviceType,Gt=me==null?void 0:me.numThreads,Bt=me==null?void 0:me.powerPreference;it?u.currentContext=it:Ye?u.currentContext=await navigator.ml.createContext(Ye):u.currentContext=await navigator.ml.createContext({deviceType:Mt,numThreads:Gt,powerPreference:Bt})}else u.currentContext=await navigator.ml.createContext();break}p=await u._OrtCreateSession(i,a,d),p===0&&Rr("Can't create a session."),u.currentContext&&(u.currentContext=void 0);let[F,I]=Cp(p),L=!!(t!=null&&t.enableGraphCapture),Q=[],Z=[],U=[];for(let te=0;tete==="gpu-buffer")&&(_=u._OrtCreateBinding(p),_===0&&Rr("Can't create IO binding."),we={handle:_,outputPreferredLocations:U,outputPreferredLocationsEncoded:U.map(te=>fn(te))}),Vn.set(p,[p,y,C,we,L,!1]),[p,Q,Z]}catch(F){throw y.forEach(I=>u._OrtFree(I)),C.forEach(I=>u._OrtFree(I)),_!==0&&u._OrtReleaseBinding(_),p!==0&&u._OrtReleaseSession(p),F}finally{u._free(i),d!==0&&u._OrtReleaseSessionOptions(d),g.forEach(F=>u._free(F)),(l=u.unmountExternalData)==null||l.call(u)}},qd=e=>{var g;let t=Hr(),i=Vn.get(e);if(!i)throw new Error(`cannot release session. invalid session id: ${e}`);let[a,u,p,d,_]=i;d&&(_&&t._OrtClearBoundOutputs(d.handle),t._OrtReleaseBinding(d.handle)),(g=t.jsepOnReleaseSession)==null||g.call(t,e),u.forEach(y=>t._OrtFree(y)),p.forEach(y=>t._OrtFree(y)),t._OrtReleaseSession(a),Vn.delete(e)},Kd=(e,t,i,a,u,p=!1)=>{if(!e){t.push(0);return}let d=Hr(),_=e[0],g=e[1],y=e[3],C,k;if(_==="string"&&y==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(p&&y!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${u} when enableGraphCapture is true.`);if(y==="gpu-buffer"){let I=e[2].gpuBuffer;k=Ki(pn(_),g);let L=d.jsepRegisterBuffer;if(!L)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');C=L(a,u,I,k)}else{let I=e[2];if(Array.isArray(I)){k=4*I.length,C=d._malloc(k),i.push(C);let L=C/4;for(let Q=0;Qd.HEAP32[I++]=Q);let L=d._OrtCreateTensor(pn(_),C,k,F,g.length,fn(y));L===0&&Rr(`Can't create tensor for input/output. session=${a}, index=${u}.`),t.push(L)}finally{d.stackRestore(l)}},Hd=async(e,t,i,a,u,p)=>{var Bt,gr;let d=Hr(),_=Vn.get(e);if(!_)throw new Error(`cannot run inference. invalid session id: ${e}`);let g=_[0],y=_[1],C=_[2],k=_[3],l=_[4],F=_[5],I=t.length,L=a.length,Q=0,Z=[],U=[],we=[],te=[],me=d.stackSave(),it=d.stackAlloc(I*4),Ye=d.stackAlloc(I*4),Mt=d.stackAlloc(L*4),Gt=d.stackAlloc(L*4);try{[Q,Z]=qi(p);for(let Wt=0;WtSi*Di,1);fr=Ni(gi);let Du=k==null?void 0:k.outputPreferredLocations[a[Wt]];if(fr==="string"){if(Du==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Si=[],Di=Yr/4;for(let Mn=0;Mn0){let Si=d.jsepGetBuffer;if(!Si)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Di=Si(Yr),Mn=Ki(gi,xi);if(Mn===void 0||!hn(fr))throw new Error(`Unsupported data type: ${fr}`);qt=!0,Kr.push([fr,Wi,{gpuBuffer:Di,download:d.jsepCreateDownloader(Di,Mn,fr),dispose:()=>{d._OrtReleaseTensor(pr)}},"gpu-buffer"])}else{let Si=Hi(fr),Di=new Si(xi);new Uint8Array(Di.buffer,Di.byteOffset,Di.byteLength).set(d.HEAPU8.subarray(Yr,Yr+Di.byteLength)),Kr.push([fr,Wi,Di,"cpu"])}}finally{d.stackRestore(cr),fr==="string"&&Yr&&d._free(Yr),qt||d._OrtReleaseTensor(pr)}}return k&&!l&&(d._OrtClearBoundOutputs(k.handle),Vn.set(e,[g,y,C,k,l,!1])),Kr}finally{d.stackRestore(me),U.forEach(Mr=>d._OrtReleaseTensor(Mr)),we.forEach(Mr=>d._OrtReleaseTensor(Mr)),te.forEach(Mr=>d._free(Mr)),Q!==0&&d._OrtReleaseRunOptions(Q),Z.forEach(Mr=>d._free(Mr))}},Xd=e=>{let t=Hr(),i=Vn.get(e);if(!i)throw new Error("invalid session id");let a=i[0],u=t._OrtEndProfiling(a);u===0&&Rr("Can't get an profile file name."),t._OrtFree(u)},Qd=e=>{let t=[];for(let i of e){let a=i[2];!Array.isArray(a)&&"buffer"in a&&t.push(a.buffer)}return t}}),Un,Li,Fa,zu,Ou,gd,Yd,wd,hs,fs,$p,Sp,Ep,Pp,Ap,Ip,Fp,zp,Op=V(()=>{z(),kp(),di(),Jr(),Un=()=>!!j.wasm.proxy&&typeof document<"u",Fa=!1,zu=!1,Ou=!1,wd=new Map,hs=(e,t)=>{let i=wd.get(e);i?i.push(t):wd.set(e,[t])},fs=()=>{if(Fa||!zu||Ou||!Li)throw new Error("worker not ready")},$p=e=>{switch(e.data.type){case"init-wasm":Fa=!1,e.data.err?(Ou=!0,Yd[1](e.data.err)):(zu=!0,Yd[0]()),gd&&(URL.revokeObjectURL(gd),gd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=wd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Sp=async()=>{if(!zu){if(Fa)throw new Error("multiple calls to 'initWasm()' detected.");if(Ou)throw new Error("previous call to 'initWasm()' failed.");if(Fa=!0,Un())return new Promise((e,t)=>{Li==null||Li.terminate(),dr().then(([i,a])=>{try{Li=a,Li.onerror=p=>t(p),Li.onmessage=$p,Yd=[e,t];let u={type:"init-wasm",in:j};Li.postMessage(u),gd=i}catch(u){t(u)}},t)});try{await Gi(j.wasm),await Ud(j),zu=!0}catch(e){throw Ou=!0,e}finally{Fa=!1}}},Ep=async e=>{if(Un())return fs(),new Promise((t,i)=>{hs("init-ep",[t,i]);let a={type:"init-ep",in:{epName:e,env:j}};Li.postMessage(a)});await Wd(j,e)},Pp=async e=>Un()?(fs(),new Promise((t,i)=>{hs("copy-from",[t,i]);let a={type:"copy-from",in:{buffer:e}};Li.postMessage(a,[e.buffer])})):_d(e),Ap=async(e,t)=>{if(Un()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return fs(),new Promise((i,a)=>{hs("create",[i,a]);let u={type:"create",in:{model:e,options:{...t}}},p=[];e instanceof Uint8Array&&p.push(e.buffer),Li.postMessage(u,p)})}else return Gd(e,t)},Ip=async e=>{if(Un())return fs(),new Promise((t,i)=>{hs("release",[t,i]);let a={type:"release",in:e};Li.postMessage(a)});qd(e)},Fp=async(e,t,i,a,u,p)=>{if(Un()){if(i.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return fs(),new Promise((d,_)=>{hs("run",[d,_]);let g=i,y={type:"run",in:{sessionId:e,inputIndices:t,inputs:g,outputIndices:a,options:p}};Li.postMessage(y,Qd(g))})}else return Hd(e,t,i,a,u,p)},zp=async e=>{if(Un())return fs(),new Promise((t,i)=>{hs("end-profiling",[t,i]);let a={type:"end-profiling",in:e};Li.postMessage(a)});Xd(e)}}),Zd,Dp,Bp,Xg=V(()=>{z(),Op(),sr(),ee(),En(),Zd=(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()}`)}},Dp=e=>{switch(e[3]){case"cpu":return new Ke(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!hn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:i,download:a,dispose:u}=e[2];return Ke.fromGpuBuffer(i,{dataType:t,dims:e[1],download:a,dispose:u})}default:throw new Error(`invalid data location: ${e[3]}`)}},Bp=class{async fetchModelAndCopyToWasmMemory(e){return Pp(await on(e))}async loadModel(e,t){rt();let i;typeof e=="string"?i=await this.fetchModelAndCopyToWasmMemory(e):i=e,[this.sessionId,this.inputNames,this.outputNames]=await Ap(i,t),et()}async dispose(){return Ip(this.sessionId)}async run(e,t,i){rt();let a=[],u=[];Object.entries(e).forEach(k=>{let l=k[0],F=k[1],I=this.inputNames.indexOf(l);if(I===-1)throw new Error(`invalid input '${l}'`);a.push(F),u.push(I)});let p=[],d=[];Object.entries(t).forEach(k=>{let l=k[0],F=k[1],I=this.outputNames.indexOf(l);if(I===-1)throw new Error(`invalid output '${l}'`);p.push(F),d.push(I)});let _=a.map((k,l)=>Zd(k,()=>`input "${this.inputNames[u[l]]}"`)),g=p.map((k,l)=>k?Zd(k,()=>`output "${this.outputNames[d[l]]}"`):null),y=await Fp(this.sessionId,u,_,d,g,i),C={};for(let k=0;k{z(),Op(),Xg(),Jr(),jp=()=>{if((typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0),j.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 j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let e=typeof navigator>"u"?Oe("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Lp=class{async init(e){jp(),await Sp(),await Ep(e)}async createInferenceSessionHandler(e,t){let i=new Bp;return await i.loadModel(e,t),Promise.resolve(i)}}}),Rp={};A(Rp,{wasmBackend:()=>Np});var Np,Yg=V(()=>{Qg(),Np=new Lp});z(),z(),z();var Zg="1.20.0",Jg=Ne;{let e=(Yg(),B(Rp)).wasmBackend;pe("webgpu",e,5),pe("webnn",e,5),pe("cpu",e,10),pe("wasm",e,10)}Object.defineProperty(j.versions,"web",{value:Zg,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":(Ft,Te,m)=>{var P;m.r(Te),m.d(Te,{Tensor:()=>Oe.Tensor,createInferenceSession:()=>fe,deviceToExecutionProviders:()=>de,isONNXProxy:()=>he,isONNXTensor:()=>q});var re=m("./src/env.js"),ke=m("?2ce3"),ze=m("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Oe=m("./node_modules/onnxruntime-common/dist/esm/index.js");const V=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),A=[];let H,B;if(re.apis.IS_NODE_ENV){switch(B=ke??(P||(P=m.t(ke,2))),process.platform){case"win32":A.push("dml");break;case"linux":process.arch==="x64"&&A.push("cuda");break}A.push("cpu"),H=["cpu"]}else B=ze,re.apis.IS_WEBNN_AVAILABLE&&A.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),re.apis.IS_WEBGPU_AVAILABLE&&A.push("webgpu"),A.push("wasm"),H=["wasm"];const le=B.InferenceSession;function de(ye=null){if(!ye)return H;switch(ye){case"auto":return A;case"gpu":return A.filter(ge=>["webgpu","cuda","dml","webnn-gpu"].includes(ge))}if(A.includes(ye))return[V[ye]??ye];throw new Error(`Unsupported device: "${ye}". Should be one of: ${A.join(", ")}.`)}let pe=null;async function fe(ye,ge){pe&&await pe;const K=le.create(ye,ge);return pe??(pe=K),await K}function q(ye){return ye instanceof B.Tensor}const ae=B==null?void 0:B.env;ae!=null&&ae.wasm&&(ae.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${re.env.version}/dist/`,ae.wasm.proxy=!re.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(ae.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(ae.wasm.simd=!1)),ae!=null&&ae.webgpu&&(ae.webgpu.powerPreference="high-performance");function he(){var ye;return(ye=ae==null?void 0:ae.wasm)==null?void 0:ye.proxy}re.env.backends.onnx=ae},"./src/configs.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{AutoConfig:()=>A,PretrainedConfig:()=>V,getKeyValueShapes:()=>Oe});var P=m("./src/utils/core.js"),re=m("./src/utils/hub.js");async function ke(H,B){return await(0,re.getModelJSON)(H,"config.json",!0,B)}function ze(H){const B={};let le={};switch(H.model_type){case"llava":case"paligemma":case"florence2":le=ze(H.text_config);break;case"moondream1":le=ze(H.phi_config);break;case"musicgen":le=ze(H.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":B.num_heads="num_attention_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.hidden_size="hidden_size",B.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":B.num_heads="num_key_value_heads",B.num_layers="num_hidden_layers",B.dim_kv="head_dim";break;case"openelm":B.num_heads="num_kv_heads",B.num_layers="num_transformer_layers",B.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":B.num_heads="num_heads",B.num_layers="num_layers",B.hidden_size="hidden_size";break;case"bloom":B.num_heads="n_head",B.num_layers="n_layer",B.hidden_size="hidden_size";break;case"mpt":B.num_heads="n_heads",B.num_layers="n_layers",B.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":B.num_decoder_layers="num_decoder_layers",B.num_decoder_heads="num_heads",B.decoder_dim_kv="d_kv",B.num_encoder_layers="num_layers",B.num_encoder_heads="num_heads",B.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="d_model",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="d_model";break;case"speecht5":B.num_decoder_layers="decoder_layers",B.num_decoder_heads="decoder_attention_heads",B.decoder_hidden_size="hidden_size",B.num_encoder_layers="encoder_layers",B.num_encoder_heads="encoder_attention_heads",B.encoder_hidden_size="hidden_size";break;case"trocr":B.num_encoder_layers=B.num_decoder_layers="decoder_layers",B.num_encoder_heads=B.num_decoder_heads="decoder_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="d_model";break;case"musicgen_decoder":B.num_encoder_layers=B.num_decoder_layers="num_hidden_layers",B.num_encoder_heads=B.num_decoder_heads="num_attention_heads",B.encoder_hidden_size=B.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const pe=ze(H.decoder),fe="num_decoder_layers"in pe,q=(0,P.pick)(H,["model_type","is_encoder_decoder"]);return fe?(q.num_decoder_layers=pe.num_decoder_layers,q.num_decoder_heads=pe.num_decoder_heads,q.decoder_hidden_size=pe.decoder_hidden_size,q.num_encoder_layers=pe.num_encoder_layers,q.num_encoder_heads=pe.num_encoder_heads,q.encoder_hidden_size=pe.encoder_hidden_size):(q.num_layers=pe.num_layers,q.num_heads=pe.num_heads,q.hidden_size=pe.hidden_size),q}const de={...le,...(0,P.pick)(H,["model_type","multi_query","is_encoder_decoder"])};for(const pe in B)de[pe]=H[B[pe]];return de}function Oe(H,{prefix:B="past_key_values"}={}){const le={},de=H.normalized_config,pe=1;if(de.is_encoder_decoder&&"num_encoder_heads"in de&&"num_decoder_heads"in de){const fe=de.encoder_dim_kv??de.encoder_hidden_size/de.num_encoder_heads,q=de.decoder_dim_kv??de.decoder_hidden_size/de.num_decoder_heads,ae=[pe,de.num_encoder_heads,0,fe],he=[pe,de.num_decoder_heads,0,q];for(let ye=0;ye{var j;m.r(Te),m.d(Te,{apis:()=>q,env:()=>R});var P=m("?569f"),re=m("?3f59"),ke=m("?154a");const ze="3.0.0-alpha.6",Oe=typeof self<"u",V=Oe&&self.constructor.name==="DedicatedWorkerGlobalScope",A=Oe&&"caches"in self,H=typeof navigator<"u"&&"gpu"in navigator,B=typeof navigator<"u"&&"ml"in navigator,le=typeof process<"u",de=le&&((j=process==null?void 0:process.release)==null?void 0:j.name)==="node",pe=!W(P),fe=!W(re),q=Object.freeze({IS_BROWSER_ENV:Oe,IS_WEBWORKER_ENV:V,IS_WEB_CACHE_AVAILABLE:A,IS_WEBGPU_AVAILABLE:H,IS_WEBNN_AVAILABLE:B,IS_PROCESS_AVAILABLE:le,IS_NODE_ENV:de,IS_FS_AVAILABLE:pe,IS_PATH_AVAILABLE:fe}),ae=pe&&fe,he=ae?re.dirname(re.dirname(ke.fileURLToPath(self.location.href))):"./",ye=ae?re.join(he,"/.cache/"):null,ge="/models/",K=ae?re.join(he,ge):ge,R={version:ze,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Oe,localModelPath:K,useFS:pe,useBrowserCache:A,useFSCache:pe,cacheDir:ye,useCustomCache:!1,customCache:null};function W(Ce){return Object.keys(Ce).length===0}},"./src/generation/configuration_utils.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{GenerationConfig:()=>re});var P=m("./src/utils/core.js");class re{constructor(ze){De(this,"max_length",20);De(this,"max_new_tokens",null);De(this,"min_length",0);De(this,"min_new_tokens",null);De(this,"early_stopping",!1);De(this,"max_time",null);De(this,"do_sample",!1);De(this,"num_beams",1);De(this,"num_beam_groups",1);De(this,"penalty_alpha",null);De(this,"use_cache",!0);De(this,"temperature",1);De(this,"top_k",50);De(this,"top_p",1);De(this,"typical_p",1);De(this,"epsilon_cutoff",0);De(this,"eta_cutoff",0);De(this,"diversity_penalty",0);De(this,"repetition_penalty",1);De(this,"encoder_repetition_penalty",1);De(this,"length_penalty",1);De(this,"no_repeat_ngram_size",0);De(this,"bad_words_ids",null);De(this,"force_words_ids",null);De(this,"renormalize_logits",!1);De(this,"constraints",null);De(this,"forced_bos_token_id",null);De(this,"forced_eos_token_id",null);De(this,"remove_invalid_values",!1);De(this,"exponential_decay_length_penalty",null);De(this,"suppress_tokens",null);De(this,"begin_suppress_tokens",null);De(this,"forced_decoder_ids",null);De(this,"guidance_scale",null);De(this,"num_return_sequences",1);De(this,"output_attentions",!1);De(this,"output_hidden_states",!1);De(this,"output_scores",!1);De(this,"return_dict_in_generate",!1);De(this,"pad_token_id",null);De(this,"bos_token_id",null);De(this,"eos_token_id",null);De(this,"encoder_no_repeat_ngram_size",0);De(this,"decoder_start_token_id",null);De(this,"generation_kwargs",{});Object.assign(this,(0,P.pick)(ze,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{ClassifierFreeGuidanceLogitsProcessor:()=>ae,ForcedBOSTokenLogitsProcessor:()=>V,ForcedEOSTokenLogitsProcessor:()=>A,LogitsProcessor:()=>ke,LogitsProcessorList:()=>Oe,LogitsWarper:()=>ze,MinLengthLogitsProcessor:()=>pe,MinNewTokensLengthLogitsProcessor:()=>fe,NoBadWordsLogitsProcessor:()=>q,NoRepeatNGramLogitsProcessor:()=>le,RepetitionPenaltyLogitsProcessor:()=>de,SuppressTokensAtBeginLogitsProcessor:()=>H,TemperatureLogitsWarper:()=>he,TopKLogitsWarper:()=>ge,TopPLogitsWarper:()=>ye,WhisperTimeStampLogitsProcessor:()=>B});var P=m("./src/utils/generic.js");m("./src/utils/tensor.js");var re=m("./src/utils/maths.js");class ke extends P.Callable{_call(R,W){throw Error("`_call` should be implemented in a subclass")}}class ze extends P.Callable{_call(R,W){throw Error("`_call` should be implemented in a subclass")}}class Oe extends P.Callable{constructor(){super(),this.processors=[]}push(R){this.processors.push(R)}extend(R){this.processors.push(...R)}_call(R,W){let j=W;for(const Ce of this.processors)j=Ce(R,j);return j}[Symbol.iterator](){return this.processors.values()}}class V extends ke{constructor(R){super(),this.bos_token_id=R}_call(R,W){for(let j=0;j=1&&Be[Be.length-1]>=this.timestamp_begin,Ge=Be.length<2||Be[Be.length-2]>=this.timestamp_begin;if(Ve&&(Ge?Se.subarray(this.timestamp_begin).fill(-1/0):Se.subarray(0,this.eos_token_id).fill(-1/0)),R[j].length===this.begin_index&&this.max_initial_timestamp_index!==null){const $e=this.timestamp_begin+this.max_initial_timestamp_index;Se.subarray($e+1).fill(-1/0)}const pt=(0,re.log_softmax)(Se),ot=Math.log(pt.subarray(this.timestamp_begin).map(Math.exp).reduce(($e,X)=>$e+X)),Tt=(0,re.max)(pt.subarray(0,this.timestamp_begin))[0];ot>Tt&&Se.subarray(0,this.timestamp_begin).fill(-1/0)}return W}}class le extends ke{constructor(R){super(),this.no_repeat_ngram_size=R}getNgrams(R){const W=R.length,j=[];for(let Se=0;Se1 to use the classifier free guidance processor, got guidance scale ${R}.`);this.guidance_scale=R}_call(R,W){if(W.dims[0]!==2*R.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 ${W.dims[0]} for the logits and ${R.length} for the input ids.`);const j=R.length,Ce=W.slice([0,j],null),Se=W.slice([j,W.dims[0]],null);for(let Be=0;Be1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${R}`);if(!Number.isInteger(j)||j<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${j}`);this.top_p=R,this.filter_value=W,this.min_tokens_to_keep=j}}class ge extends ze{constructor(R,{filter_value:W=-1/0,min_tokens_to_keep:j=1}={}){if(super(),!Number.isInteger(R)||R<0)throw new Error(`\`top_k\` must be a positive integer, but is ${R}`);this.top_k=Math.max(R,j),this.filter_value=W}}},"./src/generation/logits_sampler.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{LogitsSampler:()=>ze});var P=m("./src/utils/generic.js"),re=m("./src/utils/tensor.js"),ke=m("./src/utils/maths.js");m("./src/generation/configuration_utils.js");class ze extends P.Callable{constructor(B){super(),this.generation_config=B}async _call(B){return this.sample(B)}async sample(B){throw Error("sample should be implemented in subclasses.")}getLogits(B,le){let de=B.dims.at(-1),pe=B.data;if(le===-1)pe=pe.slice(-de);else{let fe=le*de;pe=pe.slice(fe,fe+de)}return pe}randomSelect(B){let le=0;for(let pe=0;pe1)return new A(B);if(B.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${B.num_return_sequences}.`);return new Oe(B)}}class Oe extends ze{async sample(B){const le=(0,ke.max)(B.data)[1];return[[BigInt(le),0]]}}class V extends ze{async sample(B){let le=B.dims.at(-1);this.generation_config.top_k>0&&(le=Math.min(this.generation_config.top_k,le));const[de,pe]=await(0,re.topk)(B,le),fe=(0,ke.softmax)(de.data);return Array.from({length:this.generation_config.num_beams},()=>{const q=this.randomSelect(fe);return[pe.data[q],Math.log(fe[q])]})}}class A extends ze{async sample(B){let le=B.dims.at(-1);this.generation_config.top_k>0&&(le=Math.min(this.generation_config.top_k,le));const[de,pe]=await(0,re.topk)(B,le),fe=(0,ke.softmax)(de.data);return Array.from({length:this.generation_config.num_beams},(q,ae)=>[pe.data[ae],Math.log(fe[ae])])}}},"./src/generation/stopping_criteria.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{EosTokenCriteria:()=>Oe,InterruptableStoppingCriteria:()=>V,MaxLengthCriteria:()=>ze,StoppingCriteria:()=>re,StoppingCriteriaList:()=>ke});var P=m("./src/utils/generic.js");class re extends P.Callable{_call(H,B){throw Error("StoppingCriteria needs to be subclassed")}}class ke extends P.Callable{constructor(){super(),this.criteria=[]}push(H){this.criteria.push(H)}extend(H){H instanceof ke?H=H.criteria:H instanceof re&&(H=[H]),this.criteria.push(...H)}_call(H,B){const le=new Array(H.length).fill(!1);for(const de of this.criteria){const pe=de(H,B);for(let fe=0;feB.length>=this.max_length)}}class Oe extends re{constructor(H){super(),Array.isArray(H)||(H=[H]),this.eos_token_id=H}_call(H,B){return H.map(le=>{const de=le.at(-1);return this.eos_token_id.some(pe=>de==pe)})}}class V extends re{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(H,B){return new Array(H.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{BaseStreamer:()=>ze,TextStreamer:()=>V,WhisperTextStreamer:()=>A});var P=m("./src/utils/core.js"),re=m("./src/tokenizers.js"),ke=m("./src/env.js");class ze{put(B){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Oe=ke.apis.IS_PROCESS_AVAILABLE?H=>process.stdout.write(H):H=>console.log(H);class V extends ze{constructor(B,{skip_prompt:le=!1,callback_function:de=null,token_callback_function:pe=null,decode_kwargs:fe={},...q}={}){super(),this.tokenizer=B,this.skip_prompt=le,this.callback_function=de??Oe,this.token_callback_function=pe,this.decode_kwargs={...fe,...q},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(B){var fe;if(B.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const le=B[0];(fe=this.token_callback_function)==null||fe.call(this,le),this.token_cache=(0,P.mergeArrays)(this.token_cache,le);const de=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let pe;de.endsWith(` +`)?(pe=de.slice(this.print_len),this.token_cache=[],this.print_len=0):de.length>0&&(0,re.is_chinese_char)(de.charCodeAt(de.length-1))?(pe=de.slice(this.print_len),this.print_len+=pe.length):(pe=de.slice(this.print_len,de.lastIndexOf(" ")+1),this.print_len+=pe.length),this.on_finalized_text(pe,!1)}end(){let B;this.token_cache.length>0?(B=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):B="",this.next_tokens_are_prompt=!0,this.on_finalized_text(B,!0)}on_finalized_text(B,le){var de,pe;B.length>0&&((de=this.callback_function)==null||de.call(this,B)),le&&this.callback_function===Oe&&ke.apis.IS_PROCESS_AVAILABLE&&((pe=this.callback_function)==null||pe.call(this,` +`))}}class A extends V{constructor(B,{skip_prompt:le=!1,callback_function:de=null,token_callback_function:pe=null,on_chunk_start:fe=null,on_chunk_end:q=null,on_finalize:ae=null,time_precision:he=.02,skip_special_tokens:ye=!0,decode_kwargs:ge={}}={}){super(B,{skip_prompt:le,callback_function:de,token_callback_function:pe,decode_kwargs:{skip_special_tokens:ye,...ge}}),this.timestamp_begin=B.timestamp_begin,this.on_chunk_start=fe,this.on_chunk_end=q,this.on_finalize=ae,this.time_precision=he,this.waiting_for_timestamp=!1}put(B){var de,pe;if(B.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const le=B[0];if(le.length===1){const fe=Number(le[0])-this.timestamp_begin;if(fe>=0){const q=fe*this.time_precision;this.waiting_for_timestamp?(de=this.on_chunk_end)==null||de.call(this,q):(pe=this.on_chunk_start)==null||pe.call(this,q),this.waiting_for_timestamp=!this.waiting_for_timestamp,B=[[]]}}return super.put(B)}end(){var B;super.end(),(B=this.on_finalize)==null||B.call(this)}}},"./src/models.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{ASTForAudioClassification:()=>Hn,ASTModel:()=>Kt,ASTPreTrainedModel:()=>$i,AlbertForMaskedLM:()=>sr,AlbertForQuestionAnswering:()=>fn,AlbertForSequenceClassification:()=>hn,AlbertModel:()=>an,AlbertPreTrainedModel:()=>Hi,AutoModel:()=>pu,AutoModelForAudioClassification:()=>Tu,AutoModelForAudioFrameClassification:()=>Cu,AutoModelForCTC:()=>xu,AutoModelForCausalLM:()=>_u,AutoModelForDepthEstimation:()=>Su,AutoModelForDocumentQuestionAnswering:()=>ud,AutoModelForImageClassification:()=>yu,AutoModelForImageFeatureExtraction:()=>Eu,AutoModelForImageMatting:()=>ku,AutoModelForImageSegmentation:()=>Ea,AutoModelForImageToImage:()=>$u,AutoModelForMaskGeneration:()=>Pa,AutoModelForMaskedLM:()=>gu,AutoModelForObjectDetection:()=>vu,AutoModelForQuestionAnswering:()=>Sa,AutoModelForSemanticSegmentation:()=>bu,AutoModelForSeq2SeqLM:()=>fu,AutoModelForSequenceClassification:()=>yi,AutoModelForSpeechSeq2Seq:()=>$a,AutoModelForTextToSpectrogram:()=>mu,AutoModelForTextToWaveform:()=>Rn,AutoModelForTokenClassification:()=>hu,AutoModelForVision2Seq:()=>wu,AutoModelForXVector:()=>Aa,AutoModelForZeroShotObjectDetection:()=>Mu,BartForConditionalGeneration:()=>x,BartForSequenceClassification:()=>N,BartModel:()=>Ae,BartPretrainedModel:()=>Ci,BaseModelOutput:()=>xt,BeitForImageClassification:()=>Bo,BeitModel:()=>Do,BeitPreTrainedModel:()=>Ls,BertForMaskedLM:()=>Qe,BertForQuestionAnswering:()=>Ke,BertForSequenceClassification:()=>gt,BertForTokenClassification:()=>Dt,BertModel:()=>yt,BertPreTrainedModel:()=>ft,BlenderbotForConditionalGeneration:()=>Vt,BlenderbotModel:()=>Pt,BlenderbotPreTrainedModel:()=>At,BlenderbotSmallForConditionalGeneration:()=>hr,BlenderbotSmallModel:()=>jr,BlenderbotSmallPreTrainedModel:()=>ur,BloomForCausalLM:()=>wo,BloomModel:()=>go,BloomPreTrainedModel:()=>Yn,CLIPModel:()=>ja,CLIPPreTrainedModel:()=>zn,CLIPSegForImageSegmentation:()=>Ga,CLIPSegModel:()=>Wa,CLIPSegPreTrainedModel:()=>Ts,CLIPTextModelWithProjection:()=>Vi,CLIPVisionModelWithProjection:()=>La,CamembertForMaskedLM:()=>Ee,CamembertForQuestionAnswering:()=>Ze,CamembertForSequenceClassification:()=>Xe,CamembertForTokenClassification:()=>We,CamembertModel:()=>ee,CamembertPreTrainedModel:()=>z,CausalLMOutput:()=>ln,CausalLMOutputWithPast:()=>dd,ChineseCLIPModel:()=>Ua,ChineseCLIPPreTrainedModel:()=>Va,ClapAudioModelWithProjection:()=>Ll,ClapModel:()=>Bl,ClapPreTrainedModel:()=>Dn,ClapTextModelWithProjection:()=>jl,CodeGenForCausalLM:()=>Xn,CodeGenModel:()=>to,CodeGenPreTrainedModel:()=>Ii,CohereForCausalLM:()=>no,CohereModel:()=>io,CoherePreTrainedModel:()=>Es,ConvBertForMaskedLM:()=>S,ConvBertForQuestionAnswering:()=>ne,ConvBertForSequenceClassification:()=>Y,ConvBertForTokenClassification:()=>D,ConvBertModel:()=>Ot,ConvBertPreTrainedModel:()=>Et,ConvNextForImageClassification:()=>al,ConvNextModel:()=>sl,ConvNextPreTrainedModel:()=>Zs,ConvNextV2ForImageClassification:()=>ul,ConvNextV2Model:()=>ll,ConvNextV2PreTrainedModel:()=>ol,DPTForDepthEstimation:()=>Xs,DPTModel:()=>Hs,DPTPreTrainedModel:()=>Ks,DebertaForMaskedLM:()=>zt,DebertaForQuestionAnswering:()=>Qt,DebertaForSequenceClassification:()=>Ct,DebertaForTokenClassification:()=>jt,DebertaModel:()=>_t,DebertaPreTrainedModel:()=>vt,DebertaV2ForMaskedLM:()=>Yt,DebertaV2ForQuestionAnswering:()=>dr,DebertaV2ForSequenceClassification:()=>ir,DebertaV2ForTokenClassification:()=>nr,DebertaV2Model:()=>Zt,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>Ho,DeiTModel:()=>Ko,DeiTPreTrainedModel:()=>Vs,DepthAnythingForDepthEstimation:()=>tl,DepthAnythingPreTrainedModel:()=>el,DetrForObjectDetection:()=>Lo,DetrForSegmentation:()=>Ro,DetrModel:()=>jo,DetrObjectDetectionOutput:()=>Rs,DetrPreTrainedModel:()=>es,DetrSegmentationOutput:()=>No,Dinov2ForImageClassification:()=>cl,Dinov2Model:()=>dl,Dinov2PreTrainedModel:()=>zi,DistilBertForMaskedLM:()=>Nt,DistilBertForQuestionAnswering:()=>dt,DistilBertForSequenceClassification:()=>Jr,DistilBertForTokenClassification:()=>Br,DistilBertModel:()=>Dr,DistilBertPreTrainedModel:()=>rr,DonutSwinModel:()=>Ys,DonutSwinPreTrainedModel:()=>nl,EfficientNetForImageClassification:()=>Wl,EfficientNetModel:()=>Ul,EfficientNetPreTrainedModel:()=>wa,ElectraForMaskedLM:()=>ct,ElectraForQuestionAnswering:()=>Ne,ElectraForSequenceClassification:()=>Ut,ElectraForTokenClassification:()=>$t,ElectraModel:()=>ut,ElectraPreTrainedModel:()=>xe,EsmForMaskedLM:()=>Zi,EsmForSequenceClassification:()=>Gi,EsmForTokenClassification:()=>Hr,EsmModel:()=>ii,EsmPreTrainedModel:()=>Ht,FalconForCausalLM:()=>Dl,FalconModel:()=>Ol,FalconPreTrainedModel:()=>fa,FastViTForImageClassification:()=>Co,FastViTModel:()=>To,FastViTPreTrainedModel:()=>Jn,Florence2ForConditionalGeneration:()=>Ms,Florence2PreTrainedModel:()=>Ba,GLPNForDepthEstimation:()=>il,GLPNModel:()=>rl,GLPNPreTrainedModel:()=>Qs,GPT2LMHeadModel:()=>Ka,GPT2Model:()=>qa,GPT2PreTrainedModel:()=>Cs,GPTBigCodeForCausalLM:()=>Vu,GPTBigCodeModel:()=>eo,GPTBigCodePreTrainedModel:()=>Ss,GPTJForCausalLM:()=>Ja,GPTJModel:()=>Za,GPTJPreTrainedModel:()=>$s,GPTNeoForCausalLM:()=>Xa,GPTNeoModel:()=>Ha,GPTNeoPreTrainedModel:()=>Ai,GPTNeoXForCausalLM:()=>Ya,GPTNeoXModel:()=>Qa,GPTNeoXPreTrainedModel:()=>ks,Gemma2ForCausalLM:()=>lo,Gemma2Model:()=>oo,Gemma2PreTrainedModel:()=>As,GemmaForCausalLM:()=>ao,GemmaModel:()=>so,GemmaPreTrainedModel:()=>Ps,HubertForCTC:()=>kl,HubertForSequenceClassification:()=>oa,HubertModel:()=>Hu,HubertPreTrainedModel:()=>Ku,ImageMattingOutput:()=>Au,LlamaForCausalLM:()=>ro,LlamaModel:()=>ji,LlamaPreTrainedModel:()=>Qn,LlavaForConditionalGeneration:()=>gn,LlavaPreTrainedModel:()=>Da,LongT5ForConditionalGeneration:()=>In,LongT5Model:()=>An,LongT5PreTrainedModel:()=>mn,M2M100ForConditionalGeneration:()=>bl,M2M100Model:()=>yl,M2M100PreTrainedModel:()=>ta,MBartForCausalLM:()=>St,MBartForConditionalGeneration:()=>ve,MBartForSequenceClassification:()=>qe,MBartModel:()=>be,MBartPreTrainedModel:()=>se,MPNetForMaskedLM:()=>Cn,MPNetForQuestionAnswering:()=>Sn,MPNetForSequenceClassification:()=>kn,MPNetForTokenClassification:()=>$n,MPNetModel:()=>qn,MPNetPreTrainedModel:()=>qi,MT5ForConditionalGeneration:()=>qr,MT5Model:()=>Fn,MT5PreTrainedModel:()=>_n,MarianMTModel:()=>wl,MarianModel:()=>Gu,MarianPreTrainedModel:()=>ea,MaskedLMOutput:()=>hi,MistralForCausalLM:()=>os,MistralModel:()=>as,MistralPreTrainedModel:()=>ca,MobileBertForMaskedLM:()=>Ri,MobileBertForQuestionAnswering:()=>Ji,MobileBertForSequenceClassification:()=>Rr,MobileBertModel:()=>Xr,MobileBertPreTrainedModel:()=>di,MobileNetV1ForImageClassification:()=>Zu,MobileNetV1Model:()=>Gl,MobileNetV1PreTrainedModel:()=>va,MobileNetV2ForImageClassification:()=>Kl,MobileNetV2Model:()=>ql,MobileNetV2PreTrainedModel:()=>Ma,MobileNetV3ForImageClassification:()=>Ju,MobileNetV3Model:()=>Hl,MobileNetV3PreTrainedModel:()=>xa,MobileNetV4ForImageClassification:()=>Ta,MobileNetV4Model:()=>Ln,MobileNetV4PreTrainedModel:()=>jn,MobileViTForImageClassification:()=>Po,MobileViTModel:()=>Eo,MobileViTPreTrainedModel:()=>So,MobileViTV2ForImageClassification:()=>Ao,MobileViTV2Model:()=>Wu,MobileViTV2PreTrainedModel:()=>Bs,ModelOutput:()=>nt,Moondream1ForConditionalGeneration:()=>mr,MptForCausalLM:()=>yo,MptModel:()=>Uu,MptPreTrainedModel:()=>Zn,MusicgenForCausalLM:()=>Bd,MusicgenForConditionalGeneration:()=>ba,MusicgenModel:()=>Yu,MusicgenPreTrainedModel:()=>ya,NomicBertModel:()=>Re,NomicBertPreTrainedModel:()=>ce,OPTForCausalLM:()=>vo,OPTModel:()=>bo,OPTPreTrainedModel:()=>Ds,OpenELMForCausalLM:()=>co,OpenELMModel:()=>uo,OpenELMPreTrainedModel:()=>Fi,OwlViTForObjectDetection:()=>Fo,OwlViTModel:()=>Io,OwlViTPreTrainedModel:()=>Pr,Owlv2ForObjectDetection:()=>Oo,Owlv2Model:()=>zo,Owlv2PreTrainedModel:()=>js,Phi3ForCausalLM:()=>Os,Phi3Model:()=>_o,Phi3PreTrainedModel:()=>zs,PhiForCausalLM:()=>mo,PhiModel:()=>fo,PhiPreTrainedModel:()=>Fs,PreTrainedModel:()=>ue,PretrainedMixin:()=>Vr,PyAnnoteForAudioFrameClassification:()=>sn,PyAnnoteModel:()=>ra,PyAnnotePreTrainedModel:()=>Xi,QuestionAnsweringModelOutput:()=>fi,Qwen2ForCausalLM:()=>ho,Qwen2Model:()=>po,Qwen2PreTrainedModel:()=>Is,RTDetrForObjectDetection:()=>ts,RTDetrModel:()=>Vo,RTDetrObjectDetectionOutput:()=>Uo,RTDetrPreTrainedModel:()=>bn,ResNetForImageClassification:()=>Qo,ResNetModel:()=>Xo,ResNetPreTrainedModel:()=>Us,RoFormerForMaskedLM:()=>et,RoFormerForQuestionAnswering:()=>kt,RoFormerForSequenceClassification:()=>st,RoFormerForTokenClassification:()=>bt,RoFormerModel:()=>rt,RoFormerPreTrainedModel:()=>Je,RobertaForMaskedLM:()=>wi,RobertaForQuestionAnswering:()=>Pi,RobertaForSequenceClassification:()=>ui,RobertaForTokenClassification:()=>tt,RobertaModel:()=>Tr,RobertaPreTrainedModel:()=>tr,SamImageSegmentationOutput:()=>gl,SamModel:()=>_l,SamPreTrainedModel:()=>ml,SegformerForImageClassification:()=>Rl,SegformerForSemanticSegmentation:()=>Nl,SegformerModel:()=>Dd,SegformerPreTrainedModel:()=>Bn,Seq2SeqLMOutput:()=>Ld,SequenceClassifierOutput:()=>wr,SiglipModel:()=>wn,SiglipPreTrainedModel:()=>xs,SiglipTextModel:()=>Ra,SiglipVisionModel:()=>Na,SpeechT5ForSpeechToText:()=>Il,SpeechT5ForTextToSpeech:()=>Xu,SpeechT5HifiGan:()=>da,SpeechT5Model:()=>Al,SpeechT5PreTrainedModel:()=>ua,SqueezeBertForMaskedLM:()=>pn,SqueezeBertForQuestionAnswering:()=>Ki,SqueezeBertForSequenceClassification:()=>Ni,SqueezeBertModel:()=>Kn,SqueezeBertPreTrainedModel:()=>en,StableLmForCausalLM:()=>Vl,StableLmModel:()=>ga,StableLmPreTrainedModel:()=>_a,Starcoder2ForCausalLM:()=>ha,Starcoder2Model:()=>ls,Starcoder2PreTrainedModel:()=>pa,Swin2SRForImageSuperResolution:()=>qs,Swin2SRModel:()=>Jo,Swin2SRPreTrainedModel:()=>Gs,SwinForImageClassification:()=>Zo,SwinModel:()=>Yo,SwinPreTrainedModel:()=>Ws,T5ForConditionalGeneration:()=>Pn,T5Model:()=>En,T5PreTrainedModel:()=>on,TableTransformerForObjectDetection:()=>Go,TableTransformerModel:()=>Wo,TableTransformerObjectDetectionOutput:()=>qo,TableTransformerPreTrainedModel:()=>Ns,TokenClassifierOutput:()=>oi,TrOCRForCausalLM:()=>zl,TrOCRPreTrainedModel:()=>Fl,UniSpeechForCTC:()=>Ml,UniSpeechForSequenceClassification:()=>xl,UniSpeechModel:()=>na,UniSpeechPreTrainedModel:()=>vn,UniSpeechSatForAudioFrameClassification:()=>is,UniSpeechSatForCTC:()=>sa,UniSpeechSatForSequenceClassification:()=>Tl,UniSpeechSatModel:()=>rs,UniSpeechSatPreTrainedModel:()=>On,ViTForImageClassification:()=>xo,ViTModel:()=>Mo,ViTPreTrainedModel:()=>yn,VisionEncoderDecoderModel:()=>vs,VitMatteForImageMatting:()=>$o,VitMattePreTrainedModel:()=>ko,VitsModel:()=>ma,VitsModelOutput:()=>cd,VitsPreTrainedModel:()=>Qu,Wav2Vec2BertForCTC:()=>ss,Wav2Vec2BertForSequenceClassification:()=>Cl,Wav2Vec2BertModel:()=>aa,Wav2Vec2BertPreTrainedModel:()=>ns,Wav2Vec2ForAudioFrameClassification:()=>nn,Wav2Vec2ForCTC:()=>qu,Wav2Vec2ForSequenceClassification:()=>rn,Wav2Vec2Model:()=>vl,Wav2Vec2PreTrainedModel:()=>tn,WavLMForAudioFrameClassification:()=>Pl,WavLMForCTC:()=>la,WavLMForSequenceClassification:()=>Sl,WavLMForXVector:()=>El,WavLMModel:()=>$l,WavLMPreTrainedModel:()=>Qi,WeSpeakerResNetModel:()=>ia,WeSpeakerResNetPreTrainedModel:()=>pi,WhisperForConditionalGeneration:()=>bs,WhisperModel:()=>Jt,WhisperPreTrainedModel:()=>mt,XLMForQuestionAnswering:()=>ci,XLMForSequenceClassification:()=>lr,XLMForTokenClassification:()=>ki,XLMModel:()=>ni,XLMPreTrainedModel:()=>Fr,XLMRobertaForMaskedLM:()=>Rt,XLMRobertaForQuestionAnswering:()=>Qr,XLMRobertaForSequenceClassification:()=>$r,XLMRobertaForTokenClassification:()=>Nr,XLMRobertaModel:()=>Or,XLMRobertaPreTrainedModel:()=>zr,XLMWithLMHeadModel:()=>vi,XVectorOutput:()=>Pu,YolosForObjectDetection:()=>hl,YolosModel:()=>pl,YolosObjectDetectionOutput:()=>fl,YolosPreTrainedModel:()=>Js});var P=m("./src/configs.js"),re=m("./src/backends/onnx.js"),ke=m("./src/utils/dtypes.js"),ze=m("./src/utils/generic.js"),Oe=m("./src/utils/core.js"),V=m("./src/utils/hub.js"),A=m("./src/generation/logits_process.js"),H=m("./src/generation/configuration_utils.js"),B=m("./src/utils/tensor.js"),le=m("./src/utils/maths.js"),de=m("./src/generation/stopping_criteria.js"),pe=m("./src/generation/logits_sampler.js"),fe=m("./src/env.js"),q=m("./src/models/whisper/generation_whisper.js"),ae=m("./src/models/whisper/common_whisper.js");const he={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ye=new Map,ge=new Map,K=new Map;async function R(M,T,O){let ie=O.device;ie&&typeof ie!="string"&&(ie.hasOwnProperty(T)?ie=ie[T]:(console.warn(`device not specified for "${T}". Using the default device.`),ie=null));const Ue=ie??(fe.apis.IS_NODE_ENV?"cpu":"wasm"),He=(0,re.deviceToExecutionProviders)(Ue);let wt=O.dtype;typeof wt!="string"&&(wt&&wt.hasOwnProperty(T)?wt=wt[T]:(wt=ke.DEFAULT_DEVICE_DTYPE_MAPPING[Ue]??ke.DATA_TYPES.fp32,console.warn(`dtype not specified for "${T}". Using the default dtype (${wt}) for this device (${Ue}).`)));const Lt=wt;if(ke.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Lt)){if(Lt===ke.DATA_TYPES.fp16&&Ue==="webgpu"&&!await(0,ke.isWebGpuFp16Supported)())throw new Error(`The device (${Ue}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Lt}. Should be one of: ${Object.keys(ke.DATA_TYPES).join(", ")}`);const er=ke.DEFAULT_DTYPE_SUFFIX_MAPPING[Lt],yr=`${O.subfolder??""}/${T}${er}.onnx`,_r={...O.session_options};_r.executionProviders??(_r.executionProviders=He);const Lr=(0,V.getModelFile)(M,yr,!0,O);let br=[];if(O.use_external_data_format&&(O.use_external_data_format===!0||typeof O.use_external_data_format=="object"&&O.use_external_data_format.hasOwnProperty(T)&&O.use_external_data_format[T]===!0)){if(fe.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const vr=`${T}${er}.onnx_data`,Cr=`${O.subfolder??""}/${vr}`;br.push(new Promise(async(Ar,Wr)=>{const bi=await(0,V.getModelFile)(M,Cr,!0,O);Ar({path:vr,data:bi})}))}else _r.externalData!==void 0&&(br=_r.externalData.map(async vr=>{if(typeof vr.data=="string"){const Cr=await(0,V.getModelFile)(M,vr.data,!0,O);return{...vr,data:Cr}}return vr}));if(br.length>0&&(_r.externalData=await Promise.all(br)),Ue==="webgpu"){const vr=(0,P.getKeyValueShapes)(O.config,{prefix:"present"});if(Object.keys(vr).length>0&&!(0,re.isONNXProxy)()){const Cr={};for(const Ar in vr)Cr[Ar]="gpu-buffer";_r.preferredOutputLocation=Cr}}return{buffer:await Lr,session_options:_r}}async function W(M,T,O){return Object.fromEntries(await Promise.all(Object.keys(T).map(async ie=>{const{buffer:Ue,session_options:He}=await R(M,T[ie],O),wt=await(0,re.createInferenceSession)(Ue,He);return[ie,wt]})))}function j(M,T){const O=Object.create(null),ie=[];for(const wt of M.inputNames){const Lt=T[wt];if(!(Lt instanceof B.Tensor)){ie.push(wt);continue}O[wt]=(0,re.isONNXProxy)()?Lt.clone():Lt}if(ie.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ie.join(", ")}.`);const Ue=Object.keys(T).length,He=M.inputNames.length;if(Ue>He){let wt=Object.keys(T).filter(Lt=>!M.inputNames.includes(Lt));console.warn(`WARNING: Too many inputs were provided (${Ue} > ${He}). The following inputs will be ignored: "${wt.join(", ")}".`)}return O}async function Ce(M,T){const O=j(M,T);try{const ie=Object.fromEntries(Object.entries(O).map(([He,wt])=>[He,wt.ort_tensor]));let Ue=await M.run(ie);return Ue=Se(Ue),Ue}catch(ie){throw console.error(`An error occurred during model execution: "${ie}".`),console.error("Inputs given to model:",O),ie}}function Se(M){for(let T in M)(0,re.isONNXTensor)(M[T])?M[T]=new B.Tensor(M[T]):typeof M[T]=="object"&&Se(M[T]);return M}function Be(M){if(M instanceof B.Tensor)return M;if(M.length===0)throw Error("items must be non-empty");if(Array.isArray(M[0])){if(M.some(T=>T.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 B.Tensor("int64",BigInt64Array.from(M.flat().map(T=>BigInt(T))),[M.length,M[0].length])}else return new B.Tensor("int64",BigInt64Array.from(M.map(T=>BigInt(T))),[1,M.length])}function Ve(M){return new B.Tensor("bool",[M],[1])}async function Ge(M,T){let{encoder_outputs:O,input_ids:ie,decoder_input_ids:Ue,...He}=T;if(!O){const Lt=(0,Oe.pick)(T,M.sessions.model.inputNames);O=(await pt(M,Lt)).last_hidden_state}return He.input_ids=Ue,He.encoder_hidden_states=O,M.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(He.encoder_attention_mask=T.attention_mask),await ot(M,He,!0)}async function pt(M,T){const O=M.sessions.model,ie=(0,Oe.pick)(T,O.inputNames);if(O.inputNames.includes("inputs_embeds")&&!ie.inputs_embeds){if(!T.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ie.inputs_embeds=await M.encode_text({input_ids:T.input_ids})}return O.inputNames.includes("token_type_ids")&&!ie.token_type_ids&&(ie.token_type_ids=new B.Tensor("int64",new BigInt64Array(ie.input_ids.data.length),ie.input_ids.dims)),await Ce(O,ie)}async function ot(M,T,O=!1){const ie=M.sessions[O?"decoder_model_merged":"model"],{past_key_values:Ue,...He}=T;ie.inputNames.includes("use_cache_branch")&&(He.use_cache_branch=Ve(!!Ue)),ie.inputNames.includes("position_ids")&&He.attention_mask&&!He.position_ids&&(He.position_ids=$e(He,Ue)),M.addPastKeyValues(He,Ue);const wt=(0,Oe.pick)(He,ie.inputNames);return await Ce(ie,wt)}async function Tt(M,{input_ids:T=null,attention_mask:O=null,pixel_values:ie=null,position_ids:Ue=null,inputs_embeds:He=null,past_key_values:wt=null,generation_config:Lt=null,logits_processor:er=null,...yr}){if(!He){if(He=await M.encode_text({input_ids:T}),ie&&T.dims[1]!==1){const Lr=await M.encode_image({pixel_values:ie});({inputs_embeds:He,attention_mask:O}=M._merge_input_ids_with_image_features({image_features:Lr,inputs_embeds:He,input_ids:T,attention_mask:O}))}else if(wt&&ie&&T.dims[1]===1){const Lr=T.dims[1],br=Object.values(wt)[0].dims.at(-2);O=(0,B.cat)([(0,B.ones)([T.dims[0],br]),O.slice(null,[O.dims[1]-Lr,O.dims[1]])],1)}}return await ot(M,{inputs_embeds:He,past_key_values:wt,attention_mask:O,position_ids:Ue,generation_config:Lt,logits_processor:er},!0)}function $e(M,T=null){const{input_ids:O,inputs_embeds:ie,attention_mask:Ue}=M,[He,wt]=Ue.dims,Lt=new BigInt64Array(Ue.data.length);for(let yr=0;yrHe.dims[1])){if(UeLt==M.config.image_token_index)){const Lt=M.config.num_image_tokens;if(!Lt)throw new Error("`num_image_tokens` is missing in the model configuration.");const er=He.dims[1]-(Ue-Lt);O.input_ids=He.slice(null,[-er,null]),O.attention_mask=(0,B.ones)([1,Ue+er])}}}return O}function Me(M,T,O,ie){return O.past_key_values&&(T=T.map(Ue=>[Ue.at(-1)])),{...O,decoder_input_ids:Be(T)}}function je(M,...T){return M.config.is_encoder_decoder?Me(M,...T):X(M,...T)}class ue extends ze.Callable{constructor(O,ie){super();De(this,"main_input_name","input_ids");De(this,"forward_params",["input_ids","attention_mask"]);this.config=O,this.sessions=ie;const Ue=K.get(this.constructor),He=ye.get(Ue);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,He){case he.DecoderOnly:this.can_generate=!0,this._forward=ot,this._prepare_inputs_for_generation=X;break;case he.Seq2Seq:case he.Vision2Seq:case he.Musicgen:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Me;break;case he.EncoderDecoder:this._forward=Ge;break;case he.ImageTextToText:this.can_generate=!0,this._forward=Tt,this._prepare_inputs_for_generation=je;break;default:this._forward=pt;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ie;const O=[];for(const Ue of Object.values(this.sessions))(ie=Ue==null?void 0:Ue.handler)!=null&&ie.dispose&&O.push(Ue.handler.dispose());return await Promise.all(O)}static async from_pretrained(O,{progress_callback:ie=null,config:Ue=null,cache_dir:He=null,local_files_only:wt=!1,revision:Lt="main",model_file_name:er=null,subfolder:yr="onnx",device:_r=null,dtype:Lr=null,use_external_data_format:br=null,session_options:kr={}}={}){let vr={progress_callback:ie,config:Ue,cache_dir:He,local_files_only:wt,revision:Lt,model_file_name:er,subfolder:yr,device:_r,dtype:Lr,use_external_data_format:br,session_options:kr};const Cr=K.get(this),Ar=ye.get(Cr);Ue=vr.config=await P.AutoConfig.from_pretrained(O,vr);let Wr;if(Ar===he.DecoderOnly)Wr=await Promise.all([W(O,{model:vr.model_file_name??"model"},vr),(0,V.getModelJSON)(O,"generation_config.json",!1,vr)]);else if(Ar===he.Seq2Seq||Ar===he.Vision2Seq)Wr=await Promise.all([W(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},vr),(0,V.getModelJSON)(O,"generation_config.json",!1,vr)]);else if(Ar===he.MaskGeneration)Wr=await Promise.all([W(O,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},vr)]);else if(Ar===he.EncoderDecoder)Wr=await Promise.all([W(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},vr)]);else if(Ar===he.ImageTextToText){const bi={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ue.is_encoder_decoder&&(bi.model="encoder_model"),Wr=await Promise.all([W(O,bi,vr),(0,V.getModelJSON)(O,"generation_config.json",!1,vr)])}else Ar===he.Musicgen?Wr=await Promise.all([W(O,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},vr),(0,V.getModelJSON)(O,"generation_config.json",!1,vr)]):(Ar!==he.EncoderOnly&&console.warn(`Model type for '${Cr??(Ue==null?void 0:Ue.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Wr=await Promise.all([W(O,{model:vr.model_file_name??"model"},vr)]));return new this(Ue,...Wr)}async _call(O){return await this.forward(O)}async forward(O){return await this._forward(this,O)}_get_logits_warper(O){const ie=new A.LogitsProcessorList;return O.temperature!==null&&O.temperature!==1&&ie.push(new A.TemperatureLogitsWarper(O.temperature)),O.top_k!==null&&O.top_k!==0&&ie.push(new A.TopKLogitsWarper(O.top_k)),O.top_p!==null&&O.top_p<1&&ie.push(new A.TopPLogitsWarper(O.top_p)),ie}_get_logits_processor(O,ie,Ue=null){const He=new A.LogitsProcessorList;if(O.repetition_penalty!==null&&O.repetition_penalty!==1&&He.push(new A.RepetitionPenaltyLogitsProcessor(O.repetition_penalty)),O.no_repeat_ngram_size!==null&&O.no_repeat_ngram_size>0&&He.push(new A.NoRepeatNGramLogitsProcessor(O.no_repeat_ngram_size)),O.bad_words_ids!==null&&He.push(new A.NoBadWordsLogitsProcessor(O.bad_words_ids,O.eos_token_id)),O.min_length!==null&&O.eos_token_id!==null&&O.min_length>0&&He.push(new A.MinLengthLogitsProcessor(O.min_length,O.eos_token_id)),O.min_new_tokens!==null&&O.eos_token_id!==null&&O.min_new_tokens>0&&He.push(new A.MinNewTokensLengthLogitsProcessor(ie,O.min_new_tokens,O.eos_token_id)),O.forced_bos_token_id!==null&&He.push(new A.ForcedBOSTokenLogitsProcessor(O.forced_bos_token_id)),O.forced_eos_token_id!==null&&He.push(new A.ForcedEOSTokenLogitsProcessor(O.max_length,O.forced_eos_token_id)),O.begin_suppress_tokens!==null){const wt=ie>1||O.forced_bos_token_id===null?ie:ie+1;He.push(new A.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,wt))}return O.guidance_scale!==null&&O.guidance_scale>1&&He.push(new A.ClassifierFreeGuidanceLogitsProcessor(O.guidance_scale)),Ue!==null&&He.extend(Ue),He}_prepare_generation_config(O,ie,Ue=H.GenerationConfig){const He={...this.config};for(const Lt of["decoder","generator","text_config"])Lt in He&&Object.assign(He,He[Lt]);const wt=new Ue(He);return"generation_config"in this&&Object.assign(wt,this.generation_config),O&&Object.assign(wt,O),ie&&Object.assign(wt,(0,Oe.pick)(ie,Object.getOwnPropertyNames(wt))),wt}_get_stopping_criteria(O,ie=null){const Ue=new de.StoppingCriteriaList;return O.max_length!==null&&Ue.push(new de.MaxLengthCriteria(O.max_length,this.config.max_position_embeddings??null)),O.eos_token_id!==null&&Ue.push(new de.EosTokenCriteria(O.eos_token_id)),ie&&Ue.extend(ie),Ue}_validate_model_class(){if(!this.can_generate){const O=[ds,ka,Ca,us],ie=K.get(this.constructor),Ue=new Set,He=this.config.model_type;for(const Lt of O){const er=Lt.get(He);er&&Ue.add(er[0])}let wt=`The current model class (${ie}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ue.size>0&&(wt+=` Please use the following class instead: ${[...Ue].join(", ")}`),Error(wt)}}prepare_inputs_for_generation(...O){return this._prepare_inputs_for_generation(this,...O)}_update_model_kwargs_for_generation({generated_input_ids:O,outputs:ie,model_inputs:Ue,is_encoder_decoder:He}){return Ue.past_key_values=this.getPastKeyValues(ie,Ue.past_key_values),Ue.input_ids=new B.Tensor("int64",O.flat(),[O.length,1]),He||(Ue.attention_mask=(0,B.cat)([Ue.attention_mask,(0,B.ones)([Ue.attention_mask.dims[0],1])],1)),Ue.position_ids=null,Ue}_prepare_model_inputs({inputs:O,bos_token_id:ie,model_kwargs:Ue}){const He=(0,Oe.pick)(Ue,this.forward_params),wt=this.main_input_name;if(wt in He){if(O)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else He[wt]=O;return{inputs_tensor:He[wt],model_inputs:He,model_input_name:wt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:O,model_inputs:ie,model_input_name:Ue,generation_config:He}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ie.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Lt,pixel_values:er,attention_mask:yr,..._r}=ie,Lr=await this._prepare_inputs_embeds(ie);ie={..._r,...(0,Oe.pick)(Lr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:wt}=await pt(this,ie);if(He.guidance_scale!==null&&He.guidance_scale>1)wt=(0,B.cat)([wt,(0,B.full_like)(wt,0)],0),"attention_mask"in ie&&(ie.attention_mask=(0,B.cat)([ie.attention_mask,(0,B.zeros_like)(ie.attention_mask)],0));else if(ie.decoder_input_ids){const Lt=Be(ie.decoder_input_ids).dims[0];if(Lt!==wt.dims[0]){if(wt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${wt.dims[0]}) than the decoder inputs (${Lt}).`);wt=(0,B.cat)(Array.from({length:Lt},()=>wt),0)}}return ie.encoder_outputs=wt,ie}_prepare_decoder_input_ids_for_generation({batch_size:O,model_input_name:ie,model_kwargs:Ue,decoder_start_token_id:He,bos_token_id:wt,generation_config:Lt}){let{decoder_input_ids:er,...yr}=Ue;if(er)Array.isArray(er[0])||(er=Array.from({length:O},()=>er));else if(He??(He=wt),this.config.model_type==="musicgen")er=Array.from({length:O*this.config.decoder.num_codebooks},()=>[He]);else if(Array.isArray(He)){if(He.length!==O)throw new Error(`\`decoder_start_token_id\` expcted to have length ${O} but got ${He.length}`);er=He}else er=Array.from({length:O},()=>[He]);return er=Be(er),Ue.decoder_attention_mask=(0,B.ones_like)(er),{input_ids:er,model_inputs:yr}}async generate({inputs:O=null,generation_config:ie=null,logits_processor:Ue=null,stopping_criteria:He=null,streamer:wt=null,...Lt}){this._validate_model_class(),ie=this._prepare_generation_config(ie,Lt);let{inputs_tensor:er,model_inputs:yr,model_input_name:_r}=this._prepare_model_inputs({inputs:O,model_kwargs:Lt});const Lr=this.config.is_encoder_decoder;Lr&&("encoder_outputs"in yr||(yr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:er,model_inputs:yr,model_input_name:_r,generation_config:ie})));let br;Lr?{input_ids:br,model_inputs:yr}=this._prepare_decoder_input_ids_for_generation({batch_size:yr[_r].dims.at(0),model_input_name:_r,model_kwargs:yr,decoder_start_token_id:ie.decoder_start_token_id,bos_token_id:ie.bos_token_id,generation_config:ie}):br=yr[_r];let kr=br.dims.at(-1);ie.max_new_tokens!==null&&(ie.max_length=kr+ie.max_new_tokens);const vr=this._get_logits_processor(ie,kr,Ue),Cr=this._get_stopping_criteria(ie,He),Ar=yr[_r].dims.at(0),Wr=pe.LogitsSampler.getSampler(ie),bi=new Array(Ar).fill(0),Mi=br.tolist();wt&&wt.put(Mi);let Yi=null,mi={};for(;;){yr=this.prepare_inputs_for_generation(Mi,yr,ie);const _i=await this.forward(yr);if(ie.output_attentions&&ie.return_dict_in_generate){const Ui=this.getAttentions(_i);for(const Nn in Ui)Nn in mi||(mi[Nn]=[]),mi[Nn].push(Ui[Nn])}const cs=_i.logits.slice(null,-1,null),ps=vr(Mi,cs),Ia=[];for(let Ui=0;UiUi)){ie.return_dict_in_generate&&(Yi=this.getPastKeyValues(_i,yr.past_key_values,!1));break}yr=this._update_model_kwargs_for_generation({generated_input_ids:Ia,outputs:_i,model_inputs:yr,is_encoder_decoder:Lr})}wt&&wt.end();const si=new B.Tensor("int64",Mi.flat(),[Mi.length,Mi[0].length]);return ie.return_dict_in_generate?{sequences:si,past_key_values:Yi,...mi}:si}getPastKeyValues(O,ie,Ue=!0){const He=Object.create(null);for(const wt in O)if(wt.startsWith("present")){const Lt=wt.replace("present","past_key_values");if(ie&&wt.includes("encoder"))He[Lt]=ie[Lt];else{if(Ue&&ie){const er=ie[Lt];er.location==="gpu-buffer"&&er.dispose()}He[Lt]=O[wt]}}return He}getAttentions(O){const ie={};for(const Ue of["cross_attentions","encoder_attentions","decoder_attentions"])for(const He in O)He.startsWith(Ue)&&(Ue in ie||(ie[Ue]=[]),ie[Ue].push(O[He]));return ie}addPastKeyValues(O,ie){if(ie)Object.assign(O,ie);else{const Ue=this.custom_config.kv_cache_dtype??"float32",He=Ue==="float16"?new Uint16Array:[],wt=(0,P.getKeyValueShapes)(this.config);for(const Lt in wt)O[Lt]=new B.Tensor(Ue,He,wt[Lt])}}async encode_image({pixel_values:O}){const ie=(await Ce(this.sessions.vision_encoder,{pixel_values:O})).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 (${ie.dims[1]}).`),this.config.num_image_tokens=ie.dims[1]),ie}async encode_text({input_ids:O}){return(await Ce(this.sessions.embed_tokens,{input_ids:O})).inputs_embeds}}class nt{}class xt extends nt{constructor({last_hidden_state:T,hidden_states:O=null,attentions:ie=null}){super(),this.last_hidden_state=T,this.hidden_states=O,this.attentions=ie}}class ft extends ue{}class yt extends ft{}class Qe extends ft{async _call(T){return new hi(await super._call(T))}}class gt extends ft{async _call(T){return new wr(await super._call(T))}}class Dt extends ft{async _call(T){return new oi(await super._call(T))}}class Ke extends ft{async _call(T){return new fi(await super._call(T))}}class ce extends ue{}class Re extends ce{}class Je extends ue{}class rt extends Je{}class et extends Je{async _call(T){return new hi(await super._call(T))}}class st extends Je{async _call(T){return new wr(await super._call(T))}}class bt extends Je{async _call(T){return new oi(await super._call(T))}}class kt extends Je{async _call(T){return new fi(await super._call(T))}}class Et extends ue{}class Ot extends Et{}class S extends Et{async _call(T){return new hi(await super._call(T))}}class Y extends Et{async _call(T){return new wr(await super._call(T))}}class D extends Et{async _call(T){return new oi(await super._call(T))}}class ne extends Et{async _call(T){return new fi(await super._call(T))}}class xe extends ue{}class ut extends xe{}class ct extends xe{async _call(T){return new hi(await super._call(T))}}class Ut extends xe{async _call(T){return new wr(await super._call(T))}}class $t extends xe{async _call(T){return new oi(await super._call(T))}}class Ne extends xe{async _call(T){return new fi(await super._call(T))}}class z extends ue{}class ee extends z{}class Ee extends z{async _call(T){return new hi(await super._call(T))}}class Xe extends z{async _call(T){return new wr(await super._call(T))}}class We extends z{async _call(T){return new oi(await super._call(T))}}class Ze extends z{async _call(T){return new fi(await super._call(T))}}class vt extends ue{}class _t extends vt{}class zt extends vt{async _call(T){return new hi(await super._call(T))}}class Ct extends vt{async _call(T){return new wr(await super._call(T))}}class jt extends vt{async _call(T){return new oi(await super._call(T))}}class Qt extends vt{async _call(T){return new fi(await super._call(T))}}class at extends ue{}class Zt extends at{}class Yt extends at{async _call(T){return new hi(await super._call(T))}}class ir extends at{async _call(T){return new wr(await super._call(T))}}class nr extends at{async _call(T){return new oi(await super._call(T))}}class dr extends at{async _call(T){return new fi(await super._call(T))}}class rr extends ue{}class Dr extends rr{}class Jr extends rr{async _call(T){return new wr(await super._call(T))}}class Br extends rr{async _call(T){return new oi(await super._call(T))}}class dt extends rr{async _call(T){return new fi(await super._call(T))}}class Nt extends rr{async _call(T){return new hi(await super._call(T))}}class Ht extends ue{}class ii extends Ht{}class Zi extends Ht{async _call(T){return new hi(await super._call(T))}}class Gi extends Ht{async _call(T){return new wr(await super._call(T))}}class Hr extends Ht{async _call(T){return new oi(await super._call(T))}}class di extends ue{}class Xr extends di{}class Ri extends di{async _call(T){return new hi(await super._call(T))}}class Rr extends di{async _call(T){return new wr(await super._call(T))}}class Ji extends di{async _call(T){return new fi(await super._call(T))}}class qi extends ue{}class qn extends qi{}class Cn extends qi{async _call(T){return new hi(await super._call(T))}}class kn extends qi{async _call(T){return new wr(await super._call(T))}}class $n extends qi{async _call(T){return new oi(await super._call(T))}}class Sn extends qi{async _call(T){return new fi(await super._call(T))}}class en extends ue{}class Kn extends en{}class pn extends en{async _call(T){return new hi(await super._call(T))}}class Ni extends en{async _call(T){return new wr(await super._call(T))}}class Ki extends en{async _call(T){return new fi(await super._call(T))}}class Hi extends ue{}class an extends Hi{}class hn extends Hi{async _call(T){return new wr(await super._call(T))}}class fn extends Hi{async _call(T){return new fi(await super._call(T))}}class sr extends Hi{async _call(T){return new hi(await super._call(T))}}class on extends ue{constructor(O,ie,Ue){super(O,ie);De(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ue}}class En extends on{}class Pn extends on{}class mn extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class An extends mn{}class In extends mn{}class _n extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Fn extends _n{}class qr extends _n{}class Ci extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Ae extends Ci{}class x extends Ci{}class N extends Ci{async _call(T){return new wr(await super._call(T))}}class se extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class be extends se{}class ve extends se{}class qe extends se{async _call(T){return new wr(await super._call(T))}}class St extends se{}class At extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Pt extends At{}class Vt extends At{}class ur extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class jr extends ur{}class hr extends ur{}class tr extends ue{}class Tr extends tr{}class wi extends tr{async _call(T){return new hi(await super._call(T))}}class ui extends tr{async _call(T){return new wr(await super._call(T))}}class tt extends tr{async _call(T){return new oi(await super._call(T))}}class Pi extends tr{async _call(T){return new fi(await super._call(T))}}class Fr extends ue{}class ni extends Fr{}class vi extends Fr{async _call(T){return new hi(await super._call(T))}}class lr extends Fr{async _call(T){return new wr(await super._call(T))}}class ki extends Fr{async _call(T){return new oi(await super._call(T))}}class ci extends Fr{async _call(T){return new fi(await super._call(T))}}class zr extends ue{}class Or extends zr{}class Rt extends zr{async _call(T){return new hi(await super._call(T))}}class $r extends zr{async _call(T){return new wr(await super._call(T))}}class Nr extends zr{async _call(T){return new oi(await super._call(T))}}class Qr extends zr{async _call(T){return new fi(await super._call(T))}}class $i extends ue{}class Kt extends $i{}class Hn extends $i{}class mt extends ue{constructor(O,ie,Ue){super(O,ie);De(this,"requires_attention_mask",!1);De(this,"main_input_name","input_features");De(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ue}}class Jt extends mt{}class bs extends mt{_prepare_generation_config(T,O){return super._prepare_generation_config(T,O,q.WhisperGenerationConfig)}_retrieve_init_tokens(T){const O=[T.decoder_start_token_id];let ie=T.language;const Ue=T.task;if(T.is_multilingual){ie||(console.warn("No language specified - defaulting to English (en)."),ie="en");const wt=`<|${(0,ae.whisper_language_to_code)(ie)}|>`;O.push(T.lang_to_id[wt]),O.push(T.task_to_id[Ue??"transcribe"])}else if(ie||Ue)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!T.return_timestamps&&T.no_timestamps_token_id&&O.at(-1)!==T.no_timestamps_token_id?O.push(T.no_timestamps_token_id):T.return_timestamps&&O.at(-1)===T.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),O.pop()),O.filter(He=>He!=null)}async generate({inputs:T=null,generation_config:O=null,logits_processor:ie=null,stopping_criteria:Ue=null,...He}){O=this._prepare_generation_config(O,He);const wt=He.decoder_input_ids??this._retrieve_init_tokens(O);if(O.return_timestamps&&(ie??(ie=new A.LogitsProcessorList),ie.push(new A.WhisperTimeStampLogitsProcessor(O,wt))),O.begin_suppress_tokens&&(ie??(ie=new A.LogitsProcessorList),ie.push(new A.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,wt.length))),O.return_token_timestamps){if(!O.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.");O.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),O.output_attentions=!0,O.return_dict_in_generate=!0}const Lt=await super.generate({inputs:T,generation_config:O,logits_processor:ie,decoder_input_ids:wt,...He});return O.return_token_timestamps&&(Lt.token_timestamps=this._extract_token_timestamps(Lt,O.alignment_heads,O.num_frames)),Lt}_extract_token_timestamps(T,O,ie=null,Ue=.02){if(!T.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`.");ie==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 He=this.config.median_filter_width;He===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),He=7);const wt=T.cross_attentions,Lt=Array.from({length:this.config.decoder_layers},(Cr,Ar)=>(0,B.cat)(wt.map(Wr=>Wr[Ar]),2)),er=(0,B.stack)(O.map(([Cr,Ar])=>{if(Cr>=Lt.length)throw new Error(`Layer index ${Cr} is out of bounds for cross attentions (length ${Lt.length}).`);return ie?Lt[Cr].slice(null,Ar,null,[0,ie]):Lt[Cr].slice(null,Ar)})).transpose(1,0,2,3),[yr,_r]=(0,B.std_mean)(er,-2,0,!0),Lr=er.clone();for(let Cr=0;CrWr[_i+1]-Wr[_i]),Yi=(0,Oe.mergeArrays)([1],Mi).map(si=>!!si),mi=[];for(let si=0;sibr.findIndex(kr=>kr==He)),er=Lt.every(br=>br===-1),yr=Lt.every(br=>br!==-1);if(!er&&!yr)throw new Error("Every input should contain either 0 or 1 image token.");if(er)return{inputs_embeds:T,attention_mask:Ue};const _r=[],Lr=[];for(let br=0;brHe*wt,1);T.input_labels=new B.Tensor("int64",new BigInt64Array(Ue).fill(1n),ie)}const O={image_embeddings:T.image_embeddings,image_positional_embeddings:T.image_positional_embeddings};return T.input_points&&(O.input_points=T.input_points),T.input_labels&&(O.input_labels=T.input_labels),T.input_boxes&&(O.input_boxes=T.input_boxes),await Ce(this.sessions.prompt_encoder_mask_decoder,O)}async _call(T){return new gl(await super._call(T))}}class gl extends nt{constructor({iou_scores:T,pred_masks:O}){super(),this.iou_scores=T,this.pred_masks=O}}class ea extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Gu extends ea{}class wl extends ea{}class ta extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class yl extends ta{}class bl extends ta{}class tn extends ue{}class vl extends tn{}class qu extends tn{async _call(T){return new ln(await super._call(T))}}class rn extends tn{async _call(T){return new wr(await super._call(T))}}class nn extends tn{async _call(T){return new oi(await super._call(T))}}class Xi extends ue{}class ra extends Xi{}class sn extends Xi{async _call(T){return new oi(await super._call(T))}}class pi extends ue{}class ia extends pi{}class vn extends ue{}class na extends vn{}class Ml extends vn{async _call(T){return new ln(await super._call(T))}}class xl extends vn{async _call(T){return new wr(await super._call(T))}}class On extends ue{}class rs extends On{}class sa extends On{async _call(T){return new ln(await super._call(T))}}class Tl extends On{async _call(T){return new wr(await super._call(T))}}class is extends On{async _call(T){return new oi(await super._call(T))}}class ns extends ue{}class aa extends ns{}class ss extends ns{async _call(T){return new ln(await super._call(T))}}class Cl extends ns{async _call(T){return new wr(await super._call(T))}}class Ku extends ue{}class Hu extends tn{}class kl extends tn{async _call(T){return new ln(await super._call(T))}}class oa extends tn{async _call(T){return new wr(await super._call(T))}}class Qi extends ue{}class $l extends Qi{}class la extends Qi{async _call(T){return new ln(await super._call(T))}}class Sl extends Qi{async _call(T){return new wr(await super._call(T))}}class El extends Qi{async _call(T){return new Pu(await super._call(T))}}class Pl extends Qi{async _call(T){return new oi(await super._call(T))}}class ua extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Al extends ua{}class Il extends ua{}class Xu extends ua{async generate_speech(T,O,{threshold:ie=.5,minlenratio:Ue=0,maxlenratio:He=20,vocoder:wt=null}={}){const Lt={input_ids:T},{encoder_outputs:er,encoder_attention_mask:yr}=await pt(this,Lt),_r=er.dims[1]/this.config.reduction_factor,Lr=Math.floor(_r*He),br=Math.floor(_r*Ue),kr=this.config.num_mel_bins;let vr=[],Cr=null,Ar=null,Wr=0;for(;;){++Wr;const Yi=Ve(!!Ar);let mi;Ar?mi=Ar.output_sequence_out:mi=new B.Tensor("float32",new Float32Array(kr),[1,1,kr]);let si={use_cache_branch:Yi,output_sequence:mi,encoder_attention_mask:yr,speaker_embeddings:O,encoder_hidden_states:er};this.addPastKeyValues(si,Cr),Ar=await Ce(this.sessions.decoder_model_merged,si),Cr=this.getPastKeyValues(Ar,Cr);const{prob:_i,spectrum:cs}=Ar;if(vr.push(cs),Wr>=br&&(Array.from(_i.data).filter(ps=>ps>=ie).length>0||Wr>=Lr))break}const bi=(0,B.cat)(vr),{waveform:Mi}=await Ce(wt.sessions.model,{spectrogram:bi});return{spectrogram:bi,waveform:Mi}}}class da extends ue{constructor(){super(...arguments);De(this,"main_input_name","spectrogram")}}class Fl extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class zl extends Fl{}class ca extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class as extends ca{}class os extends ca{}class pa extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class ls extends pa{}class ha extends pa{}class fa extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class Ol extends fa{}class Dl extends fa{}class Dn extends ue{}class Bl extends Dn{}class jl extends Dn{static async from_pretrained(T,O={}){return O.model_file_name??(O.model_file_name="text_model"),super.from_pretrained(T,O)}}class Ll extends Dn{static async from_pretrained(T,O={}){return O.model_file_name??(O.model_file_name="audio_model"),super.from_pretrained(T,O)}}class Qu extends ue{}class ma extends Qu{async _call(T){return new cd(await super._call(T))}}class Bn extends ue{}class Dd extends Bn{}class Rl extends Bn{}class Nl extends Bn{}class _a extends ue{constructor(T,O,ie){super(T,O),this.generation_config=ie}}class ga extends _a{}class Vl extends _a{}class wa extends ue{}class Ul extends wa{}class Wl extends wa{async _call(T){return new wr(await super._call(T))}}class ya extends ue{}class Yu extends ya{}class Bd extends ya{}class ba extends ue{constructor(O,ie,Ue){super(O,ie);De(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ue}_apply_and_filter_by_delay_pattern_mask(O){const[ie,Ue]=O.dims,He=this.config.decoder.num_codebooks,wt=Ue-He;let Lt=0;for(let _r=0;_r0&&kr<=wt&&(O.data[Lt++]=O.data[_r])}const er=Math.floor(ie/He),yr=Lt/(er*He);return new B.Tensor(O.type,O.data.slice(0,Lt),[er,He,yr])}prepare_inputs_for_generation(O,ie,Ue){let He=structuredClone(O);for(let Lt=0;Lt=er&&(He[Lt][er]=BigInt(this.config.decoder.pad_token_id));return Ue.guidance_scale!==null&&Ue.guidance_scale>1&&(He=He.concat(He)),super.prepare_inputs_for_generation(He,ie,Ue)}async generate(O){const ie=await super.generate(O),Ue=this._apply_and_filter_by_delay_pattern_mask(ie).unsqueeze_(0),{audio_values:He}=await Ce(this.sessions.encodec_decode,{audio_codes:Ue});return He}}class va extends ue{}class Gl extends va{}class Zu extends va{async _call(T){return new wr(await super._call(T))}}class Ma extends ue{}class ql extends Ma{}class Kl extends Ma{async _call(T){return new wr(await super._call(T))}}class xa extends ue{}class Hl extends xa{}class Ju extends xa{async _call(T){return new wr(await super._call(T))}}class jn extends ue{}class Ln extends jn{}class Ta extends jn{async _call(T){return new wr(await super._call(T))}}class Vr{static async from_pretrained(T,{progress_callback:O=null,config:ie=null,cache_dir:Ue=null,local_files_only:He=!1,revision:wt="main",model_file_name:Lt=null,subfolder:er="onnx",device:yr=null,dtype:_r=null,use_external_data_format:Lr=null,session_options:br={}}={}){let kr={progress_callback:O,config:ie,cache_dir:Ue,local_files_only:He,revision:wt,model_file_name:Lt,subfolder:er,device:yr,dtype:_r,use_external_data_format:Lr,session_options:br};if(kr.config=await P.AutoConfig.from_pretrained(T,kr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let vr of this.MODEL_CLASS_MAPPINGS){const Cr=vr.get(kr.config.model_type);if(Cr)return await Cr[1].from_pretrained(T,kr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${kr.config.model_type}", attempting to construct from base class.`),await ue.from_pretrained(T,kr);throw Error(`Unsupported model type: ${kr.config.model_type}`)}}De(Vr,"MODEL_CLASS_MAPPINGS",null),De(Vr,"BASE_IF_FAIL",!1);const ed=new Map([["bert",["BertModel",yt]],["nomic_bert",["NomicBertModel",Re]],["roformer",["RoFormerModel",rt]],["electra",["ElectraModel",ut]],["esm",["EsmModel",ii]],["convbert",["ConvBertModel",Ot]],["camembert",["CamembertModel",ee]],["deberta",["DebertaModel",_t]],["deberta-v2",["DebertaV2Model",Zt]],["mpnet",["MPNetModel",qn]],["albert",["AlbertModel",an]],["distilbert",["DistilBertModel",Dr]],["roberta",["RobertaModel",Tr]],["xlm",["XLMModel",ni]],["xlm-roberta",["XLMRobertaModel",Or]],["clap",["ClapModel",Bl]],["clip",["CLIPModel",ja]],["clipseg",["CLIPSegModel",Wa]],["chinese_clip",["ChineseCLIPModel",Ua]],["siglip",["SiglipModel",wn]],["mobilebert",["MobileBertModel",Xr]],["squeezebert",["SqueezeBertModel",Kn]],["wav2vec2",["Wav2Vec2Model",vl]],["wav2vec2-bert",["Wav2Vec2BertModel",aa]],["unispeech",["UniSpeechModel",na]],["unispeech-sat",["UniSpeechSatModel",rs]],["hubert",["HubertModel",Hu]],["wavlm",["WavLMModel",$l]],["audio-spectrogram-transformer",["ASTModel",Kt]],["vits",["VitsModel",ma]],["pyannote",["PyAnnoteModel",ra]],["wespeaker-resnet",["WeSpeakerResNetModel",ia]],["detr",["DetrModel",jo]],["rt_detr",["RTDetrModel",Vo]],["table-transformer",["TableTransformerModel",Wo]],["vit",["ViTModel",Mo]],["fastvit",["FastViTModel",To]],["mobilevit",["MobileViTModel",Eo]],["mobilevitv2",["MobileViTV2Model",Wu]],["owlvit",["OwlViTModel",Io]],["owlv2",["Owlv2Model",zo]],["beit",["BeitModel",Do]],["deit",["DeiTModel",Ko]],["convnext",["ConvNextModel",sl]],["convnextv2",["ConvNextV2Model",ll]],["dinov2",["Dinov2Model",dl]],["resnet",["ResNetModel",Xo]],["swin",["SwinModel",Yo]],["swin2sr",["Swin2SRModel",Jo]],["donut-swin",["DonutSwinModel",Ys]],["yolos",["YolosModel",pl]],["dpt",["DPTModel",Hs]],["glpn",["GLPNModel",rl]],["hifigan",["SpeechT5HifiGan",da]],["efficientnet",["EfficientNetModel",Ul]],["mobilenet_v1",["MobileNetV1Model",Gl]],["mobilenet_v2",["MobileNetV2Model",ql]],["mobilenet_v3",["MobileNetV3Model",Hl]],["mobilenet_v4",["MobileNetV4Model",Ln]]]),td=new Map([["t5",["T5Model",En]],["longt5",["LongT5Model",An]],["mt5",["MT5Model",Fn]],["bart",["BartModel",Ae]],["mbart",["MBartModel",be]],["marian",["MarianModel",Gu]],["whisper",["WhisperModel",Jt]],["m2m_100",["M2M100Model",yl]],["blenderbot",["BlenderbotModel",Pt]],["blenderbot-small",["BlenderbotSmallModel",jr]]]),rd=new Map([["bloom",["BloomModel",go]],["gpt2",["GPT2Model",qa]],["gptj",["GPTJModel",Za]],["gpt_bigcode",["GPTBigCodeModel",eo]],["gpt_neo",["GPTNeoModel",Ha]],["gpt_neox",["GPTNeoXModel",Qa]],["codegen",["CodeGenModel",to]],["llama",["LlamaModel",ji]],["cohere",["CohereModel",io]],["gemma",["GemmaModel",so]],["gemma2",["Gemma2Model",oo]],["openelm",["OpenELMModel",uo]],["qwen2",["Qwen2Model",po]],["phi",["PhiModel",fo]],["phi3",["Phi3Model",_o]],["mpt",["MptModel",Uu]],["opt",["OPTModel",bo]],["mistral",["MistralModel",as]],["starcoder2",["Starcoder2Model",ls]],["falcon",["FalconModel",Ol]],["stablelm",["StableLmModel",ga]]]),us=new Map([["speecht5",["SpeechT5ForSpeechToText",Il]],["whisper",["WhisperForConditionalGeneration",bs]]]),Xl=new Map([["speecht5",["SpeechT5ForTextToSpeech",Xu]]]),Ql=new Map([["vits",["VitsModel",ma]],["musicgen",["MusicgenForConditionalGeneration",ba]]]),Yl=new Map([["bert",["BertForSequenceClassification",gt]],["roformer",["RoFormerForSequenceClassification",st]],["electra",["ElectraForSequenceClassification",Ut]],["esm",["EsmForSequenceClassification",Gi]],["convbert",["ConvBertForSequenceClassification",Y]],["camembert",["CamembertForSequenceClassification",Xe]],["deberta",["DebertaForSequenceClassification",Ct]],["deberta-v2",["DebertaV2ForSequenceClassification",ir]],["mpnet",["MPNetForSequenceClassification",kn]],["albert",["AlbertForSequenceClassification",hn]],["distilbert",["DistilBertForSequenceClassification",Jr]],["roberta",["RobertaForSequenceClassification",ui]],["xlm",["XLMForSequenceClassification",lr]],["xlm-roberta",["XLMRobertaForSequenceClassification",$r]],["bart",["BartForSequenceClassification",N]],["mbart",["MBartForSequenceClassification",qe]],["mobilebert",["MobileBertForSequenceClassification",Rr]],["squeezebert",["SqueezeBertForSequenceClassification",Ni]]]),id=new Map([["bert",["BertForTokenClassification",Dt]],["roformer",["RoFormerForTokenClassification",bt]],["electra",["ElectraForTokenClassification",$t]],["esm",["EsmForTokenClassification",Hr]],["convbert",["ConvBertForTokenClassification",D]],["camembert",["CamembertForTokenClassification",We]],["deberta",["DebertaForTokenClassification",jt]],["deberta-v2",["DebertaV2ForTokenClassification",nr]],["mpnet",["MPNetForTokenClassification",$n]],["distilbert",["DistilBertForTokenClassification",Br]],["roberta",["RobertaForTokenClassification",tt]],["xlm",["XLMForTokenClassification",ki]],["xlm-roberta",["XLMRobertaForTokenClassification",Nr]]]),Ca=new Map([["t5",["T5ForConditionalGeneration",Pn]],["longt5",["LongT5ForConditionalGeneration",In]],["mt5",["MT5ForConditionalGeneration",qr]],["bart",["BartForConditionalGeneration",x]],["mbart",["MBartForConditionalGeneration",ve]],["marian",["MarianMTModel",wl]],["m2m_100",["M2M100ForConditionalGeneration",bl]],["blenderbot",["BlenderbotForConditionalGeneration",Vt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",hr]]]),ds=new Map([["bloom",["BloomForCausalLM",wo]],["gpt2",["GPT2LMHeadModel",Ka]],["gptj",["GPTJForCausalLM",Ja]],["gpt_bigcode",["GPTBigCodeForCausalLM",Vu]],["gpt_neo",["GPTNeoForCausalLM",Xa]],["gpt_neox",["GPTNeoXForCausalLM",Ya]],["codegen",["CodeGenForCausalLM",Xn]],["llama",["LlamaForCausalLM",ro]],["cohere",["CohereForCausalLM",no]],["gemma",["GemmaForCausalLM",ao]],["gemma2",["Gemma2ForCausalLM",lo]],["openelm",["OpenELMForCausalLM",co]],["qwen2",["Qwen2ForCausalLM",ho]],["phi",["PhiForCausalLM",mo]],["phi3",["Phi3ForCausalLM",Os]],["mpt",["MptForCausalLM",yo]],["opt",["OPTForCausalLM",vo]],["mbart",["MBartForCausalLM",St]],["mistral",["MistralForCausalLM",os]],["starcoder2",["Starcoder2ForCausalLM",ha]],["falcon",["FalconForCausalLM",Dl]],["trocr",["TrOCRForCausalLM",zl]],["stablelm",["StableLmForCausalLM",Vl]]]),Zl=new Map([["bert",["BertForMaskedLM",Qe]],["roformer",["RoFormerForMaskedLM",et]],["electra",["ElectraForMaskedLM",ct]],["esm",["EsmForMaskedLM",Zi]],["convbert",["ConvBertForMaskedLM",S]],["camembert",["CamembertForMaskedLM",Ee]],["deberta",["DebertaForMaskedLM",zt]],["deberta-v2",["DebertaV2ForMaskedLM",Yt]],["mpnet",["MPNetForMaskedLM",Cn]],["albert",["AlbertForMaskedLM",sr]],["distilbert",["DistilBertForMaskedLM",Nt]],["roberta",["RobertaForMaskedLM",wi]],["xlm",["XLMWithLMHeadModel",vi]],["xlm-roberta",["XLMRobertaForMaskedLM",Rt]],["mobilebert",["MobileBertForMaskedLM",Ri]],["squeezebert",["SqueezeBertForMaskedLM",pn]]]),Jl=new Map([["bert",["BertForQuestionAnswering",Ke]],["roformer",["RoFormerForQuestionAnswering",kt]],["electra",["ElectraForQuestionAnswering",Ne]],["convbert",["ConvBertForQuestionAnswering",ne]],["camembert",["CamembertForQuestionAnswering",Ze]],["deberta",["DebertaForQuestionAnswering",Qt]],["deberta-v2",["DebertaV2ForQuestionAnswering",dr]],["mpnet",["MPNetForQuestionAnswering",Sn]],["albert",["AlbertForQuestionAnswering",fn]],["distilbert",["DistilBertForQuestionAnswering",dt]],["roberta",["RobertaForQuestionAnswering",Pi]],["xlm",["XLMForQuestionAnswering",ci]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Qr]],["mobilebert",["MobileBertForQuestionAnswering",Ji]],["squeezebert",["SqueezeBertForQuestionAnswering",Ki]]]),ka=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",vs]]]),jd=new Map([["llava",["LlavaForConditionalGeneration",gn]],["moondream1",["Moondream1ForConditionalGeneration",mr]],["florence2",["Florence2ForConditionalGeneration",Ms]]]),nd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",vs]]]),eu=new Map([["vit",["ViTForImageClassification",xo]],["fastvit",["FastViTForImageClassification",Co]],["mobilevit",["MobileViTForImageClassification",Po]],["mobilevitv2",["MobileViTV2ForImageClassification",Ao]],["beit",["BeitForImageClassification",Bo]],["deit",["DeiTForImageClassification",Ho]],["convnext",["ConvNextForImageClassification",al]],["convnextv2",["ConvNextV2ForImageClassification",ul]],["dinov2",["Dinov2ForImageClassification",cl]],["resnet",["ResNetForImageClassification",Qo]],["swin",["SwinForImageClassification",Zo]],["segformer",["SegformerForImageClassification",Rl]],["efficientnet",["EfficientNetForImageClassification",Wl]],["mobilenet_v1",["MobileNetV1ForImageClassification",Zu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Kl]],["mobilenet_v3",["MobileNetV3ForImageClassification",Ju]],["mobilenet_v4",["MobileNetV4ForImageClassification",Ta]]]),sd=new Map([["detr",["DetrForObjectDetection",Lo]],["rt_detr",["RTDetrForObjectDetection",ts]],["table-transformer",["TableTransformerForObjectDetection",Go]],["yolos",["YolosForObjectDetection",hl]]]),tu=new Map([["owlvit",["OwlViTForObjectDetection",Fo]],["owlv2",["Owlv2ForObjectDetection",Oo]]]),ru=new Map([["detr",["DetrForSegmentation",Ro]],["clipseg",["CLIPSegForImageSegmentation",Ga]]]),iu=new Map([["segformer",["SegformerForSemanticSegmentation",Nl]]]),nu=new Map([["sam",["SamModel",_l]]]),ad=new Map([["wav2vec2",["Wav2Vec2ForCTC",qu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ss]],["unispeech",["UniSpeechForCTC",Ml]],["unispeech-sat",["UniSpeechSatForCTC",sa]],["wavlm",["WavLMForCTC",la]],["hubert",["HubertForCTC",kl]]]),su=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",rn]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Cl]],["unispeech",["UniSpeechForSequenceClassification",xl]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Tl]],["wavlm",["WavLMForSequenceClassification",Sl]],["hubert",["HubertForSequenceClassification",oa]],["audio-spectrogram-transformer",["ASTForAudioClassification",Hn]]]),au=new Map([["wavlm",["WavLMForXVector",El]]]),ou=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",is]],["wavlm",["WavLMForAudioFrameClassification",Pl]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",nn]],["pyannote",["PyAnnoteForAudioFrameClassification",sn]]]),lu=new Map([["vitmatte",["VitMatteForImageMatting",$o]]]),od=new Map([["swin2sr",["Swin2SRForImageSuperResolution",qs]]]),uu=new Map([["dpt",["DPTForDepthEstimation",Xs]],["depth_anything",["DepthAnythingForDepthEstimation",tl]],["glpn",["GLPNForDepthEstimation",il]]]),du=new Map([["clip",["CLIPVisionModelWithProjection",La]],["siglip",["SiglipVisionModel",Na]]]),cu=[[ed,he.EncoderOnly],[td,he.EncoderDecoder],[rd,he.DecoderOnly],[Yl,he.EncoderOnly],[id,he.EncoderOnly],[Ca,he.Seq2Seq],[us,he.Seq2Seq],[ds,he.DecoderOnly],[Zl,he.EncoderOnly],[Jl,he.EncoderOnly],[ka,he.Vision2Seq],[jd,he.ImageTextToText],[eu,he.EncoderOnly],[ru,he.EncoderOnly],[iu,he.EncoderOnly],[lu,he.EncoderOnly],[od,he.EncoderOnly],[uu,he.EncoderOnly],[sd,he.EncoderOnly],[tu,he.EncoderOnly],[nu,he.MaskGeneration],[ad,he.EncoderOnly],[su,he.EncoderOnly],[Xl,he.Seq2Seq],[Ql,he.EncoderOnly],[au,he.EncoderOnly],[ou,he.EncoderOnly],[du,he.EncoderOnly]];for(const[M,T]of cu)for(const[O,ie]of M.values())ye.set(O,T),K.set(ie,O),ge.set(O,ie);const ld=[["MusicgenForConditionalGeneration",ba,he.Musicgen],["CLIPTextModelWithProjection",Vi,he.EncoderOnly],["SiglipTextModel",Ra,he.EncoderOnly],["ClapTextModelWithProjection",jl,he.EncoderOnly],["ClapAudioModelWithProjection",Ll,he.EncoderOnly]];for(const[M,T,O]of ld)ye.set(M,O),K.set(T,M),ge.set(M,T);class pu extends Vr{}De(pu,"MODEL_CLASS_MAPPINGS",cu.map(T=>T[0])),De(pu,"BASE_IF_FAIL",!0);class yi extends Vr{}De(yi,"MODEL_CLASS_MAPPINGS",[Yl]);class hu extends Vr{}De(hu,"MODEL_CLASS_MAPPINGS",[id]);class fu extends Vr{}De(fu,"MODEL_CLASS_MAPPINGS",[Ca]);class $a extends Vr{}De($a,"MODEL_CLASS_MAPPINGS",[us]);class mu extends Vr{}De(mu,"MODEL_CLASS_MAPPINGS",[Xl]);class Rn extends Vr{}De(Rn,"MODEL_CLASS_MAPPINGS",[Ql]);class _u extends Vr{}De(_u,"MODEL_CLASS_MAPPINGS",[ds]);class gu extends Vr{}De(gu,"MODEL_CLASS_MAPPINGS",[Zl]);class Sa extends Vr{}De(Sa,"MODEL_CLASS_MAPPINGS",[Jl]);class wu extends Vr{}De(wu,"MODEL_CLASS_MAPPINGS",[ka]);class yu extends Vr{}De(yu,"MODEL_CLASS_MAPPINGS",[eu]);class Ea extends Vr{}De(Ea,"MODEL_CLASS_MAPPINGS",[ru]);class bu extends Vr{}De(bu,"MODEL_CLASS_MAPPINGS",[iu]);class vu extends Vr{}De(vu,"MODEL_CLASS_MAPPINGS",[sd]);class Mu extends Vr{}De(Mu,"MODEL_CLASS_MAPPINGS",[tu]);class Pa extends Vr{}De(Pa,"MODEL_CLASS_MAPPINGS",[nu]);class xu extends Vr{}De(xu,"MODEL_CLASS_MAPPINGS",[ad]);class Tu extends Vr{}De(Tu,"MODEL_CLASS_MAPPINGS",[su]);class Aa extends Vr{}De(Aa,"MODEL_CLASS_MAPPINGS",[au]);class Cu extends Vr{}De(Cu,"MODEL_CLASS_MAPPINGS",[ou]);class ud extends Vr{}De(ud,"MODEL_CLASS_MAPPINGS",[nd]);class ku extends Vr{}De(ku,"MODEL_CLASS_MAPPINGS",[lu]);class $u extends Vr{}De($u,"MODEL_CLASS_MAPPINGS",[od]);class Su extends Vr{}De(Su,"MODEL_CLASS_MAPPINGS",[uu]);class Eu extends Vr{}De(Eu,"MODEL_CLASS_MAPPINGS",[du]);class Ld extends nt{constructor({logits:T,past_key_values:O,encoder_outputs:ie,decoder_attentions:Ue=null,cross_attentions:He=null}){super(),this.logits=T,this.past_key_values=O,this.encoder_outputs=ie,this.decoder_attentions=Ue,this.cross_attentions=He}}class wr extends nt{constructor({logits:T}){super(),this.logits=T}}class Pu extends nt{constructor({logits:T,embeddings:O}){super(),this.logits=T,this.embeddings=O}}class oi extends nt{constructor({logits:T}){super(),this.logits=T}}class hi extends nt{constructor({logits:T}){super(),this.logits=T}}class fi extends nt{constructor({start_logits:T,end_logits:O}){super(),this.start_logits=T,this.end_logits=O}}class ln extends nt{constructor({logits:T}){super(),this.logits=T}}class dd extends nt{constructor({logits:T,past_key_values:O}){super(),this.logits=T,this.past_key_values=O}}class Au extends nt{constructor({alphas:T}){super(),this.alphas=T}}class cd extends nt{constructor({waveform:T,spectrogram:O}){super(),this.waveform=T,this.spectrogram=O}}},"./src/models/whisper/common_whisper.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{WHISPER_LANGUAGE_MAPPING:()=>re,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ke,whisper_language_to_code:()=>ze});const P=[["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"]],re=new Map(P),ke=new Map([...P.map(([Oe,V])=>[V,Oe]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ze(Oe){Oe=Oe.toLowerCase();let V=ke.get(Oe);if(V===void 0)if(re.has(Oe))V=Oe;else{const H=Oe.length===2?re.keys():re.values();throw new Error(`Language "${Oe}" is not supported. Must be one of: ${JSON.stringify(H)}`)}return V}},"./src/models/whisper/generation_whisper.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{WhisperGenerationConfig:()=>re});var P=m("./src/generation/configuration_utils.js");class re extends P.GenerationConfig{constructor(){super(...arguments);De(this,"return_timestamps",null);De(this,"return_token_timestamps",null);De(this,"num_frames",null);De(this,"alignment_heads",null);De(this,"task",null);De(this,"language",null);De(this,"no_timestamps_token_id",null);De(this,"prompt_ids",null);De(this,"is_multilingual",null);De(this,"lang_to_id",null);De(this,"task_to_id",null);De(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{TensorOpRegistry:()=>ze});var P=m("./src/backends/onnx.js"),re=m("./src/utils/tensor.js");const ke=async(Oe,V,A)=>{const H=await(0,P.createInferenceSession)(new Uint8Array(Oe),V);return async B=>{const le=Object.fromEntries(Object.entries(B).map(([pe,fe])=>[pe,fe.ort_tensor])),de=await H.run(le);return Array.isArray(A)?A.map(pe=>new re.Tensor(de[pe])):new re.Tensor(de[A])}};class ze{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ke([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=ke([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=ke([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=ke([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=ke([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=ke([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}}De(ze,"session_options",{})},"./src/pipelines.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{AudioClassificationPipeline:()=>Ve,AutomaticSpeechRecognitionPipeline:()=>pt,DepthEstimationPipeline:()=>ft,DocumentQuestionAnsweringPipeline:()=>ue,FeatureExtractionPipeline:()=>Se,FillMaskPipeline:()=>ye,ImageClassificationPipeline:()=>Tt,ImageFeatureExtractionPipeline:()=>Be,ImageSegmentationPipeline:()=>$e,ImageToImagePipeline:()=>xt,ImageToTextPipeline:()=>ot,ObjectDetectionPipeline:()=>Me,Pipeline:()=>fe,QuestionAnsweringPipeline:()=>he,SummarizationPipeline:()=>K,Text2TextGenerationPipeline:()=>ge,TextClassificationPipeline:()=>q,TextGenerationPipeline:()=>j,TextToAudioPipeline:()=>nt,TokenClassificationPipeline:()=>ae,TranslationPipeline:()=>R,ZeroShotAudioClassificationPipeline:()=>Ge,ZeroShotClassificationPipeline:()=>Ce,ZeroShotImageClassificationPipeline:()=>X,ZeroShotObjectDetectionPipeline:()=>je,pipeline:()=>gt});var P=m("./src/tokenizers.js"),re=m("./src/models.js"),ke=m("./src/processors.js"),ze=m("./src/utils/generic.js"),Oe=m("./src/utils/core.js"),V=m("./src/utils/maths.js"),A=m("./src/utils/audio.js"),H=m("./src/utils/tensor.js"),B=m("./src/utils/image.js");async function le(Ke){return Array.isArray(Ke)||(Ke=[Ke]),await Promise.all(Ke.map(ce=>B.RawImage.read(ce)))}async function de(Ke,ce){return Array.isArray(Ke)||(Ke=[Ke]),await Promise.all(Ke.map(Re=>typeof Re=="string"||Re instanceof URL?(0,A.read_audio)(Re,ce):Re instanceof Float64Array?new Float32Array(Re):Re))}function pe(Ke,ce){ce&&(Ke=Ke.map(st=>st|0));const[Re,Je,rt,et]=Ke;return{xmin:Re,ymin:Je,xmax:rt,ymax:et}}class fe extends ze.Callable{constructor({task:ce,model:Re,tokenizer:Je=null,processor:rt=null}){super(),this.task=ce,this.model=Re,this.tokenizer=Je,this.processor=rt}async dispose(){await this.model.dispose()}}class q extends fe{constructor(ce){super(ce)}async _call(ce,{top_k:Re=1}={}){const Je=this.tokenizer(ce,{padding:!0,truncation:!0}),rt=await this.model(Je),et=this.model.config.problem_type==="multi_label_classification"?kt=>kt.sigmoid():kt=>new H.Tensor("float32",(0,V.softmax)(kt.data),kt.dims),st=this.model.config.id2label,bt=[];for(const kt of rt.logits){const Et=et(kt),Ot=await(0,H.topk)(Et,Re),S=Ot[0].tolist(),D=Ot[1].tolist().map((ne,xe)=>({label:st?st[ne]:`LABEL_${ne}`,score:S[xe]}));Re===1?bt.push(...D):bt.push(D)}return Array.isArray(ce)||Re===1?bt:bt[0]}}class ae extends fe{constructor(ce){super(ce)}async _call(ce,{ignore_labels:Re=["O"]}={}){const Je=Array.isArray(ce),rt=this.tokenizer(Je?ce:[ce],{padding:!0,truncation:!0}),st=(await this.model(rt)).logits,bt=this.model.config.id2label,kt=[];for(let Et=0;Et$t==this.tokenizer.sep_token_id);kt[S].map(($t,Ne)=>$t==1&&(Ne===0||Ne>D&&Et.findIndex(z=>z==Y[Ne])===-1));const ne=et[S].tolist(),xe=st[S].tolist();for(let $t=1;$tNe==Y[$t])!==-1)&&(ne[$t]=-1/0,xe[$t]=-1/0);const ut=(0,V.softmax)(ne).map(($t,Ne)=>[$t,Ne]),ct=(0,V.softmax)(xe).map(($t,Ne)=>[$t,Ne]);ut[0][0]=0,ct[0][0]=0;const Ut=(0,Oe.product)(ut,ct).filter($t=>$t[0][1]<=$t[1][1]).map($t=>[$t[0][1],$t[1][1],$t[0][0]*$t[1][0]]).sort(($t,Ne)=>Ne[2]-$t[2]);for(let $t=0;$tne==this.tokenizer.mask_token_id);if(Et===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ot=rt[bt][Et],S=await(0,H.topk)(new H.Tensor("float32",(0,V.softmax)(Ot.data),Ot.dims),Re),Y=S[0].tolist(),D=S[1].tolist();et.push(D.map((ne,xe)=>{const ut=kt.slice();return ut[Et]=ne,{score:Y[xe],token:Number(ne),token_str:this.tokenizer.model.vocab[ne],sequence:this.tokenizer.decode(ut,{skip_special_tokens:!0})}}))}return Array.isArray(ce)?et:et[0]}}class ge extends fe{constructor(Re){super(Re);De(this,"_key","generated_text")}async _call(Re,Je={}){Array.isArray(Re)||(Re=[Re]),this.model.config.prefix&&(Re=Re.map(Et=>this.model.config.prefix+Et));const rt=this.model.config.task_specific_params;rt&&rt[this.task]&&rt[this.task].prefix&&(Re=Re.map(Et=>rt[this.task].prefix+Et));const et=this.tokenizer,st={padding:!0,truncation:!0};let bt;this instanceof R&&"_build_translation_inputs"in et?bt=et._build_translation_inputs(Re,st,Je):bt=et(Re,st);const kt=await this.model.generate({...bt,...Je});return et.batch_decode(kt,{skip_special_tokens:!0}).map(Et=>({[this._key]:Et}))}}class K extends ge{constructor(Re){super(Re);De(this,"_key","summary_text")}}class R extends ge{constructor(Re){super(Re);De(this,"_key","translation_text")}}function W(Ke){return Array.isArray(Ke)&&Ke.every(ce=>"role"in ce&&"content"in ce)}class j extends fe{constructor(ce){super(ce)}async _call(ce,Re={}){let Je=!1,rt=!1,et;if(typeof ce=="string")et=ce=[ce];else if(Array.isArray(ce)&&ce.every(D=>typeof D=="string"))Je=!0,et=ce;else{if(W(ce))ce=[ce];else if(Array.isArray(ce)&&ce.every(W))Je=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");rt=!0,et=ce.map(D=>this.tokenizer.apply_chat_template(D,{tokenize:!1,add_generation_prompt:!0}))}const st=Re.add_special_tokens??!1,bt=rt?!1:Re.return_full_text??!0;this.tokenizer.padding_side="left";const kt=this.tokenizer(et,{add_special_tokens:st,padding:!0,truncation:!0}),Et=await this.model.generate({...kt,...Re}),Ot=this.tokenizer.batch_decode(Et,{skip_special_tokens:!0});let S;!bt&&kt.input_ids.dims.at(-1)>0&&(S=this.tokenizer.batch_decode(kt.input_ids,{skip_special_tokens:!0}).map(D=>D.length));const Y=Array.from({length:ce.length},D=>[]);for(let D=0;D[Re.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(ce,Re,{hypothesis_template:Je="This example is {}.",multi_label:rt=!1}={}){const et=Array.isArray(ce);et||(ce=[ce]),Array.isArray(Re)||(Re=[Re]);const st=Re.map(Et=>Je.replace("{}",Et)),bt=rt||Re.length===1,kt=[];for(const Et of ce){const Ot=[];for(const D of st){const ne=this.tokenizer(Et,{text_pair:D,padding:!0,truncation:!0}),xe=await this.model(ne);bt?Ot.push([xe.logits.data[this.contradiction_id],xe.logits.data[this.entailment_id]]):Ot.push(xe.logits.data[this.entailment_id])}const Y=(bt?Ot.map(D=>(0,V.softmax)(D)[1]):(0,V.softmax)(Ot)).map((D,ne)=>[D,ne]).sort((D,ne)=>ne[0]-D[0]);kt.push({sequence:Et,labels:Y.map(D=>Re[D[1]]),scores:Y.map(D=>D[0])})}return et?kt:kt[0]}}class Se extends fe{constructor(ce){super(ce)}async _call(ce,{pooling:Re="none",normalize:Je=!1,quantize:rt=!1,precision:et="binary"}={}){const st=this.tokenizer(ce,{padding:!0,truncation:!0}),bt=await this.model(st);let kt=bt.last_hidden_state??bt.logits??bt.token_embeddings;if(Re!=="none")if(Re==="mean")kt=(0,H.mean_pooling)(kt,st.attention_mask);else if(Re==="cls")kt=kt.slice(null,0);else throw Error(`Pooling method '${Re}' not supported.`);return Je&&(kt=kt.normalize(2,-1)),rt&&(kt=(0,H.quantize_embeddings)(kt,et)),kt}}class Be extends fe{constructor(ce){super(ce)}async _call(ce,{pool:Re=null}={}){const Je=await le(ce),{pixel_values:rt}=await this.processor(Je),et=await this.model({pixel_values:rt});let st;if(Re){if(!("pooler_output"in et))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");st=et.pooler_output}else st=et.last_hidden_state??et.logits??et.image_embeds;return st}}class Ve extends fe{constructor(ce){super(ce)}async _call(ce,{top_k:Re=5}={}){const Je=this.processor.feature_extractor.config.sampling_rate,rt=await de(ce,Je),et=this.model.config.id2label,st=[];for(const bt of rt){const kt=await this.processor(bt),Ot=(await this.model(kt)).logits[0],S=await(0,H.topk)(new H.Tensor("float32",(0,V.softmax)(Ot.data),Ot.dims),Re),Y=S[0].tolist(),ne=S[1].tolist().map((xe,ut)=>({label:et?et[xe]:`LABEL_${xe}`,score:Y[ut]}));st.push(ne)}return Array.isArray(ce)?st:st[0]}}class Ge extends fe{constructor(ce){super(ce)}async _call(ce,Re,{hypothesis_template:Je="This is a sound of {}."}={}){const rt=!Array.isArray(ce);rt&&(ce=[ce]);const et=Re.map(Ot=>Je.replace("{}",Ot)),st=this.tokenizer(et,{padding:!0,truncation:!0}),bt=this.processor.feature_extractor.config.sampling_rate,kt=await de(ce,bt),Et=[];for(const Ot of kt){const S=await this.processor(Ot),Y=await this.model({...st,...S}),D=(0,V.softmax)(Y.logits_per_audio.data);Et.push([...D].map((ne,xe)=>({score:ne,label:Re[xe]})))}return rt?Et[0]:Et}}class pt extends fe{constructor(ce){super(ce)}async _call(ce,Re={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ce,Re);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ce,Re);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ce,Re){Re.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Re.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Je=!Array.isArray(ce);Je&&(ce=[ce]);const rt=this.processor.feature_extractor.config.sampling_rate,et=await de(ce,rt),st=[];for(const bt of et){const kt=await this.processor(bt),Ot=(await this.model(kt)).logits[0],S=[];for(const D of Ot)S.push((0,V.max)(D.data)[1]);const Y=this.tokenizer.decode(S);st.push({text:Y})}return Je?st[0]:st}async _call_whisper(ce,Re){const Je=Re.return_timestamps??!1,rt=Re.chunk_length_s??0,et=Re.force_full_sequences??!1;let st=Re.stride_length_s??null;const bt={...Re};Je==="word"&&(bt.return_token_timestamps=!0,bt.return_timestamps=!1);const kt=!Array.isArray(ce);kt&&(ce=[ce]);const Et=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ot=this.processor.feature_extractor.config.hop_length,S=this.processor.feature_extractor.config.sampling_rate,Y=await de(ce,S),D=[];for(const ne of Y){let xe=[];if(rt>0){if(st===null)st=rt/6;else if(rt<=st)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ut=S*rt,$t=S*st,Ne=Ut-2*$t;let z=0;for(;;){const ee=z+Ut,Ee=ne.subarray(z,ee),Xe=await this.processor(Ee),We=z===0,Ze=ee>=ne.length;if(xe.push({stride:[Ee.length,We?0:$t,Ze?0:$t],input_features:Xe.input_features,is_last:Ze}),Ze)break;z+=Ne}}else xe=[{stride:[ne.length,0,0],input_features:(await this.processor(ne)).input_features,is_last:!0}];for(const Ut of xe){bt.num_frames=Math.floor(Ut.stride[0]/Ot);const $t=await this.model.generate({inputs:Ut.input_features,...bt});Je==="word"?(Ut.tokens=$t.sequences.tolist()[0],Ut.token_timestamps=$t.token_timestamps.tolist()[0].map(Ne=>(0,V.round)(Ne,2))):Ut.tokens=$t[0].tolist(),Ut.stride=Ut.stride.map(Ne=>Ne/S)}const[ut,ct]=this.tokenizer._decode_asr(xe,{time_precision:Et,return_timestamps:Je,force_full_sequences:et});D.push({text:ut,...ct})}return kt?D[0]:D}}class ot extends fe{constructor(ce){super(ce)}async _call(ce,Re={}){const Je=Array.isArray(ce),rt=await le(ce),{pixel_values:et}=await this.processor(rt),st=[];for(const bt of et){bt.dims=[1,...bt.dims];const kt=await this.model.generate({inputs:bt,...Re}),Et=this.tokenizer.batch_decode(kt,{skip_special_tokens:!0}).map(Ot=>({generated_text:Ot.trim()}));st.push(Et)}return Je?st:st[0]}}class Tt extends fe{constructor(ce){super(ce)}async _call(ce,{top_k:Re=5}={}){const Je=await le(ce),{pixel_values:rt}=await this.processor(Je),et=await this.model({pixel_values:rt}),st=this.model.config.id2label,bt=[];for(const kt of et.logits){const Et=await(0,H.topk)(new H.Tensor("float32",(0,V.softmax)(kt.data),kt.dims),Re),Ot=Et[0].tolist(),Y=Et[1].tolist().map((D,ne)=>({label:st?st[D]:`LABEL_${D}`,score:Ot[ne]}));bt.push(Y)}return Array.isArray(ce)?bt:bt[0]}}class $e extends fe{constructor(ce){super(ce),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ce,{threshold:Re=.5,mask_threshold:Je=.5,overlap_mask_area_threshold:rt=.8,label_ids_to_fuse:et=null,target_sizes:st=null,subtask:bt=null}={}){if(Array.isArray(ce)&&ce.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Et=await le(ce),Ot=Et.map(ct=>[ct.height,ct.width]),{pixel_values:S,pixel_mask:Y}=await this.processor(Et),D=await this.model({pixel_values:S,pixel_mask:Y});let ne=null;if(bt!==null)ne=this.subtasks_mapping[bt];else for(let[ct,Ut]of Object.entries(this.subtasks_mapping))if(Ut in this.processor.feature_extractor){ne=this.processor.feature_extractor[Ut].bind(this.processor.feature_extractor),bt=ct;break}const xe=this.model.config.id2label,ut=[];if(bt==="panoptic"||bt==="instance"){const ct=ne(D,Re,Je,rt,et,st??Ot)[0],Ut=ct.segmentation;for(const $t of ct.segments_info){const Ne=new Uint8ClampedArray(Ut.data.length);for(let ee=0;eeJe.replace("{}",Y)),bt=this.tokenizer(st,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:kt}=await this.processor(et),Et=await this.model({...bt,pixel_values:kt}),Ot=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,V.softmax)(Y.data),S=[];for(const Y of Et.logits_per_image){const ne=[...Ot(Y)].map((xe,ut)=>({score:xe,label:Re[ut]}));ne.sort((xe,ut)=>ut.score-xe.score),S.push(ne)}return rt?S:S[0]}}class Me extends fe{constructor(ce){super(ce)}async _call(ce,{threshold:Re=.9,percentage:Je=!1}={}){const rt=Array.isArray(ce);if(rt&&ce.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const et=await le(ce),st=Je?null:et.map(D=>[D.height,D.width]),{pixel_values:bt,pixel_mask:kt}=await this.processor(et),Et=await this.model({pixel_values:bt,pixel_mask:kt}),Ot=this.processor.feature_extractor.post_process_object_detection(Et,Re,st),S=this.model.config.id2label,Y=Ot.map(D=>D.boxes.map((ne,xe)=>({score:D.scores[xe],label:S[D.classes[xe]],box:pe(ne,!Je)})));return rt?Y:Y[0]}}class je extends fe{constructor(ce){super(ce)}async _call(ce,Re,{threshold:Je=.1,top_k:rt=null,percentage:et=!1}={}){const st=Array.isArray(ce),bt=await le(ce),kt=this.tokenizer(Re,{padding:!0,truncation:!0}),Et=await this.processor(bt),Ot=[];for(let S=0;S({score:ut.scores[$t],label:Re[ut.classes[$t]],box:pe(Ut,!et)})).sort((Ut,$t)=>$t.score-Ut.score);rt!==null&&(ct=ct.slice(0,rt)),Ot.push(ct)}return st?Ot:Ot[0]}}class ue extends fe{constructor(ce){super(ce)}async _call(ce,Re,Je={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class nt extends fe{constructor(Re){super(Re);De(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Re.vocoder??null}async _call(Re,{speaker_embeddings:Je=null}={}){return this.processor?this._call_text_to_spectrogram(Re,{speaker_embeddings:Je}):this._call_text_to_waveform(Re)}async _call_text_to_waveform(Re){const Je=this.tokenizer(Re,{padding:!0,truncation:!0}),{waveform:rt}=await this.model(Je),et=this.model.config.sampling_rate;return{audio:rt.data,sampling_rate:et}}async _call_text_to_spectrogram(Re,{speaker_embeddings:Je}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await re.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 H.Tensor("float32",Je,[1,Je.length]);else if(!(Je instanceof H.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:rt}=this.tokenizer(Re,{padding:!0,truncation:!0}),{waveform:et}=await this.model.generate_speech(rt,Je,{vocoder:this.vocoder}),st=this.processor.feature_extractor.config.sampling_rate;return{audio:et.data,sampling_rate:st}}}class xt extends fe{constructor(ce){super(ce)}async _call(ce){const Re=await le(ce),Je=await this.processor(Re),rt=await this.model(Je),et=[];for(const st of rt.reconstruction){const bt=st.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");et.push(B.RawImage.fromTensor(bt))}return et.length>1?et:et[0]}}class ft extends fe{constructor(ce){super(ce)}async _call(ce){const Re=await le(ce),Je=await this.processor(Re),{predicted_depth:rt}=await this.model(Je),et=[];for(let st=0;st1?et:et[0]}}const yt=Object.freeze({"text-classification":{tokenizer:P.AutoTokenizer,pipeline:q,model:re.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:P.AutoTokenizer,pipeline:ae,model:re.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:P.AutoTokenizer,pipeline:he,model:re.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:P.AutoTokenizer,pipeline:ye,model:re.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:P.AutoTokenizer,pipeline:K,model:re.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:P.AutoTokenizer,pipeline:R,model:re.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:P.AutoTokenizer,pipeline:ge,model:re.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:P.AutoTokenizer,pipeline:j,model:re.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:P.AutoTokenizer,pipeline:Ce,model:re.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Ve,model:re.AutoModelForAudioClassification,processor:ke.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:P.AutoTokenizer,pipeline:Ge,model:re.AutoModel,processor:ke.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:P.AutoTokenizer,pipeline:pt,model:[re.AutoModelForSpeechSeq2Seq,re.AutoModelForCTC],processor:ke.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:P.AutoTokenizer,pipeline:nt,model:[re.AutoModelForTextToWaveform,re.AutoModelForTextToSpectrogram],processor:[ke.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:P.AutoTokenizer,pipeline:ot,model:re.AutoModelForVision2Seq,processor:ke.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Tt,model:re.AutoModelForImageClassification,processor:ke.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:$e,model:[re.AutoModelForImageSegmentation,re.AutoModelForSemanticSegmentation],processor:ke.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:P.AutoTokenizer,pipeline:X,model:re.AutoModel,processor:ke.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Me,model:re.AutoModelForObjectDetection,processor:ke.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:P.AutoTokenizer,pipeline:je,model:re.AutoModelForZeroShotObjectDetection,processor:ke.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:P.AutoTokenizer,pipeline:ue,model:re.AutoModelForDocumentQuestionAnswering,processor:ke.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:xt,model:re.AutoModelForImageToImage,processor:ke.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ft,model:re.AutoModelForDepthEstimation,processor:ke.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:P.AutoTokenizer,pipeline:Se,model:re.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ke.AutoProcessor,pipeline:Be,model:[re.AutoModelForImageFeatureExtraction,re.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Qe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function gt(Ke,ce=null,{progress_callback:Re=null,config:Je=null,cache_dir:rt=null,local_files_only:et=!1,revision:st="main",device:bt=null,dtype:kt=null,model_file_name:Et=null,session_options:Ot={}}={}){Ke=Qe[Ke]??Ke;const S=yt[Ke.split("_",1)[0]];if(!S)throw Error(`Unsupported pipeline: ${Ke}. Must be one of [${Object.keys(yt)}]`);ce||(ce=S.default.model,console.log(`No model specified. Using default model: "${ce}".`));const Y={progress_callback:Re,config:Je,cache_dir:rt,local_files_only:et,revision:st,device:bt,dtype:kt,model_file_name:Et,session_options:Ot},D=new Map([["tokenizer",S.tokenizer],["model",S.model],["processor",S.processor]]),ne=await Dt(D,ce,Y);ne.task=Ke,(0,Oe.dispatchCallback)(Re,{status:"ready",task:Ke,model:ce});const xe=S.pipeline;return new xe(ne)}async function Dt(Ke,ce,Re){const Je=Object.create(null),rt=[];for(let[et,st]of Ke.entries()){if(!st)continue;let bt;Array.isArray(st)?bt=new Promise(async(kt,Et)=>{var S,Y;let Ot;for(let D of st){if(D===null){kt(null);return}try{kt(await D.from_pretrained(ce,Re));return}catch(ne){if((S=ne.message)!=null&&S.includes("Unsupported model type"))Ot=ne;else if((Y=ne.message)!=null&&Y.includes("Could not locate file"))Ot=ne;else{Et(ne);return}}}Et(Ot)}):bt=st.from_pretrained(ce,Re),Je[et]=bt,rt.push(bt)}await Promise.all(rt);for(let[et,st]of Object.entries(Je))Je[et]=await st;return Je}},"./src/processors.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{ASTFeatureExtractor:()=>st,AutoProcessor:()=>$t,BeitFeatureExtractor:()=>ft,BitImageProcessor:()=>ye,CLIPFeatureExtractor:()=>K,CLIPImageProcessor:()=>R,ChineseCLIPFeatureExtractor:()=>W,ClapFeatureExtractor:()=>bt,ConvNextFeatureExtractor:()=>Ce,ConvNextImageProcessor:()=>Se,DPTFeatureExtractor:()=>ae,DPTImageProcessor:()=>he,DeiTFeatureExtractor:()=>xt,DetrFeatureExtractor:()=>gt,DonutFeatureExtractor:()=>yt,EfficientNetImageProcessor:()=>Ge,FeatureExtractor:()=>pe,Florence2Processor:()=>Ut,GLPNFeatureExtractor:()=>ge,ImageFeatureExtractor:()=>fe,MobileNetV1FeatureExtractor:()=>pt,MobileNetV2FeatureExtractor:()=>ot,MobileNetV3FeatureExtractor:()=>Tt,MobileNetV4FeatureExtractor:()=>$e,MobileViTFeatureExtractor:()=>X,MobileViTImageProcessor:()=>Me,NougatImageProcessor:()=>Qe,OwlViTFeatureExtractor:()=>je,OwlViTProcessor:()=>ct,Owlv2ImageProcessor:()=>ue,Processor:()=>S,PyAnnoteFeatureExtractor:()=>kt,PyAnnoteProcessor:()=>xe,RTDetrImageProcessor:()=>nt,SamImageProcessor:()=>Ke,SamProcessor:()=>Y,SeamlessM4TFeatureExtractor:()=>et,SegformerFeatureExtractor:()=>q,SiglipImageProcessor:()=>j,SpeechT5FeatureExtractor:()=>Ot,SpeechT5Processor:()=>ut,Swin2SRImageProcessor:()=>ce,ViTFeatureExtractor:()=>Be,ViTImageProcessor:()=>Ve,VitMatteImageProcessor:()=>Re,Wav2Vec2FeatureExtractor:()=>rt,Wav2Vec2ProcessorWithLM:()=>ne,WeSpeakerFeatureExtractor:()=>Et,WhisperFeatureExtractor:()=>Je,WhisperProcessor:()=>D,YolosFeatureExtractor:()=>Dt});var P=m("./src/utils/generic.js"),re=m("./src/utils/core.js"),ke=m("./src/utils/hub.js"),ze=m("./src/utils/maths.js"),Oe=m("./src/utils/tensor.js");m("./src/utils/image.js");var V=m("./src/utils/audio.js");function A([Ne,z,ee,Ee]){return[Ne-ee/2,z-Ee/2,Ne+ee/2,z+Ee/2]}function H(Ne,z=.5,ee=null,Ee=!1){const Xe=Ne.logits,We=Ne.pred_boxes,[Ze,vt,_t]=Xe.dims;if(ee!==null&&ee.length!==Ze)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let zt=[];for(let Ct=0;Ctz&&nr.push(rr)}else{let rr=(0,ze.max)(ir.data)[1];if(rr===_t-1||(dr=(0,ze.softmax)(ir.data),dr[rr]Jr*jt[(Br+1)%2])),Qt.boxes.push(Dr),Qt.classes.push(rr),Qt.scores.push(dr[rr])}}zt.push(Qt)}return zt}function B(Ne,z){var ee;if(!(Ne instanceof Float32Array||Ne instanceof Float64Array))throw new Error(`${z} expects input to be a Float32Array or a Float64Array, but got ${((ee=Ne==null?void 0:Ne.constructor)==null?void 0:ee.name)??typeof Ne} 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 le(Ne,z,ee=0,Ee=null){const Xe=Ne/z;let We=(0,ze.bankers_round)(Xe)*z;return Ee!==null&&We>Ee&&(We=Math.floor(Xe)*z),WeWe?zt=Math.floor(We*_t/Xe):We>Xe&&(_t=Math.floor(Xe*zt/We)),await z.resize(zt,_t,{resample:Ee}))}async crop_margin(z,ee=200){const Ee=z.clone().grayscale(),Xe=(0,ze.min)(Ee.data)[0],Ze=(0,ze.max)(Ee.data)[0]-Xe;if(Ze===0)return z;const vt=ee/255;let _t=Ee.width,zt=Ee.height,Ct=0,jt=0;const Qt=Ee.data;for(let at=0;atthis.preprocess(We)));return{pixel_values:(0,Oe.stack)(Ee.map(We=>We.pixel_values),0),original_sizes:Ee.map(We=>We.original_size),reshaped_input_sizes:Ee.map(We=>We.reshaped_input_size)}}}class q extends fe{post_process_semantic_segmentation(z,ee=null){const Ee=z.logits,Xe=Ee.dims[0];if(ee!==null&&ee.length!==Xe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const We=[];for(let Ze=0;ZeQt[rr]&&(Qt[rr]=dr[rr],at[rr]=nr)}const Zt=new Array(_t.dims[0]),Yt=jt.data;for(let nr=0;nrnr!==void 0);We.push({segmentation:jt,labels:ir})}return We}}class ae extends fe{}class he extends ae{}class ye extends fe{}class ge extends fe{}class K extends fe{}class R extends K{}class W extends fe{}class j extends fe{}class Ce extends fe{constructor(z){super(z),this.crop_pct=this.config.crop_pct??.875}async resize(z){var Ee;const ee=(Ee=this.size)==null?void 0:Ee.shortest_edge;if(ee===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ee<384){const Xe=Math.floor(ee/this.crop_pct),[We,Ze]=this.get_resize_output_image_size(z,{shortest_edge:Xe});z=await z.resize(We,Ze,{resample:this.resample}),z=await z.center_crop(ee,ee)}else z=await z.resize(ee,ee,{resample:this.resample});return z}}class Se extends Ce{}class Be extends fe{}class Ve extends fe{}class Ge extends fe{constructor(z){super(z),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ee=>ee*ee))}}class pt extends fe{}class ot extends fe{}class Tt extends fe{}class $e extends fe{}class X extends fe{}class Me extends X{}class je extends fe{post_process_object_detection(...z){return H(...z)}}class ue extends je{}class nt extends fe{post_process_object_detection(...z){return H(...z)}}class xt extends fe{}class ft extends fe{}class yt extends fe{pad_image(z,ee,Ee,Xe={}){const[We,Ze,vt]=ee;let _t=this.image_mean;Array.isArray(this.image_mean)||(_t=new Array(vt).fill(_t));let zt=this.image_std;Array.isArray(zt)||(zt=new Array(vt).fill(_t));const Ct=_t.map((jt,Qt)=>-jt/zt[Qt]);return super.pad_image(z,ee,Ee,{center:!0,constant_values:Ct,...Xe})}}class Qe extends yt{}class gt extends fe{async _call(z){const ee=await super._call(z),Ee=[ee.pixel_values.dims[0],64,64],Xe=new Oe.Tensor("int64",new BigInt64Array(Ee.reduce((We,Ze)=>We*Ze)).fill(1n),Ee);return{...ee,pixel_mask:Xe}}post_process_object_detection(...z){return H(...z)}remove_low_and_no_objects(z,ee,Ee,Xe){let We=[],Ze=[],vt=[];for(let _t=0;_tEe&&(We.push(Ct),Ze.push(at),vt.push(jt))}return[We,Ze,vt]}check_segment_validity(z,ee,Ee,Xe=.5,We=.8){let Ze=[],vt=0,_t=0;const zt=ee[Ee].data;for(let jt=0;jt=Xe&&++_t;let Ct=vt>0&&_t>0;return Ct&&(Ct=vt/_t>We),[Ct,Ze]}compute_segments(z,ee,Ee,Xe,We,Ze=null,vt=null){let[_t,zt]=vt??z[0].dims,Ct=new Oe.Tensor("int32",new Int32Array(_t*zt),[_t,zt]),jt=[];if(vt!==null)for(let ir=0;irat[rr]&&(Qt[rr]=ir,at[rr]=dr[rr])}let Zt=0;const Yt=Ct.data;for(let ir=0;irXe!==ee.dims[We]))throw Error(`The first ${Ee.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Oe.Tensor("int64",z.flat(1/0).map(BigInt),Ee)}async _call(z,{input_points:ee=null,input_labels:Ee=null,input_boxes:Xe=null}={}){const We=await super._call(z);if(ee&&(We.input_points=this.reshape_input_points(ee,We.original_sizes,We.reshaped_input_sizes)),Ee){if(!We.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");We.input_labels=this.add_input_labels(Ee,We.input_points)}return Xe&&(We.input_boxes=this.reshape_input_points(Xe,We.original_sizes,We.reshaped_input_sizes,!0)),We}async post_process_masks(z,ee,Ee,{mask_threshold:Xe=0,binarize:We=!0,pad_size:Ze=null}={}){const vt=[];Ze=Ze??this.pad_size;const _t=[Ze.height,Ze.width];for(let zt=0;ztXe&&(Zt[Yt]=1);Qt=new Oe.Tensor("bool",Zt,Qt.dims)}vt.push(Qt)}return vt}generate_crop_boxes(z,ee,{crop_n_layers:Ee=0,overlap_ratio:Xe=.3413333333333333,points_per_crop:We=32,crop_n_points_downscale_factor:Ze=1}={}){}}class ce extends fe{pad_image(z,ee,Ee,Xe={}){const[We,Ze,vt]=ee;return super.pad_image(z,ee,{width:Ze+(Ee-Ze%Ee)%Ee,height:We+(Ee-We%Ee)%Ee},{mode:"symmetric",center:!1,constant_values:-1,...Xe})}}class Re extends fe{async _call(z,ee){Array.isArray(z)||(z=[z]),Array.isArray(ee)||(ee=[ee]);const Ee=await Promise.all(z.map(Ze=>this.preprocess(Ze))),Xe=await Promise.all(ee.map(Ze=>this.preprocess(Ze,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Oe.stack)(Ee.map((Ze,vt)=>(0,Oe.cat)([Ze.pixel_values,Xe[vt].pixel_values],0)),0),original_sizes:Ee.map(Ze=>Ze.original_size),reshaped_input_sizes:Ee.map(Ze=>Ze.reshaped_input_size)}}}class Je extends pe{constructor(z){var ee;super(z),(ee=this.config).mel_filters??(ee.mel_filters=(0,V.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,V.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(z){const ee=await(0,V.spectrogram)(z,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}),Ee=ee.data,Xe=(0,ze.max)(Ee)[0];for(let We=0;Wethis.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`."),ee=z.slice(0,this.config.n_samples)):(ee=new Float32Array(this.config.n_samples),ee.set(z)),{input_features:(await this._extract_fbank_features(ee)).unsqueeze_(0)}}}class rt extends pe{_zero_mean_unit_var_norm(z){const Ee=z.reduce((We,Ze)=>We+Ze,0)/z.length,Xe=z.reduce((We,Ze)=>We+(Ze-Ee)**2,0)/z.length;return z.map(We=>(We-Ee)/Math.sqrt(Xe+1e-7))}async _call(z){B(z,"Wav2Vec2FeatureExtractor"),z instanceof Float64Array&&(z=new Float32Array(z));let ee=z;this.config.do_normalize&&(ee=this._zero_mean_unit_var_norm(ee));const Ee=[1,ee.length];return{input_values:new Oe.Tensor("float32",ee,Ee),attention_mask:new Oe.Tensor("int64",new BigInt64Array(ee.length).fill(1n),Ee)}}}class et extends pe{constructor(z){super(z);const ee=this.config.sampling_rate,Ee=(0,V.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ee/2),ee,null,"kaldi",!0);for(let Xe=0;XeEe*32768),(0,V.spectrogram)(z,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:ee,transpose:!0})}async _call(z,{padding:ee=!0,pad_to_multiple_of:Ee=2,do_normalize_per_mel_bins:Xe=!0,return_attention_mask:We=!0}={}){B(z,"SeamlessM4TFeatureExtractor");let Ze=await this._extract_fbank_features(z,this.config.max_length);if(Xe){const[Zt,Yt]=Ze.dims,ir=Ze.data;for(let nr=0;nr0){const dr=new Float32Array(Yt*(Zt+nr));dr.set(ir),dr.fill(this.config.padding_value,ir.length);const rr=Zt+nr;Ze=new Oe.Tensor(Ze.type,dr,[rr,Yt]),We&&(vt=new Oe.Tensor("int64",new BigInt64Array(rr),[1,rr]),vt.data.fill(1n,0,Zt))}}const[_t,zt]=Ze.dims,Ct=this.config.stride;if(_t%Ct!==0)throw new Error(`The number of frames (${_t}) must be a multiple of the stride (${Ct}).`);const Qt=Ze.view(1,Math.floor(_t/Ct),zt*Ct),at={input_features:Qt};if(We){const Zt=Qt.dims[1],Yt=new BigInt64Array(Zt);if(vt){const ir=vt.data;for(let nr=1,dr=0;nr<_t;nr+=Ct,++dr)Yt[dr]=ir[nr]}else Yt.fill(1n);at.attention_mask=new Oe.Tensor("int64",Yt,[1,Zt])}return at}}class st extends pe{constructor(z){super(z);const ee=this.config.sampling_rate,Ee=(0,V.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ee/2),ee,null,"kaldi",!0);for(let Xe=0;Xe0)if(Ee==="rand_trunc"){const vt=Math.floor(Math.random()*(Ze+1));z=z.subarray(vt,vt+ee),We=await this._extract_fbank_features(z,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Ee}" not implemented`);else{if(Ze<0){let vt=new Float64Array(ee);if(vt.set(z),Xe==="repeat")for(let _t=z.length;_t({id:_t,start:zt*Ee,end:Ct*Ee,confidence:jt/(Ct-zt)})))}return Xe}}class Et extends pe{constructor(z){super(z);const ee=this.config.sampling_rate,Ee=(0,V.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ee/2),ee,null,"kaldi",!0);for(let Xe=0;Xeee*32768),(0,V.spectrogram)(z,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(z){B(z,"WeSpeakerFeatureExtractor");const ee=(await this._extract_fbank_features(z)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Ee=ee.mean(1).data,Xe=ee.data,[We,Ze,vt]=ee.dims;for(let _t=0;_t/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(z){typeof z=="string"&&(z=[z]);const ee=[];for(const Ee of z)if(this.task_prompts_without_inputs.has(Ee))ee.push(this.task_prompts_without_inputs.get(Ee));else{for(const[Xe,We]of this.task_prompts_with_input)if(Ee.includes(Xe)){ee.push(We.replaceAll("{input}",Ee).replaceAll(Xe,""));break}ee.length!==z.length&&ee.push(Ee)}return ee}post_process_generation(z,ee,Ee){const Xe=this.tasks_answer_post_processing_type.get(ee)??"pure_text";z=z.replaceAll("","").replaceAll("","");let We;switch(Xe){case"pure_text":We=z;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Ze=Xe==="ocr"?"quad_boxes":"bboxes",vt=z.matchAll(this.regexes[Ze]),_t=[],zt=[];for(const[Ct,jt,...Qt]of vt)_t.push(jt?jt.trim():_t.at(-1)??""),zt.push(Qt.map((at,Zt)=>(Number(at)+.5)/this.size_per_bin*Ee[Zt%2]));We={labels:_t,[Ze]:zt};break;default:throw new Error(`Task "${ee}" (of type "${Xe}") not yet implemented.`)}return{[ee]:We}}}class $t{static async from_pretrained(z,{progress_callback:ee=null,config:Ee=null,cache_dir:Xe=null,local_files_only:We=!1,revision:Ze="main"}={}){let vt=Ee??await(0,ke.getModelJSON)(z,"preprocessor_config.json",!0,{progress_callback:ee,config:Ee,cache_dir:Xe,local_files_only:We,revision:Ze}),_t=vt.feature_extractor_type??vt.image_processor_type,zt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[_t];if(!zt)if(vt.size!==void 0)console.warn(`Feature extractor type "${_t}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),zt=fe;else throw new Error(`Unknown Feature Extractor type: ${_t}`);let Ct=this.PROCESSOR_CLASS_MAPPING[vt.processor_class]??S,jt=new zt(vt);return new Ct(jt)}}De($t,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:fe,WhisperFeatureExtractor:Je,ViTFeatureExtractor:Be,MobileViTFeatureExtractor:X,MobileViTImageProcessor:Me,MobileNetV1FeatureExtractor:pt,MobileNetV2FeatureExtractor:ot,MobileNetV3FeatureExtractor:Tt,MobileNetV4FeatureExtractor:$e,OwlViTFeatureExtractor:je,Owlv2ImageProcessor:ue,CLIPFeatureExtractor:K,CLIPImageProcessor:R,Florence2Processor:Ut,ChineseCLIPFeatureExtractor:W,SiglipImageProcessor:j,ConvNextFeatureExtractor:Ce,ConvNextImageProcessor:Se,SegformerFeatureExtractor:q,BitImageProcessor:ye,DPTImageProcessor:he,DPTFeatureExtractor:ae,GLPNFeatureExtractor:ge,BeitFeatureExtractor:ft,DeiTFeatureExtractor:xt,DetrFeatureExtractor:gt,RTDetrImageProcessor:nt,YolosFeatureExtractor:Dt,DonutFeatureExtractor:yt,NougatImageProcessor:Qe,EfficientNetImageProcessor:Ge,ViTImageProcessor:Ve,VitMatteImageProcessor:Re,SamImageProcessor:Ke,Swin2SRImageProcessor:ce,Wav2Vec2FeatureExtractor:rt,SeamlessM4TFeatureExtractor:et,SpeechT5FeatureExtractor:Ot,ASTFeatureExtractor:st,ClapFeatureExtractor:bt,PyAnnoteFeatureExtractor:kt,WeSpeakerFeatureExtractor:Et}),De($t,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:D,Wav2Vec2ProcessorWithLM:ne,PyAnnoteProcessor:xe,SamProcessor:Y,SpeechT5Processor:ut,OwlViTProcessor:ct,Florence2Processor:Ut})},"./src/tokenizers.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{AlbertTokenizer:()=>Yt,AutoTokenizer:()=>Ci,BartTokenizer:()=>Hr,BertTokenizer:()=>Zt,BlenderbotSmallTokenizer:()=>An,BlenderbotTokenizer:()=>mn,BloomTokenizer:()=>Rr,CLIPTokenizer:()=>sr,CamembertTokenizer:()=>Nt,CodeGenTokenizer:()=>fn,CodeLlamaTokenizer:()=>qn,CohereTokenizer:()=>qr,ConvBertTokenizer:()=>Jr,DebertaTokenizer:()=>dr,DebertaV2Tokenizer:()=>rr,DistilBertTokenizer:()=>dt,ElectraTokenizer:()=>ii,EsmTokenizer:()=>en,FalconTokenizer:()=>$n,GPT2Tokenizer:()=>Gi,GPTNeoXTokenizer:()=>Sn,GemmaTokenizer:()=>pn,Grok1Tokenizer:()=>Ni,HerbertTokenizer:()=>Dr,LlamaTokenizer:()=>qi,M2M100Tokenizer:()=>an,MBart50Tokenizer:()=>Xr,MBartTokenizer:()=>di,MPNetTokenizer:()=>kn,MarianTokenizer:()=>En,MobileBertTokenizer:()=>ir,NllbTokenizer:()=>Hi,NougatTokenizer:()=>_n,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Kn,RoFormerTokenizer:()=>Br,RobertaTokenizer:()=>Ri,SiglipTokenizer:()=>on,SpeechT5Tokenizer:()=>In,SqueezeBertTokenizer:()=>nr,T5Tokenizer:()=>Zi,TokenizerModel:()=>Be,VitsTokenizer:()=>Fn,Wav2Vec2CTCTokenizer:()=>Pn,WhisperTokenizer:()=>hn,XLMRobertaTokenizer:()=>Cn,XLMTokenizer:()=>Ht,is_chinese_char:()=>ge});var P=m("./src/utils/generic.js"),re=m("./src/utils/core.js"),ke=m("./src/utils/hub.js"),ze=m("./src/utils/maths.js"),Oe=m("./src/utils/tensor.js"),V=m("./src/utils/data-structures.js"),A=m("./node_modules/@huggingface/jinja/dist/index.js"),H=m("./src/models/whisper/common_whisper.js"),B=m("./src/utils/constants.js");async function le(Ae,x){const N=await Promise.all([(0,ke.getModelJSON)(Ae,"tokenizer.json",!0,x),(0,ke.getModelJSON)(Ae,"tokenizer_config.json",!0,x)]);return x.legacy!==null&&(N[1].legacy=x.legacy),N}function de(Ae,x){const N=[];let se=0;for(const be of Ae.matchAll(x)){const ve=be[0];se0&&N.push(ve),se=be.index+ve.length}return se=19968&&Ae<=40959||Ae>=13312&&Ae<=19903||Ae>=131072&&Ae<=173791||Ae>=173824&&Ae<=177983||Ae>=177984&&Ae<=178207||Ae>=178208&&Ae<=183983||Ae>=63744&&Ae<=64255||Ae>=194560&&Ae<=195103}function K(Ae,x,N){const se=[];let be=0;for(;bethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens(x){return x.map(N=>this.vocab[N]??this.unk_token)}}class Ve extends Be{constructor(x){super(x),this.tokens_to_ids=fe(x.vocab),this.unk_token_id=this.tokens_to_ids.get(x.unk_token),this.unk_token=x.unk_token,this.max_input_chars_per_word=x.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,se]of this.tokens_to_ids)this.vocab[se]=N}encode(x){const N=[];for(const se of x){const be=[...se];if(be.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let ve=!1,qe=0;const St=[];for(;qe0&&(Vt=this.config.continuing_subword_prefix+Vt),this.tokens_to_ids.has(Vt)){Pt=Vt;break}--At}if(Pt===null){ve=!0;break}St.push(Pt),qe=At}ve?N.push(this.unk_token):N.push(...St)}return N}}class Ge extends Be{constructor(x,N){super(x);const se=x.vocab.length;this.vocab=new Array(se),this.scores=new Array(se);for(let be=0;be[be,ve])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=N.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,ze.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new V.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(x){const N=x.sentence,se=N.length;let be=0;for(;be{const Ae=[...Array.from({length:94},(be,ve)=>ve+33),...Array.from({length:12},(be,ve)=>ve+161),...Array.from({length:82},(be,ve)=>ve+174)],x=Ae.slice();let N=0;for(let be=0;be<256;++be)Ae.includes(be)||(Ae.push(be),x.push(256+N),N+=1);const se=x.map(be=>String.fromCharCode(be));return Object.fromEntries(Ae.map((be,ve)=>[be,se[ve]]))})(),ot=(0,re.reverseDictionary)(pt);class Tt extends Be{constructor(x){super(x),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=fe(x.vocab),this.unk_token_id=this.tokens_to_ids.get(x.unk_token),this.unk_token=x.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,se]of this.tokens_to_ids)this.vocab[se]=N;this.bpe_ranks=new Map(x.merges.map((N,se)=>[N,se])),this.merges=x.merges.map(N=>N.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=x.end_of_word_suffix,this.continuing_subword_suffix=x.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(x){if(x.length===0)return[];const N=this.cache.get(x);if(N!==void 0)return N;const se=Array.from(x);this.end_of_word_suffix&&(se[se.length-1]+=this.end_of_word_suffix);let be=[];if(se.length>1){const ve=new V.PriorityQueue((At,Pt)=>At.score`<0x${qe.toString(16).toUpperCase().padStart(2,"0")}>`)):N.push(this.unk_token)}return N}}class $e extends Be{constructor(x,N){super(x),this.tokens_to_ids=fe(N.target_lang?x.vocab[N.target_lang]:x.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.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[se,be]of this.tokens_to_ids)this.vocab[be]=se}encode(x){return x}}class X extends P.Callable{constructor(x){super(),this.config=x}static fromConfig(x){if(x===null)return null;switch(x.type){case"BertNormalizer":return new Dt(x);case"Precompiled":return new We(x);case"Sequence":return new gt(x);case"Replace":return new Me(x);case"NFC":return new je(x);case"NFKC":return new ue(x);case"NFKD":return new nt(x);case"Strip":return new xt(x);case"StripAccents":return new ft(x);case"Lowercase":return new yt(x);case"Prepend":return new Qe(x);default:throw new Error(`Unknown Normalizer type: ${x.type}`)}}normalize(x){throw Error("normalize should be implemented in subclass.")}_call(x){return this.normalize(x)}}class Me extends X{normalize(x){const N=pe(this.config.pattern);return N===null?x:x.replaceAll(N,this.config.content)}}class je extends X{normalize(x){return x=x.normalize("NFC"),x}}class ue extends X{normalize(x){return x=x.normalize("NFKC"),x}}class nt extends X{normalize(x){return x=x.normalize("NFKD"),x}}class xt extends X{normalize(x){return this.config.strip_left&&this.config.strip_right?x=x.trim():(this.config.strip_left&&(x=x.trimStart()),this.config.strip_right&&(x=x.trimEnd())),x}}class ft extends X{normalize(x){return x=he(x),x}}class yt extends X{normalize(x){return x=x.toLowerCase(),x}}class Qe extends X{normalize(x){return x=this.config.prepend+x,x}}class gt extends X{constructor(x){super(x),this.normalizers=x.normalizers.map(N=>X.fromConfig(N))}normalize(x){return this.normalizers.reduce((N,se)=>se.normalize(N),x)}}class Dt extends X{_tokenize_chinese_chars(x){const N=[];for(let se=0;sethis.pre_tokenize_text(se,N)):this.pre_tokenize_text(x,N)).flat()}_call(x,N){return this.pre_tokenize(x,N)}}class ce extends Ke{constructor(x){super(),this.pattern=new RegExp(`[^\\s${W}]+|[${W}]`,"gu")}pre_tokenize_text(x,N){return x.trim().match(this.pattern)||[]}}class Re extends Ke{constructor(x){super(),this.config=x,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=pt,this.text_encoder=new TextEncoder}pre_tokenize_text(x,N){return this.add_prefix_space&&!x.startsWith(" ")&&(x=" "+x),(this.use_regex?x.match(this.pattern)||[]:[x]).map(be=>Array.from(this.text_encoder.encode(be),ve=>this.byte_encoder[ve]).join(""))}}class Je extends Ke{constructor(x){super(),this.config=x,this.pattern=pe(this.config.pattern,this.config.invert)}pre_tokenize_text(x,N){return this.pattern===null?[]:this.config.invert?x.match(this.pattern)||[]:de(x,this.pattern)}}class rt extends Ke{constructor(x){super(),this.config=x,this.pattern=new RegExp(`[^${W}]+|[${W}]+`,"gu")}pre_tokenize_text(x,N){return x.match(this.pattern)||[]}}class et extends Ke{constructor(x){super(),this.config=x;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text(x,N){return x.match(this.pattern)||[]}}class st extends P.Callable{constructor(x){super(),this.config=x}static fromConfig(x){if(x===null)return null;switch(x.type){case"TemplateProcessing":return new Et(x);case"ByteLevel":return new Ot(x);case"RobertaProcessing":return new kt(x);case"BertProcessing":return new bt(x);case"Sequence":return new S(x);default:throw new Error(`Unknown PostProcessor type: ${x.type}`)}}post_process(x,...N){throw Error("post_process should be implemented in subclass.")}_call(x,...N){return this.post_process(x,...N)}}class bt extends st{constructor(x){super(x),this.cls=x.cls[0],this.sep=x.sep[0]}post_process(x,N=null,{add_special_tokens:se=!0}={}){se&&(x=(0,re.mergeArrays)([this.cls],x,[this.sep]));let be=new Array(x.length).fill(0);if(N!==null){const ve=se&&this instanceof kt?[this.sep]:[],qe=se?[this.sep]:[];x=(0,re.mergeArrays)(x,ve,N,qe),be=(0,re.mergeArrays)(be,new Array(N.length+ve.length+qe.length).fill(1))}return{tokens:x,token_type_ids:be}}}class kt extends bt{}class Et extends st{constructor(x){super(x),this.single=x.single,this.pair=x.pair}post_process(x,N=null,{add_special_tokens:se=!0}={}){const be=N===null?this.single:this.pair;let ve=[],qe=[];for(const St of be)"SpecialToken"in St?se&&(ve.push(St.SpecialToken.id),qe.push(St.SpecialToken.type_id)):"Sequence"in St&&(St.Sequence.id==="A"?(ve=(0,re.mergeArrays)(ve,x),qe=(0,re.mergeArrays)(qe,new Array(x.length).fill(St.Sequence.type_id))):St.Sequence.id==="B"&&(ve=(0,re.mergeArrays)(ve,N),qe=(0,re.mergeArrays)(qe,new Array(N.length).fill(St.Sequence.type_id))));return{tokens:ve,token_type_ids:qe}}}class Ot extends st{post_process(x,N=null){return N&&(x=(0,re.mergeArrays)(x,N)),{tokens:x}}}class S extends st{constructor(x){super(x),this.processors=x.processors.map(N=>st.fromConfig(N))}post_process(x,N=null,se={}){let be;for(const ve of this.processors)if(ve instanceof Ot)x=ve.post_process(x).tokens,N&&(N=ve.post_process(N).tokens);else{const qe=ve.post_process(x,N,se);x=qe.tokens,be=qe.token_type_ids}return{tokens:x,token_type_ids:be}}}class Y extends P.Callable{constructor(x){super(),this.config=x,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=x.trim_offsets}static fromConfig(x){if(x===null)return null;switch(x.type){case"WordPiece":return new ct(x);case"Metaspace":return new Xe(x);case"ByteLevel":return new Ut(x);case"Replace":return new D(x);case"ByteFallback":return new ne(x);case"Fuse":return new xe(x);case"Strip":return new ut(x);case"Sequence":return new Ne(x);case"CTC":return new $t(x);case"BPEDecoder":return new z(x);default:throw new Error(`Unknown Decoder type: ${x.type}`)}}_call(x){return this.decode(x)}decode(x){return this.decode_chain(x).join("")}decode_chain(x){throw Error("`decode_chain` should be implemented in subclass.")}}class D extends Y{decode_chain(x){const N=pe(this.config.pattern);return N===null?x:x.map(se=>se.replaceAll(N,this.config.content))}}class ne extends Y{constructor(x){super(x),this.text_decoder=new TextDecoder}decode_chain(x){const N=[];let se=[];for(const be of x){let ve=null;if(be.length===6&&be.startsWith("<0x")&&be.endsWith(">")){const qe=parseInt(be.slice(3,5),16);isNaN(qe)||(ve=qe)}if(ve!==null)se.push(ve);else{if(se.length>0){const qe=this.text_decoder.decode(Uint8Array.from(se));N.push(qe),se=[]}N.push(be)}}if(se.length>0){const be=this.text_decoder.decode(Uint8Array.from(se));N.push(be),se=[]}return N}}class xe extends Y{decode_chain(x){return[x.join("")]}}class ut extends Y{constructor(x){super(x),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(x){return x.map(N=>{let se=0;for(let ve=0;ve(se!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=ae(N)),N))}}class Ut extends Y{constructor(x){super(x),this.byte_decoder=ot,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(x){const N=x.join(""),se=new Uint8Array([...N].map(ve=>this.byte_decoder[ve]));return this.text_decoder.decode(se)}decode_chain(x){const N=[];let se=[];for(const be of x)this.added_tokens.find(ve=>ve.content===be)!==void 0?(se.length>0&&(N.push(this.convert_tokens_to_string(se)),se=[]),N.push(be)):se.push(be);return se.length>0&&N.push(this.convert_tokens_to_string(se)),N}}class $t extends Y{constructor(x){super(x),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(x){if(x.length===0)return"";const N=[x[0]];for(let ve=1;veve!==this.pad_token).join("");return this.cleanup&&(be=ae(be).replaceAll(this.word_delimiter_token," ").trim()),be}decode_chain(x){return[this.convert_tokens_to_string(x)]}}class Ne extends Y{constructor(x){super(x),this.decoders=x.decoders.map(N=>Y.fromConfig(N))}decode_chain(x){return this.decoders.reduce((N,se)=>se.decode_chain(N),x)}}class z extends Y{constructor(x){super(x),this.suffix=this.config.suffix}decode_chain(x){return x.map((N,se)=>N.replaceAll(this.suffix,se===x.length-1?"":" "))}}class ee extends Y{decode_chain(x){let N="";for(let se=1;sese.normalize("NFKC")).join("~"):x=x.normalize("NFKC"),x}}class Ze extends Ke{constructor(x){super(),this.tokenizers=x.pretokenizers.map(N=>Ke.fromConfig(N))}pre_tokenize_text(x,N){return this.tokenizers.reduce((se,be)=>be.pre_tokenize(se,N),[x])}}class vt extends Ke{constructor(x){super()}pre_tokenize_text(x,N){return x.match(/\w+|[^\w\s]+/g)||[]}}class _t extends Ke{constructor(x){super()}pre_tokenize_text(x,N){return R(x)}}class zt extends Ke{constructor(x){super(),this.config=x,this.pattern=pe(this.config.pattern),this.content=this.config.content}pre_tokenize_text(x,N){return this.pattern===null?[x]:[x.replaceAll(this.pattern,this.config.content)]}}const Ct=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function jt(Ae,x,N,se){for(const be of Object.keys(Ae)){const ve=x-Ae[be].length,qe=N(be),St=new Array(ve).fill(qe);Ae[be]=se==="right"?(0,re.mergeArrays)(Ae[be],St):(0,re.mergeArrays)(St,Ae[be])}}function Qt(Ae,x){for(const N of Object.keys(Ae))Ae[N].length=x}class at extends P.Callable{constructor(N,se){super();De(this,"return_token_type_ids",!1);De(this,"padding_side","right");this._tokenizer_config=se,this.normalizer=X.fromConfig(N.normalizer),this.pre_tokenizer=Ke.fromConfig(N.pre_tokenizer),this.model=Be.fromConfig(N.model,se),this.post_processor=st.fromConfig(N.post_processor),this.decoder=Y.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const be of N.added_tokens){const ve=new Se(be);this.added_tokens.push(ve),this.model.tokens_to_ids.set(ve.content,ve.id),this.model.vocab[ve.id]=ve.content,ve.special&&(this.special_tokens.push(ve.content),this.all_special_ids.push(ve.id))}if(this.additional_special_tokens=se.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((be,ve)=>ve.content.length-be.content.length).map(be=>`${be.lstrip?"\\s*":""}(${(0,re.escapeRegExp)(be.content)})${be.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=se.model_max_length,this.remove_space=se.remove_space,this.clean_up_tokenization_spaces=se.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=se.do_lowercase_and_remove_accent??!1,se.padding_side&&(this.padding_side=se.padding_side),this.legacy=!1,this.chat_template=se.chat_template??null,Array.isArray(this.chat_template)){const be=Object.create(null);for(const{name:ve,template:qe}of this.chat_template){if(typeof ve!="string"||typeof qe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');be[ve]=qe}this.chat_template=be}this._compiled_template_cache=new Map}getToken(...N){for(const se of N){const be=this._tokenizer_config[se];if(be)if(typeof be=="object"){if(be.__type==="AddedToken")return be.content;throw Error(`Unknown token: ${be}`)}else return be}return null}static async from_pretrained(N,{progress_callback:se=null,config:be=null,cache_dir:ve=null,local_files_only:qe=!1,revision:St="main",legacy:At=null}={}){const Pt=await le(N,{progress_callback:se,config:be,cache_dir:ve,local_files_only:qe,revision:St,legacy:At});return new this(...Pt)}_call(N,{text_pair:se=null,add_special_tokens:be=!0,padding:ve=!1,truncation:qe=null,max_length:St=null,return_tensor:At=!0,return_token_type_ids:Pt=null}={}){const Vt=Array.isArray(N);let ur;if(Vt){if(N.length===0)throw Error("text array must be non-empty");if(se!==null){if(Array.isArray(se)){if(N.length!==se.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");ur=N.map((hr,tr)=>this._encode_plus(hr,{text_pair:se[tr],add_special_tokens:be,return_token_type_ids:Pt}))}else ur=N.map(hr=>this._encode_plus(hr,{add_special_tokens:be,return_token_type_ids:Pt}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(se))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");ur=[this._encode_plus(N,{text_pair:se,add_special_tokens:be,return_token_type_ids:Pt})]}if(St===null?ve==="max_length"?St=this.model_max_length:St=(0,ze.max)(ur.map(hr=>hr.input_ids.length))[0]:qe||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."),St=Math.min(St,this.model_max_length??1/0),ve||qe)for(let hr=0;hrSt?qe&&Qt(ur[hr],St):ve&&jt(ur[hr],St,tr=>tr==="input_ids"?this.pad_token_id:0,this.padding_side));const jr={};if(At){if(!(ve&&qe)&&ur.some(tr=>{var Tr;for(const wi of Object.keys(tr))if(tr[wi].length!==((Tr=ur[0][wi])==null?void 0:Tr.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 hr=[ur.length,ur[0].input_ids.length];for(const tr of Object.keys(ur[0]))jr[tr]=new Oe.Tensor("int64",BigInt64Array.from(ur.flatMap(Tr=>Tr[tr]).map(BigInt)),hr)}else{for(const hr of Object.keys(ur[0]))jr[hr]=ur.map(tr=>tr[hr]);if(!Vt)for(const hr of Object.keys(jr))jr[hr]=jr[hr][0]}return jr}_encode_text(N){return N===null?null:(this.added_tokens_regex?N.split(this.added_tokens_regex).filter(ve=>ve):[N]).map((ve,qe)=>{if(this.added_tokens.find(At=>At.content===ve)!==void 0)return ve;{if(this.remove_space===!0&&(ve=ve.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ve=ye(ve)),this.normalizer!==null&&(ve=this.normalizer(ve)),ve.length===0)return[];const At=this.pre_tokenizer!==null?this.pre_tokenizer(ve,{section_index:qe}):[ve];return this.model(At)}}).flat()}_encode_plus(N,{text_pair:se=null,add_special_tokens:be=!0,return_token_type_ids:ve=null}={}){const{tokens:qe,token_type_ids:St}=this._tokenize_helper(N,{pair:se,add_special_tokens:be}),At=this.model.convert_tokens_to_ids(qe),Pt={input_ids:At,attention_mask:new Array(At.length).fill(1)};return(ve??this.return_token_type_ids)&&St&&(Pt.token_type_ids=St),Pt}_tokenize_helper(N,{pair:se=null,add_special_tokens:be=!1}={}){const ve=this._encode_text(N),qe=this._encode_text(se);return this.post_processor?this.post_processor(ve,qe,{add_special_tokens:be}):{tokens:(0,re.mergeArrays)(ve??[],qe??[])}}tokenize(N,{pair:se=null,add_special_tokens:be=!1}={}){return this._tokenize_helper(N,{pair:se,add_special_tokens:be}).tokens}encode(N,{text_pair:se=null,add_special_tokens:be=!0,return_token_type_ids:ve=null}={}){return this._encode_plus(N,{text_pair:se,add_special_tokens:be,return_token_type_ids:ve}).input_ids}batch_decode(N,se={}){return N instanceof Oe.Tensor&&(N=N.tolist()),N.map(be=>this.decode(be,se))}decode(N,se={}){if(N instanceof Oe.Tensor&&(N=q(N)),!Array.isArray(N)||N.length===0||!(0,re.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,se)}decode_single(N,{skip_special_tokens:se=!1,clean_up_tokenization_spaces:be=null}){let ve=this.model.convert_ids_to_tokens(N);se&&(ve=ve.filter(St=>!this.special_tokens.includes(St)));let qe=this.decoder?this.decoder(ve):ve.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(qe=qe.replaceAll(this.decoder.end_of_word_suffix," "),se&&(qe=qe.trim())),(be??this.clean_up_tokenization_spaces)&&(qe=ae(qe)),qe}apply_chat_template(N,{tools:se=null,documents:be=null,chat_template:ve=null,add_generation_prompt:qe=!1,tokenize:St=!0,padding:At=!1,truncation:Pt=!1,max_length:Vt=null,return_tensor:ur=!0,return_dict:jr=!1,tokenizer_kwargs:hr={},...tr}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const tt=this.chat_template;if(ve!==null&&Object.hasOwn(tt,ve))ve=tt[ve];else if(ve===null&&"default"in tt)ve=tt.default;else if(ve===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(tt).sort()}.`)}else if(this.chat_template)ve=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 ve!="string")throw Error(`chat_template must be a string, but got ${typeof ve}`);let Tr=this._compiled_template_cache.get(ve);Tr===void 0&&(Tr=new A.Template(ve),this._compiled_template_cache.set(ve,Tr));const wi=Object.create(null);for(const tt of Ct){const Pi=this.getToken(tt);Pi&&(wi[tt]=Pi)}const ui=Tr.render({messages:N,add_generation_prompt:qe,tools:se,documents:be,...wi,...tr});if(St){const tt=this._call(ui,{add_special_tokens:!1,padding:At,truncation:Pt,max_length:Vt,return_tensor:ur,...hr});return jr?tt:tt.input_ids}return ui}}class Zt extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class Yt extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class ir extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class nr extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class dr extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class rr extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class Dr extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class Jr extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class Br extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class dt extends at{}class Nt extends at{}class Ht extends at{constructor(N,se){super(N,se);De(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 ii extends at{constructor(){super(...arguments);De(this,"return_token_type_ids",!0)}}class Zi extends at{}class Gi extends at{}class Hr extends at{}class di extends at{constructor(x,N){super(x,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(se=>this.languageRegex.test(se)),this.lang_to_token=se=>se}_build_translation_inputs(x,N,se){return Ki(this,x,N,se)}}class Xr extends di{}class Ri extends at{}class Rr extends at{constructor(x,N){var ve,qe;const se=".,!?…。,、।۔،",be=(qe=(ve=x.pre_tokenizer)==null?void 0:ve.pretokenizers[0])==null?void 0:qe.pattern;be&&be.Regex===` ?[^(\\s|[${se}])]+`&&(be.Regex=` ?[^\\s${se}]+`),super(x,N)}}const Ji="▁";class qi extends at{constructor(N,se){super(N,se);De(this,"padding_side","left");this.legacy=se.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Ee({replacement:Ji,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let se=super._encode_text(Ji+N.replaceAll(Ji," "));return se.length>1&&se[0]===Ji&&this.special_tokens.includes(se[1])&&(se=se.slice(1)),se}}class qn extends at{}class Cn extends at{}class kn extends at{}class $n extends at{}class Sn extends at{}class en extends at{}class Kn extends at{}class pn extends at{}class Ni extends at{}function Ki(Ae,x,N,se){if(!("language_codes"in Ae)||!Array.isArray(Ae.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ae)||!(Ae.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ae)||typeof Ae.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const be=se.src_lang,ve=se.tgt_lang;if(!Ae.language_codes.includes(ve))throw new Error(`Target language code "${ve}" is not valid. Must be one of: {${Ae.language_codes.join(", ")}}`);if(be!==void 0){if(!Ae.language_codes.includes(be))throw new Error(`Source language code "${be}" is not valid. Must be one of: {${Ae.language_codes.join(", ")}}`);for(const qe of Ae.post_processor.config.single)if("SpecialToken"in qe&&Ae.languageRegex.test(qe.SpecialToken.id)){qe.SpecialToken.id=Ae.lang_to_token(be);break}}return se.forced_bos_token_id=Ae.model.convert_tokens_to_ids([Ae.lang_to_token(ve)])[0],Ae._call(x,N)}class Hi extends at{constructor(x,N){super(x,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(se=>this.languageRegex.test(se)),this.lang_to_token=se=>se}_build_translation_inputs(x,N,se){return Ki(this,x,N,se)}}class an extends at{constructor(x,N){super(x,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(se=>this.languageRegex.test(se)).map(se=>se.slice(2,-2)),this.lang_to_token=se=>`__${se}__`}_build_translation_inputs(x,N,se){return Ki(this,x,N,se)}}class hn extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(x,{return_timestamps:N=!1,return_language:se=!1,time_precision:be=null,force_full_sequences:ve=!0}={}){if(be===null)throw Error("Must specify time_precision");let qe=null;const St=N==="word";function At(){return{language:qe,timestamp:[null,null],text:""}}const Pt=[];let Vt=At(),ur=0;const jr=this.timestamp_begin;let hr=[],tr=[],Tr=!1,wi=null;const ui=new Set(this.all_special_ids);for(const Fr of x){const ni=Fr.tokens,vi=St?Fr.token_timestamps:null;let lr=null,ki=jr;if("stride"in Fr){const[Or,Rt,$r]=Fr.stride;if(ur-=Rt,wi=Or-$r,Rt&&(ki=Rt/be+jr),$r)for(let Nr=ni.length-1;Nr>=0;--Nr){const Qr=Number(ni[Nr]);if(Qr>=jr){if(lr!==null&&(Qr-jr)*be=jr){const $r=(Rt-jr)*be+ur,Nr=(0,ze.round)($r,2);if(lr!==null&&Rt>=lr)Tr=!0;else if(Tr||hr.length>0&&Rt0?(hr.push(ci),St&&tr.push(zr)):hr.every(Or=>Or.length===0)&&(Vt=At(),hr=[],ci=[],tr=[],zr=[])}if(hr.length>0){if(ve&&N)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[Fr,ni]=this.findLongestCommonSequence(hr,tr),vi=this.decode(Fr);Vt.text=vi,St&&(Vt.words=this.collateWordTimestamps(Fr,ni,qe)),Pt.push(Vt)}let tt=Object.create(null);const Pi=Pt.map(Fr=>Fr.text).join("");if(N||se){for(let Fr=0;Fr0;let St=qe?[]:null,At=qe?N[0]:null;for(let Pt=1;PtNr===zr[Qr]&&At[ni+Qr]<=N[Pt][ki+Qr]).length:Or=lr.filter((Nr,Qr)=>Nr===zr[Qr]).length;const Rt=Fr/1e4,$r=Or/Fr+Rt;Or>1&&$r>ur&&(ur=$r,jr=[ni,vi,ki,ci])}const[tr,Tr,wi,ui]=jr,tt=Math.floor((Tr+tr)/2),Pi=Math.floor((ui+wi)/2);ve.push(...se.slice(0,tt)),se=Vt.slice(Pi),be=se.length,qe&&(St.push(...At.slice(0,tt)),At=N[Pt].slice(Pi))}return ve.push(...se),qe?(St.push(...At),[ve,St]):[ve,[]]}collateWordTimestamps(x,N,se){const[be,ve,qe]=this.combineTokensIntoWords(x,se),St=[];for(let At=0;At=be){const St=((qe-be)*se).toFixed(2);ve.push(`<|${St}|>`),ve.push([])}else ve[ve.length-1].push(qe);return ve=ve.map(qe=>typeof qe=="string"?qe:super.decode(qe,N)),ve.join("")}splitTokensOnUnicode(x){const N=this.decode(x,{decode_with_timestamps:!0}),se="�",be=[],ve=[],qe=[];let St=[],At=[],Pt=0;for(let Vt=0;Vt=this.model.tokens_to_ids.get("<|endoftext|>"),tr=Vt.startsWith(" "),Tr=Vt.trim(),wi=At.test(Tr);if(hr||tr||wi||ve.length===0)ve.push(Vt),qe.push(ur),St.push(jr);else{const ui=ve.length-1;ve[ui]+=Vt,qe[ui].push(...ur),St[ui].push(...jr)}}return[ve,qe,St]}mergePunctuations(x,N,se,be,ve){const qe=structuredClone(x),St=structuredClone(N),At=structuredClone(se);let Pt=qe.length-2,Vt=qe.length-1;for(;Pt>=0;)qe[Pt].startsWith(" ")&&be.includes(qe[Pt].trim())?(qe[Vt]=qe[Pt]+qe[Vt],St[Vt]=(0,re.mergeArrays)(St[Pt],St[Vt]),At[Vt]=(0,re.mergeArrays)(At[Pt],At[Vt]),qe[Pt]="",St[Pt]=[],At[Pt]=[]):Vt=Pt,--Pt;for(Pt=0,Vt=1;Vtur),St.filter(ur=>ur.length>0),At.filter(ur=>ur.length>0)]}get_decoder_prompt_ids({language:x=null,task:N=null,no_timestamps:se=!0}={}){const be=[];if(x){const ve=(0,H.whisper_language_to_code)(x),qe=this.model.tokens_to_ids.get(`<|${ve}|>`);if(qe===void 0)throw new Error(`Unable to find language "${ve}" in model vocabulary. Please report this issue at ${B.GITHUB_ISSUE_URL}.`);be.push(qe)}else be.push(null);if(N){if(N=N.toLowerCase(),N!=="transcribe"&&N!=="translate")throw new Error(`Task "${N}" is not supported. Must be one of: ["transcribe", "translate"]`);const ve=this.model.tokens_to_ids.get(`<|${N}|>`);if(ve===void 0)throw new Error(`Unable to find task "${N}" in model vocabulary. Please report this issue at ${B.GITHUB_ISSUE_URL}.`);be.push(ve)}else be.push(null);if(se){const ve=this.model.tokens_to_ids.get("<|notimestamps|>");if(ve===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${B.GITHUB_ISSUE_URL}.`);be.push(ve)}return be.map((ve,qe)=>[qe+1,ve]).filter(ve=>ve[1]!==null)}}class fn extends at{}class sr extends at{}class on extends at{}class En extends at{constructor(x,N){super(x,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(se=>this.languageRegex.test(se)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(x){if(x===null)return null;const[N,...se]=x.trim().split(this.languageRegex);if(se.length===0)return super._encode_text(N);if(se.length===2){const[be,ve]=se;return this.supported_language_codes.includes(be)||console.warn(`Unsupported language code "${be}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,re.mergeArrays)([be],super._encode_text(ve))}}}class Pn extends at{}class mn extends at{}class An extends at{}class In extends at{}class _n extends at{}class Fn extends at{constructor(x,N){super(x,N),this.decoder=new ee({})}}class qr extends at{}class Ci{static async from_pretrained(x,{progress_callback:N=null,config:se=null,cache_dir:be=null,local_files_only:ve=!1,revision:qe="main",legacy:St=null}={}){var jr;const[At,Pt]=await le(x,{progress_callback:N,config:se,cache_dir:be,local_files_only:ve,revision:qe,legacy:St}),Vt=((jr=Pt.tokenizer_class)==null?void 0:jr.replace(/Fast$/,""))??"PreTrainedTokenizer";let ur=this.TOKENIZER_CLASS_MAPPING[Vt];return ur||(console.warn(`Unknown tokenizer class "${Vt}", attempting to construct from base class.`),ur=at),new ur(At,Pt)}}De(Ci,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Zi,DistilBertTokenizer:dt,CamembertTokenizer:Nt,DebertaTokenizer:dr,DebertaV2Tokenizer:rr,BertTokenizer:Zt,HerbertTokenizer:Dr,ConvBertTokenizer:Jr,RoFormerTokenizer:Br,XLMTokenizer:Ht,ElectraTokenizer:ii,MobileBertTokenizer:ir,SqueezeBertTokenizer:nr,AlbertTokenizer:Yt,GPT2Tokenizer:Gi,BartTokenizer:Hr,MBartTokenizer:di,MBart50Tokenizer:Xr,RobertaTokenizer:Ri,WhisperTokenizer:hn,CodeGenTokenizer:fn,CLIPTokenizer:sr,SiglipTokenizer:on,MarianTokenizer:En,BloomTokenizer:Rr,NllbTokenizer:Hi,M2M100Tokenizer:an,LlamaTokenizer:qi,CodeLlamaTokenizer:qn,XLMRobertaTokenizer:Cn,MPNetTokenizer:kn,FalconTokenizer:$n,GPTNeoXTokenizer:Sn,EsmTokenizer:en,Wav2Vec2CTCTokenizer:Pn,BlenderbotTokenizer:mn,BlenderbotSmallTokenizer:An,SpeechT5Tokenizer:In,NougatTokenizer:_n,VitsTokenizer:Fn,Qwen2Tokenizer:Kn,GemmaTokenizer:pn,Grok1Tokenizer:Ni,CohereTokenizer:qr,PreTrainedTokenizer:at})},"./src/utils/audio.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{hamming:()=>H,hanning:()=>A,mel_filter_bank:()=>ae,read_audio:()=>Oe,spectrogram:()=>R,window_function:()=>W});var P=m("./src/utils/hub.js"),re=m("./src/utils/maths.js"),ke=m("./src/utils/core.js"),ze=m("./src/utils/tensor.js");async function Oe(j,Ce){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 Se=await(await(0,P.getFile)(j)).arrayBuffer(),Be=new AudioContext({sampleRate:Ce});typeof Ce>"u"&&console.warn(`No sampling rate provided, using default of ${Be.sampleRate}Hz.`);const Ve=await Be.decodeAudioData(Se);let Ge;if(Ve.numberOfChannels===2){const pt=Math.sqrt(2),ot=Ve.getChannelData(0),Tt=Ve.getChannelData(1);Ge=new Float32Array(ot.length);for(let $e=0;$e2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,Ce=1e3,Se=15,Be=27/Math.log(6.4))=>j>=Ce?Se+Math.log(j/Ce)*Be:3*j/200};function le(j,Ce="htk"){const Se=B[Ce];if(!Se)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?Se(j):j.map(Be=>Se(Be))}const de={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,Ce=1e3,Se=15,Be=Math.log(6.4)/27)=>j>=Se?Ce*Math.exp(Be*(j-Se)):200*j/3};function pe(j,Ce="htk"){const Se=de[Ce];if(!Se)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?Se(j):j.map(Be=>Se(Be))}function fe(j,Ce){const Se=Float64Array.from({length:Ce.length-1},(pt,ot)=>Ce[ot+1]-Ce[ot]),Be=Array.from({length:j.length},()=>new Array(Ce.length));for(let pt=0;ptnew Array(j.length));for(let pt=0;ptj+Be*Ge)}function ae(j,Ce,Se,Be,Ve,Ge=null,pt="htk",ot=!1){if(Ge!==null&&Ge!=="slaney")throw new Error('norm must be one of null or "slaney"');const Tt=le(Se,pt),$e=le(Be,pt),X=q(Tt,$e,Ce+2);let Me=pe(X,pt),je;if(ot){const nt=Ve/(j*2);je=le(Float64Array.from({length:j},(xt,ft)=>ft*nt),pt),Me=X}else je=q(0,Math.floor(Ve/2),j);const ue=fe(je,Me);if(Ge!==null&&Ge==="slaney")for(let nt=0;ntVe)throw Error(`frame_length (${Se}) may not be larger than fft_length (${Ve})`);if(Ke!==Se)throw new Error(`Length of the window (${Ke}) must equal frame_length (${Se})`);if(Be<=0)throw new Error("hop_length must be greater than zero");if(Ge===null&&X!==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(pt){if(ot!=="reflect")throw new Error(`pad_mode="${ot}" not implemented yet.`);const Y=Math.floor((Ve-1)/2)+1;j=he(j,Y,Y)}let ce=Math.floor(1+Math.floor((j.length-Se)/Be));yt!==null&&cece?gt&&(rt=Qe):rt=Je=Qe);const et=new re.FFT(Ve),st=new Float64Array(Ve),bt=new Float64Array(et.outputBufferSize),kt=new Float32Array(Re*rt);for(let Y=0;Y=1;--xe)st[xe]-=$e*st[xe-1];st[0]*=1-$e}for(let xe=0;xeMath.pow(ot,.85));break;default:throw new Error(`Unknown window type ${Ce}.`)}if(Se&&(pt=pt.subarray(0,j)),Be===null)return pt;if(j>Be)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Be})`);return pt}},"./src/utils/constants.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{GITHUB_ISSUE_URL:()=>P});const P="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{calculateDimensions:()=>V,calculateReflectOffset:()=>le,dispatchCallback:()=>P,escapeRegExp:()=>ke,isIntegralNumber:()=>Oe,isTypedArray:()=>ze,mergeArrays:()=>H,pick:()=>de,pop:()=>A,product:()=>B,reverseDictionary:()=>re});function P(pe,fe){pe&&pe(fe)}function re(pe){return Object.fromEntries(Object.entries(pe).map(([fe,q])=>[q,fe]))}function ke(pe){return pe.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ze(pe){var fe,q,ae;return((ae=(q=(fe=pe==null?void 0:pe.prototype)==null?void 0:fe.__proto__)==null?void 0:q.constructor)==null?void 0:ae.name)==="TypedArray"}function Oe(pe){return Number.isInteger(pe)||typeof pe=="bigint"}function V(pe){const fe=[];let q=pe;for(;Array.isArray(q);)fe.push(q.length),q=q[0];return fe}function A(pe,fe,q=void 0){const ae=pe[fe];if(ae!==void 0)return delete pe[fe],ae;if(q===void 0)throw Error(`Key ${fe} does not exist in object.`);return q}function H(...pe){return Array.prototype.concat.apply([],pe)}function B(...pe){return pe.reduce((fe,q)=>fe.flatMap(ae=>q.map(he=>[ae,he])))}function le(pe,fe){return Math.abs((pe+fe)%(2*fe)-fe)}function de(pe,fe){return Object.assign({},...fe.map(q=>{if(pe[q]!==void 0)return{[q]:pe[q]}}))}},"./src/utils/data-structures.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{CharTrie:()=>re,PriorityQueue:()=>P,TokenLattice:()=>ze});class P{constructor(A=(B,le)=>B>le,H=1/0){this._heap=[],this._comparator=A,this._maxSize=H}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...A){return this.extend(A)}extend(A){for(const H of A)if(this.size0&&this._swap(0,H),this._heap.pop(),this._siftDown(),A}replace(A){const H=this.peek();return this._heap[0]=A,this._siftDown(),H}_parent(A){return(A+1>>>1)-1}_left(A){return(A<<1)+1}_right(A){return A+1<<1}_greater(A,H){return this._comparator(this._heap[A],this._heap[H])}_swap(A,H){const B=this._heap[A];this._heap[A]=this._heap[H],this._heap[H]=B}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(A){for(;A>0&&this._greater(A,this._parent(A));)this._swap(A,this._parent(A)),A=this._parent(A)}_siftDown(){let A=0;for(;this._left(A)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const le=new Oe(this.bosTokenId,0,0,0,0),de=new Oe(this.eosTokenId,1,this.len,0,0);this.nodes.push(le.clone()),this.nodes.push(de.clone()),this.beginNodes[this.len].push(de),this.endNodes[0].push(le)}insert(A,H,B,le){const de=this.nodes.length,pe=new Oe(le,de,A,H,B);this.beginNodes[A].push(pe),this.endNodes[A+H].push(pe),this.nodes.push(pe)}viterbi(){const A=this.len;let H=0;for(;H<=A;){if(this.beginNodes[H].length==0)return[];for(let fe of this.beginNodes[H]){fe.prev=null;let q=0,ae=null;for(let he of this.endNodes[H]){const ye=he.backtraceScore+fe.score;(ae===null||ye>q)&&(ae=he.clone(),q=ye)}if(ae!==null)fe.prev=ae,fe.backtraceScore=q;else return[]}++H}const B=[],de=this.beginNodes[A][0].prev;if(de===null)return[];let pe=de.clone();for(;pe.prev!==null;)B.push(pe.clone()),pe=pe.clone().prev.clone();return B.reverse(),B}piece(A){return this.sentence.slice(A.pos,A.pos+A.length)}tokens(){return this.viterbi().map(H=>this.piece(H))}tokenIds(){return this.viterbi().map(H=>H.tokenId)}}class Oe{constructor(A,H,B,le,de){this.tokenId=A,this.nodeId=H,this.pos=B,this.length=le,this.score=de,this.prev=null,this.backtraceScore=0}clone(){const A=new Oe(this.tokenId,this.nodeId,this.pos,this.length,this.score);return A.prev=this.prev,A.backtraceScore=this.backtraceScore,A}}},"./src/utils/devices.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{DEVICE_TYPES:()=>P});const P=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{DATA_TYPES:()=>ze,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Oe,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>V,isWebGpuFp16Supported:()=>ke});var P=m("./src/env.js"),re=m("./src/utils/devices.js");const ke=function(){let A;return async function(){if(A===void 0)if(!P.apis.IS_WEBGPU_AVAILABLE)A=!1;else try{A=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{A=!1}return A}}(),ze=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Oe=Object.freeze({[re.DEVICE_TYPES.wasm]:ze.q8}),V=Object.freeze({[ze.fp32]:"",[ze.fp16]:"_fp16",[ze.int8]:"_int8",[ze.uint8]:"_uint8",[ze.q8]:"_quantized",[ze.q4]:"_q4",[ze.q4f16]:"_q4f16",[ze.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{Callable:()=>P});const P=class{constructor(){let re=function(...ke){return re._call(...ke)};return Object.setPrototypeOf(re,new.target.prototype)}_call(...re){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{getFile:()=>H,getModelFile:()=>fe,getModelJSON:()=>q});var P=m("?7a2c"),re=m("?a42a"),ke=m("./src/env.js"),ze=m("./src/utils/core.js");const Oe={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class V{constructor(ge){if(this.filePath=ge,this.headers=new Headers,this.exists=P.existsSync(ge),this.exists){this.status=200,this.statusText="OK";let K=P.statSync(ge);this.headers.set("content-length",K.size.toString()),this.updateContentType();let R=this;this.body=new ReadableStream({start(W){R.arrayBuffer().then(j=>{W.enqueue(new Uint8Array(j)),W.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const ge=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Oe[ge]??"application/octet-stream")}clone(){let ge=new V(this.filePath);return ge.exists=this.exists,ge.status=this.status,ge.statusText=this.statusText,ge.headers=new Headers(this.headers),ge}async arrayBuffer(){return(await P.promises.readFile(this.filePath)).buffer}async blob(){const ge=await P.promises.readFile(this.filePath);return new Blob([ge],{type:this.headers.get("content-type")})}async text(){return await P.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function A(ye,ge=null,K=null){let R;try{R=new URL(ye)}catch{return!1}return!(ge&&!ge.includes(R.protocol)||K&&!K.includes(R.hostname))}async function H(ye){var ge;if(ke.env.useFS&&!A(ye,["http:","https:","blob:"]))return new V(ye);if(typeof process<"u"&&((ge=process==null?void 0:process.release)==null?void 0:ge.name)==="node"){const K=!!(Ei!=null&&Ei.TESTING_REMOTELY),R=ke.env.version,W=new Headers;if(W.set("User-Agent",`transformers.js/${R}; is_ci/${K};`),A(ye,["http:","https:"],["huggingface.co","hf.co"])){const Ce=(Ei==null?void 0:Ei.HF_TOKEN)??(Ei==null?void 0:Ei.HF_ACCESS_TOKEN);Ce&&W.set("Authorization",`Bearer ${Ce}`)}return fetch(ye,{headers:W})}else return fetch(ye)}const B={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 le(ye,ge,K){if(!K)return null;const R=B[ye]??`Error (${ye}) occurred while trying to load file`;throw Error(`${R}: "${ge}".`)}class de{constructor(ge){this.path=ge}async match(ge){let K=re.join(this.path,ge),R=new V(K);if(R.exists)return R}async put(ge,K){const R=Buffer.from(await K.arrayBuffer());let W=re.join(this.path,ge);try{await P.promises.mkdir(re.dirname(W),{recursive:!0}),await P.promises.writeFile(W,R)}catch(j){console.warn("An error occurred while writing the file to cache:",j)}}}async function pe(ye,...ge){for(let K of ge)try{let R=await ye.match(K);if(R)return R}catch{continue}}async function fe(ye,ge,K=!0,R={}){if(!ke.env.allowLocalModels){if(R.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(!ke.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,ze.dispatchCallback)(R.progress_callback,{status:"initiate",name:ye,file:ge});let W;if(!W&&ke.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(je){console.warn("An error occurred while opening the browser cache:",je)}}if(!W&&ke.env.useFSCache&&(W=new de(R.cache_dir??ke.env.cacheDir)),!W&&ke.env.useCustomCache){if(!ke.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ke.env.customCache.match||!ke.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");W=ke.env.customCache}const j=R.revision??"main";let Ce=he(ye,ge),Se=he(ke.env.localModelPath,Ce),Be=he(ke.env.remoteHost,ke.env.remotePathTemplate.replaceAll("{model}",ye).replaceAll("{revision}",encodeURIComponent(j)),ge),Ve=j==="main"?Ce:he(ye,j,ge),Ge,pt=W instanceof de?Ve:Be,ot=!1,Tt;W&&(Tt=await pe(W,Se,pt));const $e=Tt!==void 0;if(Tt===void 0){if(ke.env.allowLocalModels)if(A(Ce,["http:","https:"])){if(R.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Ce}.`);if(!ke.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Ce}.`)}else try{Tt=await H(Se),Ge=Se}catch(ue){console.warn(`Unable to load from local path "${Se}": "${ue}"`)}if(Tt===void 0||Tt.status===404){if(R.local_files_only||!ke.env.allowRemoteModels){if(K)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Se}".`);return null}if(Tt=await H(Be),Tt.status!==200)return le(Tt.status,Be,K);Ge=pt}ot=W&&typeof Response<"u"&&Tt instanceof Response&&Tt.status===200}(0,ze.dispatchCallback)(R.progress_callback,{status:"download",name:ye,file:ge});const X={status:"progress",name:ye,file:ge};let Me;return R.progress_callback?$e&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Me=new Uint8Array(await Tt.arrayBuffer()),(0,ze.dispatchCallback)(R.progress_callback,{...X,progress:100,loaded:Me.length,total:Me.length})):Me=await ae(Tt,je=>{(0,ze.dispatchCallback)(R.progress_callback,{...X,...je})}):Me=new Uint8Array(await Tt.arrayBuffer()),ot&&Ge&&await W.match(Ge)===void 0&&await W.put(Ge,new Response(Me,{headers:Tt.headers})).catch(je=>{console.warn(`Unable to add response to browser cache: ${je}.`)}),(0,ze.dispatchCallback)(R.progress_callback,{status:"done",name:ye,file:ge}),Me}async function q(ye,ge,K=!0,R={}){let W=await fe(ye,ge,K,R);if(W===null)return{};let Ce=new TextDecoder("utf-8").decode(W);return JSON.parse(Ce)}async function ae(ye,ge){const K=ye.headers.get("Content-Length");K===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let R=parseInt(K??"0"),W=new Uint8Array(R),j=0;const Ce=ye.body.getReader();async function Se(){const{done:Be,value:Ve}=await Ce.read();if(Be)return;let Ge=j+Ve.length;if(Ge>R){R=Ge;let ot=new Uint8Array(R);ot.set(W),W=ot}W.set(Ve,j),j=Ge;const pt=j/R*100;return ge({progress:pt,loaded:j,total:R}),Se()}return await Se(),W}function he(...ye){return ye=ye.map((ge,K)=>(K&&(ge=ge.replace(new RegExp("^/"),"")),K!==ye.length-1&&(ge=ge.replace(new RegExp("/$"),"")),ge)),ye.join("/")}},"./src/utils/image.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{RawImage:()=>pe});var P=m("./src/utils/hub.js"),re=m("./src/env.js"),ke=m("./src/utils/tensor.js"),ze=m("?2b25");const Oe=typeof self<"u",V=Oe&&self.constructor.name==="DedicatedWorkerGlobalScope";let A,H,B;if(Oe)A=(fe,q)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(fe,q)},B=self.createImageBitmap,H=self.ImageData;else if(ze)B=async fe=>{const ae=(await fe.metadata()).channels,{data:he,info:ye}=await fe.rotate().raw().toBuffer({resolveWithObject:!0}),ge=new pe(new Uint8ClampedArray(he),ye.width,ye.height,ye.channels);return ae!==void 0&&ae!==ye.channels&&ge.convert(ae),ge};else throw new Error("Unable to load image processing library.");const le={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},de=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class pe{constructor(q,ae,he,ye){this.data=q,this.width=ae,this.height=he,this.channels=ye}get size(){return[this.width,this.height]}static async read(q){if(q instanceof pe)return q;if(typeof q=="string"||q instanceof URL)return await this.fromURL(q);throw new Error(`Unsupported input type: ${typeof q}`)}static fromCanvas(q){if(!Oe)throw new Error("fromCanvas() is only supported in browser environments.");const he=q.getContext("2d").getImageData(0,0,q.width,q.height).data;return new pe(he,q.width,q.height,4)}static async fromURL(q){const ae=await(0,P.getFile)(q);if(ae.status!==200)throw new Error(`Unable to read image from "${q}" (${ae.status} ${ae.statusText})`);const he=await ae.blob();return this.fromBlob(he)}static async fromBlob(q){if(Oe){const ae=await B(q),he=A(ae.width,ae.height).getContext("2d");return he.drawImage(ae,0,0),new this(he.getImageData(0,0,ae.width,ae.height).data,ae.width,ae.height,4)}else{const ae=ze(await q.arrayBuffer());return await B(ae)}}static fromTensor(q,ae="CHW"){if(q.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${q.dims.length} dimensions.`);if(ae==="CHW")q=q.transpose(1,2,0);else if(ae!=="HWC")throw new Error(`Unsupported channel format: ${ae}`);if(!(q.data instanceof Uint8ClampedArray||q.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${q.type}`);switch(q.dims[2]){case 1:case 2:case 3:case 4:return new pe(q.data,q.dims[1],q.dims[0],q.dims[2]);default:throw new Error(`Unsupported number of channels: ${q.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const q=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let ae=0,he=0;ae=0?W=he:Ce=-he,ye>=0?j=ye:Se=-ye,R.drawImage(K,W,j,q,ae,Ce,Se,q,ae),new pe(R.getImageData(0,0,q,ae).data,q,ae,4).convert(ge)}else{let ge=this.toSharp();if(he>=0&&ye>=0)ge=ge.extract({left:Math.floor(he),top:Math.floor(ye),width:q,height:ae});else if(he<=0&&ye<=0){const K=Math.floor(-ye),R=Math.floor(-he);ge=ge.extend({top:K,left:R,right:q-this.width-R,bottom:ae-this.height-K})}else{let K=[0,0],R=0;ye<0?(K[0]=Math.floor(-ye),K[1]=ae-this.height-K[0]):R=Math.floor(ye);let W=[0,0],j=0;he<0?(W[0]=Math.floor(-he),W[1]=q-this.width-W[0]):j=Math.floor(he),ge=ge.extend({top:K[0],bottom:K[1],left:W[0],right:W[1]}).extract({left:j,top:R,width:q,height:ae})}return await B(ge)}}async toBlob(q="image/png",ae=1){if(!Oe)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:q,quality:ae})}toTensor(q="CHW"){let ae=new ke.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(q!=="HWC")if(q==="CHW")ae=ae.permute(2,0,1);else throw new Error(`Unsupported channel format: ${q}`);return ae}toCanvas(){if(!Oe)throw new Error("toCanvas() is only supported in browser environments.");const q=this.clone().rgba(),ae=A(q.width,q.height),he=new H(q.data,q.width,q.height);return ae.getContext("2d").putImageData(he,0,0),ae}_update(q,ae,he,ye=null){return this.data=q,this.width=ae,this.height=he,ye!==null&&(this.channels=ye),this}clone(){return new pe(this.data.slice(),this.width,this.height,this.channels)}convert(q){if(this.channels===q)return this;switch(q){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(q){if(Oe){if(V)throw new Error("Unable to save an image from a Web Worker.");const ae=q.split(".").pop().toLowerCase(),he=de.get(ae)??"image/png",ye=await this.toBlob(he),ge=URL.createObjectURL(ye),K=document.createElement("a");K.href=ge,K.download=q,K.click(),K.remove()}else{if(re.env.useFS)return await this.toSharp().toFile(q);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Oe)throw new Error("toSharp() is only supported in server-side environments.");return ze(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{FFT:()=>fe,bankers_round:()=>he,cos_sim:()=>V,dot:()=>Oe,dynamic_time_warping:()=>ye,interpolate_data:()=>P,log_softmax:()=>ze,magnitude:()=>A,max:()=>B,medianFilter:()=>q,min:()=>H,permute_data:()=>re,round:()=>ae,softmax:()=>ke});function P(ge,[K,R,W],[j,Ce],Se="bilinear",Be=!1){const Ve=Ce/W,Ge=j/R,pt=new ge.constructor(j*Ce*K),ot=R*W,Tt=j*Ce;for(let $e=0;$e=0;--Be)j[Be]=Ve,W[Be]=K[R[Be]],Ve*=W[Be];const Ce=R.map((Be,Ve)=>j[R.indexOf(Ve)]),Se=new ge.constructor(ge.length);for(let Be=0;Be=0;--Ge)Ve+=pt%K[Ge]*Ce[Ge],pt=Math.floor(pt/K[Ge]);Se[Ve]=ge[Be]}return[Se,W]}function ke(ge){const K=B(ge)[0],R=ge.map(Ce=>Math.exp(Ce-K)),W=R.reduce((Ce,Se)=>Ce+Se,0);return R.map(Ce=>Ce/W)}function ze(ge){return ke(ge).map(W=>Math.log(W))}function Oe(ge,K){let R=0;for(let W=0;WK+R*R,0))}function H(ge){if(ge.length===0)throw Error("Array must not be empty");let K=ge[0],R=0;for(let W=1;WK&&(K=ge[W],R=W);return[Number(K),R]}function le(ge){return ge>0&&(ge&ge-1)===0}class de{constructor(K){if(this.size=K|0,this.size<=1||!le(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=K<<1,this.table=new Float64Array(this.size*2);for(let W=0;WW;W<<=1)++R;this._width=R%2===0?R-1:R,this._bitrev=new Int32Array(1<>>j&3)<>>1);for(let j=0;j>>1]=K[j];return W}toComplexArray(K,R){const W=R||this.createComplexArray();for(let j=0;j>>1],W[j+1]=0;return W}transform(K,R){if(K===R)throw new Error("Input and output buffers must be different");this._transform4(K,R,1)}realTransform(K,R){if(K===R)throw new Error("Input and output buffers must be different");this._realTransform4(K,R,1)}inverseTransform(K,R){if(K===R)throw new Error("Input and output buffers must be different");this._transform4(K,R,-1);for(let W=0;W>=2;Se>=2;Se>>=2){Be=j/Se<<1;const Tt=Be>>>2;for(Ve=0;Ve>>1,Se>>>1)}else for(Ve=0,Ge=0;Ve>>1,Se>>>1,W)}const ot=this.table;for(Se>>=2;Se>=2;Se>>=2){Be=j/Se<<1;const $e=Be>>>1,X=$e>>>1,Me=X>>>1;for(Ve=0;Ve>>1;for(let $e=2;$e>1;++pt){const ot=(pt+1-K)**2/2,Tt=Math.sqrt(Ve**2+Ge**2)**ot,$e=ot*Math.atan2(Ge,Ve),X=2*pt;Ce[X]=Tt*Math.cos($e),Ce[X+1]=Tt*Math.sin($e),Se[X]=Ce[X],Se[X+1]=-Ce[X+1]}this._slicedChirpBuffer=Ce.subarray(R,W),this._f=new de(j>>1),this._f.transform(this._chirpBuffer,Se)}_transform(K,R,W){const j=this._buffer1,Ce=this._buffer2,Se=this._outBuffer1,Be=this._outBuffer2,Ve=this._chirpBuffer,Ge=this._slicedChirpBuffer,pt=this._a;if(W)for(let ot=0;ot>1,X=R[$e];j[ot]=X*Ge[ot],j[Tt]=X*Ge[Tt]}else for(let ot=0;ot=ge.length&&(Ve=2*(ge.length-1)-Ve),W[Se++]=ge[Ve]}W.sort(),R[Ce]=W[j]}return R}function ae(ge,K){const R=Math.pow(10,K);return Math.round(ge*R)/R}function he(ge){const K=Math.round(ge);return Math.abs(ge)%1===.5?K%2===0?K:K-1:K}function ye(ge){const K=ge.length,R=ge[0].length,W=[K+1,R+1],j=Array.from({length:W[0]},()=>Array(W[1]).fill(1/0));j[0][0]=0;const Ce=Array.from({length:W[0]},()=>Array(W[1]).fill(-1));for(let pt=1;pt0||Be>0;)switch(Ve.push(Se-1),Ge.push(Be-1),Ce[Se][Be]){case 0:--Se,--Be;break;case 1:--Se;break;case 2:--Be;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Se}, ${Be}]. Please file a bug report.`)}return Ve.reverse(),Ge.reverse(),[Ve,Ge]}},"./src/utils/tensor.js":(Ft,Te,m)=>{m.r(Te),m.d(Te,{Tensor:()=>Oe,cat:()=>ge,full:()=>Se,full_like:()=>Be,interpolate:()=>H,interpolate_4d:()=>B,layer_norm:()=>q,matmul:()=>le,mean:()=>W,mean_pooling:()=>fe,ones:()=>Ve,ones_like:()=>Ge,permute:()=>A,quantize_embeddings:()=>Tt,rfft:()=>de,stack:()=>K,std_mean:()=>R,topk:()=>pe,zeros:()=>pt,zeros_like:()=>ot});var P=m("./src/utils/maths.js"),re=m("./src/backends/onnx.js"),ke=m("./src/ops/registry.js");const ze=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 Oe{constructor(...X){De(this,"ort_tensor");return(0,re.isONNXTensor)(X[0])?this.ort_tensor=X[0]:this.ort_tensor=new re.Tensor(X[0],X[1],X[2]),new Proxy(this,{get:(Me,je)=>{if(typeof je=="string"){let ue=Number(je);if(Number.isInteger(ue))return Me._getitem(ue)}return Me[je]},set:(Me,je,ue)=>Me[je]=ue})}get dims(){return this.ort_tensor.dims}set dims(X){this.ort_tensor.dims=X}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[X,...Me]=this.dims;if(Me.length>0){const je=Me.reduce((ue,nt)=>ue*nt);for(let ue=0;ue0){const ue=je.reduce((nt,xt)=>nt*xt);return this._subarray(X,ue,je)}else return new Oe(this.type,[this.data[X]],je)}indexOf(X){const Me=this.data;for(let je=0;jeKe)throw new Error(`Invalid slice: ${gt}`);const ce=[Math.max(Dt,0),Math.min(Ke,this.dims[Qe])];je.push(ce),Me.push(ce[1]-ce[0])}else throw new Error(`Invalid slice: ${gt}`)}const ue=je.map(([Qe,gt])=>gt-Qe),nt=ue.reduce((Qe,gt)=>Qe*gt),xt=this.data,ft=new xt.constructor(nt),yt=this.stride();for(let Qe=0;Qe=0;--Dt){const ce=ue[Dt];gt+=(Ke%ce+je[Dt][0])*yt[Dt],Ke=Math.floor(Ke/ce)}ft[Qe]=xt[gt]}return new Oe(this.type,ft,Me)}permute(...X){return A(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,Me=!1){return this.norm(1,X,Me)}norm(X="fro",Me=null,je=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const ue=this.data;if(Me===null){let ft=ue.reduce((yt,Qe)=>yt+Qe**X,0)**(1/X);return new Oe(this.type,[ft],[])}Me=ye(Me,this.dims.length);const nt=this.dims.slice();nt[Me]=1;const xt=new ue.constructor(ue.length/this.dims[Me]);for(let ft=0;ft=0;--Qe){const Ke=this.dims[Qe];if(Qe!==Me){const ce=gt%Ke;yt+=ce*Dt,Dt*=nt[Qe]}gt=Math.floor(gt/Ke)}xt[yt]+=ue[ft]**X}if(X!==1)for(let ft=0;ft=0;--yt){const Dt=this.dims[yt];if(yt!==Me){const Ke=Qe%Dt;ft+=Ke*gt,gt*=this.dims[yt]}Qe=Math.floor(Qe/Dt)}ue[xt]/=nt[ft]}return this}normalize(X=2,Me=1){return this.clone().normalize_(X,Me)}stride(){return j(this.dims)}squeeze(X=null){return new Oe(this.type,this.data,ae(this.dims,X))}squeeze_(X=null){return this.dims=ae(this.dims,X),this}unsqueeze(X=null){return new Oe(this.type,this.data,he(this.dims,X))}unsqueeze_(X=null){return this.dims=he(this.dims,X),this}flatten_(X=0,Me=-1){Me=(Me+this.dims.length)%this.dims.length;let je=this.dims.slice(0,X),ue=this.dims.slice(X,Me+1),nt=this.dims.slice(Me+1);return this.dims=[...je,ue.reduce((xt,ft)=>xt*ft,1),...nt],this}flatten(X=0,Me=-1){return this.clone().flatten_(X,Me)}view(...X){let Me=-1;for(let ue=0;ueft!==Me?nt*xt:nt,1);X[Me]=je.length/ue}return new Oe(this.type,je,X)}neg_(){const X=this.data;for(let Me=0;Ment*xt);if(Me!==je)throw Error(`cannot reshape array of size ${Me} into shape (${X})`);let ue=$e;for(let nt=X.length-1;nt>=0;nt--)ue=ue.reduce((xt,ft)=>{let yt=xt[xt.length-1];return yt.lengthMe!==1):typeof X=="number"?$e[X]===1&&$e.splice(X,1):Array.isArray(X)&&($e=$e.filter((Me,je)=>Me!==1||!X.includes(je))),$e}function he($e,X){return X=ye(X,$e.length+1),$e=$e.slice(),$e.splice(X,0,1),$e}function ye($e,X,Me=null,je=!0){if(je&&($e<-X||$e>=X))throw new Error(`IndexError: index ${$e} is out of bounds for dimension${Me===null?"":" "+Me} with size ${X}`);return $e<0&&($e=($e%X+X)%X),$e}function ge($e,X=0){X=ye(X,$e[0].dims.length);const Me=$e[0].dims.slice();Me[X]=$e.reduce((xt,ft)=>xt+ft.dims[X],0);const je=Me.reduce((xt,ft)=>xt*ft,1),ue=new $e[0].data.constructor(je),nt=$e[0].type;if(X===0){let xt=0;for(const ft of $e){const yt=ft.data;ue.set(yt,xt),xt+=yt.length}}else{let xt=0;for(let ft=0;ft<$e.length;++ft){const{data:yt,dims:Qe}=$e[ft];for(let gt=0;gt=0;--Ke){const Je=Qe[Ke];let rt=ce%Je;Ke===X&&(rt+=xt),Dt+=rt*Re,Re*=Me[Ke],ce=Math.floor(ce/Je)}ue[Dt]=yt[gt]}xt+=Qe[X]}}return new Oe(nt,ue,Me)}function K($e,X=0){return ge($e.map(Me=>Me.unsqueeze(X)),X)}function R($e,X=null,Me=1,je=!1){const ue=$e.data,nt=$e.dims;if(X===null){const Ke=ue.reduce((rt,et)=>rt+et,0)/ue.length,ce=Math.sqrt(ue.reduce((rt,et)=>rt+(et-Ke)**2,0)/(ue.length-Me)),Re=new Oe($e.type,[Ke],[]);return[new Oe($e.type,[ce],[]),Re]}X=ye(X,nt.length);const xt=W($e,X,je),ft=xt.data,yt=nt.slice();yt[X]=1;const Qe=new ue.constructor(ue.length/nt[X]);for(let Dt=0;Dt=0;--ce){const rt=nt[ce];if(ce!==X){const et=Re%rt;Ke+=et*Je,Je*=yt[ce]}Re=Math.floor(Re/rt)}Qe[Ke]+=(ue[Dt]-ft[Ke])**2}for(let Dt=0;Dtyt+Qe,0);return new Oe($e.type,[ft/je.length],[])}const ue=$e.dims;X=ye(X,ue.length);const nt=ue.slice();nt[X]=1;const xt=new je.constructor(je.length/ue[X]);for(let ft=0;ft=0;--Qe){const Ke=ue[Qe];if(Qe!==X){const ce=gt%Ke;yt+=ce*Dt,Dt*=nt[Qe]}gt=Math.floor(gt/Ke)}xt[yt]+=je[ft]}if(ue[X]!==1)for(let ft=0;ft=0;--Me)X[Me]=je,je*=$e[Me];return X}function Ce($e,X,Me,je){const ue=$e.reduce((nt,xt)=>nt*xt,1);return new Oe(Me,new je(ue).fill(X),$e)}function Se($e,X){let Me,je;if(typeof X=="number")Me="float32",je=Float32Array;else if(typeof X=="bigint")Me="int64",je=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof X}`);return Ce($e,X,Me,je)}function Be($e,X){return Se($e.dims,X)}function Ve($e){return Ce($e,1n,"int64",BigInt64Array)}function Ge($e){return Ve($e.dims)}function pt($e){return Ce($e,0n,"int64",BigInt64Array)}function ot($e){return pt($e.dims)}function Tt($e,X){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(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const Me=X==="binary",je=Me?"int8":"uint8",ue=Me?Int8Array:Uint8Array,nt=$e.data,xt=new ue(nt.length/8);for(let ft=0;ft0?1:0,Qe=Math.floor(ft/8),gt=ft%8;xt[Qe]|=yt<<7-gt,Me&>===0&&(xt[Qe]-=128)}return new Oe(je,xt,[$e.dims[0],$e.dims[1]/8])}}},Gn={};function Zr(Ft){var Te=Gn[Ft];if(Te!==void 0)return Te.exports;var m=Gn[Ft]={exports:{}};return cn[Ft](m,m.exports,Zr),m.exports}(()=>{var Ft=Object.getPrototypeOf?m=>Object.getPrototypeOf(m):m=>m.__proto__,Te;Zr.t=function(m,P){if(P&1&&(m=this(m)),P&8||typeof m=="object"&&m&&(P&4&&m.__esModule||P&16&&typeof m.then=="function"))return m;var re=Object.create(null);Zr.r(re);var ke={};Te=Te||[null,Ft({}),Ft([]),Ft(Ft)];for(var ze=P&2&&m;typeof ze=="object"&&!~Te.indexOf(ze);ze=Ft(ze))Object.getOwnPropertyNames(ze).forEach(Oe=>ke[Oe]=()=>m[Oe]);return ke.default=()=>m,Zr.d(re,ke),re}})(),Zr.d=(Ft,Te)=>{for(var m in Te)Zr.o(Te,m)&&!Zr.o(Ft,m)&&Object.defineProperty(Ft,m,{enumerable:!0,get:Te[m]})},Zr.o=(Ft,Te)=>Object.prototype.hasOwnProperty.call(Ft,Te),Zr.r=Ft=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Ft,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Ft,"__esModule",{value:!0})},(()=>{var Ft;if(typeof self.location.href=="string"&&(Ft=self.location.href),!Ft)throw new Error("Automatic publicPath is not supported in this browser");Ft=Ft.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Zr.p=Ft})(),Zr.b=void 0;var b={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Zr.r(b),Zr.d(b,{ASTFeatureExtractor:()=>re.ASTFeatureExtractor,ASTForAudioClassification:()=>m.ASTForAudioClassification,ASTModel:()=>m.ASTModel,ASTPreTrainedModel:()=>m.ASTPreTrainedModel,AlbertForMaskedLM:()=>m.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>m.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>m.AlbertForSequenceClassification,AlbertModel:()=>m.AlbertModel,AlbertPreTrainedModel:()=>m.AlbertPreTrainedModel,AlbertTokenizer:()=>P.AlbertTokenizer,AudioClassificationPipeline:()=>Te.AudioClassificationPipeline,AutoConfig:()=>ke.AutoConfig,AutoModel:()=>m.AutoModel,AutoModelForAudioClassification:()=>m.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>m.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>m.AutoModelForCTC,AutoModelForCausalLM:()=>m.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>m.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>m.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>m.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>m.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>m.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>m.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>m.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>m.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>m.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>m.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>m.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>m.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>m.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>m.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>m.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>m.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>m.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>m.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>m.AutoModelForVision2Seq,AutoModelForXVector:()=>m.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>m.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>re.AutoProcessor,AutoTokenizer:()=>P.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Te.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>m.BartForConditionalGeneration,BartForSequenceClassification:()=>m.BartForSequenceClassification,BartModel:()=>m.BartModel,BartPretrainedModel:()=>m.BartPretrainedModel,BartTokenizer:()=>P.BartTokenizer,BaseModelOutput:()=>m.BaseModelOutput,BaseStreamer:()=>H.BaseStreamer,BeitFeatureExtractor:()=>re.BeitFeatureExtractor,BeitForImageClassification:()=>m.BeitForImageClassification,BeitModel:()=>m.BeitModel,BeitPreTrainedModel:()=>m.BeitPreTrainedModel,BertForMaskedLM:()=>m.BertForMaskedLM,BertForQuestionAnswering:()=>m.BertForQuestionAnswering,BertForSequenceClassification:()=>m.BertForSequenceClassification,BertForTokenClassification:()=>m.BertForTokenClassification,BertModel:()=>m.BertModel,BertPreTrainedModel:()=>m.BertPreTrainedModel,BertTokenizer:()=>P.BertTokenizer,BitImageProcessor:()=>re.BitImageProcessor,BlenderbotForConditionalGeneration:()=>m.BlenderbotForConditionalGeneration,BlenderbotModel:()=>m.BlenderbotModel,BlenderbotPreTrainedModel:()=>m.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>m.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>m.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>m.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>P.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>P.BlenderbotTokenizer,BloomForCausalLM:()=>m.BloomForCausalLM,BloomModel:()=>m.BloomModel,BloomPreTrainedModel:()=>m.BloomPreTrainedModel,BloomTokenizer:()=>P.BloomTokenizer,CLIPFeatureExtractor:()=>re.CLIPFeatureExtractor,CLIPImageProcessor:()=>re.CLIPImageProcessor,CLIPModel:()=>m.CLIPModel,CLIPPreTrainedModel:()=>m.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>m.CLIPSegForImageSegmentation,CLIPSegModel:()=>m.CLIPSegModel,CLIPSegPreTrainedModel:()=>m.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>m.CLIPTextModelWithProjection,CLIPTokenizer:()=>P.CLIPTokenizer,CLIPVisionModelWithProjection:()=>m.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>m.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>m.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>m.CamembertForSequenceClassification,CamembertForTokenClassification:()=>m.CamembertForTokenClassification,CamembertModel:()=>m.CamembertModel,CamembertPreTrainedModel:()=>m.CamembertPreTrainedModel,CamembertTokenizer:()=>P.CamembertTokenizer,CausalLMOutput:()=>m.CausalLMOutput,CausalLMOutputWithPast:()=>m.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>re.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>m.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>m.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>m.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>re.ClapFeatureExtractor,ClapModel:()=>m.ClapModel,ClapPreTrainedModel:()=>m.ClapPreTrainedModel,ClapTextModelWithProjection:()=>m.ClapTextModelWithProjection,CodeGenForCausalLM:()=>m.CodeGenForCausalLM,CodeGenModel:()=>m.CodeGenModel,CodeGenPreTrainedModel:()=>m.CodeGenPreTrainedModel,CodeGenTokenizer:()=>P.CodeGenTokenizer,CodeLlamaTokenizer:()=>P.CodeLlamaTokenizer,CohereForCausalLM:()=>m.CohereForCausalLM,CohereModel:()=>m.CohereModel,CoherePreTrainedModel:()=>m.CoherePreTrainedModel,CohereTokenizer:()=>P.CohereTokenizer,ConvBertForMaskedLM:()=>m.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>m.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>m.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>m.ConvBertForTokenClassification,ConvBertModel:()=>m.ConvBertModel,ConvBertPreTrainedModel:()=>m.ConvBertPreTrainedModel,ConvBertTokenizer:()=>P.ConvBertTokenizer,ConvNextFeatureExtractor:()=>re.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>m.ConvNextForImageClassification,ConvNextImageProcessor:()=>re.ConvNextImageProcessor,ConvNextModel:()=>m.ConvNextModel,ConvNextPreTrainedModel:()=>m.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>m.ConvNextV2ForImageClassification,ConvNextV2Model:()=>m.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>m.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>re.DPTFeatureExtractor,DPTForDepthEstimation:()=>m.DPTForDepthEstimation,DPTImageProcessor:()=>re.DPTImageProcessor,DPTModel:()=>m.DPTModel,DPTPreTrainedModel:()=>m.DPTPreTrainedModel,DebertaForMaskedLM:()=>m.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>m.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>m.DebertaForSequenceClassification,DebertaForTokenClassification:()=>m.DebertaForTokenClassification,DebertaModel:()=>m.DebertaModel,DebertaPreTrainedModel:()=>m.DebertaPreTrainedModel,DebertaTokenizer:()=>P.DebertaTokenizer,DebertaV2ForMaskedLM:()=>m.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>m.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>m.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>m.DebertaV2ForTokenClassification,DebertaV2Model:()=>m.DebertaV2Model,DebertaV2PreTrainedModel:()=>m.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>P.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>re.DeiTFeatureExtractor,DeiTForImageClassification:()=>m.DeiTForImageClassification,DeiTModel:()=>m.DeiTModel,DeiTPreTrainedModel:()=>m.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>m.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>m.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Te.DepthEstimationPipeline,DetrFeatureExtractor:()=>re.DetrFeatureExtractor,DetrForObjectDetection:()=>m.DetrForObjectDetection,DetrForSegmentation:()=>m.DetrForSegmentation,DetrModel:()=>m.DetrModel,DetrObjectDetectionOutput:()=>m.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>m.DetrPreTrainedModel,DetrSegmentationOutput:()=>m.DetrSegmentationOutput,Dinov2ForImageClassification:()=>m.Dinov2ForImageClassification,Dinov2Model:()=>m.Dinov2Model,Dinov2PreTrainedModel:()=>m.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>m.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>m.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>m.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>m.DistilBertForTokenClassification,DistilBertModel:()=>m.DistilBertModel,DistilBertPreTrainedModel:()=>m.DistilBertPreTrainedModel,DistilBertTokenizer:()=>P.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Te.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>re.DonutFeatureExtractor,DonutSwinModel:()=>m.DonutSwinModel,DonutSwinPreTrainedModel:()=>m.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>m.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>re.EfficientNetImageProcessor,EfficientNetModel:()=>m.EfficientNetModel,EfficientNetPreTrainedModel:()=>m.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>m.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>m.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>m.ElectraForSequenceClassification,ElectraForTokenClassification:()=>m.ElectraForTokenClassification,ElectraModel:()=>m.ElectraModel,ElectraPreTrainedModel:()=>m.ElectraPreTrainedModel,ElectraTokenizer:()=>P.ElectraTokenizer,EosTokenCriteria:()=>B.EosTokenCriteria,EsmForMaskedLM:()=>m.EsmForMaskedLM,EsmForSequenceClassification:()=>m.EsmForSequenceClassification,EsmForTokenClassification:()=>m.EsmForTokenClassification,EsmModel:()=>m.EsmModel,EsmPreTrainedModel:()=>m.EsmPreTrainedModel,EsmTokenizer:()=>P.EsmTokenizer,FFT:()=>A.FFT,FalconForCausalLM:()=>m.FalconForCausalLM,FalconModel:()=>m.FalconModel,FalconPreTrainedModel:()=>m.FalconPreTrainedModel,FalconTokenizer:()=>P.FalconTokenizer,FastViTForImageClassification:()=>m.FastViTForImageClassification,FastViTModel:()=>m.FastViTModel,FastViTPreTrainedModel:()=>m.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Te.FeatureExtractionPipeline,FeatureExtractor:()=>re.FeatureExtractor,FillMaskPipeline:()=>Te.FillMaskPipeline,Florence2ForConditionalGeneration:()=>m.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>m.Florence2PreTrainedModel,Florence2Processor:()=>re.Florence2Processor,GLPNFeatureExtractor:()=>re.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>m.GLPNForDepthEstimation,GLPNModel:()=>m.GLPNModel,GLPNPreTrainedModel:()=>m.GLPNPreTrainedModel,GPT2LMHeadModel:()=>m.GPT2LMHeadModel,GPT2Model:()=>m.GPT2Model,GPT2PreTrainedModel:()=>m.GPT2PreTrainedModel,GPT2Tokenizer:()=>P.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>m.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>m.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>m.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>m.GPTJForCausalLM,GPTJModel:()=>m.GPTJModel,GPTJPreTrainedModel:()=>m.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>m.GPTNeoForCausalLM,GPTNeoModel:()=>m.GPTNeoModel,GPTNeoPreTrainedModel:()=>m.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>m.GPTNeoXForCausalLM,GPTNeoXModel:()=>m.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>m.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>P.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>m.Gemma2ForCausalLM,Gemma2Model:()=>m.Gemma2Model,Gemma2PreTrainedModel:()=>m.Gemma2PreTrainedModel,GemmaForCausalLM:()=>m.GemmaForCausalLM,GemmaModel:()=>m.GemmaModel,GemmaPreTrainedModel:()=>m.GemmaPreTrainedModel,GemmaTokenizer:()=>P.GemmaTokenizer,Grok1Tokenizer:()=>P.Grok1Tokenizer,HerbertTokenizer:()=>P.HerbertTokenizer,HubertForCTC:()=>m.HubertForCTC,HubertForSequenceClassification:()=>m.HubertForSequenceClassification,HubertModel:()=>m.HubertModel,HubertPreTrainedModel:()=>m.HubertPreTrainedModel,ImageClassificationPipeline:()=>Te.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Te.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>re.ImageFeatureExtractor,ImageMattingOutput:()=>m.ImageMattingOutput,ImageSegmentationPipeline:()=>Te.ImageSegmentationPipeline,ImageToImagePipeline:()=>Te.ImageToImagePipeline,ImageToTextPipeline:()=>Te.ImageToTextPipeline,InterruptableStoppingCriteria:()=>B.InterruptableStoppingCriteria,LlamaForCausalLM:()=>m.LlamaForCausalLM,LlamaModel:()=>m.LlamaModel,LlamaPreTrainedModel:()=>m.LlamaPreTrainedModel,LlamaTokenizer:()=>P.LlamaTokenizer,LlavaForConditionalGeneration:()=>m.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>m.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>m.LongT5ForConditionalGeneration,LongT5Model:()=>m.LongT5Model,LongT5PreTrainedModel:()=>m.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>m.M2M100ForConditionalGeneration,M2M100Model:()=>m.M2M100Model,M2M100PreTrainedModel:()=>m.M2M100PreTrainedModel,M2M100Tokenizer:()=>P.M2M100Tokenizer,MBart50Tokenizer:()=>P.MBart50Tokenizer,MBartForCausalLM:()=>m.MBartForCausalLM,MBartForConditionalGeneration:()=>m.MBartForConditionalGeneration,MBartForSequenceClassification:()=>m.MBartForSequenceClassification,MBartModel:()=>m.MBartModel,MBartPreTrainedModel:()=>m.MBartPreTrainedModel,MBartTokenizer:()=>P.MBartTokenizer,MPNetForMaskedLM:()=>m.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>m.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>m.MPNetForSequenceClassification,MPNetForTokenClassification:()=>m.MPNetForTokenClassification,MPNetModel:()=>m.MPNetModel,MPNetPreTrainedModel:()=>m.MPNetPreTrainedModel,MPNetTokenizer:()=>P.MPNetTokenizer,MT5ForConditionalGeneration:()=>m.MT5ForConditionalGeneration,MT5Model:()=>m.MT5Model,MT5PreTrainedModel:()=>m.MT5PreTrainedModel,MarianMTModel:()=>m.MarianMTModel,MarianModel:()=>m.MarianModel,MarianPreTrainedModel:()=>m.MarianPreTrainedModel,MarianTokenizer:()=>P.MarianTokenizer,MaskedLMOutput:()=>m.MaskedLMOutput,MaxLengthCriteria:()=>B.MaxLengthCriteria,MistralForCausalLM:()=>m.MistralForCausalLM,MistralModel:()=>m.MistralModel,MistralPreTrainedModel:()=>m.MistralPreTrainedModel,MobileBertForMaskedLM:()=>m.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>m.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>m.MobileBertForSequenceClassification,MobileBertModel:()=>m.MobileBertModel,MobileBertPreTrainedModel:()=>m.MobileBertPreTrainedModel,MobileBertTokenizer:()=>P.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>re.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>m.MobileNetV1ForImageClassification,MobileNetV1Model:()=>m.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>m.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>re.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>m.MobileNetV2ForImageClassification,MobileNetV2Model:()=>m.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>m.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>re.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>m.MobileNetV3ForImageClassification,MobileNetV3Model:()=>m.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>m.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>re.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>m.MobileNetV4ForImageClassification,MobileNetV4Model:()=>m.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>m.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>re.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>m.MobileViTForImageClassification,MobileViTImageProcessor:()=>re.MobileViTImageProcessor,MobileViTModel:()=>m.MobileViTModel,MobileViTPreTrainedModel:()=>m.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>m.MobileViTV2ForImageClassification,MobileViTV2Model:()=>m.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>m.MobileViTV2PreTrainedModel,ModelOutput:()=>m.ModelOutput,Moondream1ForConditionalGeneration:()=>m.Moondream1ForConditionalGeneration,MptForCausalLM:()=>m.MptForCausalLM,MptModel:()=>m.MptModel,MptPreTrainedModel:()=>m.MptPreTrainedModel,MusicgenForCausalLM:()=>m.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>m.MusicgenForConditionalGeneration,MusicgenModel:()=>m.MusicgenModel,MusicgenPreTrainedModel:()=>m.MusicgenPreTrainedModel,NllbTokenizer:()=>P.NllbTokenizer,NomicBertModel:()=>m.NomicBertModel,NomicBertPreTrainedModel:()=>m.NomicBertPreTrainedModel,NougatImageProcessor:()=>re.NougatImageProcessor,NougatTokenizer:()=>P.NougatTokenizer,OPTForCausalLM:()=>m.OPTForCausalLM,OPTModel:()=>m.OPTModel,OPTPreTrainedModel:()=>m.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Te.ObjectDetectionPipeline,OpenELMForCausalLM:()=>m.OpenELMForCausalLM,OpenELMModel:()=>m.OpenELMModel,OpenELMPreTrainedModel:()=>m.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>re.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>m.OwlViTForObjectDetection,OwlViTModel:()=>m.OwlViTModel,OwlViTPreTrainedModel:()=>m.OwlViTPreTrainedModel,OwlViTProcessor:()=>re.OwlViTProcessor,Owlv2ForObjectDetection:()=>m.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>re.Owlv2ImageProcessor,Owlv2Model:()=>m.Owlv2Model,Owlv2PreTrainedModel:()=>m.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>m.Phi3ForCausalLM,Phi3Model:()=>m.Phi3Model,Phi3PreTrainedModel:()=>m.Phi3PreTrainedModel,PhiForCausalLM:()=>m.PhiForCausalLM,PhiModel:()=>m.PhiModel,PhiPreTrainedModel:()=>m.PhiPreTrainedModel,Pipeline:()=>Te.Pipeline,PreTrainedModel:()=>m.PreTrainedModel,PreTrainedTokenizer:()=>P.PreTrainedTokenizer,PretrainedConfig:()=>ke.PretrainedConfig,PretrainedMixin:()=>m.PretrainedMixin,Processor:()=>re.Processor,PyAnnoteFeatureExtractor:()=>re.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>m.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>m.PyAnnoteModel,PyAnnotePreTrainedModel:()=>m.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>re.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>m.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Te.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>m.Qwen2ForCausalLM,Qwen2Model:()=>m.Qwen2Model,Qwen2PreTrainedModel:()=>m.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>P.Qwen2Tokenizer,RTDetrForObjectDetection:()=>m.RTDetrForObjectDetection,RTDetrImageProcessor:()=>re.RTDetrImageProcessor,RTDetrModel:()=>m.RTDetrModel,RTDetrObjectDetectionOutput:()=>m.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>m.RTDetrPreTrainedModel,RawImage:()=>Oe.RawImage,ResNetForImageClassification:()=>m.ResNetForImageClassification,ResNetModel:()=>m.ResNetModel,ResNetPreTrainedModel:()=>m.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>m.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>m.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>m.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>m.RoFormerForTokenClassification,RoFormerModel:()=>m.RoFormerModel,RoFormerPreTrainedModel:()=>m.RoFormerPreTrainedModel,RoFormerTokenizer:()=>P.RoFormerTokenizer,RobertaForMaskedLM:()=>m.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>m.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>m.RobertaForSequenceClassification,RobertaForTokenClassification:()=>m.RobertaForTokenClassification,RobertaModel:()=>m.RobertaModel,RobertaPreTrainedModel:()=>m.RobertaPreTrainedModel,RobertaTokenizer:()=>P.RobertaTokenizer,SamImageProcessor:()=>re.SamImageProcessor,SamImageSegmentationOutput:()=>m.SamImageSegmentationOutput,SamModel:()=>m.SamModel,SamPreTrainedModel:()=>m.SamPreTrainedModel,SamProcessor:()=>re.SamProcessor,SeamlessM4TFeatureExtractor:()=>re.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>re.SegformerFeatureExtractor,SegformerForImageClassification:()=>m.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>m.SegformerForSemanticSegmentation,SegformerModel:()=>m.SegformerModel,SegformerPreTrainedModel:()=>m.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>m.Seq2SeqLMOutput,SequenceClassifierOutput:()=>m.SequenceClassifierOutput,SiglipImageProcessor:()=>re.SiglipImageProcessor,SiglipModel:()=>m.SiglipModel,SiglipPreTrainedModel:()=>m.SiglipPreTrainedModel,SiglipTextModel:()=>m.SiglipTextModel,SiglipTokenizer:()=>P.SiglipTokenizer,SiglipVisionModel:()=>m.SiglipVisionModel,SpeechT5FeatureExtractor:()=>re.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>m.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>m.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>m.SpeechT5HifiGan,SpeechT5Model:()=>m.SpeechT5Model,SpeechT5PreTrainedModel:()=>m.SpeechT5PreTrainedModel,SpeechT5Processor:()=>re.SpeechT5Processor,SpeechT5Tokenizer:()=>P.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>m.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>m.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>m.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>m.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>m.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>P.SqueezeBertTokenizer,StableLmForCausalLM:()=>m.StableLmForCausalLM,StableLmModel:()=>m.StableLmModel,StableLmPreTrainedModel:()=>m.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>m.Starcoder2ForCausalLM,Starcoder2Model:()=>m.Starcoder2Model,Starcoder2PreTrainedModel:()=>m.Starcoder2PreTrainedModel,StoppingCriteria:()=>B.StoppingCriteria,StoppingCriteriaList:()=>B.StoppingCriteriaList,SummarizationPipeline:()=>Te.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>m.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>re.Swin2SRImageProcessor,Swin2SRModel:()=>m.Swin2SRModel,Swin2SRPreTrainedModel:()=>m.Swin2SRPreTrainedModel,SwinForImageClassification:()=>m.SwinForImageClassification,SwinModel:()=>m.SwinModel,SwinPreTrainedModel:()=>m.SwinPreTrainedModel,T5ForConditionalGeneration:()=>m.T5ForConditionalGeneration,T5Model:()=>m.T5Model,T5PreTrainedModel:()=>m.T5PreTrainedModel,T5Tokenizer:()=>P.T5Tokenizer,TableTransformerForObjectDetection:()=>m.TableTransformerForObjectDetection,TableTransformerModel:()=>m.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>m.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>m.TableTransformerPreTrainedModel,Tensor:()=>V.Tensor,Text2TextGenerationPipeline:()=>Te.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Te.TextClassificationPipeline,TextGenerationPipeline:()=>Te.TextGenerationPipeline,TextStreamer:()=>H.TextStreamer,TextToAudioPipeline:()=>Te.TextToAudioPipeline,TokenClassificationPipeline:()=>Te.TokenClassificationPipeline,TokenClassifierOutput:()=>m.TokenClassifierOutput,TokenizerModel:()=>P.TokenizerModel,TrOCRForCausalLM:()=>m.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>m.TrOCRPreTrainedModel,TranslationPipeline:()=>Te.TranslationPipeline,UniSpeechForCTC:()=>m.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>m.UniSpeechForSequenceClassification,UniSpeechModel:()=>m.UniSpeechModel,UniSpeechPreTrainedModel:()=>m.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>m.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>m.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>m.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>m.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>m.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>re.ViTFeatureExtractor,ViTForImageClassification:()=>m.ViTForImageClassification,ViTImageProcessor:()=>re.ViTImageProcessor,ViTModel:()=>m.ViTModel,ViTPreTrainedModel:()=>m.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>m.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>m.VitMatteForImageMatting,VitMatteImageProcessor:()=>re.VitMatteImageProcessor,VitMattePreTrainedModel:()=>m.VitMattePreTrainedModel,VitsModel:()=>m.VitsModel,VitsModelOutput:()=>m.VitsModelOutput,VitsPreTrainedModel:()=>m.VitsPreTrainedModel,VitsTokenizer:()=>P.VitsTokenizer,Wav2Vec2BertForCTC:()=>m.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>m.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>m.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>m.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>P.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>re.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>m.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>m.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>m.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>m.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>m.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>re.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>m.WavLMForAudioFrameClassification,WavLMForCTC:()=>m.WavLMForCTC,WavLMForSequenceClassification:()=>m.WavLMForSequenceClassification,WavLMForXVector:()=>m.WavLMForXVector,WavLMModel:()=>m.WavLMModel,WavLMPreTrainedModel:()=>m.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>re.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>m.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>m.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>re.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>m.WhisperForConditionalGeneration,WhisperModel:()=>m.WhisperModel,WhisperPreTrainedModel:()=>m.WhisperPreTrainedModel,WhisperProcessor:()=>re.WhisperProcessor,WhisperTextStreamer:()=>H.WhisperTextStreamer,WhisperTokenizer:()=>P.WhisperTokenizer,XLMForQuestionAnswering:()=>m.XLMForQuestionAnswering,XLMForSequenceClassification:()=>m.XLMForSequenceClassification,XLMForTokenClassification:()=>m.XLMForTokenClassification,XLMModel:()=>m.XLMModel,XLMPreTrainedModel:()=>m.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>m.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>m.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>m.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>m.XLMRobertaForTokenClassification,XLMRobertaModel:()=>m.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>m.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>P.XLMRobertaTokenizer,XLMTokenizer:()=>P.XLMTokenizer,XLMWithLMHeadModel:()=>m.XLMWithLMHeadModel,XVectorOutput:()=>m.XVectorOutput,YolosFeatureExtractor:()=>re.YolosFeatureExtractor,YolosForObjectDetection:()=>m.YolosForObjectDetection,YolosModel:()=>m.YolosModel,YolosObjectDetectionOutput:()=>m.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>m.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Te.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Te.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Te.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Te.ZeroShotObjectDetectionPipeline,bankers_round:()=>A.bankers_round,cat:()=>V.cat,cos_sim:()=>A.cos_sim,dot:()=>A.dot,dynamic_time_warping:()=>A.dynamic_time_warping,env:()=>Ft.env,full:()=>V.full,full_like:()=>V.full_like,getKeyValueShapes:()=>ke.getKeyValueShapes,hamming:()=>ze.hamming,hanning:()=>ze.hanning,interpolate:()=>V.interpolate,interpolate_4d:()=>V.interpolate_4d,interpolate_data:()=>A.interpolate_data,is_chinese_char:()=>P.is_chinese_char,layer_norm:()=>V.layer_norm,log_softmax:()=>A.log_softmax,magnitude:()=>A.magnitude,matmul:()=>V.matmul,max:()=>A.max,mean:()=>V.mean,mean_pooling:()=>V.mean_pooling,medianFilter:()=>A.medianFilter,mel_filter_bank:()=>ze.mel_filter_bank,min:()=>A.min,ones:()=>V.ones,ones_like:()=>V.ones_like,permute:()=>V.permute,permute_data:()=>A.permute_data,pipeline:()=>Te.pipeline,quantize_embeddings:()=>V.quantize_embeddings,read_audio:()=>ze.read_audio,rfft:()=>V.rfft,round:()=>A.round,softmax:()=>A.softmax,spectrogram:()=>ze.spectrogram,stack:()=>V.stack,std_mean:()=>V.std_mean,topk:()=>V.topk,window_function:()=>ze.window_function,zeros:()=>V.zeros,zeros_like:()=>V.zeros_like});var Ft=Zr("./src/env.js"),Te=Zr("./src/pipelines.js"),m=Zr("./src/models.js"),P=Zr("./src/tokenizers.js"),re=Zr("./src/processors.js"),ke=Zr("./src/configs.js"),ze=Zr("./src/utils/audio.js"),Oe=Zr("./src/utils/image.js"),V=Zr("./src/utils/tensor.js"),A=Zr("./src/utils/maths.js"),H=Zr("./src/generation/streamers.js"),B=Zr("./src/generation/stopping_criteria.js")})(),b.ASTFeatureExtractor,b.ASTForAudioClassification,b.ASTModel,b.ASTPreTrainedModel,b.AlbertForMaskedLM,b.AlbertForQuestionAnswering,b.AlbertForSequenceClassification,b.AlbertModel,b.AlbertPreTrainedModel,b.AlbertTokenizer,b.AudioClassificationPipeline,b.AutoConfig,b.AutoModel,b.AutoModelForAudioClassification,b.AutoModelForAudioFrameClassification,b.AutoModelForCTC;var Sg=b.AutoModelForCausalLM;b.AutoModelForDepthEstimation,b.AutoModelForDocumentQuestionAnswering,b.AutoModelForImageClassification,b.AutoModelForImageFeatureExtraction,b.AutoModelForImageMatting,b.AutoModelForImageSegmentation,b.AutoModelForImageToImage,b.AutoModelForMaskGeneration,b.AutoModelForMaskedLM,b.AutoModelForObjectDetection,b.AutoModelForQuestionAnswering,b.AutoModelForSemanticSegmentation,b.AutoModelForSeq2SeqLM,b.AutoModelForSequenceClassification,b.AutoModelForSpeechSeq2Seq,b.AutoModelForTextToSpectrogram,b.AutoModelForTextToWaveform,b.AutoModelForTokenClassification,b.AutoModelForVision2Seq,b.AutoModelForXVector,b.AutoModelForZeroShotObjectDetection,b.AutoProcessor;var Eg=b.AutoTokenizer;b.AutomaticSpeechRecognitionPipeline,b.BartForConditionalGeneration,b.BartForSequenceClassification,b.BartModel,b.BartPretrainedModel,b.BartTokenizer,b.BaseModelOutput,b.BaseStreamer,b.BeitFeatureExtractor,b.BeitForImageClassification,b.BeitModel,b.BeitPreTrainedModel,b.BertForMaskedLM,b.BertForQuestionAnswering,b.BertForSequenceClassification,b.BertForTokenClassification,b.BertModel,b.BertPreTrainedModel,b.BertTokenizer,b.BitImageProcessor,b.BlenderbotForConditionalGeneration,b.BlenderbotModel,b.BlenderbotPreTrainedModel,b.BlenderbotSmallForConditionalGeneration,b.BlenderbotSmallModel,b.BlenderbotSmallPreTrainedModel,b.BlenderbotSmallTokenizer,b.BlenderbotTokenizer,b.BloomForCausalLM,b.BloomModel,b.BloomPreTrainedModel,b.BloomTokenizer,b.CLIPFeatureExtractor,b.CLIPImageProcessor,b.CLIPModel,b.CLIPPreTrainedModel,b.CLIPSegForImageSegmentation,b.CLIPSegModel,b.CLIPSegPreTrainedModel,b.CLIPTextModelWithProjection,b.CLIPTokenizer,b.CLIPVisionModelWithProjection,b.CamembertForMaskedLM,b.CamembertForQuestionAnswering,b.CamembertForSequenceClassification,b.CamembertForTokenClassification,b.CamembertModel,b.CamembertPreTrainedModel,b.CamembertTokenizer,b.CausalLMOutput,b.CausalLMOutputWithPast,b.ChineseCLIPFeatureExtractor,b.ChineseCLIPModel,b.ChineseCLIPPreTrainedModel,b.ClapAudioModelWithProjection,b.ClapFeatureExtractor,b.ClapModel,b.ClapPreTrainedModel,b.ClapTextModelWithProjection,b.CodeGenForCausalLM,b.CodeGenModel,b.CodeGenPreTrainedModel,b.CodeGenTokenizer,b.CodeLlamaTokenizer,b.CohereForCausalLM,b.CohereModel,b.CoherePreTrainedModel,b.CohereTokenizer,b.ConvBertForMaskedLM,b.ConvBertForQuestionAnswering,b.ConvBertForSequenceClassification,b.ConvBertForTokenClassification,b.ConvBertModel,b.ConvBertPreTrainedModel,b.ConvBertTokenizer,b.ConvNextFeatureExtractor,b.ConvNextForImageClassification,b.ConvNextImageProcessor,b.ConvNextModel,b.ConvNextPreTrainedModel,b.ConvNextV2ForImageClassification,b.ConvNextV2Model,b.ConvNextV2PreTrainedModel,b.DPTFeatureExtractor,b.DPTForDepthEstimation,b.DPTImageProcessor,b.DPTModel,b.DPTPreTrainedModel,b.DebertaForMaskedLM,b.DebertaForQuestionAnswering,b.DebertaForSequenceClassification,b.DebertaForTokenClassification,b.DebertaModel,b.DebertaPreTrainedModel,b.DebertaTokenizer,b.DebertaV2ForMaskedLM,b.DebertaV2ForQuestionAnswering,b.DebertaV2ForSequenceClassification,b.DebertaV2ForTokenClassification,b.DebertaV2Model,b.DebertaV2PreTrainedModel,b.DebertaV2Tokenizer,b.DeiTFeatureExtractor,b.DeiTForImageClassification,b.DeiTModel,b.DeiTPreTrainedModel,b.DepthAnythingForDepthEstimation,b.DepthAnythingPreTrainedModel,b.DepthEstimationPipeline,b.DetrFeatureExtractor,b.DetrForObjectDetection,b.DetrForSegmentation,b.DetrModel,b.DetrObjectDetectionOutput,b.DetrPreTrainedModel,b.DetrSegmentationOutput,b.Dinov2ForImageClassification,b.Dinov2Model,b.Dinov2PreTrainedModel,b.DistilBertForMaskedLM,b.DistilBertForQuestionAnswering,b.DistilBertForSequenceClassification,b.DistilBertForTokenClassification,b.DistilBertModel,b.DistilBertPreTrainedModel,b.DistilBertTokenizer,b.DocumentQuestionAnsweringPipeline,b.DonutFeatureExtractor,b.DonutSwinModel,b.DonutSwinPreTrainedModel,b.EfficientNetForImageClassification,b.EfficientNetImageProcessor,b.EfficientNetModel,b.EfficientNetPreTrainedModel,b.ElectraForMaskedLM,b.ElectraForQuestionAnswering,b.ElectraForSequenceClassification,b.ElectraForTokenClassification,b.ElectraModel,b.ElectraPreTrainedModel,b.ElectraTokenizer,b.EosTokenCriteria,b.EsmForMaskedLM,b.EsmForSequenceClassification,b.EsmForTokenClassification,b.EsmModel,b.EsmPreTrainedModel,b.EsmTokenizer,b.FFT,b.FalconForCausalLM,b.FalconModel,b.FalconPreTrainedModel,b.FalconTokenizer,b.FastViTForImageClassification,b.FastViTModel,b.FastViTPreTrainedModel,b.FeatureExtractionPipeline,b.FeatureExtractor,b.FillMaskPipeline,b.Florence2ForConditionalGeneration,b.Florence2PreTrainedModel,b.Florence2Processor,b.GLPNFeatureExtractor,b.GLPNForDepthEstimation,b.GLPNModel,b.GLPNPreTrainedModel,b.GPT2LMHeadModel,b.GPT2Model,b.GPT2PreTrainedModel,b.GPT2Tokenizer,b.GPTBigCodeForCausalLM,b.GPTBigCodeModel,b.GPTBigCodePreTrainedModel,b.GPTJForCausalLM,b.GPTJModel,b.GPTJPreTrainedModel,b.GPTNeoForCausalLM,b.GPTNeoModel,b.GPTNeoPreTrainedModel,b.GPTNeoXForCausalLM,b.GPTNeoXModel,b.GPTNeoXPreTrainedModel,b.GPTNeoXTokenizer,b.Gemma2ForCausalLM,b.Gemma2Model,b.Gemma2PreTrainedModel,b.GemmaForCausalLM,b.GemmaModel,b.GemmaPreTrainedModel,b.GemmaTokenizer,b.Grok1Tokenizer,b.HerbertTokenizer,b.HubertForCTC,b.HubertForSequenceClassification,b.HubertModel,b.HubertPreTrainedModel,b.ImageClassificationPipeline,b.ImageFeatureExtractionPipeline,b.ImageFeatureExtractor,b.ImageMattingOutput,b.ImageSegmentationPipeline,b.ImageToImagePipeline,b.ImageToTextPipeline;var Pg=b.InterruptableStoppingCriteria;b.LlamaForCausalLM,b.LlamaModel,b.LlamaPreTrainedModel,b.LlamaTokenizer,b.LlavaForConditionalGeneration,b.LlavaPreTrainedModel,b.LongT5ForConditionalGeneration,b.LongT5Model,b.LongT5PreTrainedModel,b.M2M100ForConditionalGeneration,b.M2M100Model,b.M2M100PreTrainedModel,b.M2M100Tokenizer,b.MBart50Tokenizer,b.MBartForCausalLM,b.MBartForConditionalGeneration,b.MBartForSequenceClassification,b.MBartModel,b.MBartPreTrainedModel,b.MBartTokenizer,b.MPNetForMaskedLM,b.MPNetForQuestionAnswering,b.MPNetForSequenceClassification,b.MPNetForTokenClassification,b.MPNetModel,b.MPNetPreTrainedModel,b.MPNetTokenizer,b.MT5ForConditionalGeneration,b.MT5Model,b.MT5PreTrainedModel,b.MarianMTModel,b.MarianModel,b.MarianPreTrainedModel,b.MarianTokenizer,b.MaskedLMOutput,b.MaxLengthCriteria,b.MistralForCausalLM,b.MistralModel,b.MistralPreTrainedModel,b.MobileBertForMaskedLM,b.MobileBertForQuestionAnswering,b.MobileBertForSequenceClassification,b.MobileBertModel,b.MobileBertPreTrainedModel,b.MobileBertTokenizer,b.MobileNetV1FeatureExtractor,b.MobileNetV1ForImageClassification,b.MobileNetV1Model,b.MobileNetV1PreTrainedModel,b.MobileNetV2FeatureExtractor,b.MobileNetV2ForImageClassification,b.MobileNetV2Model,b.MobileNetV2PreTrainedModel,b.MobileNetV3FeatureExtractor,b.MobileNetV3ForImageClassification,b.MobileNetV3Model,b.MobileNetV3PreTrainedModel,b.MobileNetV4FeatureExtractor,b.MobileNetV4ForImageClassification,b.MobileNetV4Model,b.MobileNetV4PreTrainedModel,b.MobileViTFeatureExtractor,b.MobileViTForImageClassification,b.MobileViTImageProcessor,b.MobileViTModel,b.MobileViTPreTrainedModel,b.MobileViTV2ForImageClassification,b.MobileViTV2Model,b.MobileViTV2PreTrainedModel,b.ModelOutput,b.Moondream1ForConditionalGeneration,b.MptForCausalLM,b.MptModel,b.MptPreTrainedModel,b.MusicgenForCausalLM,b.MusicgenForConditionalGeneration,b.MusicgenModel,b.MusicgenPreTrainedModel,b.NllbTokenizer,b.NomicBertModel,b.NomicBertPreTrainedModel,b.NougatImageProcessor,b.NougatTokenizer,b.OPTForCausalLM,b.OPTModel,b.OPTPreTrainedModel,b.ObjectDetectionPipeline,b.OpenELMForCausalLM,b.OpenELMModel,b.OpenELMPreTrainedModel,b.OwlViTFeatureExtractor,b.OwlViTForObjectDetection,b.OwlViTModel,b.OwlViTPreTrainedModel,b.OwlViTProcessor,b.Owlv2ForObjectDetection,b.Owlv2ImageProcessor,b.Owlv2Model,b.Owlv2PreTrainedModel,b.Phi3ForCausalLM,b.Phi3Model,b.Phi3PreTrainedModel,b.PhiForCausalLM,b.PhiModel,b.PhiPreTrainedModel,b.Pipeline,b.PreTrainedModel,b.PreTrainedTokenizer,b.PretrainedConfig,b.PretrainedMixin,b.Processor,b.PyAnnoteFeatureExtractor,b.PyAnnoteForAudioFrameClassification,b.PyAnnoteModel,b.PyAnnotePreTrainedModel,b.PyAnnoteProcessor,b.QuestionAnsweringModelOutput,b.QuestionAnsweringPipeline,b.Qwen2ForCausalLM,b.Qwen2Model,b.Qwen2PreTrainedModel,b.Qwen2Tokenizer,b.RTDetrForObjectDetection,b.RTDetrImageProcessor,b.RTDetrModel,b.RTDetrObjectDetectionOutput,b.RTDetrPreTrainedModel,b.RawImage,b.ResNetForImageClassification,b.ResNetModel,b.ResNetPreTrainedModel,b.RoFormerForMaskedLM,b.RoFormerForQuestionAnswering,b.RoFormerForSequenceClassification,b.RoFormerForTokenClassification,b.RoFormerModel,b.RoFormerPreTrainedModel,b.RoFormerTokenizer,b.RobertaForMaskedLM,b.RobertaForQuestionAnswering,b.RobertaForSequenceClassification,b.RobertaForTokenClassification,b.RobertaModel,b.RobertaPreTrainedModel,b.RobertaTokenizer,b.SamImageProcessor,b.SamImageSegmentationOutput,b.SamModel,b.SamPreTrainedModel,b.SamProcessor,b.SeamlessM4TFeatureExtractor,b.SegformerFeatureExtractor,b.SegformerForImageClassification,b.SegformerForSemanticSegmentation,b.SegformerModel,b.SegformerPreTrainedModel,b.Seq2SeqLMOutput,b.SequenceClassifierOutput,b.SiglipImageProcessor,b.SiglipModel,b.SiglipPreTrainedModel,b.SiglipTextModel,b.SiglipTokenizer,b.SiglipVisionModel,b.SpeechT5FeatureExtractor,b.SpeechT5ForSpeechToText,b.SpeechT5ForTextToSpeech,b.SpeechT5HifiGan,b.SpeechT5Model,b.SpeechT5PreTrainedModel,b.SpeechT5Processor,b.SpeechT5Tokenizer,b.SqueezeBertForMaskedLM,b.SqueezeBertForQuestionAnswering,b.SqueezeBertForSequenceClassification,b.SqueezeBertModel,b.SqueezeBertPreTrainedModel,b.SqueezeBertTokenizer,b.StableLmForCausalLM,b.StableLmModel,b.StableLmPreTrainedModel,b.Starcoder2ForCausalLM,b.Starcoder2Model,b.Starcoder2PreTrainedModel,b.StoppingCriteria,b.StoppingCriteriaList,b.SummarizationPipeline,b.Swin2SRForImageSuperResolution,b.Swin2SRImageProcessor,b.Swin2SRModel,b.Swin2SRPreTrainedModel,b.SwinForImageClassification,b.SwinModel,b.SwinPreTrainedModel,b.T5ForConditionalGeneration,b.T5Model,b.T5PreTrainedModel,b.T5Tokenizer,b.TableTransformerForObjectDetection,b.TableTransformerModel,b.TableTransformerObjectDetectionOutput,b.TableTransformerPreTrainedModel,b.Tensor,b.Text2TextGenerationPipeline,b.TextClassificationPipeline,b.TextGenerationPipeline;var Ag=b.TextStreamer;b.TextToAudioPipeline,b.TokenClassificationPipeline,b.TokenClassifierOutput,b.TokenizerModel,b.TrOCRForCausalLM,b.TrOCRPreTrainedModel,b.TranslationPipeline,b.UniSpeechForCTC,b.UniSpeechForSequenceClassification,b.UniSpeechModel,b.UniSpeechPreTrainedModel,b.UniSpeechSatForAudioFrameClassification,b.UniSpeechSatForCTC,b.UniSpeechSatForSequenceClassification,b.UniSpeechSatModel,b.UniSpeechSatPreTrainedModel,b.ViTFeatureExtractor,b.ViTForImageClassification,b.ViTImageProcessor,b.ViTModel,b.ViTPreTrainedModel,b.VisionEncoderDecoderModel,b.VitMatteForImageMatting,b.VitMatteImageProcessor,b.VitMattePreTrainedModel,b.VitsModel,b.VitsModelOutput,b.VitsPreTrainedModel,b.VitsTokenizer,b.Wav2Vec2BertForCTC,b.Wav2Vec2BertForSequenceClassification,b.Wav2Vec2BertModel,b.Wav2Vec2BertPreTrainedModel,b.Wav2Vec2CTCTokenizer,b.Wav2Vec2FeatureExtractor,b.Wav2Vec2ForAudioFrameClassification,b.Wav2Vec2ForCTC,b.Wav2Vec2ForSequenceClassification,b.Wav2Vec2Model,b.Wav2Vec2PreTrainedModel,b.Wav2Vec2ProcessorWithLM,b.WavLMForAudioFrameClassification,b.WavLMForCTC,b.WavLMForSequenceClassification,b.WavLMForXVector,b.WavLMModel,b.WavLMPreTrainedModel,b.WeSpeakerFeatureExtractor,b.WeSpeakerResNetModel,b.WeSpeakerResNetPreTrainedModel,b.WhisperFeatureExtractor,b.WhisperForConditionalGeneration,b.WhisperModel,b.WhisperPreTrainedModel,b.WhisperProcessor,b.WhisperTextStreamer,b.WhisperTokenizer,b.XLMForQuestionAnswering,b.XLMForSequenceClassification,b.XLMForTokenClassification,b.XLMModel,b.XLMPreTrainedModel,b.XLMRobertaForMaskedLM,b.XLMRobertaForQuestionAnswering,b.XLMRobertaForSequenceClassification,b.XLMRobertaForTokenClassification,b.XLMRobertaModel,b.XLMRobertaPreTrainedModel,b.XLMRobertaTokenizer,b.XLMTokenizer,b.XLMWithLMHeadModel,b.XVectorOutput,b.YolosFeatureExtractor,b.YolosForObjectDetection,b.YolosModel,b.YolosObjectDetectionOutput,b.YolosPreTrainedModel,b.ZeroShotAudioClassificationPipeline,b.ZeroShotClassificationPipeline,b.ZeroShotImageClassificationPipeline,b.ZeroShotObjectDetectionPipeline,b.bankers_round,b.cat,b.cos_sim,b.dot,b.dynamic_time_warping;var Ig=b.env;b.full,b.full_like,b.getKeyValueShapes,b.hamming,b.hanning,b.interpolate,b.interpolate_4d,b.interpolate_data,b.is_chinese_char,b.layer_norm,b.log_softmax,b.magnitude,b.matmul,b.max,b.mean,b.mean_pooling,b.medianFilter,b.mel_filter_bank,b.min,b.ones,b.ones_like,b.permute,b.permute_data,b.pipeline,b.quantize_embeddings,b.read_audio,b.rfft,b.round,b.softmax,b.spectrogram,b.stack,b.std_mean,b.topk,b.window_function,b.zeros,b.zeros_like,Ig.backends.onnx.wasm.wasmPaths="/";async function Fg(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}class vc{static async getInstance(Te=null){return this.fp16??(this.fp16=await Fg()),this.model_id??(this.model_id=this.fp16?"HuggingFaceTB/smollm-360M-instruct-add-basics-onnx-fp16":"HuggingFaceTB/SmolLM-360M-Instruct"),this.tokenizer??(this.tokenizer=Eg.from_pretrained(this.model_id,{progress_callback:Te})),this.model??(this.model=Sg.from_pretrained(this.model_id,{dtype:this.fp16?"fp16":"q4",device:"webgpu",progress_callback:Te})),Promise.all([this.tokenizer,this.model])}}const Nu=new Pg;async function zg(Ft){const[Te,m]=await vc.getInstance(),P=Te.apply_chat_template(Ft,{add_generation_prompt:!0,return_dict:!0});let re,ke=0,ze;const Oe=le=>{re??(re=performance.now()),ke++>0&&(ze=ke/(performance.now()-re)*1e3)},V=le=>{self.postMessage({status:"update",output:le,tps:ze,numTokens:ke})},A=new Ag(Te,{skip_prompt:!0,skip_special_tokens:!0,callback_function:V,token_callback_function:Oe});self.postMessage({status:"start"});const H=await m.generate({...P,max_new_tokens:1024,streamer:A,stopping_criteria:Nu}),B=Te.batch_decode(H,{skip_special_tokens:!0});self.postMessage({status:"complete",output:B})}async function Og(){self.postMessage({status:"loading",data:"Loading model..."});const[Ft,Te]=await vc.getInstance(P=>{self.postMessage(P)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const m=Ft("a");await Te.generate({...m,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async Ft=>{const{type:Te,data:m}=Ft.data;switch(Te){case"load":Og();break;case"generate":Nu.reset(),zg(m);break;case"interrupt":Nu.interrupt();break;case"reset":Nu.reset();break}})})();