diff --git "a/assets/worker-BSStYFQ8.js" "b/assets/worker-BSStYFQ8.js" new file mode 100644--- /dev/null +++ "b/assets/worker-BSStYFQ8.js" @@ -0,0 +1,2770 @@ +var zf=Object.defineProperty;var Bf=(Te,A,s)=>A in Te?zf(Te,A,{enumerable:!0,configurable:!0,writable:!0,value:s}):Te[A]=s;var ge=(Te,A,s)=>Bf(Te,typeof A!="symbol"?A+"":A,s);var Pn={},d_={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Te,A,s)=>{Te.exports=s.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Te,A,s)=>{s.r(A),s.d(A,{Environment:()=>Ze,Interpreter:()=>at,Template:()=>gt,parse:()=>re,tokenize:()=>M});var f=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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"}),O=Object.freeze({set:f.Set,for:f.For,in:f.In,is:f.Is,if:f.If,else:f.Else,endif:f.EndIf,elif:f.ElseIf,endfor:f.EndFor,and:f.And,or:f.Or,not:f.Not,"not in":f.NotIn,macro:f.Macro,endmacro:f.EndMacro,true:f.BooleanLiteral,false:f.BooleanLiteral,none:f.NullLiteral,True:f.BooleanLiteral,False:f.BooleanLiteral,None:f.NullLiteral}),N=class{constructor(F,ne){this.value=F,this.type=ne}};function Q(F){return/\w/.test(F)}function U(F){return/[0-9]/.test(F)}var w=[["{%",f.OpenStatement],["%}",f.CloseStatement],["{{",f.OpenExpression],["}}",f.CloseExpression],["(",f.OpenParen],[")",f.CloseParen],["{",f.OpenCurlyBracket],["}",f.CloseCurlyBracket],["[",f.OpenSquareBracket],["]",f.CloseSquareBracket],[",",f.Comma],[".",f.Dot],[":",f.Colon],["|",f.Pipe],["<=",f.ComparisonBinaryOperator],[">=",f.ComparisonBinaryOperator],["==",f.ComparisonBinaryOperator],["!=",f.ComparisonBinaryOperator],["<",f.ComparisonBinaryOperator],[">",f.ComparisonBinaryOperator],["+",f.AdditiveBinaryOperator],["-",f.AdditiveBinaryOperator],["*",f.MultiplicativeBinaryOperator],["/",f.MultiplicativeBinaryOperator],["%",f.MultiplicativeBinaryOperator],["=",f.Equals]],v=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y(F,ne={}){return F.endsWith(` +`)&&(F=F.slice(0,-1)),F=F.replace(/{#.*?#}/gs,"{##}"),ne.lstrip_blocks&&(F=F.replace(/^[ \t]*({[#%])/gm,"$1")),ne.trim_blocks&&(F=F.replace(/([#%]})\n/g,"$1")),F.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(F,ne={}){var st,pt,It;const K=[],pe=y(F,ne);let Fe=0;const Qe=St=>{let Ft="";for(;St(pe[Fe]);){if(pe[Fe]==="\\"){if(++Fe,Fe>=pe.length)throw new SyntaxError("Unexpected end of input");const At=pe[Fe++],nr=v.get(At);if(nr===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);Ft+=nr;continue}if(Ft+=pe[Fe++],Fe>=pe.length)throw new SyntaxError("Unexpected end of input")}return Ft};e:for(;Fe0){K.push(new N(At,f.Text));continue}}Qe(At=>/\s/.test(At));const Ft=pe[Fe];if(Ft==="-"||Ft==="+"){const At=(pt=K.at(-1))==null?void 0:pt.type;if(At===f.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${Ft}`);switch(At){case f.Identifier:case f.NumericLiteral:case f.BooleanLiteral:case f.NullLiteral:case f.StringLiteral:case f.CloseParen:case f.CloseSquareBracket:break;default:{++Fe;const nr=Qe(U);K.push(new N(`${Ft}${nr}`,nr.length>0?f.NumericLiteral:f.UnaryOperator));continue}}}for(const[At,nr]of w)if(pe.slice(Fe,Fe+At.length)===At){K.push(new N(At,nr)),Fe+=At.length;continue e}if(Ft==="'"||Ft==='"'){++Fe;const At=Qe(nr=>nr!==Ft);K.push(new N(At,f.StringLiteral)),++Fe;continue}if(U(Ft)){const At=Qe(U);K.push(new N(At,f.NumericLiteral));continue}if(Q(Ft)){const At=Qe(Q),nr=Object.hasOwn(O,At)?O[At]:f.Identifier;nr===f.In&&((It=K.at(-1))==null?void 0:It.type)===f.Not?(K.pop(),K.push(new N("not in",f.NotIn))):K.push(new N(At,nr));continue}throw new SyntaxError(`Unexpected character: ${Ft}`)}return K}var b=class{constructor(){ge(this,"type","Statement")}},L=class extends b{constructor(ne){super();ge(this,"type","Program");this.body=ne}},q=class extends b{constructor(ne,K,pe){super();ge(this,"type","If");this.test=ne,this.body=K,this.alternate=pe}},se=class extends b{constructor(ne,K,pe,Fe){super();ge(this,"type","For");this.loopvar=ne,this.iterable=K,this.body=pe,this.defaultBlock=Fe}},ie=class extends b{constructor(ne,K){super();ge(this,"type","Set");this.assignee=ne,this.value=K}},z=class extends b{constructor(ne,K,pe){super();ge(this,"type","Macro");this.name=ne,this.args=K,this.body=pe}},W=class extends b{constructor(){super(...arguments);ge(this,"type","Expression")}},Y=class extends W{constructor(ne,K,pe){super();ge(this,"type","MemberExpression");this.object=ne,this.property=K,this.computed=pe}},D=class extends W{constructor(ne,K){super();ge(this,"type","CallExpression");this.callee=ne,this.args=K}},$=class extends W{constructor(ne){super();ge(this,"type","Identifier");this.value=ne}},g=class extends W{constructor(ne){super();ge(this,"type","Literal");this.value=ne}},C=class extends g{constructor(){super(...arguments);ge(this,"type","NumericLiteral")}},T=class extends g{constructor(){super(...arguments);ge(this,"type","StringLiteral")}},ee=class extends g{constructor(){super(...arguments);ge(this,"type","BooleanLiteral")}},J=class extends g{constructor(){super(...arguments);ge(this,"type","NullLiteral")}},le=class extends g{constructor(){super(...arguments);ge(this,"type","ArrayLiteral")}},de=class extends g{constructor(){super(...arguments);ge(this,"type","TupleLiteral")}},fe=class extends g{constructor(){super(...arguments);ge(this,"type","ObjectLiteral")}},ke=class extends W{constructor(ne,K,pe){super();ge(this,"type","BinaryExpression");this.operator=ne,this.left=K,this.right=pe}},xe=class extends W{constructor(ne,K){super();ge(this,"type","FilterExpression");this.operand=ne,this.filter=K}},Le=class extends W{constructor(ne,K){super();ge(this,"type","SelectExpression");this.iterable=ne,this.test=K}},qe=class extends W{constructor(ne,K,pe){super();ge(this,"type","TestExpression");this.operand=ne,this.negate=K,this.test=pe}},Ue=class extends W{constructor(ne,K){super();ge(this,"type","UnaryExpression");this.operator=ne,this.argument=K}},ut=class extends W{constructor(ne=void 0,K=void 0,pe=void 0){super();ge(this,"type","SliceExpression");this.start=ne,this.stop=K,this.step=pe}},ue=class extends W{constructor(ne,K){super();ge(this,"type","KeywordArgumentExpression");this.key=ne,this.value=K}};function re(F){const ne=new L([]);let K=0;function pe(nt,_t){const Ot=F[K++];if(!Ot||Ot.type!==nt)throw new Error(`Parser Error: ${_t}. ${Ot.type} !== ${nt}.`);return Ot}function Fe(){switch(F[K].type){case f.Text:return pt();case f.OpenStatement:return It();case f.OpenExpression:return St();default:throw new SyntaxError(`Unexpected token type: ${F[K].type}`)}}function Qe(...nt){return K+nt.length<=F.length&&nt.some((_t,Ot)=>_t!==F[K+Ot].type)}function st(...nt){return K+nt.length<=F.length&&nt.every((_t,Ot)=>_t===F[K+Ot].type)}function pt(){return new T(pe(f.Text,"Expected text token").value)}function It(){pe(f.OpenStatement,"Expected opening statement token");let nt;switch(F[K].type){case f.Set:++K,nt=Ft(),pe(f.CloseStatement,"Expected closing statement token");break;case f.If:++K,nt=At(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndIf,"Expected endif token"),pe(f.CloseStatement,"Expected %} token");break;case f.Macro:++K,nt=nr(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndMacro,"Expected endmacro token"),pe(f.CloseStatement,"Expected %} token");break;case f.For:++K,nt=kr(),pe(f.OpenStatement,"Expected {% token"),pe(f.EndFor,"Expected endfor token"),pe(f.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${F[K].type}`)}return nt}function St(){pe(f.OpenExpression,"Expected opening expression token");const nt=Ar();return pe(f.CloseExpression,"Expected closing expression token"),nt}function Ft(){const nt=Ar();if(st(f.Equals)){++K;const _t=Ft();return new ie(nt,_t)}return nt}function At(){var lr,bs,tr,ts,Rs,Js,Ns,vs;const nt=Ar();pe(f.CloseStatement,"Expected closing statement token");const _t=[],Ot=[];for(;!(((lr=F[K])==null?void 0:lr.type)===f.OpenStatement&&(((bs=F[K+1])==null?void 0:bs.type)===f.ElseIf||((tr=F[K+1])==null?void 0:tr.type)===f.Else||((ts=F[K+1])==null?void 0:ts.type)===f.EndIf));)_t.push(Fe());if(((Rs=F[K])==null?void 0:Rs.type)===f.OpenStatement&&((Js=F[K+1])==null?void 0:Js.type)!==f.EndIf)if(++K,st(f.ElseIf))pe(f.ElseIf,"Expected elseif token"),Ot.push(At());else for(pe(f.Else,"Expected else token"),pe(f.CloseStatement,"Expected closing statement token");!(((Ns=F[K])==null?void 0:Ns.type)===f.OpenStatement&&((vs=F[K+1])==null?void 0:vs.type)===f.EndIf);)Ot.push(Fe());return new q(nt,_t,Ot)}function nr(){const nt=as();if(nt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const _t=Bs();pe(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndMacro);)Ot.push(Fe());return new z(nt,_t,Ot)}function gr(nt=!1){const _t=nt?as:Ar,Ot=[_t()],lr=st(f.Comma);for(;lr&&(++K,Ot.push(_t()),!!st(f.Comma)););return lr?new de(Ot):Ot[0]}function kr(){const nt=gr(!0);if(!(nt instanceof $||nt instanceof de))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${nt.type} instead`);pe(f.In,"Expected `in` keyword following loop variable");const _t=Ar();pe(f.CloseStatement,"Expected closing statement token");const Ot=[];for(;Qe(f.OpenStatement,f.EndFor)&&Qe(f.OpenStatement,f.Else);)Ot.push(Fe());const lr=[];if(st(f.OpenStatement,f.Else))for(++K,++K,pe(f.CloseStatement,"Expected closing statement token");Qe(f.OpenStatement,f.EndFor);)lr.push(Fe());return new se(nt,_t,Ot,lr)}function Ar(){return Qr()}function Qr(){const nt=os();if(st(f.If)){++K;const _t=os();if(st(f.Else)){++K;const Ot=os();return new q(_t,[nt],[Ot])}else return new Le(nt,_t)}return nt}function os(){let nt=Xs();for(;st(f.Or);){const _t=F[K];++K;const Ot=Xs();nt=new ke(_t,nt,Ot)}return nt}function Xs(){let nt=zs();for(;st(f.And);){const _t=F[K];++K;const Ot=zs();nt=new ke(_t,nt,Ot)}return nt}function zs(){let nt;for(;st(f.Not);){const _t=F[K];++K;const Ot=zs();nt=new Ue(_t,Ot)}return nt??Ms()}function Ms(){let nt=Nt();for(;st(f.ComparisonBinaryOperator)||st(f.In)||st(f.NotIn);){const _t=F[K];++K;const Ot=Nt();nt=new ke(_t,nt,Ot)}return nt}function Nt(){let nt=cs();for(;st(f.AdditiveBinaryOperator);){const _t=F[K];++K;const Ot=cs();nt=new ke(_t,nt,Ot)}return nt}function Qs(){const nt=$s();return st(f.OpenParen)?ks(nt):nt}function ks(nt){let _t=new D(nt,Bs());return st(f.OpenParen)&&(_t=ks(_t)),_t}function Bs(){pe(f.OpenParen,"Expected opening parenthesis for arguments list");const nt=Ss();return pe(f.CloseParen,"Expected closing parenthesis for arguments list"),nt}function Ss(){const nt=[];for(;!st(f.CloseParen);){let _t=Ar();if(st(f.Equals)){if(++K,!(_t instanceof $))throw new SyntaxError("Expected identifier for keyword argument");const Ot=Ar();_t=new ue(_t,Ot)}nt.push(_t),st(f.Comma)&&++K}return nt}function is(){const nt=[];let _t=!1;for(;!st(f.CloseSquareBracket);)st(f.Colon)?(nt.push(void 0),++K,_t=!0):(nt.push(Ar()),st(f.Colon)&&(++K,_t=!0));if(nt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(_t){if(nt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ut(...nt)}return nt[0]}function $s(){let nt=as();for(;st(f.Dot)||st(f.OpenSquareBracket);){const _t=F[K];++K;let Ot;const lr=_t.type!==f.Dot;if(lr)Ot=is(),pe(f.CloseSquareBracket,"Expected closing square bracket");else if(Ot=as(),Ot.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");nt=new Y(nt,Ot,lr)}return nt}function cs(){let nt=As();for(;st(f.MultiplicativeBinaryOperator);){const _t=F[K];++K;const Ot=As();nt=new ke(_t,nt,Ot)}return nt}function As(){let nt=Ys();for(;st(f.Is);){++K;const _t=st(f.Not);_t&&++K;let Ot=as();if(Ot instanceof ee?Ot=new $(Ot.value.toString()):Ot instanceof J&&(Ot=new $("none")),!(Ot instanceof $))throw new SyntaxError("Expected identifier for the test");nt=new qe(nt,_t,Ot)}return nt}function Ys(){let nt=Qs();for(;st(f.Pipe);){++K;let _t=as();if(!(_t instanceof $))throw new SyntaxError("Expected identifier for the filter");st(f.OpenParen)&&(_t=ks(_t)),nt=new xe(nt,_t)}return nt}function as(){const nt=F[K];switch(nt.type){case f.NumericLiteral:return++K,new C(Number(nt.value));case f.StringLiteral:return++K,new T(nt.value);case f.BooleanLiteral:return++K,new ee(nt.value.toLowerCase()==="true");case f.NullLiteral:return++K,new J(null);case f.Identifier:return++K,new $(nt.value);case f.OpenParen:{++K;const _t=gr();if(F[K].type!==f.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${F[K].type} instead`);return++K,_t}case f.OpenSquareBracket:{++K;const _t=[];for(;!st(f.CloseSquareBracket);)_t.push(Ar()),st(f.Comma)&&++K;return++K,new le(_t)}case f.OpenCurlyBracket:{++K;const _t=new Map;for(;!st(f.CloseCurlyBracket);){const Ot=Ar();pe(f.Colon,"Expected colon between key and value in object literal");const lr=Ar();_t.set(Ot,lr),st(f.Comma)&&++K}return++K,new fe(_t)}default:throw new SyntaxError(`Unexpected token: ${nt.type}`)}}for(;K=0?(ne=(ne??(ne=0))<0?Math.max(F.length+ne,0):Math.min(ne,F.length),K=(K??(K=F.length))<0?Math.max(F.length+K,0):Math.min(K,F.length)):(ne=(ne??(ne=F.length-1))<0?Math.max(F.length+ne,-1):Math.min(ne,F.length-1),K=(K??(K=-1))<-1?Math.max(F.length+K,-1):Math.min(K,F.length-1));const Qe=[];for(let st=ne;Fe*stne.toUpperCase())}var et=class{constructor(F=void 0){ge(this,"type","RuntimeValue");ge(this,"value");ge(this,"builtins",new Map);this.value=F}__bool__(){return new Je(!!this.value)}},Xe=class extends et{constructor(){super(...arguments);ge(this,"type","NumericValue")}},oe=class extends et{constructor(){super(...arguments);ge(this,"type","StringValue");ge(this,"builtins",new Map([["upper",new je(()=>new oe(this.value.toUpperCase()))],["lower",new je(()=>new oe(this.value.toLowerCase()))],["strip",new je(()=>new oe(this.value.trim()))],["title",new je(()=>new oe(Be(this.value)))],["length",new Xe(this.value.length)],["rstrip",new je(()=>new oe(this.value.trimEnd()))],["lstrip",new je(()=>new oe(this.value.trimStart()))]]))}},Je=class extends et{constructor(){super(...arguments);ge(this,"type","BooleanValue")}},De=class extends et{constructor(){super(...arguments);ge(this,"type","ObjectValue");ge(this,"builtins",new Map([["get",new je(([ne,K])=>{if(!(ne instanceof oe))throw new Error(`Object key must be a string: got ${ne.type}`);return this.value.get(ne.value)??K??new We})],["items",new je(()=>new ve(Array.from(this.value.entries()).map(([ne,K])=>new ve([new oe(ne),K]))))]]))}__bool__(){return new Je(this.value.size>0)}},ce=class extends De{constructor(){super(...arguments);ge(this,"type","KeywordArgumentsValue")}},ve=class extends et{constructor(){super(...arguments);ge(this,"type","ArrayValue");ge(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new Je(this.value.length>0)}},Re=class extends ve{constructor(){super(...arguments);ge(this,"type","TupleValue")}},je=class extends et{constructor(){super(...arguments);ge(this,"type","FunctionValue")}},We=class extends et{constructor(){super(...arguments);ge(this,"type","NullValue")}},Ne=class extends et{constructor(){super(...arguments);ge(this,"type","UndefinedValue")}},Ze=class{constructor(F){ge(this,"variables",new Map([["namespace",new je(F=>{if(F.length===0)return new De(new Map);if(F.length!==1||!(F[0]instanceof De))throw new Error("`namespace` expects either zero arguments or a single object argument");return F[0]})]]));ge(this,"tests",new Map([["boolean",F=>F.type==="BooleanValue"],["callable",F=>F instanceof je],["odd",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${F.type}`);return F.value%2!==0}],["even",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${F.type}`);return F.value%2===0}],["false",F=>F.type==="BooleanValue"&&!F.value],["true",F=>F.type==="BooleanValue"&&F.value],["none",F=>F.type==="NullValue"],["string",F=>F.type==="StringValue"],["number",F=>F.type==="NumericValue"],["integer",F=>F.type==="NumericValue"&&Number.isInteger(F.value)],["iterable",F=>F.type==="ArrayValue"||F.type==="StringValue"],["mapping",F=>F.type==="ObjectValue"],["lower",F=>{const ne=F.value;return F.type==="StringValue"&&ne===ne.toLowerCase()}],["upper",F=>{const ne=F.value;return F.type==="StringValue"&&ne===ne.toUpperCase()}],["none",F=>F.type==="NullValue"],["defined",F=>F.type!=="UndefinedValue"],["undefined",F=>F.type==="UndefinedValue"],["equalto",(F,ne)=>F.value===ne.value],["eq",(F,ne)=>F.value===ne.value]]));this.parent=F}set(F,ne){return this.declareVariable(F,ft(ne))}declareVariable(F,ne){if(this.variables.has(F))throw new SyntaxError(`Variable already declared: ${F}`);return this.variables.set(F,ne),ne}setVariable(F,ne){return this.variables.set(F,ne),ne}resolve(F){if(this.variables.has(F))return this;if(this.parent)return this.parent.resolve(F);throw new Error(`Unknown variable: ${F}`)}lookupVariable(F){try{return this.resolve(F).variables.get(F)??new Ne}catch{return new Ne}}},at=class{constructor(F){ge(this,"global");this.global=F??new Ze}run(F){return this.evaluate(F,this.global)}evaluateBinaryExpression(F,ne){const K=this.evaluate(F.left,ne);switch(F.operator.value){case"and":return K.__bool__().value?this.evaluate(F.right,ne):K;case"or":return K.__bool__().value?K:this.evaluate(F.right,ne)}const pe=this.evaluate(F.right,ne);switch(F.operator.value){case"==":return new Je(K.value==pe.value);case"!=":return new Je(K.value!=pe.value)}if(K instanceof Ne||pe instanceof Ne)throw new Error("Cannot perform operation on undefined values");if(K instanceof We||pe instanceof We)throw new Error("Cannot perform operation on null values");if(K instanceof Xe&&pe instanceof Xe)switch(F.operator.value){case"+":return new Xe(K.value+pe.value);case"-":return new Xe(K.value-pe.value);case"*":return new Xe(K.value*pe.value);case"/":return new Xe(K.value/pe.value);case"%":return new Xe(K.value%pe.value);case"<":return new Je(K.value":return new Je(K.value>pe.value);case">=":return new Je(K.value>=pe.value);case"<=":return new Je(K.value<=pe.value)}else if(K instanceof ve&&pe instanceof ve)switch(F.operator.value){case"+":return new ve(K.value.concat(pe.value))}else if(pe instanceof ve){const Fe=pe.value.find(Qe=>Qe.value===K.value)!==void 0;switch(F.operator.value){case"in":return new Je(Fe);case"not in":return new Je(!Fe)}}if(K instanceof oe||pe instanceof oe)switch(F.operator.value){case"+":return new oe(K.value.toString()+pe.value.toString())}if(K instanceof oe&&pe instanceof oe)switch(F.operator.value){case"in":return new Je(pe.value.includes(K.value));case"not in":return new Je(!pe.value.includes(K.value))}if(K instanceof oe&&pe instanceof De)switch(F.operator.value){case"in":return new Je(pe.value.has(K.value));case"not in":return new Je(!pe.value.has(K.value))}throw new SyntaxError(`Unknown operator "${F.operator.value}" between ${K.type} and ${pe.type}`)}evaluateArguments(F,ne){const K=[],pe=new Map;for(const Fe of F)if(Fe.type==="KeywordArgumentExpression"){const Qe=Fe;pe.set(Qe.key.value,this.evaluate(Qe.value,ne))}else{if(pe.size>0)throw new Error("Positional arguments must come before keyword arguments");K.push(this.evaluate(Fe,ne))}return[K,pe]}evaluateFilterExpression(F,ne){const K=this.evaluate(F.operand,ne);if(F.filter.type==="Identifier"){const pe=F.filter;if(pe.value==="tojson")return new oe(dt(K));if(K instanceof ve)switch(pe.value){case"list":return K;case"first":return K.value[0];case"last":return K.value[K.value.length-1];case"length":return new Xe(K.value.length);case"reverse":return new ve(K.value.reverse());case"sort":return new ve(K.value.sort((Fe,Qe)=>{if(Fe.type!==Qe.type)throw new Error(`Cannot compare different types: ${Fe.type} and ${Qe.type}`);switch(Fe.type){case"NumericValue":return Fe.value-Qe.value;case"StringValue":return Fe.value.localeCompare(Qe.value);default:throw new Error(`Cannot compare type: ${Fe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${pe.value}`)}else if(K instanceof oe)switch(pe.value){case"length":return new Xe(K.value.length);case"upper":return new oe(K.value.toUpperCase());case"lower":return new oe(K.value.toLowerCase());case"title":return new oe(Be(K.value));case"capitalize":return new oe(K.value.charAt(0).toUpperCase()+K.value.slice(1));case"trim":return new oe(K.value.trim());case"indent":return new oe(K.value.split(` +`).map((Fe,Qe)=>Qe===0||Fe.length===0?Fe:" "+Fe).join(` +`));case"string":return K;default:throw new Error(`Unknown StringValue filter: ${pe.value}`)}else if(K instanceof Xe)switch(pe.value){case"abs":return new Xe(Math.abs(K.value));default:throw new Error(`Unknown NumericValue filter: ${pe.value}`)}else if(K instanceof De)switch(pe.value){case"items":return new ve(Array.from(K.value.entries()).map(([Fe,Qe])=>new ve([new oe(Fe),Qe])));case"length":return new Xe(K.value.size);default:throw new Error(`Unknown ObjectValue filter: ${pe.value}`)}throw new Error(`Cannot apply filter "${pe.value}" to type: ${K.type}`)}else if(F.filter.type==="CallExpression"){const pe=F.filter;if(pe.callee.type!=="Identifier")throw new Error(`Unknown filter: ${pe.callee.type}`);const Fe=pe.callee.value;if(Fe==="tojson"){const[,Qe]=this.evaluateArguments(pe.args,ne),st=Qe.get("indent")??new We;if(!(st instanceof Xe||st instanceof We))throw new Error("If set, indent must be a number");return new oe(dt(K,st.value))}if(K instanceof ve){switch(Fe){case"selectattr":case"rejectattr":{const Qe=Fe==="selectattr";if(K.value.some(At=>!(At instanceof De)))throw new Error(`\`${Fe}\` can only be applied to array of objects`);if(pe.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${Fe}\` must be strings`);const[st,pt,It]=pe.args.map(At=>this.evaluate(At,ne));let St;if(pt){const At=ne.tests.get(pt.value);if(!At)throw new Error(`Unknown test: ${pt.value}`);St=At}else St=(...At)=>At[0].__bool__().value;const Ft=K.value.filter(At=>{const nr=At.value.get(st.value),gr=nr?St(nr,It):!1;return Qe?gr:!gr});return new ve(Ft)}case"map":{const[,Qe]=this.evaluateArguments(pe.args,ne);if(Qe.has("attribute")){const st=Qe.get("attribute");if(!(st instanceof oe))throw new Error("attribute must be a string");const pt=Qe.get("default"),It=K.value.map(St=>{if(!(St instanceof De))throw new Error("items in map must be an object");return St.value.get(st.value)??pt??new Ne});return new ve(It)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Fe}`)}else if(K instanceof oe){switch(Fe){case"indent":{const[Qe,st]=this.evaluateArguments(pe.args,ne),pt=Qe.at(0)??st.get("width")??new Xe(4);if(!(pt instanceof Xe))throw new Error("width must be a number");const It=Qe.at(1)??st.get("first")??new Je(!1),St=Qe.at(2)??st.get("blank")??new Je(!1),Ft=K.value.split(` +`),At=" ".repeat(pt.value),nr=Ft.map((gr,kr)=>!It.value&&kr===0||!St.value&&gr.length===0?gr:At+gr);return new oe(nr.join(` +`))}}throw new Error(`Unknown StringValue filter: ${Fe}`)}else throw new Error(`Cannot apply filter "${Fe}" to type: ${K.type}`)}throw new Error(`Unknown filter: ${F.filter.type}`)}evaluateTestExpression(F,ne){const K=this.evaluate(F.operand,ne),pe=ne.tests.get(F.test.value);if(!pe)throw new Error(`Unknown test: ${F.test.value}`);const Fe=pe(K);return new Je(F.negate?!Fe:Fe)}evaluateUnaryExpression(F,ne){const K=this.evaluate(F.argument,ne);switch(F.operator.value){case"not":return new Je(!K.value);default:throw new SyntaxError(`Unknown operator: ${F.operator.value}`)}}evalProgram(F,ne){return this.evaluateBlock(F.body,ne)}evaluateBlock(F,ne){let K="";for(const pe of F){const Fe=this.evaluate(pe,ne);Fe.type!=="NullValue"&&Fe.type!=="UndefinedValue"&&(K+=Fe.value)}return new oe(K)}evaluateIdentifier(F,ne){return ne.lookupVariable(F.value)}evaluateCallExpression(F,ne){const[K,pe]=this.evaluateArguments(F.args,ne);pe.size>0&&K.push(new ce(pe));const Fe=this.evaluate(F.callee,ne);if(Fe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Fe.type}`);return Fe.value(K,ne)}evaluateSliceExpression(F,ne,K){if(!(F instanceof ve||F instanceof oe))throw new Error("Slice object must be an array or string");const pe=this.evaluate(ne.start,K),Fe=this.evaluate(ne.stop,K),Qe=this.evaluate(ne.step,K);if(!(pe instanceof Xe||pe instanceof Ne))throw new Error("Slice start must be numeric or undefined");if(!(Fe instanceof Xe||Fe instanceof Ne))throw new Error("Slice stop must be numeric or undefined");if(!(Qe instanceof Xe||Qe instanceof Ne))throw new Error("Slice step must be numeric or undefined");return F instanceof ve?new ve(Pe(F.value,pe.value,Fe.value,Qe.value)):new oe(Pe(Array.from(F.value),pe.value,Fe.value,Qe.value).join(""))}evaluateMemberExpression(F,ne){const K=this.evaluate(F.object,ne);let pe;if(F.computed){if(F.property.type==="SliceExpression")return this.evaluateSliceExpression(K,F.property,ne);pe=this.evaluate(F.property,ne)}else pe=new oe(F.property.value);let Fe;if(K instanceof De){if(!(pe instanceof oe))throw new Error(`Cannot access property with non-string: got ${pe.type}`);Fe=K.value.get(pe.value)??K.builtins.get(pe.value)}else if(K instanceof ve||K instanceof oe)if(pe instanceof Xe)Fe=K.value.at(pe.value),K instanceof oe&&(Fe=new oe(K.value.at(pe.value)));else if(pe instanceof oe)Fe=K.builtins.get(pe.value);else throw new Error(`Cannot access property with non-string/non-number: got ${pe.type}`);else{if(!(pe instanceof oe))throw new Error(`Cannot access property with non-string: got ${pe.type}`);Fe=K.builtins.get(pe.value)}return Fe instanceof et?Fe:new Ne}evaluateSet(F,ne){const K=this.evaluate(F.value,ne);if(F.assignee.type==="Identifier"){const pe=F.assignee.value;ne.setVariable(pe,K)}else if(F.assignee.type==="MemberExpression"){const pe=F.assignee,Fe=this.evaluate(pe.object,ne);if(!(Fe instanceof De))throw new Error("Cannot assign to member of non-object");if(pe.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Fe.value.set(pe.property.value,K)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(F.assignee)}`);return new We}evaluateIf(F,ne){const K=this.evaluate(F.test,ne);return this.evaluateBlock(K.__bool__().value?F.body:F.alternate,ne)}evaluateFor(F,ne){const K=new Ze(ne);let pe,Fe;if(F.iterable.type==="SelectExpression"){const St=F.iterable;Fe=this.evaluate(St.iterable,K),pe=St.test}else Fe=this.evaluate(F.iterable,K);if(!(Fe instanceof ve))throw new Error(`Expected iterable type in for loop: got ${Fe.type}`);const Qe=[],st=[];for(let St=0;Stgr.setVariable(F.loopvar.value,At);else if(F.loopvar.type==="TupleLiteral"){const gr=F.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const kr=At;if(gr.value.length!==kr.value.length)throw new Error(`Too ${gr.value.length>kr.value.length?"few":"many"} items to unpack`);nr=Ar=>{for(let Qr=0;Qr0?Qe[St-1]:new Ne],["nextitem",St{var st;const Fe=new Ze(pe);K=K.slice();let Qe;((st=K.at(-1))==null?void 0:st.type)==="KeywordArgumentsValue"&&(Qe=K.pop());for(let pt=0;ptthis.evaluate(K,ne)));case"TupleLiteral":return new Re(F.value.map(K=>this.evaluate(K,ne)));case"ObjectLiteral":{const K=new Map;for(const[pe,Fe]of F.value){const Qe=this.evaluate(pe,ne);if(!(Qe instanceof oe))throw new Error(`Object keys must be strings: got ${Qe.type}`);K.set(Qe.value,this.evaluate(Fe,ne))}return new De(K)}case"Identifier":return this.evaluateIdentifier(F,ne);case"CallExpression":return this.evaluateCallExpression(F,ne);case"MemberExpression":return this.evaluateMemberExpression(F,ne);case"UnaryExpression":return this.evaluateUnaryExpression(F,ne);case"BinaryExpression":return this.evaluateBinaryExpression(F,ne);case"FilterExpression":return this.evaluateFilterExpression(F,ne);case"TestExpression":return this.evaluateTestExpression(F,ne);default:throw new SyntaxError(`Unknown node type: ${F.type}`)}}};function ft(F){switch(typeof F){case"number":return new Xe(F);case"string":return new oe(F);case"boolean":return new Je(F);case"undefined":return new Ne;case"object":return F===null?new We:Array.isArray(F)?new ve(F.map(ft)):new De(new Map(Object.entries(F).map(([ne,K])=>[ne,ft(K)])));case"function":return new je((ne,K)=>{const pe=F(...ne.map(Fe=>Fe.value))??null;return ft(pe)});default:throw new Error(`Cannot convert to runtime value: ${F}`)}}function dt(F,ne,K){const pe=K??0;switch(F.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(F.value);case"ArrayValue":case"ObjectValue":{const Fe=ne?" ".repeat(ne):"",Qe=` +`+Fe.repeat(pe),st=Qe+Fe;if(F.type==="ArrayValue"){const pt=F.value.map(It=>dt(It,ne,pe+1));return ne?`[${st}${pt.join(`,${st}`)}${Qe}]`:`[${pt.join(", ")}]`}else{const pt=Array.from(F.value.entries()).map(([It,St])=>{const Ft=`"${It}": ${dt(St,ne,pe+1)}`;return ne?`${st}${Ft}`:Ft});return ne?`{${pt.join(",")}${Qe}}`:`{${pt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${F.type}`)}}var gt=class{constructor(F){ge(this,"parsed");const ne=M(F,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=re(ne)}render(F){const ne=new Ze;ne.set("false",!1),ne.set("true",!0),ne.set("raise_exception",Fe=>{throw new Error(Fe)}),ne.set("range",he);for(const[Fe,Qe]of Object.entries(F))ne.set(Fe,Qe);return new at(ne).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{registerBackend:()=>N,resolveBackendAndExecutionProviders:()=>U});const f=new Map,O=[],N=(w,v,y)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const M=f.get(w);if(M===void 0)f.set(w,{backend:v,priority:y});else{if(M.priority>y)return;if(M.priority===y&&M.backend!==v)throw new Error(`cannot register backend "${w}" using priority ${y}`)}if(y>=0){const b=O.indexOf(w);b!==-1&&O.splice(b,1);for(let L=0;L{const v=f.get(w);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const y=!!v.initPromise;try{return y||(v.initPromise=v.backend.init(w)),await v.initPromise,v.initialized=!0,v.backend}catch(M){return y||(v.error=`${M}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},U=async w=>{const v=w.executionProviders||[],y=v.map(ie=>typeof ie=="string"?ie:ie.name),M=y.length===0?O:y;let b;const L=[],q=new Set;for(const ie of M){const z=await Q(ie);typeof z=="string"?L.push({name:ie,err:z}):(b||(b=z),b===z&&q.add(ie))}if(!b)throw new Error(`no available backend found. ERR: ${L.map(ie=>`[${ie.name}] ${ie.err}`).join(", ")}`);for(const{name:ie,err:z}of L)y.includes(ie)&&console.warn(`removing requested execution provider "${ie}" from session options because it is not available: ${z}`);const se=v.filter(ie=>q.has(typeof ie=="string"?ie:ie.name));return[b,new Proxy(w,{get:(ie,z)=>z==="executionProviders"?se:Reflect.get(ie,z)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Te,A,s)=>{s.r(A),s.d(A,{registerBackend:()=>f.registerBackend});var f=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{env:()=>N});var f=s("./node_modules/onnxruntime-common/dist/esm/version.js");let O="warning";const N={wasm:{},webgl:{},webgpu:{},versions:{common:f.version},set logLevel(Q){if(Q!==void 0){if(typeof Q!="string"||["verbose","info","warning","error","fatal"].indexOf(Q)===-1)throw new Error(`Unsupported logging level: ${Q}`);O=Q}},get logLevel(){return O}};Object.defineProperty(N,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Te,A,s)=>{s.r(A),s.d(A,{env:()=>O});var f=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const O=f.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Te,A,s)=>{s.r(A),s.d(A,{InferenceSession:()=>N.InferenceSession,TRACE:()=>U.TRACE,TRACE_FUNC_BEGIN:()=>U.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>U.TRACE_FUNC_END,Tensor:()=>Q.Tensor,TrainingSession:()=>w.TrainingSession,env:()=>O.env,registerBackend:()=>f.registerBackend});var f=s("./node_modules/onnxruntime-common/dist/esm/backend.js"),O=s("./node_modules/onnxruntime-common/dist/esm/env.js"),N=s("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Q=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),s("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var U=s("./node_modules/onnxruntime-common/dist/esm/trace.js");s("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),s("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var w=s("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{InferenceSession:()=>Q});var f=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),O=s("./node_modules/onnxruntime-common/dist/esm/tensor.js"),N=s("./node_modules/onnxruntime-common/dist/esm/trace.js");class Q{constructor(w){this.handler=w}async run(w,v,y){(0,N.TRACE_FUNC_BEGIN)();const M={};let b={};if(typeof w!="object"||w===null||w instanceof O.Tensor||Array.isArray(w))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let L=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof O.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(v)){if(v.length===0)throw new TypeError("'fetches' cannot be an empty array.");L=!1;for(const ie of v){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);M[ie]=null}if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(v);for(const W of this.outputNames)if(z.indexOf(W)!==-1){const Y=v[W];(Y===null||Y instanceof O.Tensor)&&(ie=!0,L=!1,M[W]=Y)}if(ie){if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of this.inputNames)if(typeof w[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(L)for(const ie of this.outputNames)M[ie]=null;const q=await this.handler.run(w,M,b),se={};for(const ie in q)if(Object.hasOwnProperty.call(q,ie)){const z=q[ie];z instanceof O.Tensor?se[ie]=z:se[ie]=new O.Tensor(z.type,z.data,z.dims)}return(0,N.TRACE_FUNC_END)(),se}async release(){return this.handler.dispose()}static async create(w,v,y,M){(0,N.TRACE_FUNC_BEGIN)();let b,L={};if(typeof w=="string"){if(b=w,typeof v=="object"&&v!==null)L=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof Uint8Array){if(b=w,typeof v=="object"&&v!==null)L=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(w instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&w instanceof SharedArrayBuffer){const z=w;let W=0,Y=w.byteLength;if(typeof v=="object"&&v!==null)L=v;else if(typeof v=="number"){if(W=v,!Number.isSafeInteger(W))throw new RangeError("'byteOffset' must be an integer.");if(W<0||W>=z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${z.byteLength}).`);if(Y=w.byteLength-W,typeof y=="number"){if(Y=y,!Number.isSafeInteger(Y))throw new RangeError("'byteLength' must be an integer.");if(Y<=0||W+Y>z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${z.byteLength-W}].`);if(typeof M=="object"&&M!==null)L=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else if(typeof y<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");b=new Uint8Array(z,W,Y)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[q,se]=await(0,f.resolveBackendAndExecutionProviders)(L),ie=await q.createInferenceSessionHandler(b,se);return(0,N.TRACE_FUNC_END)(),new Q(ie)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(Te,A,s)=>{s.r(A),s.d(A,{InferenceSession:()=>O});var f=s("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const O=f.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Te,A,s)=>{s.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Te,A,s)=>{s.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{tensorToDataURL:()=>f,tensorToImageData:()=>O});const f=(N,Q)=>{const U=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);U.width=N.dims[3],U.height=N.dims[2];const w=U.getContext("2d");if(w!=null){let v,y;(Q==null?void 0:Q.tensorLayout)!==void 0&&Q.tensorLayout==="NHWC"?(v=N.dims[2],y=N.dims[3]):(v=N.dims[3],y=N.dims[2]);const M=(Q==null?void 0:Q.format)!==void 0?Q.format:"RGB",b=Q==null?void 0:Q.norm;let L,q;b===void 0||b.mean===void 0?L=[255,255,255,255]:typeof b.mean=="number"?L=[b.mean,b.mean,b.mean,b.mean]:(L=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(L[3]=b.mean[3])),b===void 0||b.bias===void 0?q=[0,0,0,0]:typeof b.bias=="number"?q=[b.bias,b.bias,b.bias,b.bias]:(q=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(q[3]=b.bias[3]));const se=y*v;let ie=0,z=se,W=se*2,Y=-1;M==="RGBA"?(ie=0,z=se,W=se*2,Y=se*3):M==="RGB"?(ie=0,z=se,W=se*2):M==="RBG"&&(ie=0,W=se,z=se*2);for(let D=0;D{const U=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let w;if(U!=null){let v,y,M;(Q==null?void 0:Q.tensorLayout)!==void 0&&Q.tensorLayout==="NHWC"?(v=N.dims[2],y=N.dims[1],M=N.dims[3]):(v=N.dims[3],y=N.dims[2],M=N.dims[1]);const b=Q!==void 0&&Q.format!==void 0?Q.format:"RGB",L=Q==null?void 0:Q.norm;let q,se;L===void 0||L.mean===void 0?q=[255,255,255,255]:typeof L.mean=="number"?q=[L.mean,L.mean,L.mean,L.mean]:(q=[L.mean[0],L.mean[1],L.mean[2],255],L.mean[3]!==void 0&&(q[3]=L.mean[3])),L===void 0||L.bias===void 0?se=[0,0,0,0]:typeof L.bias=="number"?se=[L.bias,L.bias,L.bias,L.bias]:(se=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(se[3]=L.bias[3]));const ie=y*v;if(Q!==void 0&&(Q.format!==void 0&&M===4&&Q.format!=="RGBA"||M===3&&Q.format!=="RGB"&&Q.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const z=4;let W=0,Y=1,D=2,$=3,g=0,C=ie,T=ie*2,ee=-1;b==="RGBA"?(g=0,C=ie,T=ie*2,ee=ie*3):b==="RGB"?(g=0,C=ie,T=ie*2):b==="RBG"&&(g=0,T=ie,C=ie*2),w=U.createImageData(v,y);for(let J=0;J{s.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{bufferToTensor:()=>O,tensorFromGpuBuffer:()=>U,tensorFromImage:()=>N,tensorFromMLTensor:()=>w,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>Q});var f=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=(y,M)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:b,width:L}=M,q=M.norm??{mean:255,bias:0};let se,ie;typeof q.mean=="number"?se=[q.mean,q.mean,q.mean,q.mean]:se=[q.mean[0],q.mean[1],q.mean[2],q.mean[3]??255],typeof q.bias=="number"?ie=[q.bias,q.bias,q.bias,q.bias]:ie=[q.bias[0],q.bias[1],q.bias[2],q.bias[3]??0];const z=M.format!==void 0?M.format:"RGBA",W=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",Y=b*L,D=W==="RGBA"?new Float32Array(Y*4):new Float32Array(Y*3);let $=4,g=0,C=1,T=2,ee=3,J=0,le=Y,de=Y*2,fe=-1;z==="RGB"&&($=3,g=0,C=1,T=2,ee=-1),W==="RGBA"?fe=Y*3:W==="RBG"?(J=0,de=Y,le=Y*2):W==="BGR"&&(de=0,le=Y,J=Y*2);for(let xe=0;xe{const b=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,L=typeof ImageData<"u"&&y instanceof ImageData,q=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,se=typeof y=="string";let ie,z=M??{};const W=()=>{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=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(b){const D=W();D.width=y.width,D.height=y.height;const $=Y(D);if($!=null){let g=y.height,C=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(g=M.resizedHeight,C=M.resizedWidth),M!==void 0){if(z=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");z.tensorFormat="RGBA",z.height=g,z.width=C}else z.tensorFormat="RGBA",z.height=g,z.width=C;$.drawImage(y,0,0),ie=$.getImageData(0,0,C,g).data}else throw new Error("Can not access image data")}else if(L){let D,$;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(D=M.resizedHeight,$=M.resizedWidth):(D=y.height,$=y.width),M!==void 0&&(z=M),z.format="RGBA",z.height=D,z.width=$,M!==void 0){const g=W();g.width=$,g.height=D;const C=Y(g);if(C!=null)C.putImageData(y,0,0),ie=C.getImageData(0,0,$,D).data;else throw new Error("Can not access image data")}else ie=y.data}else if(q){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const D=W();D.width=y.width,D.height=y.height;const $=Y(D);if($!=null){const g=y.height,C=y.width;return $.drawImage(y,0,0,C,g),ie=$.getImageData(0,0,C,g).data,z.height=g,z.width=C,O(ie,z)}else throw new Error("Can not access image data")}else{if(se)return new Promise((D,$)=>{const g=W(),C=Y(g);if(!y||!C)return $();const T=new Image;T.crossOrigin="Anonymous",T.src=y,T.onload=()=>{g.width=T.width,g.height=T.height,C.drawImage(T,0,0,g.width,g.height);const ee=C.getImageData(0,0,g.width,g.height);z.height=g.height,z.width=g.width,D(O(ee.data,z))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ie!==void 0)return O(ie,z);throw new Error("Input data provided is not supported - aborted tensor creation")},Q=(y,M)=>{const{width:b,height:L,download:q,dispose:se}=M,ie=[1,L,b,4];return new f.Tensor({location:"texture",type:"float32",texture:y,dims:ie,download:q,dispose:se})},U=(y,M)=>{const{dataType:b,dims:L,download:q,dispose:se}=M;return new f.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:y,dims:L,download:q,dispose:se})},w=(y,M)=>{const{dataType:b,dims:L,download:q,dispose:se}=M;return new f.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:y,dims:L,download:q,dispose:se})},v=(y,M,b)=>new f.Tensor({location:"cpu-pinned",type:y,data:M,dims:b??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Te,A,s)=>{s.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Te,A,s)=>{s.r(A),s.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>O,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>f,checkTypedArray:()=>Q});const f=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),O=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let N=!1;const Q=()=>{if(!N){N=!0;const U=typeof BigInt64Array<"u"&&BigInt64Array.from,w=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;U&&(f.set("int64",BigInt64Array),O.set(BigInt64Array,"int64")),w&&(f.set("uint64",BigUint64Array),O.set(BigUint64Array,"uint64")),v?(f.set("float16",Float16Array),O.set(Float16Array,"float16")):f.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{Tensor:()=>U});var f=s("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),O=s("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),N=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Q=s("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class U{constructor(v,y,M){(0,N.checkTypedArray)();let b,L;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,L=v.dims,v.location){case"cpu-pinned":{const se=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!se)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof se))throw new TypeError(`buffer should be of type ${se.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let se,ie;if(typeof v=="string")if(b=v,ie=M,v==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");se=y}else{const z=N.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(z===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(y)){if(v==="float16"&&z===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${z.name} as data.`);v==="uint64"||v==="int64"?se=z.from(y,BigInt):se=z.from(y)}else if(y instanceof z)se=y;else if(y instanceof Uint8ClampedArray)if(v==="uint8")se=Uint8Array.from(y);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${z}`)}else if(ie=y,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const z=typeof v[0];if(z==="string")b="string",se=v;else if(z==="boolean")b="bool",se=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${z}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",se=Uint8Array.from(v);else{const z=N.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(z===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=z,se=v}if(ie===void 0)ie=[se.length];else if(!Array.isArray(ie))throw new TypeError("A tensor's dims must be a number array");L=ie,this.cpuData=se,this.dataLocation="cpu"}const q=(0,Q.calculateSize)(L);if(this.cpuData&&q!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(q/2)===this.cpuData.length))throw new Error(`Tensor's size(${q}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=L,this.size=q}static async fromImage(v,y){return(0,O.tensorFromImage)(v,y)}static fromTexture(v,y){return(0,O.tensorFromTexture)(v,y)}static fromGpuBuffer(v,y){return(0,O.tensorFromGpuBuffer)(v,y)}static fromMLTensor(v,y){return(0,O.tensorFromMLTensor)(v,y)}static fromPinnedBuffer(v,y,M){return(0,O.tensorFromPinnedBuffer)(v,y,M)}toDataURL(v){return(0,f.tensorToDataURL)(this,v)}toImageData(v){return(0,f.tensorToImageData)(this,v)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(v){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const y=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=y,v&&this.disposer&&(this.disposer(),this.disposer=void 0),y}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(v){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Q.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{calculateSize:()=>O,tensorReshape:()=>N});var f=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=Q=>{let U=1;for(let w=0;w{switch(Q.location){case"cpu":return new f.Tensor(Q.type,Q.data,U);case"cpu-pinned":return new f.Tensor({location:"cpu-pinned",data:Q.data,type:Q.type,dims:U});case"texture":return new f.Tensor({location:"texture",texture:Q.texture,type:Q.type,dims:U});case"gpu-buffer":return new f.Tensor({location:"gpu-buffer",gpuBuffer:Q.gpuBuffer,type:Q.type,dims:U});case"ml-tensor":return new f.Tensor({location:"ml-tensor",mlTensor:Q.mlTensor,type:Q.type,dims:U});default:throw new Error(`tensorReshape: tensor location ${Q.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Te,A,s)=>{s.r(A),s.d(A,{Tensor:()=>O});var f=s("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const O=f.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Te,A,s)=>{s.r(A),s.d(A,{TRACE:()=>O,TRACE_FUNC_BEGIN:()=>Q,TRACE_FUNC_END:()=>U});var f=s("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const O=(w,v)=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||console.timeStamp(`${w}::ORT::${v}`)},N=(w,v)=>{var b;const y=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let M=!1;for(let L=0;L{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("BEGIN",w)},U=w=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||N("END",w)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Te,A,s)=>{s.r(A),s.d(A,{TrainingSession:()=>Q});var f=s("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),O=s("./node_modules/onnxruntime-common/dist/esm/tensor.js");const N="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Q{constructor(w,v,y){this.handler=w,this.hasOptimizerModel=v,this.hasEvalModel=y}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(w,v){const y=w.evalModel||"",M=w.optimizerModel||"",b=v||{},[L,q]=await(0,f.resolveBackendAndExecutionProviders)(b);if(L.createTrainingSessionHandler){const se=await L.createTrainingSessionHandler(w.checkpointState,w.trainModel,y,M,q);return new Q(se,!!w.optimizerModel,!!w.evalModel)}else throw new Error(N)}typeNarrowingForRunStep(w,v,y,M,b){const L={};let q={};if(typeof y!="object"||y===null||y instanceof O.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let se=!0;if(typeof M=="object"){if(M===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(M instanceof O.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(M)){if(M.length===0)throw new TypeError("'fetches' cannot be an empty array.");se=!1;for(const ie of M){if(typeof ie!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ie)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ie}.`);L[ie]=null}if(typeof b=="object"&&b!==null)q=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ie=!1;const z=Object.getOwnPropertyNames(M);for(const W of v)if(z.indexOf(W)!==-1){const Y=M[W];(Y===null||Y instanceof O.Tensor)&&(ie=!0,se=!1,L[W]=Y)}if(ie){if(typeof b=="object"&&b!==null)q=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else q=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ie of w)if(typeof y[ie]>"u")throw new Error(`input '${ie}' is missing in 'feeds'.`);if(se)for(const ie of v)L[ie]=null;return[L,q]}convertHandlerReturnTypeToMapOfTensors(w){const v={};for(const y in w)if(Object.hasOwnProperty.call(w,y)){const M=w[y];M instanceof O.Tensor?v[y]=M:v[y]=new O.Tensor(M.type,M.data,M.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(w,v,y){const[M,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,w,v,y),L=await this.handler.runTrainStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(L)}async runOptimizerStep(w){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(w||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(w,v,y){if(this.hasEvalModel){const[M,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,w,v,y),L=await this.handler.runEvalStep(w,M,b);return this.convertHandlerReturnTypeToMapOfTensors(L)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(w=!0){return this.handler.getParametersSize(w)}async loadParametersBuffer(w,v=!0){const y=await this.getParametersSize(v);if(w.length!==4*y)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(w,v)}async getContiguousParameters(w=!0){return this.handler.getContiguousParameters(w)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Te,A,s)=>{s.r(A),s.d(A,{TrainingSession:()=>O});var f=s("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const O=f.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Te,A,s)=>{s.r(A),s.d(A,{version:()=>f});const f="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs":(Te,A,s)=>{s.r(A),s.d(A,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>We,TRACE_FUNC_END:()=>Ne,Tensor:()=>ce,default:()=>g_,env:()=>T,registerBackend:()=>q});/*! + * ONNX Runtime Web v1.21.0-dev.20241205-d27fecd3d3 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var f=Object.defineProperty,O=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyNames,Q=Object.prototype.hasOwnProperty,U=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),w=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var r in t)f(e,r,{get:t[r],enumerable:!0})},y=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of N(t))!Q.call(e,o)&&o!==r&&f(e,o,{get:()=>t[o],enumerable:!(n=O(t,o))||n.enumerable});return e},M=e=>y(f({},"__esModule",{value:!0}),e),b,L,q,se,ie,z=w(()=>{b=new Map,L=[],q=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=L.indexOf(e);o!==-1&&L.splice(o,1);for(let a=0;a{let t=b.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ie=async e=>{let t=e.executionProviders||[],r=t.map(p=>typeof p=="string"?p:p.name),n=r.length===0?L:r,o,a=[],i=new Set;for(let p of n){let h=await se(p);typeof h=="string"?a.push({name:p,err:h}):(o||(o=h),o===h&&i.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)r.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let d=t.filter(p=>i.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?d:Reflect.get(p,h)})]}}),W=w(()=>{z()}),Y,D=w(()=>{Y="1.21.0-dev.20241205-6ed77cc374"}),$,g,C=w(()=>{D(),$="warning",g={wasm:{},webgl:{},webgpu:{},versions:{common:Y},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}`);$=e}},get logLevel(){return $}},Object.defineProperty(g,"logLevel",{enumerable:!0})}),T,ee=w(()=>{C(),T=g}),J,le,de=w(()=>{J=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,h;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?h=[0,0,0,0]:typeof d.bias=="number"?h=[d.bias,d.bias,d.bias,d.bias]:(h=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(h[3]=d.bias[3]));let k=a*o,S=0,u=k,B=k*2,R=-1;i==="RGBA"?(S=0,u=k,B=k*2,R=k*3):i==="RGB"?(S=0,u=k,B=k*2):i==="RBG"&&(S=0,B=k,u=k*2);for(let j=0;j{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let o,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],i=e.dims[3]):(o=e.dims[3],a=e.dims[2],i=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let S=a*o;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,B=0,R=1,j=2,Z=3,te=0,X=S,_e=S*2,me=-1;d==="RGBA"?(te=0,X=S,_e=S*2,me=S*3):d==="RGB"?(te=0,X=S,_e=S*2):d==="RBG"&&(te=0,_e=S,X=S*2),n=r.createImageData(o,a);for(let ye=0;ye{De(),fe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},a,i;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),S=4,u=0,B=1,R=2,j=3,Z=0,te=h,X=h*2,_e=-1;d==="RGB"&&(S=3,u=0,B=1,R=2,j=-1),p==="RGBA"?_e=h*3:p==="RBG"?(Z=0,X=h,te=h*2):p==="BGR"&&(X=0,te=h,Z=h*2);for(let me=0;me{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,d=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(r){let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(u=t.resizedHeight,B=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=u,d.width=B}else d.tensorFormat="RGBA",d.height=u,d.width=B;S.drawImage(e,0,0),i=S.getImageData(0,0,B,u).data}else throw new Error("Can not access image data")}else if(n){let k,S;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,S=t.resizedWidth):(k=e.height,S=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=k,d.width=S,t!==void 0){let u=p();u.width=S,u.height=k;let B=h(u);if(B!=null)B.putImageData(e,0,0),i=B.getImageData(0,0,S,k).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let S=h(k);if(S!=null){let u=e.height,B=e.width;return S.drawImage(e,0,0,B,u),i=S.getImageData(0,0,B,u).data,d.height=u,d.width=B,fe(i,d)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,S)=>{let u=p(),B=h(u);if(!e||!B)return S();let R=new Image;R.crossOrigin="Anonymous",R.src=e,R.onload=()=>{u.width=R.width,u.height=R.height,B.drawImage(R,0,0,u.width,u.height);let j=B.getImageData(0,0,u.width,u.height);d.height=u.height,d.width=u.width,k(fe(j.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return fe(i,d);throw new Error("Input data provided is not supported - aborted tensor creation")},xe=(e,t)=>{let{width:r,height:n,download:o,dispose:a}=t,i=[1,n,r,4];return new Je({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:a})},Le=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:a}=t;return new Je({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:o,dispose:a})},qe=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:a}=t;return new Je({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:o,dispose:a})},Ue=(e,t,r)=>new Je({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),ue,re,he,Pe,Be=w(()=>{ue=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"]]),he=!1,Pe=()=>{if(!he){he=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(ue.set("int64",BigInt64Array),re.set(BigInt64Array,"int64")),t&&(ue.set("uint64",BigUint64Array),re.set(BigUint64Array,"uint64")),r?(ue.set("float16",Float16Array),re.set(Float16Array,"float16")):ue.set("float16",Uint16Array)}}}),et,Xe,oe=w(()=>{De(),et=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Je(e.type,e.data,t);case"cpu-pinned":return new Je({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Je({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Je({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Je({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Je,De=w(()=>{de(),ut(),Be(),oe(),Je=class{constructor(e,t,r){Pe();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=ue.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,d;if(typeof e=="string")if(n=e,d=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let p=ue.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?i=p.from(t,BigInt):i=p.from(t)}else if(t instanceof p)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",i=e;else if(p==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let p=re.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,i=e}if(d===void 0)d=[i.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=i,this.dataLocation="cpu"}let a=et(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,t){return ke(e,t)}static fromTexture(e,t){return xe(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return qe(e,t)}static fromPinnedBuffer(e,t,r){return Ue(e,t,r)}toDataURL(e){return J(this,e)}toImageData(e){return le(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),ce,ve=w(()=>{De(),ce=Je}),Re,je,We,Ne,Ze=w(()=>{C(),Re=(e,t)=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||console.timeStamp(`${e}::ORT::${t}`)},je=(e,t)=>{var o;let r=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||je("BEGIN",e)},Ne=e=>{(typeof g.trace>"u"?!g.wasm.trace:!g.trace)||je("END",e)}}),at,ft=w(()=>{z(),ve(),Ze(),at=class c_{constructor(t){this.handler=t}async run(t,r,n){We();let o={},a={};if(typeof t!="object"||t===null||t instanceof ce||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ce)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(r);for(let S of this.outputNames)if(k.indexOf(S)!==-1){let u=r[S];(u===null||u instanceof ce)&&(h=!0,i=!1,o[S]=u)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)o[h]=null;let d=await this.handler.run(t,o,a),p={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let k=d[h];k instanceof ce?p[h]=k:p[h]=new ce(k.type,k.data,k.dims)}return Ne(),p}async release(){return this.handler.dispose()}static async create(t,r,n,o){We();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,S=0,u=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(S=r,!Number.isSafeInteger(S))throw new RangeError("'byteOffset' must be an integer.");if(S<0||S>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(u=t.byteLength-S,typeof n=="number"){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||S+u>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-S}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,S,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,p]=await ie(i),h=await d.createInferenceSessionHandler(a,p);return Ne(),new c_(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),dt,gt=w(()=>{ft(),dt=at}),F=w(()=>{}),ne=w(()=>{}),K=w(()=>{}),pe=w(()=>{}),Fe={};v(Fe,{InferenceSession:()=>dt,TRACE:()=>Re,TRACE_FUNC_BEGIN:()=>We,TRACE_FUNC_END:()=>Ne,Tensor:()=>ce,env:()=>T,registerBackend:()=>q});var Qe=w(()=>{W(),ee(),gt(),ve(),F(),ne(),Ze(),K(),pe()}),st=w(()=>{}),pt={};v(pt,{default:()=>Ft});var It,St,Ft,At=w(()=>{var e;kh(),Ot(),Ss(),It="ort-wasm-proxy-worker",St=((e=globalThis.self)==null?void 0:e.name)===It,St&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":nt(n.wasm).then(()=>{vc(n).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})})},o=>{postMessage({type:r,err:o})});break;case"init-ep":{let{epName:o,env:a}=n;qs(a,o).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:o}=n,a=yp(o);postMessage({type:r,out:a});break}case"create":{let{model:o,options:a}=n;Vp(o,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":Wp(n),postMessage({type:r});break;case"run":{let{sessionId:o,inputIndices:a,inputs:i,outputIndices:d,options:p}=n;Kp(o,a,i,d,new Array(d.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:h},qp([...i,...h]))},h=>{postMessage({type:r,err:h})});break}case"end-profiling":Hp(n),postMessage({type:r});break;default:}}catch(o){postMessage({type:r,err:o})}}),Ft=St?null:t=>new Worker(t??os,{type:"module",name:It})}),nr={};v(nr,{default:()=>Ar});var gr,kr,Ar,Qr=w(()=>{var e;kr=(gr=import.meta.url,async function(t={}){function r(){return jt.buffer!=Gt.buffer&&Er(),Gt}function n(){return jt.buffer!=Gt.buffer&&Er(),Cr}function o(){return jt.buffer!=Gt.buffer&&Er(),ot}function a(){return jt.buffer!=Gt.buffer&&Er(),Et}function i(){return jt.buffer!=Gt.buffer&&Er(),cr}function d(){return jt.buffer!=Gt.buffer&&Er(),Lr}function p(){return jt.buffer!=Gt.buffer&&Er(),ys}function h(){return jt.buffer!=Gt.buffer&&Er(),Lo}var k,S,u=Object.assign({},t),B=new Promise((l,m)=>{k=l,S=m}),R=typeof window=="object",j=typeof importScripts=="function",Z=j&&self.name=="em-pthread";u.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(u.Fb||(u.Fb=new Map)).set(l,m)},u.unmountExternalData=()=>{delete u.Fb};var te=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let X=()=>{let l=(E,I,G)=>(...we)=>{let Ke=pn,tt=I==null?void 0:I();we=E(...we);let bt=I==null?void 0:I();return tt!==bt&&(E=bt,G(tt),I=G=null),pn!=Ke?new Promise((kt,Wt)=>{mh={resolve:kt,reject:Wt}}):we},m=E=>async(...I)=>{var G;try{if(u.Gb)throw Error("Session already started");let we=u.Gb={hc:I[0],errors:[]},Ke=await E(...I);if(u.Gb!==we)throw Error("Session mismatch");(G=u.Hb)==null||G.flush();let tt=we.errors;if(0kt),0u._OrtCreateSession,E=>u._OrtCreateSession=E),u._OrtRun=m(l(u._OrtRun,()=>u._OrtRun,E=>u._OrtRun=E)),u._OrtRunWithBinding=m(l(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,E=>u._OrtRunWithBinding=E)),u._OrtBindInput=l(u._OrtBindInput,()=>u._OrtBindInput,E=>u._OrtBindInput=E),X=void 0};u.jsepInit=(l,m)=>{if(X==null||X(),l==="webgpu"){[u.Hb,u.Vb,u.Zb,u.Ob,u.Yb,u.kb,u.$b,u.cc,u.Wb,u.Xb,u.ac]=m;let E=u.Hb;u.jsepRegisterBuffer=(I,G,we,Ke)=>E.registerBuffer(I,G,we,Ke),u.jsepGetBuffer=I=>E.getBuffer(I),u.jsepCreateDownloader=(I,G,we)=>E.createDownloader(I,G,we),u.jsepOnCreateSession=I=>{E.onCreateSession(I)},u.jsepOnReleaseSession=I=>{E.onReleaseSession(I)},u.jsepOnRunStart=I=>E.onRunStart(I),u.dc=(I,G)=>{E.upload(I,G)}}else if(l==="webnn"){[u.Hb,u.bc,u.Pb,u.jsepEnsureTensor,u.ec,u.jsepDownloadTensor]=m,u.jsepReleaseTensorId=u.Pb;let E=u.Hb;u.jsepOnRunStart=I=>E.onRunStart(I),u.jsepRegisterMLContext=(I,G)=>{E.registerMLContext(I,G)},u.jsepOnReleaseSession=I=>{E.onReleaseSession(I)},u.jsepCreateMLTensorDownloader=(I,G)=>E.createMLTensorDownloader(I,G),u.jsepRegisterMLTensor=(I,G,we)=>E.registerMLTensor(I,G,we),u.jsepCreateMLContext=I=>E.createMLContext(I),u.jsepRegisterMLConstant=(I,G,we,Ke,tt)=>E.registerMLConstant(I,G,we,Ke,tt,u.Fb)}};var _e,me,ye=Object.assign({},u),Ae="./this.program",Ie=(l,m)=>{throw m},Ge="";(R||j)&&(j?Ge=self.location.href:typeof document<"u"&&document.currentScript&&(Ge=document.currentScript.src),gr&&(Ge=gr),Ge=Ge.startsWith("blob:")?"":Ge.substr(0,Ge.replace(/[?#].*/,"").lastIndexOf("/")+1),j&&(me=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),_e=(l,m,E)=>{var I=new XMLHttpRequest;I.open("GET",l,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?m(I.response):E()},I.onerror=E,I.send(null)});var lt,xt=console.log.bind(console),Kt=console.error.bind(console),Yt=xt,Ct=Kt;if(Object.assign(u,ye),ye=null,Z){let l=function(m){try{var E=m.data,I=E.cmd;if(I==="load"){let G=[];self.onmessage=we=>G.push(we),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let we of G)l(we);self.onmessage=l};for(let we of E.handlers)u[we]&&!u[we].proxy||(u[we]=(...Ke)=>{postMessage({Nb:"callHandler",pc:we,args:Ke})},we=="print"&&(Yt=u[we]),we=="printErr"&&(Ct=u[we]));jt=E.wasmMemory,Er(),Jt(E.wasmModule)}else if(I==="run"){wh(E.pthread_ptr,0,0,1,0,0),ph(E.pthread_ptr),M_(),Jh(),$t||(Xm(),$t=!0);try{b_(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else I==="cancel"?Ma()&&Op(-1):E.target!=="setimmediate"&&(I==="checkMailbox"?$t&&Tp():I&&(Ct(`worker: received unknown command ${I}`),Ct(E)))}catch(G){throw Qm(),G}};var Jt,$t=!1;Ct=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Ma()})},u.instantiateWasm=(m,E)=>new Promise(I=>{Jt=G=>{G=new WebAssembly.Instance(G,Hh()),E(G),I()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}u.wasmBinary&&(lt=u.wasmBinary);var jt,vr,Ht,Gt,Cr,ot,Et,cr,Lr,ys,Hr,un,Lo,Ir=!1;function Er(){var l=jt.buffer;u.HEAP8=Gt=new Int8Array(l),u.HEAP16=ot=new Int16Array(l),u.HEAPU8=Cr=new Uint8Array(l),u.HEAPU16=Et=new Uint16Array(l),u.HEAP32=cr=new Int32Array(l),u.HEAPU32=Lr=new Uint32Array(l),u.HEAPF32=ys=new Float32Array(l),u.HEAPF64=Lo=new Float64Array(l),u.HEAP64=Hr=new BigInt64Array(l),u.HEAPU64=un=new BigUint64Array(l)}if(!Z){if(!((jt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof te))throw Ct("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");Er()}var Kn=[],Ec=[],Zp=[],Pc=0,Cc=null;function Uh(){if(--Pc==0&&Cc){var l=Cc;Cc=null,l()}}function Hn(l){throw Ct(l="Aborted("+l+")"),Ir=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),S(l),l}var eh,Vh=l=>l.startsWith("data:application/octet-stream;base64,"),Wh=l=>l.startsWith("file://");function Gh(l){if(l==eh&<)return new Uint8Array(lt);if(me)return me(l);throw"both async and sync fetching of the wasm failed"}function Kh(l,m,E){return function(I){if(!lt&&(R||j)){if(typeof fetch=="function"&&!Wh(I))return fetch(I,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${I}'`;return G.arrayBuffer()}).catch(()=>Gh(I));if(_e)return new Promise((G,we)=>{_e(I,Ke=>G(new Uint8Array(Ke)),we)})}return Promise.resolve().then(()=>Gh(I))}(l).then(I=>WebAssembly.instantiate(I,m)).then(E,I=>{Ct(`failed to asynchronously prepare wasm: ${I}`),Hn(I)})}function Hh(){return{a:{O:y_,Aa:w_,b:T_,aa:rm,B:om,qa:im,Y:lm,_:um,ra:dm,oa:cm,ha:pm,na:hm,L:mm,Z:_m,W:fm,pa:gm,X:wm,va:x_,F:E_,Q:P_,P:k_,E:$_,u:A_,q:I_,G:O_,A:N_,R:j_,ua:U_,ka:V_,U:W_,ba:G_,H:K_,ja:ph,ta:H_,t:q_,Ba:X_,x:J_,n:Z_,l:tf,c:dh,o:rf,j:of,w:af,p:lf,f:uf,s:df,m:cf,e:pf,k:hf,i:mf,h:_f,d:ff,ea:gf,fa:wf,ga:yf,ca:Im,da:Om,T:Mf,g:bf,D:vf,I:Tf,M:xf,y:Ef,sa:Pf,V:Cf,v:Dm,z:kf,N:Sf,S:$f,za:Af,ya:If,la:Bm,ma:Rm,$:oh,C:Nm,K:jm,ia:Um,J:Vm,a:jt,xa:nh,wa:Km,r:Df}}}var th={874308:(l,m,E,I,G)=>{if(u===void 0||!u.Fb)return 1;if((l=zr(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=u.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),I=Number(I>>>0),m+E>l.byteLength)return 3;try{let we=l.subarray(m,m+E);switch(G){case 0:n().set(we,I>>>0);break;case 1:u.dc(I,we);break;default:return 4}return 0}catch{return 4}},875023:(l,m,E)=>{u.ec(l,n().subarray(m>>>0,m+E>>>0))},875086:()=>u.bc(),875127:l=>{u.Pb(l)},875163:()=>{u.Wb()},875194:()=>{u.Xb()},875223:()=>{u.ac()},875248:l=>u.Vb(l),875281:l=>u.Zb(l),875313:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E),!0)},875376:(l,m,E)=>{u.Ob(Number(l),Number(m),Number(E))},875433:()=>typeof wasmOffsetConverter<"u",875490:l=>{u.kb("Abs",l,void 0)},875541:l=>{u.kb("Neg",l,void 0)},875592:l=>{u.kb("Floor",l,void 0)},875645:l=>{u.kb("Ceil",l,void 0)},875697:l=>{u.kb("Reciprocal",l,void 0)},875755:l=>{u.kb("Sqrt",l,void 0)},875807:l=>{u.kb("Exp",l,void 0)},875858:l=>{u.kb("Erf",l,void 0)},875909:l=>{u.kb("Sigmoid",l,void 0)},875964:(l,m,E)=>{u.kb("HardSigmoid",l,{alpha:m,beta:E})},876043:l=>{u.kb("Log",l,void 0)},876094:l=>{u.kb("Sin",l,void 0)},876145:l=>{u.kb("Cos",l,void 0)},876196:l=>{u.kb("Tan",l,void 0)},876247:l=>{u.kb("Asin",l,void 0)},876299:l=>{u.kb("Acos",l,void 0)},876351:l=>{u.kb("Atan",l,void 0)},876403:l=>{u.kb("Sinh",l,void 0)},876455:l=>{u.kb("Cosh",l,void 0)},876507:l=>{u.kb("Asinh",l,void 0)},876560:l=>{u.kb("Acosh",l,void 0)},876613:l=>{u.kb("Atanh",l,void 0)},876666:l=>{u.kb("Tanh",l,void 0)},876718:l=>{u.kb("Not",l,void 0)},876769:(l,m,E)=>{u.kb("Clip",l,{min:m,max:E})},876838:l=>{u.kb("Clip",l,void 0)},876890:(l,m)=>{u.kb("Elu",l,{alpha:m})},876948:l=>{u.kb("Gelu",l,void 0)},877e3:l=>{u.kb("Relu",l,void 0)},877052:(l,m)=>{u.kb("LeakyRelu",l,{alpha:m})},877116:(l,m)=>{u.kb("ThresholdedRelu",l,{alpha:m})},877186:(l,m)=>{u.kb("Cast",l,{to:m})},877244:l=>{u.kb("Add",l,void 0)},877295:l=>{u.kb("Sub",l,void 0)},877346:l=>{u.kb("Mul",l,void 0)},877397:l=>{u.kb("Div",l,void 0)},877448:l=>{u.kb("Pow",l,void 0)},877499:l=>{u.kb("Equal",l,void 0)},877552:l=>{u.kb("Greater",l,void 0)},877607:l=>{u.kb("GreaterOrEqual",l,void 0)},877669:l=>{u.kb("Less",l,void 0)},877721:l=>{u.kb("LessOrEqual",l,void 0)},877780:(l,m,E,I,G)=>{u.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},877955:(l,m,E,I,G)=>{u.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878129:(l,m,E,I,G)=>{u.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878303:(l,m,E,I,G)=>{u.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878478:(l,m,E,I,G)=>{u.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878652:(l,m,E,I,G)=>{u.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878825:(l,m,E,I,G)=>{u.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},878998:(l,m,E,I,G)=>{u.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879175:(l,m,E,I,G)=>{u.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879355:(l,m,E,I,G)=>{u.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},879535:l=>{u.kb("Where",l,void 0)},879588:(l,m,E)=>{u.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},879712:(l,m,E,I)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zr(E),format:I?"NHWC":"NCHW"})},879845:(l,m,E,I)=>{u.kb("DepthToSpace",l,{blocksize:m,mode:zr(E),format:I?"NHWC":"NCHW"})},879978:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve,ar)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:I,kernelShape:[G],pads:[we,Ke],strides:[tt],wIsConst:()=>!!r()[kt>>>0],outputPadding:Wt?Array.from(i().subarray(Number(Wt)>>>0,Number(pr)>>>0)):[],outputShape:Mr?Array.from(i().subarray(Number(Mr)>>>0,Number(Ve)>>>0)):[],activation:zr(ar)})},880411:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("ConvTranspose",l,{format:tt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:I,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!r()[bt>>>0],outputPadding:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],outputShape:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[],activation:zr(Ve)})},881072:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve,ar)=>{u.kb("ConvTranspose",l,{format:bt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:I,kernelShape:[G],pads:[we,Ke],strides:[tt],wIsConst:()=>!!r()[kt>>>0],outputPadding:Wt?Array.from(i().subarray(Number(Wt)>>>0,Number(pr)>>>0)):[],outputShape:Mr?Array.from(i().subarray(Number(Mr)>>>0,Number(Ve)>>>0)):[],activation:zr(ar)})},881505:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("ConvTranspose",l,{format:tt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:I,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(we)>>>0,4+(Number(we)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Ke)>>>0,2+(Number(Ke)>>>0)>>>0)),wIsConst:()=>!!r()[bt>>>0],outputPadding:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],outputShape:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[],activation:zr(Ve)})},882166:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882257:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("AveragePool",l,{format:Ve?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],strides:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[]})},882736:(l,m)=>{u.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},882827:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("AveragePool",l,{format:Ve?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],strides:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[]})},883306:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883393:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("MaxPool",l,{format:Ve?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],strides:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[]})},883868:(l,m)=>{u.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},883955:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve)=>{u.kb("MaxPool",l,{format:Ve?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:I,storage_order:G,dilations:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],kernel_shape:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],pads:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],strides:pr?Array.from(i().subarray(Number(pr)>>>0,Number(Mr)>>>0)):[]})},884430:(l,m,E,I,G)=>{u.kb("Gemm",l,{alpha:m,beta:E,transA:I,transB:G})},884534:l=>{u.kb("MatMul",l,void 0)},884588:(l,m,E,I)=>{u.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:I})},884696:(l,m,E,I)=>{u.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:I})},884804:(l,m)=>{u.kb("Softmax",l,{axis:m})},884867:(l,m)=>{u.kb("Concat",l,{axis:m})},884927:(l,m,E,I,G)=>{u.kb("Split",l,{axis:m,numOutputs:E,splitSizes:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},885083:l=>{u.kb("Expand",l,void 0)},885137:(l,m)=>{u.kb("Gather",l,{axis:Number(m)})},885208:(l,m)=>{u.kb("GatherElements",l,{axis:Number(m)})},885287:(l,m)=>{u.kb("GatherND",l,{batch_dims:Number(m)})},885366:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt)=>{u.kb("Resize",l,{antialias:m,axes:E?Array.from(i().subarray(Number(E)>>>0,Number(I)>>>0)):[],coordinateTransformMode:zr(G),cubicCoeffA:we,excludeOutside:Ke,extrapolationValue:tt,keepAspectRatioPolicy:zr(bt),mode:zr(kt),nearestMode:zr(Wt)})},885728:(l,m,E,I,G,we,Ke)=>{u.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[],axes:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[]})},885992:l=>{u.kb("Tile",l,void 0)},886044:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886158:(l,m,E)=>{u.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},886272:l=>{u.kb("Range",l,void 0)},886325:(l,m)=>{u.kb("Einsum",l,{equation:zr(m)})},886406:(l,m,E,I,G)=>{u.kb("Pad",l,{mode:m,value:E,pads:I?Array.from(i().subarray(Number(I)>>>0,Number(G)>>>0)):[]})},886549:(l,m,E,I,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!I,format:we?"NHWC":"NCHW"})},886718:(l,m,E,I,G,we)=>{u.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!I,format:we?"NHWC":"NCHW"})},886887:(l,m,E)=>{u.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},886984:(l,m,E)=>{u.kb("DequantizeLinear",l,{axis:m,blockSize:E})},887074:(l,m,E,I,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zr(E),padding_mode:zr(I),format:G?"NHWC":"NCHW"})},887244:(l,m,E,I,G)=>{u.kb("GridSample",l,{align_corners:m,mode:zr(E),padding_mode:zr(I),format:G?"NHWC":"NCHW"})},887414:(l,m)=>{u.kb("ScatterND",l,{reduction:zr(m)})},887499:(l,m,E,I,G,we,Ke,tt,bt)=>{u.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:I,scale:G,doRotary:we,qkvHiddenSizes:Ke?Array.from(i().subarray(Number(tt)>>>0,Number(tt)+Ke>>>0)):[],pastPresentShareBuffer:!!bt})},887771:l=>{u.kb("BiasAdd",l,void 0)},887826:l=>{u.kb("BiasSplitGelu",l,void 0)},887887:l=>{u.kb("FastGelu",l,void 0)},887943:(l,m,E,I,G,we,Ke,tt,bt,kt,Wt,pr,Mr,Ve,ar,Br)=>{u.kb("Conv",l,{format:pr?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(i().subarray(Number(E)>>>0,Number(I)>>>0)):[],group:G,kernel_shape:we?Array.from(i().subarray(Number(we)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(i().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(i().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],w_is_const:()=>!!r()[Number(Mr)>>>0],activation:zr(Ve),activation_params:ar?Array.from(p().subarray(Number(ar)>>>0,Number(Br)>>>0)):[]})},888527:l=>{u.kb("Gelu",l,void 0)},888579:(l,m,E,I,G,we,Ke,tt,bt)=>{u.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:I,softcap:G,doRotary:we,rotaryInterleaved:Ke,smoothSoftmax:tt,localWindowSize:bt})},888796:(l,m,E,I)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!I})},888907:(l,m,E,I)=>{u.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!I})},889018:(l,m,E,I,G,we)=>{u.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:I,bits:G,blockSize:we})},889145:(l,m,E,I,G,we)=>{u.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:I,scale:G,doRotary:we})},889304:(l,m)=>{u.kb("QuickGelu",l,{alpha:m})},889368:(l,m,E,I,G)=>{u.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:I,scale:G})},889507:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889609:(l,m,E)=>{u.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},889711:(l,m,E,I)=>{u.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:I})},889832:l=>{u.$b(l)},889866:(l,m)=>u.cc(Number(l),Number(m),u.Gb.hc,u.Gb.errors)};function w_(l,m,E){return Cm(async()=>{await u.Yb(Number(l),Number(m),Number(E))})}function y_(){return typeof wasmOffsetConverter<"u"}function rh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var sh=l=>{l.terminate(),l.onmessage=()=>{}},qh=l=>{qn.length==0&&(em(),Zh(qn[0]));var m=qn.pop();if(!m)return 6;Bo.push(m),dn[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},zo=0,Or=(l,m,...E)=>{for(var I=2*E.length,G=bh(),we=Mh(8*I),Ke=we>>>3,tt=0;tt>>0]=bt)}return l=Ym(l,0,I,we,m),Fp(G),l};function nh(l){if(Z)return Or(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw Xh(l),"unwind";nh(l)},qn=[],Bo=[],Qh=[],dn={},Yh=l=>{var m=l.Bb;delete dn[m],qn.push(l),Bo.splice(Bo.indexOf(l),1),l.Bb=0,yh(m)};function Jh(){Qh.forEach(l=>l())}var Zh=l=>new Promise(m=>{l.onmessage=G=>{var we=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Ma()){var Ke=dn[G.targetThread];Ke?Ke.postMessage(G,G.transferList):Ct(`Internal error! Worker sent a message "${we}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else we==="checkMailbox"?Tp():we==="spawnThread"?qh(G):we==="cleanupThread"?Yh(dn[G.thread]):we==="killThread"?(G=G.thread,we=dn[G],delete dn[G],sh(we),yh(G),Bo.splice(Bo.indexOf(we),1),we.Bb=0):we==="cancelThread"?dn[G.thread].postMessage({cmd:"cancel"}):we==="loaded"?(l.loaded=!0,m(l)):we==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):we==="callHandler"?u[G.handler](...G.args):we&&Ct(`worker sent an unknown command ${we}`)},l.onerror=G=>{throw Ct(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,I=[];for(E of[])u.hasOwnProperty(E)&&I.push(E);l.postMessage({cmd:"load",handlers:I,wasmMemory:jt,wasmModule:vr})});function em(){var l=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});qn.push(l)}var vp=l=>{for(;0{var l=Ma(),m=d()[l+52>>>2>>>0];l=d()[l+56>>>2>>>0],Zm(m,m-l),Fp(m)},b_=(l,m)=>{zo=0,l=e_(l,m),0>>=0);throw m>>>=0,E>>>=0,d()[I.Kb+16>>>2>>>0]=0,d()[I.Kb+4>>>2>>>0]=m,d()[I.Kb+8>>>2>>>0]=E,l}function tm(l,m,E,I){return Z?Or(2,1,l,m,E,I):rm(l,m,E,I)}function rm(l,m,E,I){if(l>>>=0,m>>>=0,E>>>=0,I>>>=0,te===void 0)return Ct("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?tm(l,m,E,I):(l={ic:E,Bb:l,Rb:I,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):qh(l))}var sm=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,nm=(l,m,E)=>{var I=(m>>>=0)+E;for(E=m;l[E]&&!(E>=I);)++E;if(16(G=(240&G)==224?(15&G)<<12|we<<6|Ke:(7&G)<<18|we<<12|Ke<<6|63&l[m++])?I+=String.fromCharCode(G):(G-=65536,I+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else I+=String.fromCharCode(G)}return I},zr=(l,m)=>(l>>>=0)?nm(n(),l,m):"";function om(l,m,E){return Z?Or(3,1,l,m,E):0}function im(l,m){if(Z)return Or(4,1,l,m)}var ih=l=>{for(var m=0,E=0;E=I?m++:2047>=I?m+=2:55296<=I&&57343>=I?(m+=4,++E):m+=3}return m},am=(l,m,E,I)=>{if(!(0>>=0;I=E+I-1;for(var we=0;we=Ke&&(Ke=65536+((1023&Ke)<<10)|1023&l.charCodeAt(++we)),127>=Ke){if(E>=I)break;m[E++>>>0]=Ke}else{if(2047>=Ke){if(E+1>=I)break;m[E++>>>0]=192|Ke>>6}else{if(65535>=Ke){if(E+2>=I)break;m[E++>>>0]=224|Ke>>12}else{if(E+3>=I)break;m[E++>>>0]=240|Ke>>18,m[E++>>>0]=128|Ke>>12&63}m[E++>>>0]=128|Ke>>6&63}m[E++>>>0]=128|63&Ke}}return m[E>>>0]=0,E-G},wa=(l,m,E)=>am(l,n(),m,E);function lm(l,m){if(Z)return Or(5,1,l,m)}function um(l,m,E){if(Z)return Or(6,1,l,m,E)}function dm(l,m,E){return Z?Or(7,1,l,m,E):0}function cm(l,m){if(Z)return Or(8,1,l,m)}function pm(l,m,E){if(Z)return Or(9,1,l,m,E)}function hm(l,m,E,I){if(Z)return Or(10,1,l,m,E,I)}function mm(l,m,E,I){if(Z)return Or(11,1,l,m,E,I)}function _m(l,m,E,I){if(Z)return Or(12,1,l,m,E,I)}function fm(l){if(Z)return Or(13,1,l)}function gm(l,m){if(Z)return Or(14,1,l,m)}function wm(l,m,E){if(Z)return Or(15,1,l,m,E)}var ym,Xn,x_=()=>{Hn("")},cn=l=>{for(var m="";n()[l>>>0];)m+=ym[n()[l++>>>0]];return m},ah={},lh={};function xn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(I,G,we={}){var Ke=G.name;if(!I)throw new Xn(`type "${Ke}" must have a positive integer typeid pointer`);if(lh.hasOwnProperty(I)){if(we.Tb)return;throw new Xn(`Cannot register type '${Ke}' twice`)}lh[I]=G,ah.hasOwnProperty(I)&&(G=ah[I],delete ah[I],G.forEach(tt=>tt()))}(l,m,E)}var Mm=(l,m,E)=>{switch(m){case 1:return E?I=>r()[I>>>0]:I=>n()[I>>>0];case 2:return E?I=>o()[I>>>1>>>0]:I=>a()[I>>>1>>>0];case 4:return E?I=>i()[I>>>2>>>0]:I=>d()[I>>>2>>>0];case 8:return E?I=>Hr[I>>>3]:I=>un[I>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function E_(l,m,E){E>>>=0,xn(l>>>=0,{name:m=cn(m>>>0),fromWireType:I=>I,toWireType:function(I,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(I=typeof G)=="object"||I==="array"||I==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Qn,readValueFromPointer:Mm(m,E,m.indexOf("u")==-1),Eb:null})}var Qn=8;function P_(l,m,E,I){xn(l>>>=0,{name:m=cn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,we){return we?E:I},argPackAdvance:Qn,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var uh=[],En=[];function dh(l){9<(l>>>=0)&&--En[l+1]==0&&(En[l]=void 0,uh.push(l))}var Cs=l=>{if(!l)throw new Xn("Cannot use deleted val. handle = "+l);return En[l]},Ls=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=uh.pop()||En.length;return En[m]=l,En[m+1]=1,m}};function ch(l){return this.fromWireType(d()[l>>>2>>>0])}var C_={name:"emscripten::val",fromWireType:l=>{var m=Cs(l);return dh(l),m},toWireType:(l,m)=>Ls(m),argPackAdvance:Qn,readValueFromPointer:ch,Eb:null};function k_(l){return xn(l>>>0,C_)}var S_=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(p()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(h()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function $_(l,m,E){E>>>=0,xn(l>>>=0,{name:m=cn(m>>>0),fromWireType:I=>I,toWireType:(I,G)=>G,argPackAdvance:Qn,readValueFromPointer:S_(m,E),Eb:null})}function A_(l,m,E,I,G){if(l>>>=0,E>>>=0,m=cn(m>>>0),G===-1&&(G=4294967295),G=tt=>tt,I===0){var we=32-8*E;G=tt=>tt<>>we}var Ke=m.includes("unsigned")?function(tt,bt){return bt>>>0}:function(tt,bt){return bt};xn(l,{name:m,fromWireType:G,toWireType:Ke,argPackAdvance:Qn,readValueFromPointer:Mm(m,E,I!==0),Eb:null})}function I_(l,m,E){function I(we){var Ke=d()[we>>>2>>>0];return we=d()[we+4>>>2>>>0],new G(r().buffer,we,Ke)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];xn(l>>>=0,{name:E=cn(E>>>0),fromWireType:I,argPackAdvance:Qn,readValueFromPointer:I},{Tb:!0})}function O_(l,m){l>>>=0;var E=(m=cn(m>>>0))==="std::string";xn(l,{name:m,fromWireType:function(I){var G=d()[I>>>2>>>0],we=I+4;if(E)for(var Ke=we,tt=0;tt<=G;++tt){var bt=we+tt;if(tt==G||n()[bt>>>0]==0){if(Ke=zr(Ke,bt-Ke),kt===void 0)var kt=Ke;else kt+="\0",kt+=Ke;Ke=bt+1}}else{for(kt=Array(G),tt=0;tt>>0]);kt=kt.join("")}return hn(I),kt},toWireType:function(I,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var we=typeof G=="string";if(!(we||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new Xn("Cannot pass non-string to std::string");var Ke=E&&we?ih(G):G.length,tt=Ip(4+Ke+1),bt=tt+4;if(d()[tt>>>2>>>0]=Ke,E&&we)wa(G,bt,Ke+1);else if(we)for(we=0;we>>0]=kt}else for(we=0;we>>0]=G[we];return I!==null&&I.push(hn,tt),tt},argPackAdvance:Qn,readValueFromPointer:ch,Eb(I){hn(I)}})}var bm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,F_=(l,m)=>{for(var E=l>>1,I=E+m/2;!(E>=I)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&bm)return bm.decode(n().slice(l,E));for(E="",I=0;!(I>=m/2);++I){var G=o()[l+2*I>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},D_=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var I=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=we,m+=2}return o()[m>>>1>>>0]=0,m-I},L_=l=>2*l.length,z_=(l,m)=>{for(var E=0,I="";!(E>=m/4);){var G=i()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,I+=String.fromCharCode(55296|G>>10,56320|1023&G)):I+=String.fromCharCode(G)}return I},B_=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var I=m;E=I+E-4;for(var G=0;G=we&&(we=65536+((1023&we)<<10)|1023&l.charCodeAt(++G)),i()[m>>>2>>>0]=we,(m+=4)+4>E)break}return i()[m>>>2>>>0]=0,m-I},R_=l=>{for(var m=0,E=0;E=I&&++E,m+=4}return m};function N_(l,m,E){if(l>>>=0,m>>>=0,E=cn(E>>>=0),m===2)var I=F_,G=D_,we=L_,Ke=tt=>a()[tt>>>1>>>0];else m===4&&(I=z_,G=B_,we=R_,Ke=tt=>d()[tt>>>2>>>0]);xn(l,{name:E,fromWireType:tt=>{for(var bt,kt=d()[tt>>>2>>>0],Wt=tt+4,pr=0;pr<=kt;++pr){var Mr=tt+4+pr*m;pr!=kt&&Ke(Mr)!=0||(Wt=I(Wt,Mr-Wt),bt===void 0?bt=Wt:(bt+="\0",bt+=Wt),Wt=Mr+m)}return hn(tt),bt},toWireType:(tt,bt)=>{if(typeof bt!="string")throw new Xn(`Cannot pass non-string to C++ string type ${E}`);var kt=we(bt),Wt=Ip(4+kt+m);return d()[Wt>>>2>>>0]=kt/m,G(bt,Wt+4,kt+m),tt!==null&&tt.push(hn,Wt),Wt},argPackAdvance:Qn,readValueFromPointer:ch,Eb(tt){hn(tt)}})}function j_(l,m){xn(l>>>=0,{Ub:!0,name:m=cn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var U_=()=>1;function V_(l){wh(l>>>0,!j,1,!R,131072,!1),Jh()}var vm=l=>{if(!Ir)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(Tp),l+=128,Atomics.store(i(),l>>>2,1))}var Tp=()=>{var l=Ma();l&&(ph(l),vm(Jm))};function W_(l,m){(l>>>=0)==m>>>0?setTimeout(Tp):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=dn[l])&&l.postMessage({cmd:"checkMailbox"})}var hh=[];function G_(l,m,E,I,G){for(m>>>=0,I/=2,hh.length=I,E=G>>>0>>>3,G=0;G>>0];return(m?th[m]:Lf[l])(...hh)}function K_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):Yh(dn[l])}function H_(l){}var xp=(l,m)=>{var E=lh[l];if(E===void 0)throw l=qm(l),E=cn(l),hn(l),new Xn(`${m} has unknown type ${E}`);return E},Tm=(l,m,E)=>{var I=[];return l=l.toWireType(I,E),I.length&&(d()[m>>>2>>>0]=Ls(I)),l};function q_(l,m,E){return m>>>=0,E>>>=0,l=Cs(l>>>0),m=xp(m,"emval::as"),Tm(m,E,l)}function X_(l,m){return m>>>=0,l=Cs(l>>>0),(m=xp(m,"emval::as")).toWireType(null,l)}var Ep=l=>{try{l()}catch(m){Hn(m)}},Yn=0,pn=null,xm=0,Pp=[],Em={},Pm={},Q_=0,mh=null,Y_=[];function Cm(l){return function(m){if(!Ir){if(Yn===0){var E=!1,I=!1;m((G=0)=>{if(!Ir&&(xm=G,E=!0,I)){Yn=2,Ep(()=>s_(pn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var we=function(){var bt=i()[pn+8>>>2>>>0];return bt=Rt[Pm[bt]],--zo,bt()}()}catch(bt){we=bt,G=!0}var Ke=!1;if(!pn){var tt=mh;tt&&(mh=null,(G?tt.reject:tt.resolve)(we),Ke=!0)}if(G&&!Ke)throw we}}),I=!0,E||(Yn=1,pn=function(){var G=Ip(65548),we=G+12;d()[G>>>2>>>0]=we,d()[G+4>>>2>>>0]=we+65536,we=Pp[0];var Ke=Em[we];return Ke===void 0&&(Ke=Q_++,Em[we]=Ke,Pm[Ke]=we),we=Ke,i()[G+8>>>2>>>0]=we,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Ep(()=>t_(pn)))}else Yn===2?(Yn=0,Ep(n_),hn(pn),pn=null,Y_.forEach(vm)):Hn(`invalid state: ${Yn}`);return xm}}(m=>{l().then(m)})}function J_(l){return l>>>=0,Cm(()=>(l=Cs(l)).then(Ls))}var Cp=[];function Z_(l,m,E,I){return E>>>=0,I>>>=0,(l=Cp[l>>>0])(null,m=Cs(m>>>0),E,I)}var ef={},kp=l=>{var m=ef[l];return m===void 0?cn(l):m};function tf(l,m,E,I,G){return E>>>=0,I>>>=0,G>>>=0,(l=Cp[l>>>0])(m=Cs(m>>>0),m[E=kp(E)],I,G)}var km=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rf(l){return(l>>>=0)==0?Ls(km()):(l=kp(l),Ls(km()[l]))}var sf=l=>{var m=Cp.length;return Cp.push(l),m},nf=(l,m)=>{for(var E=Array(l),I=0;I>>2>>>0],"parameter "+I);return E},Sm=(l,m)=>Object.defineProperty(m,"name",{value:l});function of(l,m,E){var I=(m=nf(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { +`,we=0,Ke=[];E===0&&Ke.push("obj");for(var tt=["retType"],bt=[I],kt=0;ktWt.name).join(", ")}) => ${I.name}>`,sf(Sm(E,l))}function af(l){return l=kp(l>>>0),Ls(u[l])}function lf(l,m){return m>>>=0,l=Cs(l>>>0),m=Cs(m),Ls(l[m])}function uf(l){9<(l>>>=0)&&(En[l+1]+=1)}function df(){return Ls([])}function cf(l){l=Cs(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function hf(){return Ls({})}function mf(l){for(var m=Cs(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}dh(l)}function _f(l,m,E){m>>>=0,E>>>=0,l=Cs(l>>>0),m=Cs(m),E=Cs(E),l[m]=E}function ff(l,m){return m>>>=0,l=(l=xp(l>>>0,"_emval_take_value")).readValueFromPointer(m),Ls(l)}function gf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var ya=l=>l%4==0&&(l%100!=0||l%400==0),$m=[0,31,60,91,121,152,182,213,244,274,305,335],Am=[0,31,59,90,120,151,181,212,243,273,304,334];function wf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var E=(ya(l.getFullYear())?$m:Am)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=E,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var I=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=I&&l.getTimezoneOffset()==Math.min(I,E)),i()[m+32>>>2>>>0]=l}function yf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),E=i()[l+32>>>2>>>0],I=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),we=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ke=Math.min(we,G);return 0>E?i()[l+32>>>2>>>0]=+(G!=we&&Ke==I):0>>2>>>0]=m.getDay(),E=(ya(m.getFullYear())?$m:Am)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=E,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Im(l,m,E,I,G,we,Ke){return Z?Or(16,1,l,m,E,I,G,we,Ke):-52}function Om(l,m,E,I,G,we){if(Z)return Or(17,1,l,m,E,I,G,we)}function Mf(l,m,E,I){l>>>=0,m>>>=0,E>>>=0,I>>>=0;var G=new Date().getFullYear(),we=new Date(G,0,1),Ke=new Date(G,6,1);G=we.getTimezoneOffset();var tt=Ke.getTimezoneOffset(),bt=Math.max(G,tt);d()[l>>>2>>>0]=60*bt,i()[m>>>2>>>0]=+(G!=tt),we=(l=kt=>kt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(we),Ke=l(Ke),tt{_h.length=0;for(var E;E=n()[l++>>>0];){var I=E!=105;m+=(I&=E!=112)&&m%8?4:0,_h.push(E==112?d()[m>>>2>>>0]:E==106?Hr[m>>>3]:E==105?i()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=I?8:4}return _h};function bf(l,m,E){return l>>>=0,m=Fm(m>>>0,E>>>0),th[l](...m)}function vf(l,m,E){return l>>>=0,m=Fm(m>>>0,E>>>0),th[l](...m)}var Tf=()=>{},xf=()=>Date.now();function Ef(l,m){return Ct(zr(l>>>0,m>>>0))}var Dm,Pf=()=>{throw zo+=1,"unwind"};function Cf(){return 4294901760}Dm=()=>performance.timeOrigin+performance.now();var kf=()=>navigator.hardwareConcurrency;function Sf(){return Hn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function $f(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var I=m*(1+.2/E);I=Math.min(I,l+100663296);var G=Math;I=Math.max(l,I);e:{G=(G.min.call(G,4294901760,I+(65536-I%65536)%65536)-jt.buffer.byteLength+65535)/65536;try{jt.grow(G),Er();var we=1;break e}catch{}we=void 0}if(we)return!0}return!1}var Sp=()=>(Hn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),kc={},Lm=l=>{l.forEach(m=>{Sp()})};function Af(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),Lm(l),kc.Qb=Sp(),kc.fc=l,kc.Qb}function If(l,m,E){if(l>>>=0,m>>>=0,kc.Qb==l)var I=kc.fc;else(I=Error().stack.toString().split(` +`))[0]=="Error"&&I.shift(),Lm(I);for(var G=3;I[G]&&Sp()!=l;)++G;for(l=0;l>>2>>>0]=Sp();return l}var fh,gh={},zm=()=>{if(!fh){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Ae};for(l in gh)gh[l]===void 0?delete m[l]:m[l]=gh[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);fh=E}return fh};function Bm(l,m){if(Z)return Or(18,1,l,m);l>>>=0,m>>>=0;var E=0;return zm().forEach((I,G)=>{var we=m+E;for(G=d()[l+4*G>>>2>>>0]=we,we=0;we>>0]=I.charCodeAt(we);r()[G>>>0]=0,E+=I.length+1}),0}function Rm(l,m){if(Z)return Or(19,1,l,m);l>>>=0,m>>>=0;var E=zm();d()[l>>>2>>>0]=E.length;var I=0;return E.forEach(G=>I+=G.length+1),d()[m>>>2>>>0]=I,0}function Nm(l){return Z?Or(20,1,l):52}function jm(l,m,E,I){return Z?Or(21,1,l,m,E,I):52}function Um(l,m,E,I){return Z?Or(22,1,l,m,E,I):70}var Of=[null,[],[]];function Vm(l,m,E,I){if(Z)return Or(23,1,l,m,E,I);m>>>=0,E>>>=0,I>>>=0;for(var G=0,we=0;we>>2>>>0],tt=d()[m+4>>>2>>>0];m+=8;for(var bt=0;bt>>0],Wt=Of[l];kt===0||kt===10?((l===1?Yt:Ct)(nm(Wt,0)),Wt.length=0):Wt.push(kt)}G+=tt}return d()[I>>>2>>>0]=G,0}var Wm=[31,29,31,30,31,30,31,31,30,31,30,31],Gm=[31,28,31,30,31,30,31,31,30,31,30,31],Ff=(l,m)=>{r().set(l,m>>>0)};function Km(l,m,E,I){function G(Ve,ar,Br){for(Ve=typeof Ve=="number"?Ve.toString():Ve||"";Ve.lengthi_?-1:0Ro-Ve.getDate())){Ve.setDate(Ve.getDate()+ar);break}ar-=Ro-Ve.getDate()+1,Ve.setDate(1),11>Br?Ve.setMonth(Br+1):(Ve.setMonth(0),Ve.setFullYear(Ve.getFullYear()+1))}return Br=new Date(Ve.getFullYear()+1,0,4),ar=tt(new Date(Ve.getFullYear(),0,4)),Br=tt(Br),0>=Ke(ar,Ve)?0>=Ke(Br,Ve)?Ve.getFullYear()+1:Ve.getFullYear():Ve.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,I>>>=0;var kt=d()[I+40>>>2>>>0];for(var Wt in I={lc:i()[I>>>2>>>0],kc:i()[I+4>>>2>>>0],Ib:i()[I+8>>>2>>>0],Mb:i()[I+12>>>2>>>0],Jb:i()[I+16>>>2>>>0],Db:i()[I+20>>>2>>>0],vb:i()[I+24>>>2>>>0],Cb:i()[I+28>>>2>>>0],sc:i()[I+32>>>2>>>0],jc:i()[I+36>>>2>>>0],mc:kt?zr(kt):""},E=zr(E),kt={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})E=E.replace(new RegExp(Wt,"g"),kt[Wt]);var pr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Mr="January February March April May June July August September October November December".split(" ");for(Wt in kt={"%a":Ve=>pr[Ve.vb].substring(0,3),"%A":Ve=>pr[Ve.vb],"%b":Ve=>Mr[Ve.Jb].substring(0,3),"%B":Ve=>Mr[Ve.Jb],"%C":Ve=>we((Ve.Db+1900)/100|0,2),"%d":Ve=>we(Ve.Mb,2),"%e":Ve=>G(Ve.Mb,2," "),"%g":Ve=>bt(Ve).toString().substring(2),"%G":bt,"%H":Ve=>we(Ve.Ib,2),"%I":Ve=>((Ve=Ve.Ib)==0?Ve=12:12{for(var ar=0,Br=0;Br<=Ve.Jb-1;ar+=(ya(Ve.Db+1900)?Wm:Gm)[Br++]);return we(Ve.Mb+ar,3)},"%m":Ve=>we(Ve.Jb+1,2),"%M":Ve=>we(Ve.kc,2),"%n":()=>` +`,"%p":Ve=>0<=Ve.Ib&&12>Ve.Ib?"AM":"PM","%S":Ve=>we(Ve.lc,2),"%t":()=>" ","%u":Ve=>Ve.vb||7,"%U":Ve=>we(Math.floor((Ve.Cb+7-Ve.vb)/7),2),"%V":Ve=>{var ar=Math.floor((Ve.Cb+7-(Ve.vb+6)%7)/7);if(2>=(Ve.vb+371-Ve.Cb-2)%7&&ar++,ar)ar==53&&((Br=(Ve.vb+371-Ve.Cb)%7)==4||Br==3&&ya(Ve.Db)||(ar=1));else{ar=52;var Br=(Ve.vb+7-Ve.Cb-1)%7;(Br==4||Br==5&&ya(Ve.Db%400-1))&&ar++}return we(ar,2)},"%w":Ve=>Ve.vb,"%W":Ve=>we(Math.floor((Ve.Cb+7-(Ve.vb+6)%7)/7),2),"%y":Ve=>(Ve.Db+1900).toString().substring(2),"%Y":Ve=>Ve.Db+1900,"%z":Ve=>{var ar=0<=(Ve=Ve.jc);return Ve=Math.abs(Ve)/60,(ar?"+":"-")+("0000"+(Ve/60*100+Ve%60)).slice(-4)},"%Z":Ve=>Ve.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),kt)E.includes(Wt)&&(E=E.replace(new RegExp(Wt,"g"),kt[Wt](I)));return Wt=function(Ve){var ar=Array(ih(Ve)+1);return am(Ve,ar,0,ar.length),ar}(E=E.replace(/\0\0/g,"%")),Wt.length>m?0:(Ff(Wt,l),Wt.length-1)}function Df(l,m,E,I){return Km(l>>>0,m>>>0,E>>>0,I>>>0)}Z||function(){for(var l=u.numThreads-1;l--;)em();Kn.unshift(()=>{Pc++,function(m){Z?m():Promise.all(qn.map(Zh)).then(m)}(()=>Uh())})}();for(var Hm=Array(256),$p=0;256>$p;++$p)Hm[$p]=String.fromCharCode($p);ym=Hm,Xn=u.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},u.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},En.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>En.length/2-5-uh.length;var Lf=[nh,Xh,tm,om,im,lm,um,dm,cm,pm,hm,mm,_m,fm,gm,wm,Im,Om,Bm,Rm,Nm,jm,Um,Vm],Rt=function(){function l(E,I){return Rt=E.exports,Rt=function(){var G=Rt,we={};for(let[Ke,tt]of Object.entries(G))we[Ke]=typeof tt=="function"?(...bt)=>{Pp.push(Ke);try{return tt(...bt)}finally{Ir||(Pp.pop(),pn&&Yn===1&&Pp.length===0&&(Yn=0,zo+=1,Ep(r_),typeof Fibers<"u"&&Fibers.tc()))}}:tt;return we}(),Rt=function(){var G=Rt,we=tt=>bt=>tt(bt)>>>0,Ke=tt=>()=>tt()>>>0;return(G=Object.assign({},G)).Da=we(G.Da),G.gb=Ke(G.gb),G.ib=we(G.ib),G.emscripten_main_runtime_thread_id=Ke(G.emscripten_main_runtime_thread_id),G.tb=we(G.tb),G.ub=Ke(G.ub),G}(),Qh.push(Rt.jb),Ec.unshift(Rt.Ca),vr=I,Uh(),Rt}var m=Hh();if(Pc++,u.instantiateWasm)try{return u.instantiateWasm(m,l)}catch(E){Ct(`Module.instantiateWasm callback failed with error: ${E}`),S(E)}return eh||(eh=u.locateFile?Vh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ge):Ge+"ort-wasm-simd-threaded.jsep.wasm":new URL(s("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),s.b).href),function(E,I){var G=eh;return lt||typeof WebAssembly.instantiateStreaming!="function"||Vh(G)||Wh(G)||typeof fetch!="function"?Kh(G,E,I):fetch(G,{credentials:"same-origin"}).then(we=>WebAssembly.instantiateStreaming(we,E).then(I,function(Ke){return Ct(`wasm streaming compile failed: ${Ke}`),Ct("falling back to ArrayBuffer instantiation"),Kh(G,E,I)}))}(m,function(E){l(E.instance,E.module)}).catch(S),{}}(),qm=l=>(qm=Rt.Da)(l),Xm=()=>(Xm=Rt.Ea)();u._OrtInit=(l,m)=>(u._OrtInit=Rt.Fa)(l,m),u._OrtGetLastError=(l,m)=>(u._OrtGetLastError=Rt.Ga)(l,m),u._OrtCreateSessionOptions=(l,m,E,I,G,we,Ke,tt,bt,kt)=>(u._OrtCreateSessionOptions=Rt.Ha)(l,m,E,I,G,we,Ke,tt,bt,kt),u._OrtAppendExecutionProvider=(l,m)=>(u._OrtAppendExecutionProvider=Rt.Ia)(l,m),u._OrtAddFreeDimensionOverride=(l,m,E)=>(u._OrtAddFreeDimensionOverride=Rt.Ja)(l,m,E),u._OrtAddSessionConfigEntry=(l,m,E)=>(u._OrtAddSessionConfigEntry=Rt.Ka)(l,m,E),u._OrtReleaseSessionOptions=l=>(u._OrtReleaseSessionOptions=Rt.La)(l),u._OrtCreateSession=(l,m,E)=>(u._OrtCreateSession=Rt.Ma)(l,m,E),u._OrtReleaseSession=l=>(u._OrtReleaseSession=Rt.Na)(l),u._OrtGetInputOutputCount=(l,m,E)=>(u._OrtGetInputOutputCount=Rt.Oa)(l,m,E),u._OrtGetInputName=(l,m)=>(u._OrtGetInputName=Rt.Pa)(l,m),u._OrtGetOutputName=(l,m)=>(u._OrtGetOutputName=Rt.Qa)(l,m),u._OrtFree=l=>(u._OrtFree=Rt.Ra)(l),u._OrtCreateTensor=(l,m,E,I,G,we)=>(u._OrtCreateTensor=Rt.Sa)(l,m,E,I,G,we),u._OrtGetTensorData=(l,m,E,I,G)=>(u._OrtGetTensorData=Rt.Ta)(l,m,E,I,G),u._OrtReleaseTensor=l=>(u._OrtReleaseTensor=Rt.Ua)(l),u._OrtCreateRunOptions=(l,m,E,I)=>(u._OrtCreateRunOptions=Rt.Va)(l,m,E,I),u._OrtAddRunConfigEntry=(l,m,E)=>(u._OrtAddRunConfigEntry=Rt.Wa)(l,m,E),u._OrtReleaseRunOptions=l=>(u._OrtReleaseRunOptions=Rt.Xa)(l),u._OrtCreateBinding=l=>(u._OrtCreateBinding=Rt.Ya)(l),u._OrtBindInput=(l,m,E)=>(u._OrtBindInput=Rt.Za)(l,m,E),u._OrtBindOutput=(l,m,E,I)=>(u._OrtBindOutput=Rt._a)(l,m,E,I),u._OrtClearBoundOutputs=l=>(u._OrtClearBoundOutputs=Rt.$a)(l),u._OrtReleaseBinding=l=>(u._OrtReleaseBinding=Rt.ab)(l),u._OrtRunWithBinding=(l,m,E,I,G)=>(u._OrtRunWithBinding=Rt.bb)(l,m,E,I,G),u._OrtRun=(l,m,E,I,G,we,Ke,tt)=>(u._OrtRun=Rt.cb)(l,m,E,I,G,we,Ke,tt),u._OrtEndProfiling=l=>(u._OrtEndProfiling=Rt.db)(l),u._JsepOutput=(l,m,E)=>(u._JsepOutput=Rt.eb)(l,m,E),u._JsepGetNodeName=l=>(u._JsepGetNodeName=Rt.fb)(l);var Ap,Ma=()=>(Ma=Rt.gb)(),hn=u._free=l=>(hn=u._free=Rt.hb)(l),Ip=u._malloc=l=>(Ip=u._malloc=Rt.ib)(l),wh=(l,m,E,I,G,we)=>(wh=Rt.lb)(l,m,E,I,G,we),Qm=()=>(Qm=Rt.mb)(),Ym=(l,m,E,I,G)=>(Ym=Rt.nb)(l,m,E,I,G),yh=l=>(yh=Rt.ob)(l),Op=l=>(Op=Rt.pb)(l),Jm=()=>(Jm=Rt.qb)(),Zm=(l,m)=>(Zm=Rt.rb)(l,m),Fp=l=>(Fp=Rt.sb)(l),Mh=l=>(Mh=Rt.tb)(l),bh=()=>(bh=Rt.ub)(),e_=u.dynCall_ii=(l,m)=>(e_=u.dynCall_ii=Rt.wb)(l,m),t_=l=>(t_=Rt.xb)(l),r_=()=>(r_=Rt.yb)(),s_=l=>(s_=Rt.zb)(l),n_=()=>(n_=Rt.Ab)();function o_(){0bh(),u.stackRestore=l=>Fp(l),u.stackAlloc=l=>Mh(l),u.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":r()[l>>>0]=m;break;case"i16":o()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":Hr[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":d()[l>>>2>>>0]=m;break;default:Hn(`invalid type for setValue: ${E}`)}},u.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return r()[l>>>0];case"i16":return o()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return Hr[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return d()[l>>>2>>>0];default:Hn(`invalid type for getValue: ${m}`)}},u.UTF8ToString=zr,u.stringToUTF8=wa,u.lengthBytesUTF8=ih,Cc=function l(){Ap||o_(),Ap||(Cc=l)},o_(),u.PTR_SIZE=4,B}),Ar=kr,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&kr()}),os,Xs,zs,Ms,Nt,Qs,ks,Bs,Ss=w(()=>{var e,t;st(),os=import.meta.url??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Xs=typeof location>"u"?void 0:location.origin,zs=(r,n)=>{try{let o=n??os;return(o?new URL(r,o):new URL(r)).origin===Xs}catch{return!1}},Ms=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Nt=(At(),M(pt)).default,Qs=async()=>{if(!os)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zs(os))return[void 0,Nt()];let r=await Ms(os);return[r,Nt(r)]},ks=(Qr(),M(nr)).default,Bs=async(r,n,o)=>[void 0,ks]}),is,$s,cs,As,Ys,as,nt,_t,Ot=w(()=>{Ss(),$s=!1,cs=!1,As=!1,Ys=()=>{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}},as=()=>{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}},nt=async e=>{if($s)return Promise.resolve();if(cs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(As)throw new Error("previous call to 'initializeWebAssembly()' failed.");cs=!0;let t=e.initTimeout,r=e.numThreads;if(!as())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Ys();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let o=e.wasmPaths,a=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,d=(i==null?void 0:i.href)??i,p=o==null?void 0:o.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[S,u]=await Bs(d,a,r>1),B=!1,R=[];if(t>0&&R.push(new Promise(j=>{setTimeout(()=>{B=!0,j()},t)})),R.push(new Promise((j,Z)=>{let te={numThreads:r};k?te.wasmBinary=k:(h||a)&&(te.locateFile=(X,_e)=>h??(a??_e)+X),u(te).then(X=>{cs=!1,$s=!0,is=X,j(),S&&URL.revokeObjectURL(S)},X=>{cs=!1,As=!0,Z(X)})})),await Promise.race(R),B)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},_t=()=>{if($s&&is)return is;throw new Error("WebAssembly is not initialized yet.")}}),lr,bs,tr,ts=w(()=>{Ot(),lr=(e,t)=>{let r=_t(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},bs=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,a])=>{let i=t?t+o:o;if(typeof a=="object")bs(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},tr=e=>{let t=_t(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let a=Number(t.getValue(o,n===4?"i32":"i64")),i=t.getValue(o+n,"*"),d=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(r)}}}),Rs,Js=w(()=>{Ot(),ts(),Rs=e=>{let t=_t(),r=0,n=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=lr(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,a),r===0&&tr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&bs(e.extra,"",new WeakSet,(i,d)=>{let p=lr(i,n),h=lr(d,n);t._OrtAddRunConfigEntry(r,p,h)!==0&&tr(`Can't set a run config entry: ${i} - ${d}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),Ns,vs,Sn,js,$n,Jn=w(()=>{Ot(),ts(),Ns=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}`)}},vs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Sn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},js=(e,t,r)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let d=lr("deviceType",r),p=lr(i,r);_t()._OrtAddSessionConfigEntry(e,d,p)!==0&&tr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let d=lr("preferredLayout",r),p=lr(i.preferredLayout,r);_t()._OrtAddSessionConfigEntry(e,d,p)!==0&&tr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=lr(o,r);_t()._OrtAppendExecutionProvider(e,a)!==0&&tr(`Can't append execution provider: ${o}.`)}},$n=e=>{let t=_t(),r=0,n=[],o=e||{};Sn(o);try{let a=Ns(o.graphOptimizationLevel??"all"),i=vs(o.executionMode??"sequential"),d=typeof o.logId=="string"?lr(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof o.optimizedModelFilePath=="string"?lr(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,d,p,h,k),r===0&&tr("Can't create session options."),o.executionProviders&&js(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let S=lr("enableGraphCapture",n),u=lr(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,S,u)!==0&&tr(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[S,u]of Object.entries(o.freeDimensionOverrides)){if(typeof S!="string")throw new Error(`free dimension override name must be a string: ${S}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let B=lr(S,n);t._OrtAddFreeDimensionOverride(r,B,u)!==0&&tr(`Can't set a free dimension override: ${S} - ${u}.`)}return o.extra!==void 0&&bs(o.extra,"",new WeakSet,(S,u)=>{let B=lr(S,n),R=lr(u,n);t._OrtAddSessionConfigEntry(r,B,R)!==0&&tr(`Can't set a session config entry: ${S} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&tr("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Us,Ts,ls,mn,Zs,_n,en,xs,zt=w(()=>{Us=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}`)}},Ts=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}`)}},ls=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,a)=>o*a,1);return r>0?Math.ceil(n*r):void 0},mn=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}`)}},Zs=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}`)}},_n=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",en=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",xs=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),fn,An=w(()=>{st(),fn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(d){if(d instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw d}let i=0;for(;;){let{done:d,value:p}=await o.read();if(d)break;let h=p.byteLength;new Uint8Array(a,i,h).set(p),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),In,On,Vs,Fn,gn,Dn,ir,Yr=w(()=>{zt(),In=["V","I","W","E","F"],On=(e,t)=>{console.log(`[${In[e]},${new Date().toISOString()}]${t}`)},gn=(e,t)=>{Vs=e,Fn=t},Dn=(e,t)=>{let r=Zs(e),n=Zs(Vs);r>=n&&On(r,typeof t=="function"?t():t)},ir=(...e)=>{Fn&&Dn(...e)}}),wn,Ln=w(()=>{zt(),wn=(e,t)=>new(mn(t))(e)}),yn=w(()=>{}),Mn,Ee,P,H,ae,Me,Ce,He,ct,yt=w(()=>{Yr(),yn(),Mn=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]]),Ee=[],P=e=>Math.ceil(Number(e)/16)*16,H=e=>{for(let t=0;tae++,Ce=async(e,t,r,n)=>{let o=P(r),a=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,o),e.flush(),await a.mapAsync(GPUMapMode.READ);let d=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(d,0,r)),p}else return new Uint8Array(d.slice(0,r))}finally{a.destroy()}},He=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Mn)Ee.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let r=t.buffer,n=t.byteOffset,o=t.byteLength,a=P(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(r,n,o)),d.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(d,0,i.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),d.destroy(),ir("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=P(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return ir("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else n=Me();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ir("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ir("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=H(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||a){let d=(o?this.freeBuffers:this.freeUniformBuffers).get(r);d?d.length>0?n=d.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let i={id:Me(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),ir("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,r=this.storageCache.get(t);if(!r){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return ir("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(e,t){let r=this.storageCache.get(Number(e));if(!r)throw new Error("data does not exist");await Ce(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Mn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(ir("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ct=(...e)=>new He(...e)}),ht,it,Pt=w(()=>{ht=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}},it=e=>new ht(e)}),hr,rr,$e,wr,Rr,Jr,Zr,Bt=w(()=>{hr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},rr=class{static calcShape(e,t,r=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||o<2)return;let d=hr.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[i[a-2],i[a-1]]=d}for(let d=r?3:1;d<=a;d++){let p=n-d<0?1:e[n-d],h=o-d<0?1:t[o-d];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)i[a-d]=Math.max(p,h);else{if(k>1)return;i[a-d]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let o=1;o<=r;o++)if(e[r-o]!==1&&e[r-o]!==t[n-o])return!1;return!0}},$e=class Dp{static size(t){return Dp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){o[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");o[a]=1,r/=t[a],a--}for(a--;a>=0;a--)o[a]=t[a];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Dp.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Dp.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let a=r;a=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,a)=>o+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},wr=class Sc{static adjustPoolAttributes(t,r,n,o,a,i){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d=n.length?n.push(r[d+2]):n[d]=r[d+2];for(let d=0;d=n[d]||i[d+n.length]>=n[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,o,a,i,d){if(d){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{zt(),Bt(),Nr=64,ps=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},er=(e,t=1)=>{let r=ps(e,t);return typeof r=="string"?r:r[0]},mr=(e,t=1)=>{let r=ps(e,t);return typeof r=="string"?r:r[1]},vt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:$e.computeStrides(r)})}),t},yr=e=>e%4===0?4:e%2===0?2:1,Es=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Fr=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,qr=(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,Mt=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,br=(e,t,r,n,o)=>{let a=typeof r=="number",i=a?r:r.length,d=[...new Array(i).keys()],p=i<2?"u32":i<=4?`vec${i}`:`array`,h=ps(t,o),k=typeof h=="string"?h:h[1],S=typeof h=="string"?h:h[0],u={indices:p,value:k,storage:S,tensor:t},B=ot=>typeof ot=="string"?ot:`${ot}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},j=a?"uniforms.":"",Z=`${j}${e}_shape`,te=`${j}${e}_strides`,X="";for(let ot=0;ot ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${X} + return indices; + }`,me=ot=>(R.offsetToIndices=!0,i<2?ot:`o2i_${e}(${ot})`),ye=[];if(i>=2)for(let ot=i-1;ot>=0;ot--)ye.push(`${Mt(te,ot,i)} * (indices[${ot}])`);let Ae=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${ye.join("+")}; + }`,Ie=ot=>(R.indicesToOffset=!0,i<2?ot:`i2o_${e}(${ot})`),Ge=(...ot)=>i===0?"0u":`${u.indices}(${ot.map(B).join(",")})`,lt=(ot,Et)=>i<2?`${ot}`:`${Mt(ot,Et,i)}`,xt=(ot,Et,cr)=>i<2?`${ot}=${cr};`:`${Mt(ot,Et,i)}=${cr};`,Kt={},Yt=(ot,Et)=>{R.broadcastedIndicesToOffset=!0;let cr=`${Et.name}broadcastedIndicesTo${e}Offset`;if(cr in Kt)return`${cr}(${ot})`;let Lr=[];for(let ys=i-1;ys>=0;ys--){let Hr=Et.indicesGet("outputIndices",ys+Et.rank-i);Lr.push(`${lt(te,ys)} * (${Hr} % ${lt(Z,ys)})`)}return Kt[cr]=`fn ${cr}(outputIndices: ${Et.type.indices}) -> u32 { + return ${Lr.length>0?Lr.join("+"):"0u"}; + }`,`${cr}(${ot})`},Ct=(ot,Et)=>(()=>{if(u.storage===u.value)return`${e}[${ot}]=${Et};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${ot}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${ot}]=vec2(u32(${Et}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Jt=ot=>(()=>{if(u.storage===u.value)return`${e}[${ot}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${ot}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${ot}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${ot}] & 0xFFu), bool(${e}[${ot}] & 0xFF00u), bool(${e}[${ot}] & 0xFF0000u), bool(${e}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),$t=i<2?"":` + fn get_${e}ByIndices(indices: ${u.indices}) -> ${k} { + return ${Jt(`i2o_${e}(indices)`)}; + }`,jt=i<2?"":(()=>{let ot=d.map(cr=>`d${cr}: u32`).join(", "),Et=d.map(cr=>`d${cr}`).join(", ");return` + fn get_${e}(${ot}) -> ${k} { + return get_${e}ByIndices(${Ge(Et)}); + }`})(),vr=(...ot)=>{if(ot.length!==i)throw new Error(`indices length must be ${i}`);let Et=ot.map(B).join(",");return i===0?Jt("0u"):i===1?Jt(Et[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}(${Et})`)},Ht=ot=>i<2?Jt(ot):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${e}ByIndices(${ot})`),Gt=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${k}) { + ${Ct(`i2o_${e}(indices)`,"value")} + }`,Cr=i<2?"":(()=>{let ot=d.map(cr=>`d${cr}: u32`).join(", "),Et=d.map(cr=>`d${cr}`).join(", ");return` + fn set_${e}(${ot}, value: ${k}) { + set_${e}ByIndices(${Ge(Et)}, value); + }`})();return{impl:()=>{let ot=[],Et=!1;return R.offsetToIndices&&(ot.push(_e),Et=!0),R.indicesToOffset&&(ot.push(Ae),Et=!0),R.broadcastedIndicesToOffset&&(Object.values(Kt).forEach(cr=>ot.push(cr)),Et=!0),R.set&&(ot.push(Cr),Et=!0),R.setByIndices&&(ot.push(Gt),Et=!0),R.get&&(ot.push(jt),Et=!0),R.getByIndices&&(ot.push($t),Et=!0),!a&&Et&&ot.unshift(`const ${Z} = ${u.indices}(${r.join(",")});`,`const ${te} = ${u.indices}(${$e.computeStrides(r).join(",")});`),ot.join(` +`)},type:u,offsetToIndices:me,indicesToOffset:Ie,broadcastedIndicesToOffset:Yt,indices:Ge,indicesGet:lt,indicesSet:xt,set:(...ot)=>{if(ot.length!==i+1)throw new Error(`indices length must be ${i}`);let Et=ot[i];if(typeof Et!="string")throw new Error("value must be string");let cr=ot.slice(0,i).map(B).join(",");return i===0?Ct("0u",Et):i===1?Ct(cr[0],Et):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}(${cr}, ${Et})`)},setByOffset:Ct,setByIndices:(ot,Et)=>i<2?Ct(ot,Et):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${e}ByIndices(${ot}, ${Et});`),get:vr,getByOffset:Jt,getByIndices:Ht,usage:n,name:e,strides:te,shape:Z,rank:i}},ze=(e,t,r,n=1)=>br(e,t,r,"input",n),wt=(e,t,r,n=1)=>br(e,t,r,"output",n),rs=(e,t,r)=>br(e,t,r,"atomicOutput",1),tn=(e,t,r,n=1)=>br(e,t,r,"internal",n),Zn=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Nr){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) + fn main(${a}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let r=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,r=1){return this.uniforms.push({name:e,type:t,length:r}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},bn=(e,t)=>new Zn(e,t)}),Ta,No,xa,Ea,jo,Pa,ss,Uo,Ca,Ws=w(()=>{zt(),Bt(),Pt(),Qt(),Ta=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},No=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,xa=(e,t)=>$e.sortBasedOnPerm(e,No(e.length,t)),Ea=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=No(n,t),a=xa(e.dims,o),i=e.dims,d=a,p=n<2||Pa(o,e.dims),h;if(p)return h=R=>{let j=ze("input",r,i,4),Z=wt("output",r,d,4);return` + ${R.registerUniform("output_size","u32").declareVariables(j,Z)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=$e.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:h};let{newShape:k,newPerm:S}=jo(e.dims,o),u=$e.areEqual(S,[2,3,1]),B=$e.areEqual(S,[3,1,2]);if(k.length===2||u||B){i=u?[k[0],k[1]*k[2]]:B?[k[0]*k[1],k[2]]:k,d=[i[1],i[0]];let R=16;return h=j=>{let Z=ze("a",r,i.length),te=wt("output",r,d.length);return` + ${j.registerUniform("output_size","u32").declareVariables(Z,te)} + var tile : array, ${R}>; + ${j.mainStart([R,R,1])} + let stride = (uniforms.output_shape[1] - 1) / ${R} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${R}u + local_id.x; + let input_row = workgroup_id_x * ${R}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${R}u + local_id.x; + let output_row = workgroup_id_y * ${R}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${te.setByIndices(`${te.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let j=$e.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d[1]/R),y:Math.ceil(d[0]/R)},programUniforms:[{type:12,data:j},...vt(i,d)]}},getShaderSource:h}}return h=R=>{let j=ze("a",r,i.length),Z=wt("output",r,d.length);return` + ${R.registerUniform("output_size","u32").declareVariables(j,Z)} + + ${Ea(o,n,j,Z)} + + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${Z.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${Z.setByOffset("global_idx",j.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let R=$e.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(i,d)]}},getShaderSource:h}},Uo=(e,t)=>{Ta(e.inputs),e.compute(ss(e.inputs[0],t.perm))},Ca=e=>it({perm:e.perm})}),Vo,Oc,ka,Wo,Sa,eo,$a,Aa,Ia,Oa,hs,Fa,Da,Go,La,Ko,rn,za,Fc,Ba,Dc,Lc=w(()=>{zt(),Bt(),Qt(),ei(),Ws(),Vo={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"},Oc={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"},ka={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Wo={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Sa=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,o]},$a=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let a=0;a{for(let r=0;r{let r=[];if(!Aa(e,t)){for(let n=0;nr.push(n))}return r},Oa=(e,t,r,n,o,a,i)=>{let d=r[0].dims,p=$e.size(a),h=$e.size(i),k=ze("_A",r[0].dataType,d),S=wt("output",o,a),u=64;p===1&&(u=256);let B=` + var aBestValues : array; + `,R=j=>` + ${j.registerUniform("reduceSize","u32").declareVariables(k,S)} + ${B} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${j.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${ka[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${k.getByOffset("offset + k")}); + bestValue = ${Vo[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${u}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${Oc[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${S.setByOffset("outputIndex",`${n==="mean"?`${S.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${S.type.storage}(${Wo[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${u}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},hs=(e,t,r,n)=>{let o=e.inputs.length===1?r:Ho(e.inputs,r),a=o.axes;a.length===0&&!o.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((B,R)=>R));let i=$e.normalizeAxes(a,e.inputs[0].dims.length),d=i,p=e.inputs[0],h=Ia(d,e.inputs[0].dims.length);h.length>0&&(p=e.compute(ss(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=Sa(d.length,p.dims.length));let[k,S]=eo(p.dims,d),u=k;o.keepDims&&(u=$a(k,i)),e.compute(Oa(t,o.cacheKey,[p],n,e.inputs[0].dataType,u,S),{inputs:[p]})},Fa=(e,t)=>{hs(e,"ReduceMeanShared",t,"mean")},Da=(e,t)=>{hs(e,"ReduceL1Shared",t,"l1")},Go=(e,t)=>{hs(e,"ReduceL2Shared",t,"l2")},La=(e,t)=>{hs(e,"ReduceLogSumExpShared",t,"logSumExp")},Ko=(e,t)=>{hs(e,"ReduceMaxShared",t,"max")},rn=(e,t)=>{hs(e,"ReduceMinShared",t,"min")},za=(e,t)=>{hs(e,"ReduceProdShared",t,"prod")},Fc=(e,t)=>{hs(e,"ReduceSumShared",t,"sum")},Ba=(e,t)=>{hs(e,"ReduceSumSquareShared",t,"sumSquare")},Dc=(e,t)=>{hs(e,"ReduceLogSumShared",t,"logSum")}}),us,Ra,to,Ho,ms,Na,ro,ja,Ua,Va,qo,Wa,Ga,Xo,Ka,_s,Qo,Ha,qa,Yo,Xa,Qa,Jo,Ya,Ja,Zo,ei=w(()=>{zt(),Bt(),Pt(),Qt(),Lc(),us=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.")},Ra=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],to=(e,t,r,n,o,a,i=!1,d=!1)=>{let p=[],h=r[0].dims,k=h.length,S=$e.normalizeAxes(o,k),u=!d&&S.length===0;h.forEach((j,Z)=>{u||S.indexOf(Z)>=0?i&&p.push(1):p.push(j)});let B=p.length,R=$e.size(p);return{name:e,shaderCache:t,getShaderSource:j=>{let Z=[],te=ze("_A",r[0].dataType,k),X=wt("output",a,B),_e=n(te,X,S),me=_e[2];for(let ye=0,Ae=0;ye=0?(i&&Ae++,me=`for(var j${ye}: u32 = 0; j${ye} < ${h[ye]}; j${ye}++) { + ${_e[2].includes("last_index")?`let last_index = j${ye};`:""} + ${te.indicesSet("input_indices",ye,`j${ye}`)} + ${me} + }`):(Z.push(`${te.indicesSet("input_indices",ye,X.indicesGet("output_indices",Ae))};`),Ae++);return` + + ${j.registerUniform("output_size","u32").declareVariables(te,X)} + + ${j.mainStart()} + ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${te.type.indices}; + let output_indices = ${X.offsetToIndices("global_idx")}; + + ${Z.join(` +`)} + ${_e[0]} // init ops for reduce max/min + ${_e[1]} + ${me} + ${_e[3]} + ${_e.length===4?X.setByOffset("global_idx","value"):_e.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...vt(h,p)]})}},Ho=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),it({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},ms=(e,t,r,n)=>{let o=e.inputs,a=o.length===1?r:Ho(o,r);e.compute(to(t,{hint:a.cacheKey,inputDependencies:["rank"]},[o[0]],a.noopWithEmptyAxes&&a.axes.length===0?Ra:n,a.axes,o[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Na=(e,t)=>{us(e.inputs),ms(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},ro=(e,t)=>{us(e.inputs),ms(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},ja=(e,t)=>{us(e.inputs),ms(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ua=(e,t)=>{us(e.inputs),ms(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Va=(e,t)=>{us(e.inputs),ms(e,"ReduceMax",t,(r,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},qo=(e,t)=>{us(e.inputs),ms(e,"ReduceMean",t,(r,n,o)=>{let a=1;for(let i=0;i=0||o.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Wa=(e,t)=>{us(e.inputs),ms(e,"ReduceMin",t,(r,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},Ga=(e,t)=>{us(e.inputs),ms(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Xo=(e,t)=>{us(e.inputs),ms(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Ka=(e,t)=>{us(e.inputs),ms(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},_s=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let a=0;a1024},Qo=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):Fa(e,t)},Ha=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ro(e,t):Da(e,t)},qa=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ja(e,t):Go(e,t)},Yo=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ua(e,t):La(e,t)},Xa=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Va(e,t):Ko(e,t)},Qa=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wa(e,t):rn(e,t)},Jo=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ga(e,t):za(e,t)},Ya=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xo(e,t):Fc(e,t)},Ja=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ka(e,t):Ba(e,t)},Zo=(e,t)=>{_s(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Na(e,t):Dc(e,t)}}),ti,ri,Za,si,el=w(()=>{zt(),Pt(),ei(),ti=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.")},ri=(e,t)=>{ti(e.inputs);let r=(n,o,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(to("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Za=(e,t)=>{ti(e.inputs);let r=(n,o,a)=>{let i=[];for(let d=0;d=0||a.length===0)&&i.push(`input_indices[${d}] = 0;`);return[`${i.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(to("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},si=e=>it(e)}),tl,so,ni,rl,sl,vn,nl,ol,no=w(()=>{zt(),Bt(),yn(),Qt(),tl=(e,t)=>{let r=e[0],n=e[1],o=e[2],a=e[3],i=e[4],d=e[5];if(i&&d)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=r.dims[0],h=r.dims[1],k=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let S=o.dims[0]/3,u=S,B=u;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let _e of t.qkvHiddenSizes)if(_e%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");S=t.qkvHiddenSizes[0],u=t.qkvHiddenSizes[1],B=t.qkvHiddenSizes[2]}let R=h;if(S!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==S+u+B)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let j=0;if(i){if(u!==B)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(j=i.dims[3])}let Z=R+j,te=-1,X=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(d){if(d.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(d.dims[0]!==p||d.dims[1]!==t.numHeads||d.dims[2]!==h||d.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:j,kvSequenceLength:R,totalSequenceLength:Z,maxSequenceLength:te,inputHiddenSize:k,hiddenSize:S,vHiddenSize:B,headSize:Math.floor(S/t.numHeads),vHeadSize:Math.floor(B/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},so=(e,t,r)=>t&&e?` + let total_sequence_length_input = u32(${t.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,ni=(e,t,r,n,o,a,i,d)=>{let p=yr(i?1:a),h=64,k=a/p;k{let X=wt("x",e.dataType,e.dims,p),_e=[X],me=i?ze("seq_lens",i.dataType,i.dims):void 0;me&&_e.push(me);let ye=d?ze("total_sequence_length_input",d.dataType,d.dims):void 0;ye&&_e.push(ye);let Ae=mr(e.dataType),Ie=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${te.registerUniforms(Ie).declareVariables(..._e)} + ${te.mainStart([h,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${so(me,ye,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${R}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${R}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(p){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${h}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${R}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${R}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(p){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${p}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${h}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${X.type.value}(${Ae}(1.0) / ${Ae}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${R}(x[offset + i]); + x[offset + i] = ${X.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${X.type.value}(${Ae}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${B};${p}`,inputDependencies:j},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:o,z:t*r},programUniforms:u})}},rl=(e,t,r,n,o,a,i,d,p)=>{let h=i+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],S=e>1&&n,u=a.kvNumHeads?a.kvNumHeads:a.numHeads,B=S?[a.batchSize,u,h,a.headSize]:void 0,R=a.nReps?a.nReps:1,j=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=yr(a.headSize),te=a.headSize/Z,X=12,_e={x:Math.ceil(h/X),y:Math.ceil(a.sequenceLength/X),z:a.batchSize*a.numHeads},me=[{type:12,data:a.sequenceLength},{type:12,data:te},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:j},{type:12,data:i},{type:12,data:a.kvSequenceLength},{type:12,data:R}],ye=S&&n&&$e.size(n.dims)>0,Ae=["type","type"];ye&&Ae.push("type"),o&&Ae.push("type"),d&&Ae.push("type"),p&&Ae.push("type");let Ie=[{dims:k,dataType:t.dataType,gpuDataType:0}];S&&Ie.push({dims:B,dataType:t.dataType,gpuDataType:0});let Ge=lt=>{let xt=ze("q",t.dataType,t.dims,Z),Kt=ze("key",r.dataType,r.dims,Z),Yt=[xt,Kt];if(ye){let Gt=ze("past_key",n.dataType,n.dims,Z);Yt.push(Gt)}o&&Yt.push(ze("attention_bias",o.dataType,o.dims));let Ct=d?ze("seq_lens",d.dataType,d.dims):void 0;Ct&&Yt.push(Ct);let Jt=p?ze("total_sequence_length_input",p.dataType,p.dims):void 0;Jt&&Yt.push(Jt);let $t=wt("output",t.dataType,k),jt=[$t];S&&jt.push(wt("present_key",t.dataType,B,Z));let vr=mr(1,Z),Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${X}u; + + var tileQ: array<${xt.type.storage}, ${X*X}>; + var tileK: array<${xt.type.storage}, ${X*X}>; + ${lt.registerUniforms(Ht).declareVariables(...Yt,...jt)} + ${lt.mainStart([X,X,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${so(Ct,Jt,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${ye&&S?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${S?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${vr}(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; + ${ye&&S?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${S?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${vr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(Z){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: ${Z}`)}})()}; + output[outputIdx] = ${$t.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${o!==void 0};${n!==void 0};${e}`,inputDependencies:Ae},getRunData:()=>({outputs:Ie,dispatchGroup:_e,programUniforms:me}),getShaderSource:Ge}},sl=(e,t,r,n,o,a,i=void 0,d=void 0)=>{let p=a+o.kvSequenceLength,h=o.nReps?o.nReps:1,k=o.vHiddenSize*h,S=e>1&&n,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,B=S?[o.batchSize,u,p,o.headSize]:void 0,R=[o.batchSize,o.sequenceLength,k],j=12,Z={x:Math.ceil(o.vHeadSize/j),y:Math.ceil(o.sequenceLength/j),z:o.batchSize*o.numHeads},te=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:k},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:h}],X=S&&n&&$e.size(n.dims)>0,_e=["type","type"];X&&_e.push("type"),i&&_e.push("type"),d&&_e.push("type");let me=[{dims:R,dataType:t.dataType,gpuDataType:0}];S&&me.push({dims:B,dataType:t.dataType,gpuDataType:0});let ye=Ae=>{let Ie=ze("probs",t.dataType,t.dims),Ge=ze("v",r.dataType,r.dims),lt=[Ie,Ge];X&<.push(ze("past_value",n.dataType,n.dims));let xt=i?ze("seq_lens",i.dataType,i.dims):void 0;i&<.push(xt);let Kt=d?ze("total_sequence_length_input",d.dataType,d.dims):void 0;d&<.push(Kt);let Yt=[wt("output",t.dataType,R)];S&&Yt.push(wt("present_value",t.dataType,B));let Ct=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${j}u; + var tileQ: array<${Ie.type.value}, ${j*j}>; + var tileV: array<${Ie.type.value}, ${j*j}>; + ${Ae.registerUniforms(Ct).declareVariables(...lt,...Yt)} + ${Ae.mainStart([j,j,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${so(xt,Kt,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${X&&S?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${S?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Ie.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; + ${X&&S?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${S?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:_e},getRunData:()=>({outputs:me,dispatchGroup:Z,programUniforms:te}),getShaderSource:ye}},vn=(e,t,r,n,o,a,i,d,p,h,k=void 0,S=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(d?1:0)),B=u>1?h.pastSequenceLength:0,R=B+h.kvSequenceLength,j=p&&$e.size(p.dims)>0?p:void 0,Z=[t,r];u>1&&i&&$e.size(i.dims)>0&&Z.push(i),j&&Z.push(j),k&&Z.push(k),S&&Z.push(S);let te=e.compute(rl(u,t,r,i,j,h,B,k,S),{inputs:Z,outputs:u>1?[-1,1]:[-1]})[0];e.compute(ni(te,h.batchSize,h.numHeads,B,h.sequenceLength,R,k,S),{inputs:k&&S?[te,k,S]:[te],outputs:[]});let X=[te,n];u>1&&d&&$e.size(d.dims)>0&&X.push(d),k&&X.push(k),S&&X.push(S),e.compute(sl(u,te,n,d,h,B,k,S),{inputs:X,outputs:u>1?[0,2]:[0]})},nl=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,a=t.headSize,i=12,d={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=S=>{let u=wt("output_q",p[0].dataType,r),B=wt("output_k",p[0].dataType,r),R=wt("output_v",p[0].dataType,r),j=ze("input",p[0].dataType,p[0].dims),Z=ze("weight",p[1].dataType,p[1].dims),te=ze("bias",p[2].dataType,p[2].dims),X=j.type.storage,_e=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${X}, ${i*i}>; + var tileWeightQ: array<${X}, ${i*i}>; + var tileWeightK: array<${X}, ${i*i}>; + var tileWeightV: array<${X}, ${i*i}>; + ${S.registerUniforms(_e).declareVariables(j,Z,te,u,B,R)} + ${S.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${X}(0); + var valueK = ${X}(0); + var valueV = ${X}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:d,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},ol=(e,t)=>{let r=tl(e.inputs,t),[n,o,a]=nl(e,r);return vn(e,n,o,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}}),il,al,oi,ll,zc=w(()=>{Qe(),zt(),Bt(),Pt(),Qt(),il=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,o,a)=>{let i=o.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);o.forEach((d,p)=>{if(d!==n[p])throw new Error(`${a}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},al=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,a=e[0].dims,i=n?yr(a[a.length-1]):1,d=o==="NHWC"&&a.length>1?i:1,p=$e.size(a)/i,h=n,k=h?a.length:a,S=ze("x",e[0].dataType,e[0].dims,i),u=ze("scale",e[1].dataType,e[1].dims,d),B=ze("bias",e[2].dataType,e[2].dims,d),R=ze("inputMean",e[3].dataType,e[3].dims,d),j=ze("inputVar",e[4].dataType,e[4].dims,d),Z=wt("y",e[0].dataType,k,i),te=()=>{let _e="";if(n)_e=`let cOffset = ${a.length===1?"0u":o==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")_e=` + ${Z.indicesSet("outputIndices","0","0")} + let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{_e=`var cIndices = ${u.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let me=1;me` + const epsilon = ${r}; + ${_e.registerUniform("outputSize","u32").declareVariables(S,u,B,R,j,Z)} + ${_e.mainStart()} + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${Z.offsetToIndices(`global_idx * ${i}`)}; + ${te()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${B.getByOffset("cOffset")}; + let inputMean = ${R.getByOffset("cOffset")}; + let inputVar = ${j.getByOffset("cOffset")}; + let x = ${S.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${Z.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:X,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...vt(a)]:[{type:12,data:p}]})}},oi=e=>it(e),ll=(e,t)=>{let{inputs:r,outputCount:n}=e,o=oi({...t,outputCount:n});if(T.webgpu.validateInputContent&&il(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(al(r,o))}}),ii,ul,dl,cl=w(()=>{Bt(),Qt(),ii=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")},ul=e=>{let t=e[0].dims,r=e[0].dims[2],n=$e.size(t)/4,o=e[0].dataType,a=ze("input",o,t,4),i=ze("bias",o,[r],4),d=ze("residual",o,t,4),p=wt("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${r}u / 4; + ${h.declareVariables(a,i,d,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},dl=e=>{ii(e.inputs),e.compute(ul(e.inputs))}}),pl,ur,ai,hl,ml,li,_l,fl,ui,gl,wl,di,yl,Ml,ci,bl,zn,vl,oo,pi,Tl,xl,hi,El,Pl,mi,Cl,kl,_i,Sl,$l,fi,Al,Il,gi,wi,Ol,io,yi,Fl,Dl,Ll,Mi,zl,Bl,bi=w(()=>{zt(),Bt(),Pt(),Qt(),pl=(e,t,r,n,o,a,i)=>{let d=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=ze("inputData",r,[d],4),k=wt("outputData",n,[d],4),S=[{name:"vec_size",type:"u32"}];return i&&S.push(...i),` + ${e.registerUniforms(S).declareVariables(h,k)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${h.getByOffset("global_idx")}; + ${k.setByOffset("global_idx",p)} + }`},ur=(e,t,r,n,o,a=e.dataType,i,d)=>{let p=[{type:12,data:Math.ceil($e.size(e.dims)/4)}];return i&&p.push(...i),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>pl(h,$e.size(e.dims),e.dataType,a,r,n,d),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil($e.size(h[0].dims)/64/4)},programUniforms:p})}},ai=e=>{e.compute(ur(e.inputs[0],"Abs","abs"))},hl=e=>{e.compute(ur(e.inputs[0],"Acos","acos"))},ml=e=>{e.compute(ur(e.inputs[0],"Acosh","acosh"))},li=e=>{e.compute(ur(e.inputs[0],"Asin","asin"))},_l=e=>{e.compute(ur(e.inputs[0],"Asinh","asinh"))},fl=e=>{e.compute(ur(e.inputs[0],"Atan","atan"))},ui=e=>{e.compute(ur(e.inputs[0],"Atanh","atanh"))},gl=e=>it(e),wl=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ur(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},di=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return it({min:t,max:r})},yl=(e,t)=>{let r=t||di(e.inputs),n=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Ml=e=>{e.compute(ur(e.inputs[0],"Ceil","ceil"))},ci=e=>{e.compute(ur(e.inputs[0],"Cos","cos"))},bl=e=>{e.compute(ur(e.inputs[0],"Cosh","cosh"))},zn=e=>it(e),vl=(e,t)=>{let r=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},oo=(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)); +}`,pi=e=>{let t=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,oo(t)))},Tl=e=>{e.compute(ur(e.inputs[0],"Exp","exp"))},xl=e=>{e.compute(ur(e.inputs[0],"Floor","floor"))},hi=e=>{let t=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,oo(t)))},El=(e,t)=>{let r=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Pl=e=>{e.compute(ur(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(ur(e.inputs[0],"Neg",t=>`-${t}`))},Cl=e=>{e.compute(ur(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},kl=e=>{let t=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},_i=e=>{e.compute(ur(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Sl=e=>it(e),$l=(e,t)=>{let r=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},fi=e=>{e.compute(ur(e.inputs[0],"Sin","sin"))},Al=e=>{e.compute(ur(e.inputs[0],"Sinh","sinh"))},Il=e=>{e.compute(ur(e.inputs[0],"Sqrt","sqrt"))},gi=e=>{e.compute(ur(e.inputs[0],"Tan","tan"))},wi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ol=e=>{e.compute(ur(e.inputs[0],"Tanh",wi))},io=(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 ${wi("v")}; +} +`,yi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Fl=e=>{let t=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"FastGelu",yi,io(t),void 0,e.inputs[0].dataType))},Dl=(e,t)=>{let r=mr(e.inputs[0].dataType);return e.compute(ur(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Ll=e=>{e.compute(ur(e.inputs[0],"Log","log"))},Mi=(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; +} +`,zl=e=>`quick_gelu_impl(${e})`,Bl=(e,t)=>{let r=mr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"QuickGelu",zl,Mi(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Rl,vi,Nl,Bc=w(()=>{Bt(),Qt(),bi(),Rl=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")},vi=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=ze("input",e[0].dataType,e[0].dims,4),n=ze("bias",e[0].dataType,[e[0].dims[2]],4),o=wt("output",e[0].dataType,t,4),a=$e.size(t)/4,i=er(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:d=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${d.declareVariables(r,n,o)} + + ${oo(i)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Nl=e=>{Rl(e.inputs),e.compute(vi(e.inputs))}}),jl,Ul,ds,Vl,Wl,Gl,Kl,Ti,Hl,ql,xi,Xl,Ql,Yl=w(()=>{zt(),Bt(),Qt(),jl=(e,t,r,n,o,a,i,d,p,h,k,S)=>{let u,B;typeof d=="string"?u=B=(X,_e)=>`${d}((${X}),(${_e}))`:typeof d=="function"?u=B=d:(u=d.scalar,B=d.vector);let R=wt("outputData",k,n.length,4),j=ze("aData",p,t.length,4),Z=ze("bData",h,r.length,4),te;if(o)if(a){let X=$e.size(t)===1,_e=$e.size(r)===1,me=t.length>0&&t[t.length-1]%4===0,ye=r.length>0&&r[r.length-1]%4===0;X||_e?te=R.setByOffset("global_idx",B(X?`${j.type.value}(${j.getByOffset("0")}.x)`:j.getByOffset("global_idx"),_e?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):te=` + let outputIndices = ${R.offsetToIndices("global_idx * 4u")}; + let offsetA = ${j.broadcastedIndicesToOffset("outputIndices",R)}; + let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",R)}; + ${R.setByOffset("global_idx",B(i||me?j.getByOffset("offsetA / 4u"):`${j.type.value}(${j.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||ye?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else te=R.setByOffset("global_idx",B(j.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let X=(_e,me,ye="")=>{let Ae=`aData[indexA${me}][componentA${me}]`,Ie=`bData[indexB${me}][componentB${me}]`;return` + let outputIndices${me} = ${R.offsetToIndices(`global_idx * 4u + ${me}u`)}; + let offsetA${me} = ${j.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; + let offsetB${me} = ${Z.broadcastedIndicesToOffset(`outputIndices${me}`,R)}; + let indexA${me} = offsetA${me} / 4u; + let indexB${me} = offsetB${me} / 4u; + let componentA${me} = offsetA${me} % 4u; + let componentB${me} = offsetB${me} % 4u; + ${_e}[${me}] = ${ye}(${u(Ae,Ie)}); + `};k===9?te=` + var data = vec4(0); + ${X("data",0,"u32")} + ${X("data",1,"u32")} + ${X("data",2,"u32")} + ${X("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:te=` + ${X("outputData[global_idx]",0)} + ${X("outputData[global_idx]",1)} + ${X("outputData[global_idx]",2)} + ${X("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(j,Z,R)} + + ${S??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${te} + }`},Ul=(e,t,r,n,o,a,i=r.dataType)=>{let d=r.dims.map(j=>Number(j)??1),p=n.dims.map(j=>Number(j)??1),h=!$e.areEqual(d,p),k=d,S=$e.size(d),u=!1,B=!1,R=[h];if(h){let j=rr.calcShape(d,p,!1);if(!j)throw new Error("Can't perform binary op on the given tensors");k=j.slice(),S=$e.size(k);let Z=$e.size(d)===1,te=$e.size(p)===1,X=d.length>0&&d[d.length-1]%4===0,_e=p.length>0&&p[p.length-1]%4===0;R.push(Z),R.push(te),R.push(X),R.push(_e);let me=1;for(let ye=1;yej.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:j=>jl(j,d,p,k,u,h,B,o,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:k,dataType:i}],dispatchGroup:{x:Math.ceil(S/64/4)},programUniforms:[{type:12,data:Math.ceil($e.size(k)/4)},...vt(d,p,k)]})}},ds=(e,t,r,n,o,a)=>{e.compute(Ul(t,o??"",e.inputs[0],e.inputs[1],r,n,a))},Vl=e=>{ds(e,"Add",(t,r)=>`${t}+${r}`)},Wl=e=>{ds(e,"Div",(t,r)=>`${t}/${r}`)},Gl=e=>{ds(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Kl=e=>{ds(e,"Mul",(t,r)=>`${t}*${r}`)},Ti=e=>{let t=ze("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ds(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Hl=e=>{ds(e,"Sub",(t,r)=>`${t}-${r}`)},ql=e=>{ds(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},xi=e=>{ds(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Xl=e=>{ds(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ql=e=>{ds(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Jl,Zl,Ei,eu,tu,Pi,Rc=w(()=>{zt(),Bt(),Pt(),Qt(),Jl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],o=n.dataType,a=n.dims.length;e.forEach((i,d)=>{if(d!==r){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},Zl=(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; + }`,Ei=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=$e.size(r),a=new Array(e.length),i=new Array(e.length),d=0,p=[],h=[],k=[{type:12,data:o}];for(let j=0;j`uniforms.sizeInConcatAxis${j}`).join(","),R=j=>` + + ${(()=>{j.registerUniform("outputSize","u32");for(let Z=0;Z(${B}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Ei(i,S)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:k}),getShaderSource:R}},tu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=$e.normalizeAxis(t.axis,n.length);Jl(r,o);let a=n.slice();a[o]=r.reduce((d,p)=>d+(p.dims.length>o?p.dims[o]:0),0);let i=r.filter(d=>$e.size(d.dims)>0);e.compute(eu(i,o,a,r[0].dataType),{inputs:i})},Pi=e=>it({axis:e.axis})}),sn,Is,nn,Ci,Gs=w(()=>{zt(),Bt(),sn=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Is=(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})},nn=(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"})},Ci=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=(e==null?void 0:e.activation_params)||[Jr,Zr];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),Vr,ru,ao=w(()=>{Vr=(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.`)}},ru=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),su,Nc=w(()=>{su=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)); +} +`}),Bn,lo,ki=w(()=>{zt(),Bt(),Qt(),Gs(),Bn=(e,t,r,n,o)=>{let a=n-r;return` + ${Array.from({length:r}).map((i,d)=>` + if (${Mt(t.shape,d,t.rank)} != 1) { + ${t.indicesSet(e,d,Mt(o,d+a,n))} + } else { + ${t.indicesSet(e,d,0)} + }`).join("")} +`},lo=(e,t,r,n,o=!1,a)=>{let i=e[0].dims,d=e[1].dims,p=i[i.length-2],h=d[d.length-1],k=i[i.length-1],S=yr(h),u=yr(k),B=yr(p),R=$e.size(r)/S/B,j=e.length>2,Z=n?n.slice(0,-2):r.slice(0,-2),te=[$e.size(Z),p,h],X=[{type:12,data:R},{type:12,data:p},{type:12,data:h},{type:12,data:k}];Is(t,X),X.push(...vt(Z,i,d)),j&&X.push(...vt(e[2].dims)),X.push(...vt(te));let _e=me=>{let ye=tn("batch_dims",e[0].dataType,Z.length),Ae=ze("a",e[0].dataType,i.length,u),Ie=ze("b",e[1].dataType,d.length,S),Ge=wt("output",e[0].dataType,te.length,S),lt=er(Ge.type.tensor),xt=sn(t,Ge.type.value,lt),Kt=[Ae,Ie],Yt="";if(j){let $t=o?S:1;Kt.push(ze("bias",e[2].dataType,e[2].dims.length,$t)),Yt=`${o?`value += bias[col / ${$t}];`:`value += ${Ge.type.value}(bias[row + i]);`}`}let Ct=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];nn(t,Ct);let Jt=()=>{let $t=`var a_data: ${Ae.type.value};`;for(let jt=0;jt; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { + ${Jt()} + } + for (var i = 0u; i < ${B}u; i++) { + var value = values[i]; + ${Yt} + ${xt} + let cur_indices = ${Ge.type.indices}(batch, row + i, col); + let offset = ${Ge.indicesToOffset("cur_indices")}; + ${Ge.setByOffset(`offset / ${S}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${S};${u};${B};${o}`,inputDependencies:j?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:X}),getShaderSource:_e}}}),nu,ou,uo,Si,iu,co,au,po,ho=w(()=>{zt(),Bt(),Qt(),Gs(),ki(),ao(),nu=(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":""}); + `,ou=(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];"} + }`,uo=(e,t,r="f32",n,o=!1,a=32,i=!1,d=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=o?p:a,S=o?a:p,u=k/t[0],B=a/t[1];if(!((o&&u===4&&e[1]===4||!o&&(u===3||u===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${u} must be 3 or 4. + tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${k/u}>, ${S}>; +var mm_Bsub: array, ${h/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${u}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${p}; + + let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${B}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${nu(o,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${ou(o,u)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Si=(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":""}); + `,iu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",co=(e,t,r="f32",n,o=!1,a=32,i=!1,d=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],S=o?h:a,u=o?a:h;if(!(u%t[1]===0&&S%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${S} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let B=u/t[1],R=S/t[0],j=a/t[1],Z=p?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${k}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${S}; inputCol = inputCol + ${t[0]}) { + ${Si(o,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${h}; + +let tileRowA = i32(localId.y) * ${B}; +let tileColA = i32(localId.x) * ${R}; +let tileRowB = i32(localId.y) * ${j}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Si(o,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${j}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${iu(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${u}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(d/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${d}`:"0"}; + + var acc : array, rowPerThread>; + ${Z} + } +`},au=(e,t,r,n,o=!1)=>{let[a,i,d,p]=n,h=er(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Vr(e,h)} { + var value = ${Vr(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${Bn("aIndices",i,i.rank-2,a.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Vr(e,h)} { + var value = ${Vr(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${d.type.indices}; + ${Bn("bIndices",d,d.rank-2,a.rank,"batchIndices")} + ${d.indicesSet("bIndices",d.rank-2,"u32(row)")} + ${d.indicesSet("bIndices",d.rank-1,"u32(colIn)")} + value = ${d.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Vr(e,h)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${o?"bias[colIn]":`${Vr(e,h)}(bias[row])`};`:""} + ${r} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},po=(e,t,r,n,o=!1,a)=>{let i=e[0].dims,d=e[1].dims,p=i.slice(0,-2),h=d.slice(0,-2),k=n?n.slice(0,-2):r.slice(0,-2),S=$e.size(k),u=i[i.length-2],B=i[i.length-1],R=d[d.length-1],j=B%4===0&&R%4===0,Z=u<=8?[4,1,1]:[4,4,1],te=[8,8,1],X=[Math.ceil(R/te[0]/Z[0]),Math.ceil(u/te[1]/Z[1]),Math.ceil(S/te[2]/Z[2])],_e=j?4:1,me=[...p,u,B/_e],ye=me.length,Ae=[...h,B,R/_e],Ie=Ae.length,Ge=[S,u,R/_e],lt=[{type:6,data:u},{type:6,data:R},{type:6,data:B}];Is(t,lt),lt.push(...vt(k,me,Ae));let xt=["rank","rank"],Kt=e.length>2;Kt&&(lt.push(...vt(e[2].dims)),xt.push("rank")),lt.push(...vt(Ge));let Yt=Ct=>{let Jt=k.length,$t=tn("batchDims",e[0].dataType,Jt,1),jt=er(e[0].dataType),vr=ze("a",e[0].dataType,ye,_e),Ht=ze("b",e[1].dataType,Ie,_e),Gt=wt("result",e[0].dataType,Ge.length,_e),Cr=[vr,Ht];if(Kt){let ys=o?_e:1;Cr.push(ze("bias",e[2].dataType,e[2].dims.length,ys))}let ot=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];nn(t,ot);let Et=er(Gt.type.tensor),cr=sn(t,Gt.type.value,Et),Lr=au(_e,Kt,cr,[$t,vr,Ht,Gt],o);return` + ${Ct.registerUniforms(ot).registerInternalVariables($t).declareVariables(...Cr,Gt)} + ${Lr} + ${j?uo(Z,te,jt,$t):co(Z,te,jt,$t)} + `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${j};${o}`,inputDependencies:xt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:X[0],y:X[1],z:X[2]},programUniforms:lt}),getShaderSource:Yt}}}),lu,uu,du=w(()=>{zt(),Yr(),Qt(),Gs(),ao(),Nc(),ho(),lu=(e,t,r,n,o=!1,a,i=4,d=4,p=4,h="f32")=>{let k=lt=>{switch(lt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${lt} is not supported.`)}},S=lt=>{switch(lt){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 ${lt} is not supported.`)}},u=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,B=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,R=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",j=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",te=e?"col":"row",X=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${Z} / outWidth; + let outCol = ${Z} % outWidth; + + let WRow = ${te} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${te} / 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 = ${te} % inChannels; + var resData = ${Vr(i,h)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${j}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${k(i)} + } + return resData;`,_e=e?t&&n?` + let col = colIn * ${i}; + ${X}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${X} + } + return ${Vr(i,h)}(0.0);`:n&&r?` + let col = colIn * ${i}; + ${X}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${X} + } + return ${Vr(i,h)}(0.0);`,me=`${S(d)}`,ye=Vr(p,h),Ae=Vr(e?i:d,h),Ie=Vr(e?d:i,h),Ge=sn(a,ye,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ae} { + ${e?_e:me} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ie} { + ${e?me:_e} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ye}) { + let col = colIn * ${p}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${B} + ${ru(o)} + ${Ge} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},uu=(e,t,r,n,o,a,i,d,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],S=r[0],u=h?r[2]:r[3],B=h?r[1]:r[2],R=h?r[3]:r[1],j=h&&(k%4===0||k%3===0)&&R%4===0,Z=h?R:u*B,te=h?u*B:R,X=[8,8,1],_e=n<=8?[4,1,1]:[4,4,1],me=[Math.ceil(Z/X[0]/_e[0]),Math.ceil(te/X[1]/_e[1]),Math.ceil(S/X[2]/_e[2])];ir("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${me}`);let ye=j?h&&k%4!==0?3:4:1,Ae=X[1]*_e[1],Ie=X[0]*_e[0],Ge=Math.max(X[0]*ye,X[1]),lt=n%Ae===0,xt=o%Ie===0,Kt=a%Ge===0,Yt=j?[ye,4,4]:[1,1,1],Ct=[{type:6,data:n},{type:6,data:o},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Is(t,Ct),Ct.push(...vt(e[0].dims,e[1].dims));let Jt=["rank","rank"];i&&(Ct.push(...vt(e[2].dims)),Jt.push("rank")),Ct.push(...vt(r));let $t=jt=>{let vr=[{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}];nn(t,vr);let Ht=j?4:1,Gt=er(e[0].dataType),Cr=` + fn setOutputAtIndex(flatIndex : i32, value : ${j?`vec4<${Gt}>`:Gt}) { + result[flatIndex] = ${j?`vec4<${Gt}>`:Gt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${j?`vec4<${Gt}>`:Gt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${j?"/ 4":""}, value); + }`,ot=ze("x",e[0].dataType,e[0].dims.length,ye===3?1:ye),Et=ze("w",e[1].dataType,e[1].dims.length,Ht),cr=[ot,Et],Lr=wt("result",e[0].dataType,r.length,Ht);if(i){let ys=ze("bias",e[2].dataType,e[2].dims.length,Ht);cr.push(ys),Cr+=` + fn getBiasByOutputCoords(coords : vec4) -> ${j?`vec4<${Gt}>`:Gt} { + return bias[coords.${h?"w":"y"}${j?"/ 4":""}]; + }`}return` + ${su("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 }; + ${jt.registerUniforms(vr).declareVariables(...cr,Lr)} + ${Cr} + ${lu(h,lt,xt,Kt,i,t,Yt[0],Yt[1],Yt[2],Gt)} + ${j?uo(_e,X,Gt,void 0,!h,Ge):co(_e,X,Gt,void 0,!h,Ge,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ye};${j};${lt};${xt};${Kt};${Ae};${Ie};${Ge}`,inputDependencies:Jt},getRunData:()=>({outputs:[{dims:p?p(r):r,dataType:e[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:Ct}),getShaderSource:$t}}}),cu,$i,Tn,pu,Ai,Ii,hu,mu,jc=w(()=>{zt(),Yr(),Bt(),Qt(),Gs(),ao(),cu=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Tn=(e,t)=>t<=1?e:e+(e-1)*(t-1),pu=(e,t,r,n=1)=>{let o=Tn(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Ai=(e,t,r,n,o)=>{o==null&&(o=pu(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*o>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*o)/n[i]+1));return a},Ii=(e,t,r,n,o,a,i,d,p,h)=>{let k,S,u,B;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let R=Ai([t,r,n,1],[d,p,h],1,[o,a,i],e);S=R[0],u=R[1],B=R[2]}else if(Array.isArray(e)){if(!e.every((j,Z,te)=>j===te[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let R=Ai([t,r,n,1],[d,p,h],1,[o,a,i],e[0]);S=R[0],u=R[1],B=R[2]}else if(e==="SAME_UPPER"){S=Math.ceil(t/o),u=Math.ceil(r/a),B=Math.ceil(n/i);let R=(S-1)*o+d-t,j=(u-1)*a+p-r,Z=(B-1)*i+h-n,te=Math.floor(R/2),X=R-te,_e=Math.floor(j/2),me=j-_e,ye=Math.floor(Z/2),Ae=Z-ye;k={top:_e,bottom:me,left:ye,right:Ae,front:te,back:X}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:S,outHeight:u,outWidth:B}},hu=(e,t,r,n,o,a=!1,i="channelsLast")=>{let d,p,h,k,S;if(i==="channelsLast")[d,p,h,k,S]=e;else if(i==="channelsFirst")[d,S,p,h,k]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,B,R,j]=t,[Z,te,X]=$i(r),[_e,me,ye]=$i(n),Ae=Tn(B,_e),Ie=Tn(R,me),Ge=Tn(j,ye),{padInfo:lt,outDepth:xt,outHeight:Kt,outWidth:Yt}=Ii(o,p,h,k,Z,te,X,Ae,Ie,Ge),Ct=a?u*S:u,Jt=[0,0,0,0,0];return i==="channelsFirst"?Jt=[d,Ct,xt,Kt,Yt]:i==="channelsLast"&&(Jt=[d,xt,Kt,Yt,Ct]),{batchSize:d,dataFormat:i,inDepth:p,inHeight:h,inWidth:k,inChannels:S,outDepth:xt,outHeight:Kt,outWidth:Yt,outChannels:Ct,padInfo:lt,strideDepth:Z,strideHeight:te,strideWidth:X,filterDepth:B,filterHeight:R,filterWidth:j,effectiveFilterDepth:Ae,effectiveFilterHeight:Ie,effectiveFilterWidth:Ge,dilationDepth:_e,dilationHeight:me,dilationWidth:ye,inShape:e,outShape:Jt,filterShape:t}},mu=(e,t,r,n,o,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],p={x:r.map((Z,te)=>te)},h=[Math.ceil(cu(p.x.map(Z=>r[Z]))/d[0]),1,1];ir("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,S=$e.size(r),u=[{type:12,data:S},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Is(t,u),u.push(...vt(e[0].dims,e[1].dims));let B=["rank","rank"],R=e.length===3;R&&(u.push(...vt(e[2].dims)),B.push("rank")),u.push(...vt(r));let j=Z=>{let te=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];nn(t,te);let X=1,_e=er(e[0].dataType),me=ze("x",e[0].dataType,e[0].dims.length,k),ye=ze("W",e[1].dataType,e[1].dims.length,X),Ae=[me,ye],Ie=wt("result",e[0].dataType,r.length,X),Ge="";if(R){let Kt=ze("bias",e[2].dataType,e[2].dims.length,X);Ae.push(Kt),Ge+=` + fn getBiasByOutputCoords(coords : array) -> ${_e} { + return bias[${i?Mt("coords",4,5):Mt("coords",1,5)}]; + }`}let lt=Vr(k,_e),xt=sn(t,lt,_e);return` + ${Ge} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${me.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${ye.getByIndices("aIndices")}; + } + ${Z.registerUniforms(te).declareVariables(...Ae,Ie)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ie.offsetToIndices("global_idx")}; + let batch = ${Mt("coords",0,me.rank)}; + let d2 = ${i?Mt("coords",me.rank-1,me.rank):Mt("coords",1,me.rank)}; + let xFRCCorner = vec3(${i?Mt("coords",1,me.rank):Mt("coords",2,me.rank)}, + ${i?Mt("coords",2,me.rank):Mt("coords",3,me.rank)}, + ${i?Mt("coords",3,me.rank):Mt("coords",4,me.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?Mt("uniforms.x_shape",1,me.rank):Mt("uniforms.x_shape",2,me.rank)}; + let xShapeZ = ${i?Mt("uniforms.x_shape",2,me.rank):Mt("uniforms.x_shape",3,me.rank)}; + let xShapeW = ${i?Mt("uniforms.x_shape",3,me.rank):Mt("uniforms.x_shape",4,me.rank)}; + let xShapeU = ${i?Mt("uniforms.x_shape",4,me.rank):Mt("uniforms.x_shape",1,me.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${R?"value = value + getBiasByOutputCoords(coords)":""}; + ${xt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${k};${R}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:u}),getShaderSource:j}}}),_u,mo,Uc=w(()=>{zt(),Bt(),Qt(),Gs(),_u=(e,t,r,n)=>{let o=e.length>2,a=o?"value += b[output_channel];":"",i=e[0].dims,d=e[1].dims,p=t.format==="NHWC",h=p?r[3]:r[1],k=h/t.group,S=p&&k>=4?yr(h):1,u=$e.size(r)/S,B=[{type:12,data:u},{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:k}];Is(t,B),B.push(...vt(i,[d[0],d[1],d[2],d[3]/S]));let R=o?["rank","rank","rank"]:["rank","rank"];B.push(...vt([r[0],r[1],r[2],r[3]/S]));let j=Z=>{let te=wt("output",e[0].dataType,r.length,S),X=er(te.type.tensor),_e=sn(t,te.type.value,X),me=ze("x",e[0].dataType,i.length),ye=ze("w",e[1].dataType,d.length,S),Ae=[me,ye];o&&Ae.push(ze("b",e[2].dataType,e[2].dims,S));let Ie=[{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"}];nn(t,Ie);let Ge=p?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${me.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${ye.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${me.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${ye.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${Z.registerUniforms(Ie).declareVariables(...Ae,te)} + + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${te.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${p?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${S} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; + + var value: ${te.type.value} = ${te.type.value}(0); + ${Ge} + ${a} + ${_e} + ${te.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${S}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:j}},mo=(e,t,r,n)=>{let o=e.length>2,a=yr(r[3]),i=yr(r[2]),d=$e.size(r)/a/i,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[r[0],r[1],r[2],r[3]/a],S=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Is(t,S),S.push(...vt(p,h,k));let u=(i-1)*t.strides[1]+h[1],B=R=>{let j=wt("output",e[0].dataType,k.length,a),Z=er(j.type.tensor),te=sn(t,j.type.value,Z),X=ze("x",e[0].dataType,p.length,a),_e=ze("w",e[1].dataType,h.length,a),me=[X,_e];o&&me.push(ze("b",e[2].dataType,e[2].dims,a));let ye=o?"value += b[output_channel];":"",Ae=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return nn(t,Ae),` + ${R.registerUniforms(Ae).declareVariables(...me,j)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${X.type.value}, ${u}>; + var values: array<${j.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${h[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${u}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${X.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${X.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { + let w_val = ${_e.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${ye} + ${te} + ${j.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${u};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:S}),getShaderSource:B}}}),fu,_o,gu,fo,go,Oi,wu,Fi,Di,Vc=w(()=>{Bt(),du(),jc(),ho(),Uc(),Gs(),ki(),Ws(),fu=(e,t,r,n,o,a)=>{let i=e[0],d=e.slice(a?1:2,a?3:4),p=d.length,h=t[0],k=t.slice(2).map((u,B)=>u+(u-1)*(r[B]-1)),S=d.map((u,B)=>u+n[B]+n[B+p]).map((u,B)=>Math.floor((u-k[B]+o[B])/o[B]));return S.splice(0,0,i),S.splice(a?3:1,0,h),S},_o=[2,3,1,0],gu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fo=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=Ci(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,a=e.group,i=e.kernel_shape,d=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:a,kernelShape:i,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Oi=(e,t,r,n)=>{let o=r.format==="NHWC",a=fu(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let Ae=[t[0]];if(o){let Ie=e.kernelCustomData.wT??e.compute(ss(t[1],_o),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ie),Ae.push(Ie)}else Ae.push(t[1]);t.length===3&&Ae.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(mo(Ae,r,a,n),{inputs:Ae}):e.compute(_u(Ae,r,a,n),{inputs:Ae});return}let i=t.length===3,d=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],k=t[1].dims[2],S=t[1].dims[3],u=a[o?1:2],B=a[o?2:3],R=a[o?3:1],j=o&&k===d&&S===p&&r.pads[0]===0&&r.pads[1]===0;if(j||k===1&&S===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let Ae=a[0],Ie,Ge,lt,xt=[];if(o){let Ct=e.kernelCustomData.wT??e.compute(ss(t[1],_o),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ct),j){let Jt=d*p*h;Ie=t[0].reshape([1,Ae,Jt]),Ge=Ct.reshape([1,Jt,R]),lt=[1,Ae,R]}else Ie=t[0].reshape([Ae,d*p,h]),Ge=Ct.reshape([1,h,R]),lt=[Ae,u*B,R];xt.push(Ie),xt.push(Ge)}else Ie=t[0].reshape([Ae,h,d*p]),Ge=t[1].reshape([1,R,h]),lt=[Ae,R,u*B],xt.push(Ge),xt.push(Ie);i&&xt.push(t[2]);let Kt=lt[2],Yt=xt[0].dims[xt[0].dims.length-1];Kt<8&&Yt<8?e.compute(lo(xt,r,a,lt,o,n),{inputs:xt}):e.compute(po(xt,r,a,lt,o,n),{inputs:xt});return}let Z=!0,te=e.kernelCustomData.wT??e.compute(ss(t[1],_o),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let X=[t[0],te];i&&X.push(t[2]);let _e=o?u*B:R,me=o?R:u*B,ye=k*S*h;e.compute(uu(X,r,a,_e,me,ye,i,Z,n),{inputs:X})},wu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),d=[1].concat(t.kernelShape),p=fo({...t,pads:o,strides:a,dilations:i,kernelShape:d},n);Oi(e,n,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Fi=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",o=fo(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=hu(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(mu(t,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},Di=(e,t)=>{if(gu(e.inputs,t),e.inputs[0].dims.length===3)wu(e,t);else if(e.inputs[0].dims.length===5)Fi(e,e.inputs,t);else{let r=fo(t,e.inputs);Oi(e,e.inputs,r)}}}),yu,Wc=w(()=>{zt(),Yr(),Bt(),Qt(),yu=(e,t,r)=>{let n=e.length>2,o=t.outputShape,a=t.format==="NHWC",i=t.group,d=e[1].dims,p=d[2]/i,h=d[3],k=a?yr(h):1,S=$e.size(o)/k,u=[Math.ceil(S/64),1,1];ir("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let B=["rank","rank"],R=[t.strides[0],t.strides[1]],j=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Z=[t.dilations[0],t.dilations[1]],te=[j[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),j[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],X=[te[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),te[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],_e=[{type:12,data:S},{type:12,data:R},{type:12,data:j},{type:12,data:Z},{type:12,data:te},{type:6,data:X},{type:12,data:p},{type:12,data:h},...vt(e[0].dims,e[1].dims)];n&&(_e.push(...vt(e[2].dims)),B.push("rank")),_e.push(...vt(o));let me=ye=>{let Ae=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:R.length},{name:"filter_dims",type:"u32",length:j.length},{name:"dilations",type:"u32",length:j.length},{name:"effective_filter_dims",type:"u32",length:te.length},{name:"pads",type:"i32",length:X.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ie=er(e[0].dataType),Ge=a?1:2,lt=a?2:3,xt=a?3:1,Kt=ze("W",e[1].dataType,e[1].dims.length,k),Yt=ze("Dy",e[0].dataType,e[0].dims.length),Ct=[Yt,Kt];n&&Ct.push(ze("bias",e[2].dataType,[o[xt]].length,k));let Jt=wt("result",e[0].dataType,o.length,k),$t=` + let outputIndices = ${Jt.offsetToIndices(`global_idx * ${k}`)}; + let batch = ${Jt.indicesGet("outputIndices",0)}; + let d1 = ${Jt.indicesGet("outputIndices",xt)}; + let r = ${Jt.indicesGet("outputIndices",Ge)}; + let c = ${Jt.indicesGet("outputIndices",lt)}; + 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 = ${Jt.type.value}(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 = (${Ie}(dyRCorner) + ${Ie}(wR)) / ${Ie}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${Ie}(uniforms.Dy_shape[${Ge}]) || 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 = (${Ie}(dyCCorner) + ${Ie}(wC)) / ${Ie}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${Ie}(uniforms.Dy_shape[${lt}]) || + 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 = ${a?Yt.get("batch","idyR","idyC","inputChannel"):Yt.get("batch","inputChannel","idyR","idyC")}; + let w_offset = ${Kt.indicesToOffset(`${Kt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Kt.getByOffset(`w_offset / ${k}`)}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd${n?` + bias[d1 / ${k}]`:""}; + ${Jt.setByOffset("global_idx","value")}; + `;return` + ${ye.registerUniforms(Ae).declareVariables(...Ct,Jt)} + ${ye.mainStart()} + ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${$t}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}`,inputDependencies:B},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:_e}),getShaderSource:me}}}),Li,Mu,bu,wo,vu,Tu,yo,xu,Eu,Pu=w(()=>{Wc(),Gs(),Ws(),Li=(e,t,r,n,o,a)=>(e-1)*t+r+(n-1)*o+1-a,Mu=(e,t,r,n,o)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[o]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[o]=a)},bu=(e,t,r,n,o,a,i,d,p,h)=>{let k=e.length-2,S=h.length===0;p.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((S,u)=>S*u,1)===0){r.length=0;for(let S=2;SS+u,0)===0){let S=t[0].dims.length-2;p=new Array(S).fill(1)}let h=e.strides.slice();if(h.reduce((S,u)=>S+u,0)===0){let S=t[0].dims.length-2;h=new Array(S).fill(1)}bu(d,r,p,e.autoPad,e.group,o,h,n,i,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:r,pads:o,outputPadding:i,outputShape:a,dilations:p,strides:h}),k},vu=e=>{let t=Ci(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,a=e.group,i=e.kernelShape,d=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,S=e.outputShape;return{autoPad:n,format:r,dilations:o,group:a,kernelShape:i,outputPadding:k,outputShape:S,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Tu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,d)=>i+d,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,d)=>i+d,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,d)=>i+d,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,d)=>i+d,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},yo=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(ss(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let a=[t[0],o];t.length===3&&a.push(t[2]),e.compute(yu(a,r,n),{inputs:a})},xu=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],i=[1].concat(i),a=[1].concat(a),o=[1].concat(o);let p=wo({...t,pads:d,strides:i,dilations:a,kernelShape:o},n);yo(e,n,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Eu=(e,t)=>{if(Tu(e.inputs,t),e.inputs[0].dims.length===3)xu(e,t);else{let r=wo(t,e.inputs);yo(e,e.inputs,r)}}}),Cu,ku,Su,Gc=w(()=>{zt(),Bt(),Pt(),Qt(),Cu=(e,t,r,n)=>{let o=$e.size(t),a=t.length,i=ze("input",e,a),d=wt("output",e,a),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=$e.normalizeAxis(p,a),k=S=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,B=Mt("uniforms.input_shape","uniforms.axis",a),R=n.reverse?u+(n.exclusive?" + 1":""):"0",j=n.reverse?B:u+(n.exclusive?"":" + 1");return` + ${S.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,d)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${d.offsetToIndices("global_idx")}; + var sum = ${d.type.value}(0); + let first : i32 = ${R}; + let last : i32 = ${j}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...vt(t,t)]}),getShaderSource:k}},ku=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(Cu(n,r,o,t),{inputs:[0]})},Su=e=>{let t=e.exclusive===1,r=e.reverse===1;return it({exclusive:t,reverse:r})}}),$u,Au,zi,Iu,Ou,Fu=w(()=>{zt(),Bt(),Pt(),Qt(),$u=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.")},Au=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let a=0;a{let r,n,o,a,i,d,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([r,n,o,a]=e.dims,i=k?[r,n,o,h,h,a/h**2]:[r,n,o,a/h**2,h,h],d=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=k?[r,h,h,a/h**2,n,o]:[r,a/h**2,h,h,n,o],d=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let S=e.reshape(i),u=S.dims.length,B=e.dataType,R=ze("a",B,u),j=wt("output",B,u),Z=te=>` + ${te.registerUniform("output_size","u32").declareVariables(R,j)} + + ${Au(d,u,R,j)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${j.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${j.setByOffset("global_idx",R.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:te=>{let X=p?[r,n*h,o*h,a/h**2]:[r,a/h**2,n*h,o*h],_e=$e.size(X),me=S.dims,ye=$e.sortBasedOnPerm(me,d);return{outputs:[{dims:X,dataType:te[0].dataType}],dispatchGroup:{x:Math.ceil(_e/64)},programUniforms:[{type:12,data:_e},...vt(me,ye)]}},getShaderSource:Z}},Iu=(e,t)=>{$u(e.inputs),e.compute(zi(e.inputs[0],t))},Ou=e=>it({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Mo,Rn,Os,Du,Lu,zu,Bu,bo,Ru,Nu,ju,Kc=w(()=>{zt(),Bt(),Pt(),Qt(),Mo="[a-zA-Z]|\\.\\.\\.",Rn="("+Mo+")+",Os="^"+Rn+"$",Du="("+Rn+",)*"+Rn,Lu="^"+Du+"$",zu=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Bu=class{constructor(e,t){var o;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Lu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let d=e[i].dims.slice();if(!a.match(RegExp(Os)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,d,i);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Rn)))throw new Error("Invalid RHS");(o=n.match(RegExp(Mo,"g")))==null||o.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let o=r.length,a=!1,i=[],d=0;if(!e.match(RegExp(Os))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(Mo,"g")),h=new zu(n);return p==null||p.forEach((k,S)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let u=o-p.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(d,d+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let B=0;Be+"_max",Ru=(e,t,r,n)=>{let o=e.map(h=>h.length).map((h,k)=>ze(`input${k}`,t,h)),a=$e.size(n),i=wt("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),p=h=>{let k=[],S="var prod = 1.0;",u="var sum = 0.0;",B="sum += prod;",R=[],j=[],Z=[],te=[],X=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((me,ye)=>{var Ae;if(r.rhs.symbolToIndices.has(ye)){let Ie=(Ae=r.rhs.symbolToIndices.get(ye))==null?void 0:Ae[0];Ie!==void 0&&r.lhs.forEach((Ge,lt)=>{if(me.inputIndices.includes(lt)){let xt=Ge.symbolToIndices.get(ye);if(xt===void 0)throw new Error("Invalid symbol error");xt.forEach(Kt=>{k.push(`${o[lt].indicesSet(`input${lt}Indices`,Kt,i.indicesGet("outputIndices",Ie))}`)})}})}else r.lhs.forEach((Ie,Ge)=>{if(me.inputIndices.includes(Ge)){let lt=Ie.symbolToIndices.get(ye);if(lt===void 0)throw new Error("Invalid symbol error");lt.forEach(xt=>{R.push(`${o[Ge].indicesSet(`input${Ge}Indices`,xt,`${ye}`)}`)}),te.push(`prod *= ${o[Ge].getByIndices(`input${Ge}Indices`)};`)}}),j.push(`for(var ${ye}: u32 = 0; ${ye} < uniforms.${bo(ye)}; ${ye}++) {`),Z.push("}")});let _e=X?[...k,`let sum = ${o.map((me,ye)=>me.getByIndices(`input${ye}Indices`)).join(" * ")};`]:[...k,u,...j,...R,S,...te,B,...Z];return` + ${h.registerUniforms(d.map(me=>({name:`${bo(me)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((me,ye)=>`var input${ye}Indices: ${o[ye].type.indices};`).join(` +`)} + ${_e.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(S=>r.symbolToInfo.has(S)).map(S=>{var u;return{type:12,data:((u=r.symbolToInfo.get(S))==null?void 0:u.dimValue)||0}});h.push({type:12,data:a});let k=e.map((S,u)=>[...vt(S)]).reduce((S,u)=>S.concat(u),h);return k.push(...vt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Nu=(e,t)=>{let r=new Bu(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((a,i)=>a.dims);e.compute(Ru(o,e.inputs[0].dataType,r,n))},ju=e=>{let t=e.equation.replace(/\s+/g,"");return it({equation:t})}}),vo,Bi,Uu,Vu,Nn,Hc=w(()=>{zt(),Bt(),Qt(),vo=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Bi(e,t):Bi(t,e),Vu=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Uu(t,r),o=e[0].dataType,a=o===9||$e.size(t)===1,i=o===9||t.length>0&&t[t.length-1]%4===0?4:1,d=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil($e.size(n)/d),h=S=>{let u=ze("input",o,t.length,i),B=wt("output",o,n.length,d),R;if(o===9){let j=(Z,te,X="")=>` + let outputIndices${te} = ${B.offsetToIndices(`outputOffset + ${te}u`)}; + let offset${te} = ${u.broadcastedIndicesToOffset(`outputIndices${te}`,B)}; + let index${te} = offset${te} / 4u; + let component${te} = offset${te} % 4u; + ${Z}[${te}] = ${X}(${u.getByOffset(`index${te}`)}[component${te}]); + `;R=` + let outputOffset = global_idx * ${d}; + var data = vec4(0); + ${j("data",0,"u32")} + ${j("data",1,"u32")} + ${j("data",2,"u32")} + ${j("data",3,"u32")} + ${B.setByOffset("global_idx","data")} + }`}else R=` + let outputIndices = ${B.offsetToIndices(`global_idx * ${d}`)}; + let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",B)}; + let data = ${B.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); + ${B.setByOffset("global_idx","data")} + }`;return` + ${S.registerUniform("vec_size","u32").declareVariables(u,B)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${R}`},k=[{type:12,data:p},...vt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${i}${d}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Nn=e=>{vo(e.inputs),e.compute(Vu(e.inputs),{inputs:[0]})}}),Wu,Gu,qc=w(()=>{zt(),Bt(),Qt(),bi(),Wu=e=>{let t=e[0].dataType,r=$e.size(e[0].dims),n=$e.size(e[1].dims),o=n%4===0,a=i=>{let d=ze("x",t,[1],4),p=ze("bias",t,[1],4),h=wt("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],S=B=>` + let bias${B}_offset: u32 = (global_idx * 4 + ${B}) % uniforms.bias_size; + let bias${B} = ${p.getByOffset(`bias${B}_offset / 4`)}[bias${B}_offset % 4];`,u=o?` + let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${S(0)}${S(1)}${S(2)}${S(3)} + let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(k).declareVariables(d,p,h)} + + ${io(mr(t))} + + ${i.mainStart(Nr)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${d.getByOffset("global_idx")}; + ${u} + let x_in = x + bias; + ${h.setByOffset("global_idx",yi("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Nr/4)}})}},Gu=e=>{e.inputs.length<2||$e.size(e.inputs[1].dims)===0?Fl(e):e.compute(Wu(e.inputs))}}),To,Ku,Hu,qu,Rp=w(()=>{zt(),Bt(),Pt(),Qt(),To=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ku=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,a=$e.normalizeAxis(t.axis,o),i=r.slice(0);i.splice(a,1,...n);let d=r[a],p=e[0].dataType===9?4:1,h=Math.ceil($e.size(i)/p),k=[{type:12,data:h},{type:6,data:d},{type:12,data:a},...vt(e[0].dims,e[1].dims,i)],S=u=>{let B=ze("data",e[0].dataType,e[0].dims.length,p),R=ze("inputIndices",e[1].dataType,e[1].dims.length),j=wt("output",e[0].dataType,i.length,p),Z=X=>{let _e=n.length,me=`var indicesIndices${X} = ${R.type.indices}(0);`;for(let ye=0;ye<_e;ye++)me+=`${_e>1?`indicesIndices${X}[${ye}]`:`indicesIndices${X}`} = ${i.length>1?`outputIndices${X}[uniforms.axis + ${ye}]`:`outputIndices${X}`};`;me+=` + var idx${X} = ${R.getByIndices(`indicesIndices${X}`)}; + if (idx${X} < 0) { + idx${X} = idx${X} + uniforms.axisDimLimit; + } + var dataIndices${X} : ${B.type.indices}; + `;for(let ye=0,Ae=0;ye1?`dataIndices${X}[${ye}]`:`dataIndices${X}`} = u32(idx${X});`,Ae+=_e):(me+=`${o>1?`dataIndices${X}[${ye}]`:`dataIndices${X}`} = ${i.length>1?`outputIndices${X}[${Ae}]`:`outputIndices${X}`};`,Ae++);return me},te;if(e[0].dataType===9){let X=(_e,me,ye="")=>` + let outputIndices${me} = ${j.offsetToIndices(`outputOffset + ${me}u`)}; + ${Z(me)}; + let offset${me} = ${B.indicesToOffset(`dataIndices${me}`)}; + let index${me} = offset${me} / 4u; + let component${me} = offset${me} % 4u; + ${_e}[${me}] = ${ye}(${B.getByOffset(`index${me}`)}[component${me}]); + `;te=` + let outputOffset = global_idx * ${p}; + var value = vec4(0); + ${X("value",0,"u32")} + ${X("value",1,"u32")} + ${X("value",2,"u32")} + ${X("value",3,"u32")} + ${j.setByOffset("global_idx","value")} + `}else te=` + let outputIndices = ${j.offsetToIndices("global_idx")}; + ${Z("")}; + let value = ${B.getByIndices("dataIndices")}; + ${j.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(B,R,j)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${te} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:S}},Hu=e=>it({axis:e.axis}),qu=(e,t)=>{let r=e.inputs;To(r),e.compute(Ku(e.inputs,t))}}),Xu,Qu,Yu,jn=w(()=>{zt(),Bt(),Qt(),Xu=(e,t,r,n,o,a,i,d,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:o},{type:12,data:r},{type:12,data:i},{type:12,data:d},{type:12,data:p}],k=[a];h.push(...vt(t.dims,k));let S=u=>{let B=ze("indices_data",t.dataType,t.dims.length),R=wt("input_slice_offsets_data",12,1,1),j=[B,R],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:r.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${u.registerUniforms(Z).declareVariables(...j)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${r.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${r.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:S},{inputs:[t],outputs:[-1]})[0]},Qu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=r[0].dataType,a=r[1].dims,i=a[a.length-1],d=$e.sizeToDimension(a,a.length-1),p=$e.sizeFromDimension(n,t.batchDims+i),h=$e.sizeToDimension(n,t.batchDims),k=$e.sizeFromDimension(n,t.batchDims),S=d/h,u=new Array(i),B=p;for(let me=0;men.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(j)),te=$e.size(Z),X=[{type:12,data:te},{type:12,data:p},...vt(r[0].dims,R.dims,Z)],_e=me=>{let ye=ze("data",r[0].dataType,r[0].dims.length),Ae=ze("slice_offsets",12,R.dims.length),Ie=wt("output",r[0].dataType,Z.length);return` + ${me.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(ye,Ae,Ie)} + ${me.mainStart()} + ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:o}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:X}),getShaderSource:_e},{inputs:[r[0],R]})},Yu=e=>({batchDims:e.batch_dims,cacheKey:""})}),Ju,Zu,ed,td,Xc=w(()=>{zt(),Bt(),Pt(),Qt(),Ju=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=$e.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==o.dims.length||!o.dims.map((d,p)=>p===r?Math.ceil(d/n)===a.dims[p]:d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((d,p)=>d===a.dims[p]).reduce((d,p)=>d&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Zu=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,a=$e.normalizeAxis(t.gatherAxis,o),i=$e.normalizeAxis(t.quantizeAxis,o),d=r.slice(0);d.splice(a,1,...n);let p=$e.size(d),h=e[2].dataType,k=e[0].dataType===22,S=[{type:12,data:p},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...vt(...e.map((B,R)=>B.dims),d)],u=B=>{let R=ze("data",e[0].dataType,e[0].dims.length),j=ze("inputIndices",e[1].dataType,e[1].dims.length),Z=ze("scales",e[2].dataType,e[2].dims.length),te=e.length>3?ze("zeroPoint",e[3].dataType,e[3].dims.length):void 0,X=wt("output",h,d.length),_e=[R,j,Z];te&&_e.push(te);let me=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${B.registerUniforms(me).declareVariables(..._e,X)} + ${B.mainStart()} + let output_indices = ${X.offsetToIndices("global_idx")}; + var indices_indices = ${j.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${X.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${j.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${X.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${R.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${X.indicesGet("output_indices","i")}; + ${R.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${j.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${r[a]}; + } + ${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${d.length}; i++) { + let index = ${X.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${R.indicesSet("data_indices","i","index")}; + } + let data_offset = ${R.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${Z.getByIndices("scale_indices")}; + ${te?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${te.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${te.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${mr(h)}(quantized_data - zero_point) * scale; + ${X.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((B,R)=>R!==1).map(B=>B.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(B,R)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:S}),getShaderSource:u}},ed=(e,t)=>{let r=e.inputs;Ju(r,t),e.compute(Zu(e.inputs,t))},td=e=>it({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),xo,Qc,rd,sd,Yc=w(()=>{zt(),Bt(),Pt(),Qt(),xo=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.`)},Qc=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,a=e[1].dims,i=e[1].dataType,d=$e.normalizeAxis(t.axis,o),p=r[d],h=a.slice(0),k=$e.size(h),S=ze("input",n,o),u=ze("indicesInput",i,a.length),B=wt("output",n,h.length),R=[{type:12,data:k},{type:6,data:p},{type:12,data:d}];return R.push(...vt(r,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:R}),getShaderSource:j=>` + ${j.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(S,u,B)} + ${j.mainStart()} + ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${B.offsetToIndices("global_idx")}; + + var idx = ${u.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${S.type.indices}(outputIndices); + ${S.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${S.getByIndices("inputIndices")}; + + ${B.setByOffset("global_idx","value")}; + }`}},rd=e=>it({axis:e.axis}),sd=(e,t)=>{let r=e.inputs;xo(r),e.compute(Qc(e.inputs,t))}}),nd,od,Ri,id,Jc=w(()=>{zt(),Bt(),Qt(),nd=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")},od=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,a,i]=Rr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),d=[o,a];if(!d)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(o/p),S=!0,u=$e.size(d),B=[{type:12,data:S?h:u},{type:12,data:o},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],R=["type","type"];e.length===3&&(B.push(...vt(e[2].dims)),R.push("rank")),B.push(...vt(d));let j=te=>{let X="";t.transA&&t.transB?X="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?X="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?X="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(X="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let _e=t.alpha===1?"":"value *= uniforms.alpha;",me=ze("a",e[0].dataType,e[0].dims),ye=ze("b",e[1].dataType,e[1].dims),Ae=me.type.value,Ie=null,Ge=[me,ye];e.length===3&&(Ie=ze("c",e[2].dataType,e[2].dims.length),Ge.push(Ie));let lt=wt("output",e[0].dataType,d.length);Ge.push(lt);let xt=[{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` + ${te.registerUniforms(xt).declareVariables(...Ge)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Ae}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${X} + } + + ${_e} + ${Ie!=null?`let cOffset = ${Ie.broadcastedIndicesToOffset("vec2(m, n)",lt)}; value += ${Ae}(uniforms.beta) * ${Ie.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},Z=te=>{let X=ze("a",e[0].dataType,e[0].dims),_e=ze("b",e[1].dataType,e[1].dims),me=null,ye=[X,_e];e.length===3&&(me=ze("c",e[2].dataType,e[2].dims.length),ye.push(me));let Ae=wt("output",e[0].dataType,d.length);ye.push(Ae);let Ie=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],Ge="",lt="";t.transA&&t.transB?(lt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); + } + `,Ge="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(lt=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); + } + `,Ge="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(lt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); + } + `,Ge="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(lt=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${X.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${_e.type.value}(0); + } + `,Ge="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let xt=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${te.registerUniforms(Ie).declareVariables(...ye)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${te.mainStart([p,p,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; + let num_tiles = (uniforms.K - 1) / ${p} + 1; + var k_start = 0u; + var value = ${Ae.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${lt} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${Ge} + } + workgroupBarrier(); + } + + ${xt} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",Ae)}; value += ${Ae.type.value}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return S?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:B}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:B}),getShaderSource:j}},Ri=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},id=(e,t)=>{nd(e.inputs),e.compute(od(e.inputs,t))}}),fs,Fs,on,Ks,ad,ld,Eo,ud,dd,cd,pd,Ni,Po,Zc,ep=w(()=>{zt(),Bt(),Pt(),Qt(),[fs,Fs,on,Ks]=[0,1,2,3],ad=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},ld=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,Eo=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,ud=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,dd=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,cd=(e,t,r)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${fs}] = batch; + indices[${Fs}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${on}] = u32(r); + indices[${Ks}] = u32(c); + } + `;case"border":return` + indices[${on}] = u32(clamp(r, 0, H - 1)); + indices[${Ks}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${on}] = gs_reflect(r, border[1], border[3]); + indices[${Ks}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,pd=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${fs}], indices[${Fs}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${fs}], indices[${Fs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${fs}], indices[${Fs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${fs}], indices[${Fs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${fs}], indices[${Fs}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${t}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${fs}], indices[${Fs}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Ni=(e,t)=>{let r=ze("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=ze("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[fs,Fs,on,Ks]=[0,3,1,2]);let i=wt("output",e[0].dataType,a.length),d=r.type.value,p=$e.size(a),h=[{type:12,data:p},...vt(e[0].dims,n,a)],k=S=>` + ${S.registerUniform("output_size","u32").declareVariables(r,o,i)} + ${ld} + ${Eo(d)} + ${ud(t)} + ${dd(t)} + ${cd(r,d,t)} + + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${on}]); + let W_in = i32(uniforms.x_shape[${Ks}]); + + ${t.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${fs}], indices[${on}], indices[${Ks}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${pd(i,d,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:S=>{let u=$e.size(a);return{outputs:[{dims:a,dataType:S[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}},getShaderSource:k}},Po=(e,t)=>{ad(e.inputs),e.compute(Ni(e.inputs,t))},Zc=e=>it({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),es,ji,hd,Ui,Vi,Un,md,Wi=w(()=>{zt(),Bt(),Pt(),yn(),no(),Qt(),Ws(),es=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,ji=(e,t)=>{let r=e[0],n=es(e,1),o=es(e,2),a=es(e,3),i=es(e,4),d=es(e,5),p=es(e,6),h=es(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=r.dims[0],S=r.dims[1],u=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],B=S,R=0,j=0,Z=Math.floor(u/t.numHeads);if(p&&h&&$e.size(p.dims)&&$e.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');R=p.dims[2],j=p.dims[2]}else if(p&&$e.size(p.dims)||h&&$e.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te;if(n&&$e.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');te=2,B=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');te=5,B=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');te=0,B=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}if(a&&$e.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let X=R+B,_e=0;if(i&&$e.size(i.dims)>0){_e=8;let Ie=i.dims;throw Ie.length===1?Ie[0]===k?_e=1:Ie[0]===3*k+2&&(_e=3):Ie.length===2&&Ie[0]===k&&Ie[1]===X&&(_e=5),_e===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let me=!1,ye=u;if(o&&$e.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(B!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ye=o.dims[2]}else{if(B!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ye=o.dims[1]*o.dims[3],me=!0}}let Ae=!1;if(i&&$e.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(d&&$e.size(d.dims)>0){if(d.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(d.dims[0]!==k||d.dims[1]!==t.numHeads||d.dims[2]!==S||d.dims[3]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:S,pastSequenceLength:R,kvSequenceLength:B,totalSequenceLength:X,maxSequenceLength:j,inputHiddenSize:0,hiddenSize:u,vHiddenSize:ye,headSize:Z,vHeadSize:Math.floor(ye/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:_e,scale:t.scale,broadcastResPosBias:Ae,passPastInKv:me,qkvFormat:te}},hd=e=>it({...e}),Ui=it({perm:[0,2,1,3]}),Vi=(e,t,r,n,o,a,i)=>{let d=[n,o,a],p=$e.size(d),h=[{type:12,data:p},{type:12,data:i},{type:12,data:a}],k=S=>{let u=wt("qkv_with_bias",t.dataType,d),B=ze("qkv",t.dataType,d),R=ze("bias",r.dataType,d),j=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${S.registerUniforms(j).declareVariables(B,R,u)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:d,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,r],outputs:[-1]})[0]},Un=(e,t,r,n,o,a,i,d)=>{let p=a;if(i&&$e.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=Vi(e,a,i,t,n,r*o,d),p=p.reshape([t,n,r,o]),r===1||n===1?p:e.compute(ss(p,Ui.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,r,o])),r===1||n===1?p:e.compute(ss(p,Ui.perm),{inputs:[p],outputs:[-1]})[0]},md=(e,t)=>{let r=ji(e.inputs,t),n=e.inputs[0],o=es(e.inputs,1),a=es(e.inputs,2),i=es(e.inputs,3),d=es(e.inputs,4),p=es(e.inputs,5),h=es(e.inputs,6),k=es(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let S=o&&a&&o.dims.length===4&&a.dims.length===4,u=Un(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(S)return vn(e,u,o,a,d,void 0,h,k,p,r);if(!o||!a)throw new Error("key and value must be provided");let B=Un(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,i,r.hiddenSize),R=Un(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);vn(e,u,B,R,d,void 0,h,k,p,r)}}),tp,rp,Gi,Ki,Hi,_d,qi,fd=w(()=>{zt(),Bt(),Pt(),Qt(),tp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},rp=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),it({numOutputs:n,axis:t.axis,splitSizes:r})},Gi=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Mt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Ki=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=$e.size(r),o=e[0].dataType,a=$e.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),d=ze("input",o,r.length),p=new Array(t.numOutputs),h=[],k=[],S=0,u=[{type:12,data:n}];for(let R=0;R` + ${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(d,...i)} + ${Gi(p.length)} + ${Ki(i)} + + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${d.offsetToIndices("global_idx")}; + var index = ${d.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Mt("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${d.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u})}},_d=(e,t)=>{tp(e.inputs);let r=e.inputs.length===1?t:rp(e.inputs,t);e.compute(Hi(e.inputs,r),{inputs:[0]})},qi=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return it({axis:t,numOutputs:n,splitSizes:r})}}),gd,Xi,Qi,wd,yd=w(()=>{Pt(),no(),Wi(),fd(),Ws(),gd=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],o=e[2],a=e[3],i=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,p=r.dims[0],h=r.dims[1],k=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],S=h,u=0,B=!n||n.dims.length===0,R=Math.floor(B?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);B&&(k=R*t.numHeads);let j=a&&a.dims.length!==0,Z=i&&i.dims.length!==0;if(j&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===R)throw new Error("BSNH pastKey/pastValue is not supported");if(j&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=a.dims[2]}else if(j||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let te=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');S=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==R)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');S=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==R)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');S=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');te=3}let X=0,_e=!1,me=t.kvNumHeads?R*t.kvNumHeads:k;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(S!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');me=o.dims[2]}else{if(S!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');me=o.dims[1]*o.dims[3],_e=!0}}let ye=e.length>4?e[5]:void 0;if(ye&&ye.dims.length!==1&&ye.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:u,kvSequenceLength:S,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:me,headSize:R,vHeadSize:Math.floor(me/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_e,qkvFormat:te}},Xi=it({perm:[0,2,1,3]}),Qi=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(ss(n,Xi.perm),{inputs:[n],outputs:[-1]})[0]),n},wd=(e,t)=>{var Z;let r=gd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,d=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=r.kvNumHeads?r.kvNumHeads:r.numHeads,S=it({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,k*r.headSize,k*r.headSize]}),[u,B,R]=!o&&!a?e.compute(Hi([n],S),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,a],j=Un(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,u,void 0,0);vn(e,j,Qi(e,B,r),Qi(e,R,r),void 0,void 0,i,d,void 0,r,p,h)}}),Yi,Md,bd,vd,sp=w(()=>{zt(),Bt(),Ws(),Qt(),Yi=(e,t,r,n,o,a,i,d)=>{let p=yr(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,S=o*i,u=64;S===1&&(u=256);let B=[o,i,a/p],R=[o,i,2],j=["rank","type","type"],Z=[];Z.push(...vt(B,R));let te=X=>{let _e=ze("x",t.dataType,3,p),me=ze("scale",r.dataType,r.dims),ye=ze("bias",n.dataType,n.dims),Ae=wt("output",1,3,2),Ie=[_e,me,ye,Ae];return` + var workgroup_shared : array<${k}, ${u}>; + const workgroup_size = ${u}u; + ${X.declareVariables(...Ie)} + ${X.mainStart(u)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${h}(0); + var squared_sum = ${h}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${h}(${_e.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${k}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${qr("workgroup_shared[0][0]",p)} / f32(hight * ${p}); + let squared_sum_final = ${qr("workgroup_shared[0][1]",p)} / f32(hight * ${p}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${d})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${d};${u}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:S},programUniforms:Z}),getShaderSource:te},{inputs:[t,r,n],outputs:[-1]})[0]},Md=(e,t,r)=>{let n=t[0].dims,o=n,a=2,i=n[0],d=n[1],p=$e.sizeFromDimension(n,a),h=yr(p),k=$e.size(o)/h,S=Yi(e,t[0],t[1],t[2],i,p,d,r.epsilon),u=[i,d,p/h],B=[i,d],R=["type","none"],j=Z=>{let te=ze("x",t[0].dataType,u.length,h),X=ze("scale_shift",1,B.length,2),_e=wt("output",t[0].dataType,u.length,h),me=[te,X,_e];return` + ${Z.registerUniform("output_size","u32").declareVariables(...me)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${_e.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${X.getByIndices("vec2(batch, channel)")}; + let value = ${te.getByOffset("global_idx")} * ${_e.type.value}(scale_shift.x) + ${_e.type.value}(scale_shift.y); + ${_e.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...vt(u,B,u)]}),getShaderSource:j},{inputs:[t[0],S]})},bd=(e,t,r)=>{let n=t[0].dims,o=n,a=n[0],i=n[n.length-1],d=$e.sizeFromDimension(n,1)/i,p=yr(i),h=$e.size(o)/p,k=[{type:12,data:d},{type:12,data:Math.floor(i/p)}],S=["type","type"],u=!1,B=[0,n.length-1];for(let te=0;ten[B[X]])),j=Yi(e,R,t[1],t[2],a,d,i,r.epsilon),Z=te=>{let X=er(t[0].dataType),_e=p===1?"vec2f":`mat${p}x2f`,me=Ie=>{let Ge=Ie===0?"x":"y",lt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${X}(${lt}(scale.${Ge}))`;case 2:return`vec2<${X}>(${lt}(scale[0].${Ge}, scale[1].${Ge}))`;case 4:return`vec4<${X}>(${lt}(scale[0].${Ge}, scale[1].${Ge}, scale[2].${Ge}, scale[3].${Ge}))`;default:throw new Error(`Not supported compoents ${p}`)}},ye=ze("input",t[0].dataType,t[0].dims,p),Ae=wt("output",t[0].dataType,o,p);return` + @group(0) @binding(0) var input : array<${ye.type.storage}>; + @group(0) @binding(1) var scale_input : array<${_e}>; + @group(0) @binding(2) var output : array<${Ae.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${te.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${me(0)}, ${me(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],j]})},vd=(e,t)=>{t.format==="NHWC"?bd(e,e.inputs,t):Md(e,e.inputs,t)}}),Td,xd,Ed,np=w(()=>{zt(),Bt(),Qt(),Td=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},xd=(e,t,r)=>{let n=t.simplified,o=e[0].dims,a=e[1],i=!n&&e[2],d=o,p=$e.normalizeAxis(t.axis,o.length),h=$e.sizeToDimension(o,p),k=$e.sizeFromDimension(o,p),S=$e.size(a.dims),u=i?$e.size(i.dims):0;if(S!==k||i&&u!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. + Size of scale and bias (if provided) must match this. + Got scale size of ${S} and bias size of ${u}`);let B=[];for(let ye=0;ye1,X=r>2,_e=ye=>{let Ae=er(e[0].dataType),Ie=[ze("x",e[0].dataType,e[0].dims,R),ze("scale",a.dataType,a.dims,R)];i&&Ie.push(ze("bias",i.dataType,i.dims,R)),Ie.push(wt("output",e[0].dataType,d,R)),te&&Ie.push(wt("mean_data_output",1,B)),X&&Ie.push(wt("inv_std_output",1,B));let Ge=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${ye.registerUniforms(Ge).declareVariables(...Ie)} + ${ye.mainStart()} + ${ye.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Es("f32",R)}; + var mean_square_vector = ${Es("f32",R)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Fr(Ae,R,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${qr("mean_vector",R)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${qr("mean_square_vector",R)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Fr(Ae,R,"x[j + offset]")}; + let f32scale = ${Fr(Ae,R,"scale[j]")}; + output[j + offset] = ${Ie[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Fr(Ae,R,"bias[j]")}`:""} + ); + } + + ${te?"mean_data_output[global_idx] = mean":""}; + ${X?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},me=[{dims:d,dataType:e[0].dataType}];return te&&me.push({dims:B,dataType:1}),X&&me.push({dims:B,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${r};${n}`,inputDependencies:j},getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:_e}},Ed=(e,t)=>{Td(e.inputs),e.compute(xd(e.inputs,t,e.outputCount))}}),Ji,Pd,op=w(()=>{Bt(),ki(),ho(),Ji=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.")},Pd=e=>{Ji(e.inputs);let t=rr.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(lo(e.inputs,{activation:""},t));else{let o=t[t.length-2],a=$e.size(e.inputs[0].dims.slice(0,-2)),i=$e.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&o===1&&i===1){let d=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,r]),h=[1,a,r],k=[d,p];e.compute(po(k,{activation:""},t,h),{inputs:k})}else e.compute(po(e.inputs,{activation:""},t))}}}),Zi,Cd,kd,_r,ip,Np=w(()=>{zt(),Bt(),Pt(),Qt(),Zi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!$e.areEqual(i.dims,[t.n,o,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if($e.size(d)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if($e.size(p)!==h)throw new Error("zeroPoints input size error.")}},Cd=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],a=t.k,i=t.n,d=r.slice(0,n-2),p=$e.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=yr(t.k),u=yr(h),B=yr(i),R=d.concat([o,i]),j=o>1&&i/B%2===0?2:1,Z=$e.size(R)/B/j,te=64,X=[],_e=[p,o,a/S],me=$e.convertShape(e[1].dims).slice();me.splice(-1,1,h/u),X.push(...vt(_e)),X.push(...vt(me)),X.push(...vt(e[2].dims)),e.length===4&&X.push(...vt($e.convertShape(e[3].dims)));let ye=[p,o,i/B];X.push(...vt(ye));let Ae=Ie=>{let Ge=_e.length,lt=ze("a",e[0].dataType,Ge,S),xt=ze("b",12,me.length,u),Kt=ze("scales",e[2].dataType,e[2].dims.length),Yt=[lt,xt,Kt],Ct=e.length===4?ze("zero_points",12,e[3].dims.length):void 0;Ct&&Yt.push(Ct);let Jt=ye.length,$t=wt("output",e[0].dataType,Jt,B),jt=er(e[0].dataType),vr=(()=>{switch(S){case 1:return`array<${jt}, 8>`;case 2:return`mat4x2<${jt}>`;case 4:return`mat2x4<${jt}>`;default:throw new Error(`${S}-component is not supported.`)}})(),Ht=()=>{let ot=` + // reuse a data + var input_offset = ${lt.indicesToOffset(`${lt.type.indices}(batch, row, word_offset)`)}; + var a_data: ${vr}; + for (var j: u32 = 0; j < ${8/S}; j++) { + a_data[j] = ${lt.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Et=0;Et> 4) & b_mask); + b_quantized_values = ${vr}(${Array.from({length:4},(cr,Lr)=>`${jt}(b_value_lower[${Lr}]), ${jt}(b_value_upper[${Lr}])`).join(", ")}); + b_dequantized_values = ${S===1?`${vr}(${Array.from({length:8},(cr,Lr)=>`(b_quantized_values[${Lr}] - ${Ct?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${vr}(${Array(8).fill(`${Ct?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; + workgroup_shared[local_id.x * ${j} + ${Math.floor(Et/B)}]${B>1?`[${Et%B}]`:""} += ${Array.from({length:8/S},(cr,Lr)=>`${S===1?`a_data[${Lr}] * b_dequantized_values[${Lr}]`:`dot(a_data[${Lr}], b_dequantized_values[${Lr}])`}`).join(" + ")}; + `;return ot},Gt=()=>{let ot=` + var col_index = col * ${B}; + ${Ct?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${jt}(8);`} + `;for(let Et=0;Et> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${Ct.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Et} = ${jt}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return ot},Cr=()=>{let ot=`col_index = col * ${B};`;for(let Et=0;Et; + var b_value_upper: vec4; + var b_quantized_values: ${vr}; + var b_dequantized_values: ${vr};`,ot};return` + var workgroup_shared: array<${$t.type.value}, ${j*te}>; + ${Ie.declareVariables(...Yt,$t)} + ${Ie.mainStart([te,1,1])} + let output_indices = ${$t.offsetToIndices(`(global_idx / ${te}) * ${j}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${te}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/S}; + ${Gt()} + for (var word: u32 = 0; word < ${h}; word += ${u}) { + ${Cr()} + for (var i: u32 = 0; i < ${u}; i++) { + ${Ht()} + word_offset += ${8/S}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${j}) { + var output_value: ${$t.type.value} = ${$t.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${te}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${j}; + } + ${$t.setByIndices(`${$t.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${S};${u};${B};${j};${te}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:k}],dispatchGroup:{x:Z},programUniforms:X}),getShaderSource:Ae}},kd=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],a=t.k,i=t.n,d=r.slice(0,n-2),p=$e.size(d),h=e[1].dims[2]/4,k=e[0].dataType,S=yr(t.k),u=yr(h),B=d.concat([o,i]),R=128,j=i%8===0?8:i%4===0?4:1,Z=R/j,te=Z*u*8,X=te/S,_e=te/t.blockSize,me=$e.size(B)/j,ye=[],Ae=[p,o,a/S],Ie=$e.convertShape(e[1].dims).slice();Ie.splice(-1,1,h/u),ye.push(...vt(Ae)),ye.push(...vt(Ie)),ye.push(...vt(e[2].dims)),e.length===4&&ye.push(...vt($e.convertShape(e[3].dims)));let Ge=[p,o,i];ye.push(...vt(Ge));let lt=xt=>{let Kt=Ae.length,Yt=ze("a",e[0].dataType,Kt,S),Ct=ze("b",12,Ie.length,u),Jt=ze("scales",e[2].dataType,e[2].dims.length),$t=[Yt,Ct,Jt],jt=e.length===4?ze("zero_points",12,e[3].dims.length):void 0;jt&&$t.push(jt);let vr=Ge.length,Ht=wt("output",e[0].dataType,vr),Gt=er(e[0].dataType),Cr=()=>{switch(S){case 1:return` + let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Gt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${Gt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Gt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${S}-component is not supported.`)}};return` + var sub_a: array<${Yt.type.value}, ${X}>; + var inter_results: array, ${j}>; + ${xt.declareVariables(...$t,Ht)} + ${xt.mainStart([Z,j,1])} + let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${j}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${_e} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${X}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${X}; a_offset += ${R}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Yt.getByIndices(`${Yt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Yt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${_e} + local_id.x; + ${jt?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${jt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Gt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Gt}(8);`} + let scale = ${Jt.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${Ct.getByIndices(`${Ct.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/S}; + for (var i: u32 = 0; i < ${u}; i++) { + ${Cr()} + let b_value = ${u===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${Gt}>(${Array.from({length:4},(ot,Et)=>`${Gt}(b_value_lower[${Et}]), ${Gt}(b_value_upper[${Et}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Gt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ot,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; + word_offset += ${8/S}; + } + workgroupBarrier(); + } + + if (local_idx < ${j}) { + var output_value: ${Ht.type.value} = ${Ht.type.value}(0); + for (var b = 0u; b < ${Z}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${S};${u};${Z};${j}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:me},programUniforms:ye}),getShaderSource:lt}},_r=(e,t)=>{Zi(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(kd(e.inputs,t)):e.compute(Cd(e.inputs,t))},ip=e=>it(e)}),ap,ea,Sd,$d,Ad,Id,ta,ra,lp,up=w(()=>{zt(),Bt(),Qt(),ap=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].")}},ea=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,r)}; + if (k < 0) { + break; + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + break; + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},Sd=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Mt("uniforms.x_shape",o,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},$d=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k = i32(${Mt("uniforms.x_shape",o,t)}) - 1; + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Ad=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + k = i32(${e.indicesGet("indices",o)}) - ${Mt("uniforms.pads",o,r)}; + if (k < 0) { + k += i32(${Mt("uniforms.x_shape",o,t)}]); + } + if (k >= i32(${Mt("uniforms.x_shape",o,t)})) { + k -= i32(${Mt("uniforms.x_shape",o,t)}); + } + offset += k * i32(${Mt("uniforms.x_strides",o,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Id=(e,t,r)=>{switch(r.mode){case 0:return ea(e,t,r.pads.length);case 1:return Sd(e,t,r.pads.length);case 2:return $d(e,t,r.pads.length);case 3:return Ad(e,t,r.pads.length);default:throw new Error("Invalid mode")}},ta=(e,t)=>{let r=$e.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=$e.size(r),a=[{type:12,data:o},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...vt(e[0].dims,r));let d=["rank"],p=h=>{let k=wt("output",e[0].dataType,r.length),S=ze("x",e[0].dataType,n.length),u=S.type.value,B=Id(k,n.length,t),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&R.push({name:"constant_value",type:i?u:"f32"}),` + ${h.registerUniforms(R).declareVariables(S,k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + + var value = ${u}(0); + ${B} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($e.size(r)/64)},programUniforms:a}),getShaderSource:p}},ra=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,a=new Int32Array(2*o).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(d));let i=[];return a.forEach(d=>i.push(d)),{mode:t.mode,value:n,pads:i}}else return t},lp=(e,t)=>{ap(e.inputs);let r=ra(e.inputs,t);e.compute(ta(e.inputs,r),{inputs:[0]})}}),Vn,Co,Od,Fd,sa,Dd,Ld,na,oa,zd,Bd,ia,Rd,Nd,aa,jd,dp,Ud,Vd,cp=w(()=>{Qe(),zt(),Bt(),Qt(),Vn=e=>{if(T.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Co=(e,t,r)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),d=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();wr.adjustPoolAttributes(r,o,i,d,p,h);let k=wr.computePoolOutputShape(r,o,d,p,i,h,t.autoPad),S=Object.assign({},t);a?Object.assign(S,{kernelShape:i,strides:d,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(S,{kernelShape:i,strides:d,pads:h,cacheKey:t.cacheKey});let u=k.slice();return u.push(u.splice(1,1)[0]),[S,n?u:k]},Od=(e,t)=>{let r=t.format==="NHWC",n=$e.size(e),o=$e.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],S=!!(h+k);a.push({type:12,data:d},{type:12,data:p},{type:12,data:h},{type:12,data:k}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(t.kernelShape.length===2){let B=t.kernelShape[t.kernelShape.length-2],R=t.strides[t.strides.length-2],j=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];u=!!(j+Z),a.push({type:12,data:B},{type:12,data:R},{type:12,data:j},{type:12,data:Z}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,S,u]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=$e.computeStrides(t.kernelShape);a.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:d.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,i,!!p,!1,!1]}},Fd=(e,t,r,n,o,a,i,d,p,h,k,S)=>{let u=o.format==="NHWC",B=t.type.value,R=wt("output",t.type.tensor,n);if(o.kernelShape.length<=2){let j="",Z="",te="",X=r-(u?2:1);if(k?j=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${X}] < 0 || xIndices[${X}] + >= uniforms.x_shape[${X}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:j=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,o.kernelShape.length===2){let _e=r-(u?3:2);S?Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${_e}] < 0 || xIndices[${_e}] >= uniforms.x_shape[${_e}]) { + pad += i32(uniforms.kw); + continue; + } + `:Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; + `,te=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,R)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${R.offsetToIndices("global_idx")}; + var xIndices = ${R.offsetToIndices("global_idx")}; + + var value = ${B}(${d}); + var pad = 0; + ${Z} + ${j} + ${te} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let j=o.kernelShape.length,Z=o.pads.length,te="";return h?te=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:te=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(p).declareVariables(t,R)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${R.offsetToIndices("global_idx")}; + var xIndices = ${R.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${B}(${d}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${j-1}u; j++) { + offsets[j] = offset / ${Mt("uniforms.kernelStrides","j",j)}; + offset -= offsets[j] * ${Mt("uniforms.kernelStrides","j",j)}; + } + offsets[${j-1}] = offset; + + isPad = false; + for (var j = ${r-j}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${Mt("uniforms.strides",`j - ${r-j}u`,j)} + + offsets[j - ${r-j}u] - ${Mt("uniforms.pads","j - 2u",Z)}; + ${te} + } + ${i} + + output[global_idx] = value; + }`}},sa=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Dd=e=>`${sa(e)};${e.countIncludePad}`,Ld=e=>`${sa(e)};${e.storageOrder};${e.dilations}`,na=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}),oa=(e,t,r,n)=>{let[o,a]=Co(t,n,r),i=ze("x",t.dataType,t.dims.length),d=i.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[k,S,u,B,R]=Od(a,o);k.push(...vt(t.dims,a));let j=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil($e.size(a)/64)},programUniforms:k}),getShaderSource:Z=>Fd(Z,i,t.dims.length,a.length,o,p,h,0,S,u,B,R)}},zd=e=>{let t=e.count_include_pad!==0,r=na(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:Dd(n)}},Bd=(e,t)=>{Vn(e.inputs),e.compute(oa("AveragePool",e.inputs[0],!1,t))},ia={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Rd=e=>{let t=e.format;return{format:t,...ia,cacheKey:t}},Nd=(e,t)=>{Vn(e.inputs),e.compute(oa("GlobalAveragePool",e.inputs[0],!0,t))},aa=(e,t,r,n)=>{let[o,a]=Co(t,n,r),i=` + value = max(x_val, value); + `,d="",p=ze("x",t.dataType,t.dims.length),h=["rank"],[k,S,u,B,R]=Od(a,o);return k.push(...vt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${u};${B};${R}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil($e.size(a)/64)},programUniforms:k}),getShaderSource:j=>Fd(j,p,t.dims.length,a.length,o,i,d,t.dataType===10?-65504:-1e5,S,u,B,R)}},jd=(e,t)=>{Vn(e.inputs),e.compute(aa("MaxPool",e.inputs[0],!1,t))},dp=e=>{let t=e.storage_order,r=e.dilations,n=na(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...n,cacheKey:""};return{...o,cacheKey:Ld(o)}},Ud=e=>{let t=e.format;return{format:t,...ia,cacheKey:t}},Vd=(e,t)=>{Vn(e.inputs),e.compute(aa("GlobalMaxPool",e.inputs[0],!0,t))}}),Wd,Gd,Kd,pp,Hd=w(()=>{zt(),Bt(),Pt(),Qt(),Wd=(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((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,a)=>a===t.axis||o===e[0].dims[a]).reduce((o,a)=>o&&a,!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 r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Gd=(e,t)=>{let r=$e.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,a=e[0].dims,i=e[1].dataType,d=$e.size(a),p=n===3||n===2,h=p?[Math.ceil($e.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,S=e.length>2?e[2]:void 0,u=S?p?[Math.ceil($e.size(S.dims)/4)]:S.dims:void 0,B=k.length===0||k.length===1&&k[0]===1,R=B===!1&&k.length===1,j=yr(d),Z=B&&(!p||j===4),te=Z?j:1,X=Z&&!p?j:1,_e=ze("input",p?12:n,h.length,X),me=ze("scale",i,k.length),ye=S?ze("zero_point",p?12:n,u.length):void 0,Ae=wt("output",i,a.length,te),Ie=[_e,me];ye&&Ie.push(ye);let Ge=[h,k];S&&Ge.push(u);let lt=[{type:12,data:d/te},{type:12,data:r},{type:12,data:t.blockSize},...vt(...Ge,a)],xt=Kt=>{let Yt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${Kt.registerUniforms(Yt).declareVariables(...Ie,Ae)} + ${Kt.mainStart()} + ${Kt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Ae.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${_e.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${te===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${_e.getByOffset("global_idx")};`}; + + // Set scale input + ${B?`let scale_value= ${me.getByOffset("0")}`:R?` + let scale_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${me.getByOffset("scale_index")};`:` + var scale_indices: ${me.type.indices} = output_indices; + let index = ${me.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${me.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${me.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${ye?B?p?` + let zero_point_input = ${ye.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ye.getByOffset("0")}`:R?p?` + let zero_point_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${ye.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Ae.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${ye.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${me.indicesToOffset("scale_indices")}; + let zero_point_input = ${ye.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ye.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":_e.type.value}(0);`}; + // Compute and write output + ${Ae.setByOffset("global_idx",`${Ae.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ye?["rank","rank","rank"]:["rank","rank"]},getShaderSource:xt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(d/te/64),y:1,z:1},programUniforms:lt})}},Kd=(e,t)=>{Wd(e.inputs,t),e.compute(Gd(e.inputs,t))},pp=e=>it({axis:e.axis,blockSize:e.blockSize})}),qd,Xd,Qd,hp=w(()=>{Qe(),zt(),Qt(),qd=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||a)throw new Error("Range these inputs' contents are invalid.")},Xd=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),a=[o],i=o,d=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...vt(a)],p=h=>{let k=wt("output",n,a.length),S=k.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:S},{name:"delta",type:S}];return` + ${h.registerUniforms(u).declareVariables(k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${S}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d})}},Qd=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),T.webgpu.validateInputContent&&qd(t,r,n),e.compute(Xd(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Yd,Jd,Zd,ec,mp=w(()=>{zt(),Bt(),Pt(),Qt(),Yd=(e,t,r,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,a=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${r};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:` + ${o}bitcast<${n}>(oldValue) + (${r})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:` + ${o}max(bitcast(oldValue), (${r}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${a}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${r}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Jd=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,a=1,i=Math.ceil($e.size(n)/a),d=n[n.length-1],p=$e.sizeFromDimension(r,d),h=[{type:12,data:i},{type:12,data:d},{type:12,data:p},...vt(e[1].dims,e[2].dims,o)],k=S=>{let u=ze("indices",e[1].dataType,e[1].dims.length),B=ze("updates",e[2].dataType,e[2].dims.length,a),R=t.reduction!=="none"&&t.reduction!==""?rs("output",e[0].dataType,o.length):wt("output",e[0].dataType,o.length,a);return` + ${S.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(u,B,R)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var data_offset = 0u; + let indices_start = uniforms.last_index_dimension * global_idx; + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${Yd(t.reduction,"output[data_offset + i]","value",R.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:k}},Zd=e=>it({reduction:e.reduction}),ec=(e,t)=>{e.compute(Jd(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),tc,rc,sc,nc,oc,ic,ac,lc,uc,dc,cc,la,pc,hc,mc,_c,fc,gc,wc,jp=w(()=>{zt(),Bt(),Pt(),Qt(),tc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},rc=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((o,a)=>n[o]=e[a]),n},sc=(e,t,r,n,o,a)=>{let[i,d,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(k=>a.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0){if(e[d].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");tc(n,t),t.axes.length>0&&rc(n,t.axes,h).forEach((k,S)=>n[S]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>o.push(Number(k))),o.length!==0&&o.length!==h&&r>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},nc=(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`)}})()+"}",oc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",ic=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=o[i],n[i+r]=o[t.length+i]}),n):o},ac=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>o.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>o[a]=r[i])}else r.forEach(a=>o.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((a,i)=>Math.round(a*t[i]))}return o},lc=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>o[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),o.forEach((a,i)=>o[i]=Math.round(a*t[i]))),o},uc=(e,t,r,n,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Mt("uniforms.scales","i",n)}; + var roi_low = ${Mt("uniforms.roi","i",o)}; + var roi_hi = ${Mt("uniforms.roi",`i + ${t.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Mt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Mt("uniforms.output_shape","i",r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,dc=(e,t,r,n,o,a,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Mt("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Mt("uniforms.roi","i",a)}; + var roi_hi = ${Mt("uniforms.roi",`i + ${r.length}`,a)}; + var input_shape_i = ${Mt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${Mt("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,cc=(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 >= ${Mt("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,la=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",pc=(e,t,r,n,o)=>{let[a,i,d,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; + ${la(e,p,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${h} = originalIndices[${i}]; + var col:${h} = originalIndices[${d}]; + ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[d]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${r[i]} - 1)); + col = max(0, min(col, ${r[d]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${h} = getInputValue(batch, channel, row1, col1); + var x12: ${h} = getInputValue(batch, channel, row1, col2); + var x21: ${h} = getInputValue(batch, channel, row2, col1); + var x22: ${h} = getInputValue(batch, channel, row2, col2); + var dx1: ${h} = abs(row - ${h}(row1)); + var dx2: ${h} = abs(${h}(row2) - row); + var dy1: ${h} = abs(col - ${h}(col1)); + var dy2: ${h} = abs(${h}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},hc=(e,t,r,n,o,a,i,d,p,h)=>{let k=r.length===2,[S,u]=k?[0,1]:[2,3],B=e.type.value,R=j=>{let Z=j===S?"row":"col";return` + fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${B} { + var output_index = ${t.indicesGet("output_indices",j)}; + var originalIdx: ${B} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[j]}, + ${n[j]}, ${r[j]}, ${a[j]}, ${a[j]} + ${r.length}); + var fractOriginalIdx: ${B} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${d} && (originalIdx < 0 || originalIdx > (${r[j]} - 1))) { + return ${p}; + } + var data: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${Z}: ${B} = originalIdx + ${B}(i); + if (${Z} < 0 || ${Z} >= ${r[j]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:d?`return ${p};`:`${Z} = max(0, min(${Z}, ${r[j]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",j,`u32(${Z})`)}; + data[i + 1] = ${j===S?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${R(S)}; + ${R(u)}; + fn getCubicInterpolationCoefs(s: ${B}) -> array<${B}, 4> { + var absS = abs(s); + var coeffs: array<${B}, 4> = array<${B}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${B} = 1.0 - absS; + var twoMinusAbsS: ${B} = 2.0 - absS; + var onePlusAbsS: ${B} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${B}, 4>, coefs: array<${B}, 4>) -> ${B} { + var coefsSum: ${B} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${B} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},mc=(e,t,r,n,o)=>{let[a,i,d,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; + ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)}; + ${la(e,h,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${k} = originalIndices[${i}]; + var height:${k} = originalIndices[${d}]; + var width:${k} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${r[i]} - 1)); + height = max(0, min(height, ${r[d]} - 1)); + width = max(0, min(width, ${r[p]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${k} = abs(depth - ${k}(depth1)); + var dx2: ${k} = abs(${k}(depth2) - depth); + var dy1: ${k} = abs(height - ${k}(height1)); + var dy2: ${k} = abs(${k}(height2) - height); + var dz1: ${k} = abs(width - ${k}(width1)); + var dz2: ${k} = abs(${k}(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); + }`},_c=(e,t,r,n,o,a)=>{let i=e.dims,d=ic(a,t.axes,i.length),p=ac(i,n,o,t.axes),h=n.slice();n.length===0&&(h=i.map((X,_e)=>X===0?1:p[_e]/X),t.keepAspectRatioPolicy!=="stretch"&&(p=lc(i,h,t)));let k=wt("output",e.dataType,p.length),S=ze("input",e.dataType,i.length),u=$e.size(p),B=i.length===p.length&&i.every((X,_e)=>X===p[_e]),R=t.coordinateTransformMode==="tf_crop_and_resize",j=t.extrapolationValue,Z=S.type.value,te=X=>` + ${B?"":` + ${nc(t.coordinateTransformMode,Z)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${cc(S,i)}; + ${oc(t.nearestMode,r,Z)}; + ${dc(S,k,i,p,h.length,d.length,R)}; + `;case"linear":return` + ${uc(k,i,p,h.length,d.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${pc(S,k,i,R,j)}`;if(i.length===3||i.length===5)return`${mc(S,k,i,R,j)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${hc(S,k,i,p,h,d,t.cubicCoeffA,R,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${X.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(S,k)} + ${X.mainStart()} + ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${B?"output[global_idx] = input[global_idx];":` + let output_indices = ${k.offsetToIndices("global_idx")}; + var input_indices: ${S.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${S.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${h.length>0?h:""}|${o.length>0?o:""}|${d.length>0?d:""}|${B}|${i}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:h},{type:1,data:d},...vt(i,p)]})}},fc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},gc=(e,t)=>{let r=[],n=[],o=[],a=fc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");sc(e.inputs,t,a,r,n,o),e.compute(_c(e.inputs[0],t,a,r,n,o),{inputs:[0]})},wc=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,d=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return it({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:d,mode:p,nearestMode:h})}}),Xt,yc,jr,Wr=w(()=>{zt(),Bt(),Pt(),Qt(),Xt=(e,t)=>{let[r,n,o,a]=e,{numHeads:i,rotaryEmbeddingDim:d}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!$e.areEqual(n.dims,[])&&!$e.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!$e.areEqual(o.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],k=o.dims[0],S=$e.sizeFromDimension(r.dims,1)/h,u=d===0?o.dims[1]*2:S/i;if(d>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(u/2!==o.dims[1]&&d/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},yc=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:a}=t,i=e[0].dims[0],d=$e.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=d/p,k=e[2].dims[1],S=o===0?k*2:h/n,u=new Array(i,p,h/S,S-k),B=$e.computeStrides(u),R=[{type:1,data:a},{type:12,data:u},{type:12,data:B},...e[0].dims.length===3?new Array({type:12,data:[d,h,S,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,S,p*S,1]}):[],...vt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],j=Z=>{let te=ze("input",e[0].dataType,e[0].dims.length),X=ze("position_ids",e[1].dataType,e[1].dims.length),_e=ze("cos_cache",e[2].dataType,e[2].dims.length),me=ze("sin_cache",e[3].dataType,e[3].dims.length),ye=wt("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:B.length},{name:"input_output_strides",type:"u32",length:B.length}]),` + ${Z.declareVariables(te,X,_e,me,ye)} + + ${Z.mainStart(Nr)} + let half_rotary_emb_dim = uniforms.${_e.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${X.broadcastedIndicesToOffset("bsnh.xy",wt("",X.type.tensor,2))}; + let position_id = + u32(${X.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${te.getByOffset("i")} * ${_e.get("position_id","bsnh[3]")} - + ${te.getByOffset("j")} * ${me.get("position_id","bsnh[3]")}; + ${ye.setByOffset("i","re")} + let im = ${te.getByOffset("i")} * ${me.get("position_id","bsnh[3]")} + + ${te.getByOffset("j")} * ${_e.get("position_id","bsnh[3]")}; + ${ye.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${ye.setByOffset("k",te.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:it({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:j,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($e.size(u)/Nr)},programUniforms:R})}},jr=(e,t)=>{Xt(e.inputs,t),e.compute(yc(e.inputs,t))}}),Xr,an,_p,fp=w(()=>{zt(),Bt(),Qt(),Xr=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},an=(e,t,r,n)=>{let o=t.simplified,a=e[0].dims,i=$e.size(a),d=a,p=i,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],S=!o&&e.length>3,u=e.length>4,B=n&&r>1,R=n&&r>2,j=r>3,Z=64,te=yr(h),X=[{type:12,data:p},{type:12,data:te},{type:12,data:h},{type:1,data:t.epsilon}],_e=ye=>{let Ae=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ie=[ze("x",e[0].dataType,e[0].dims,te),ze("skip",e[1].dataType,e[1].dims,te),ze("gamma",e[2].dataType,e[2].dims,te)];S&&Ie.push(ze("beta",e[3].dataType,e[3].dims,te)),u&&Ie.push(ze("bias",e[4].dataType,e[4].dims,te)),Ie.push(wt("output",e[0].dataType,d,te)),B&&Ie.push(wt("mean_output",1,k)),R&&Ie.push(wt("inv_std_output",1,k)),j&&Ie.push(wt("input_skip_bias_sum",e[0].dataType,d,te));let Ge=er(e[0].dataType),lt=er(1,te);return` + + ${ye.registerUniforms(Ae).declareVariables(...Ie)} + var sum_shared : array<${lt}, ${Z}>; + var sum_squared_shared : array<${lt}, ${Z}>; + + ${ye.mainStart([Z,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${Z}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${Z}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${Z-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[offset1d + i]":Ge+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${j?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Fr(Ge,te,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${Z}; + 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 = ${qr("sum",te)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${qr("square_sum",te)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${B?"mean_output[global_idx] = mean;":""} + ${R?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${Ge}(mean)`}) * + ${Ge}(inv_std_dev) * gamma[offset1d + i] + ${S?"+ beta[offset1d + i]":""}; + } + }`},me=[{dims:d,dataType:e[0].dataType}];return r>1&&me.push({dims:k,dataType:1}),r>2&&me.push({dims:k,dataType:1}),r>3&&me.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${te};${B};${R};${j}`,inputDependencies:e.map((ye,Ae)=>"type")},getShaderSource:_e,getRunData:()=>({outputs:me,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:X})}},_p=(e,t)=>{Xr(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(an(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Mc,_,x,V,be,Oe,Se,Ye,rt=w(()=>{zt(),Bt(),Pt(),Qt(),Mc=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},_=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},x=(e,t)=>{if(e.length>1){let r=_(e,1),n=_(e,2),o=_(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),it({starts:r,ends:n,axes:o})}else return t},V=(e,t,r,n,o)=>{let a=e;return e<0&&(a+=r[n[t]]),o[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},be=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${Mt("uniforms.input_shape","i",r.length)}; + let steps_i = ${Mt("uniforms.steps","i",r.length)}; + let signs_i = ${Mt("uniforms.signs","i",r.length)}; + let starts_i = ${Mt("uniforms.starts","i",r.length)}; + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Oe=(e,t)=>{let r=e[0].dims,n=$e.size(r),o=t.axes.length>0?$e.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=_(e,4);a.forEach(te=>te!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(o.length).fill(1));let i=t.starts.map((te,X)=>V(te,X,r,o,a)),d=t.ends.map((te,X)=>V(te,X,r,o,a));if(o.length!==i.length||o.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let te=0;teMath.sign(te));a.forEach((te,X,_e)=>{if(te<0){let me=(d[X]-i[X])/te,ye=i[X],Ae=ye+me*a[X];i[X]=Ae,d[X]=ye,_e[X]=-te}});let h=r.slice(0);o.forEach((te,X)=>{h[te]=Math.ceil((d[te]-i[te])/a[te])});let k={dims:h,dataType:e[0].dataType},S=wt("output",e[0].dataType,h.length),u=ze("input",e[0].dataType,e[0].dims.length),B=$e.size(h),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],j=[{type:12,data:B},{type:12,data:i},{type:6,data:p},{type:12,data:a},...vt(e[0].dims,h)],Z=te=>` + ${te.registerUniforms(R).declareVariables(u,S)} + ${be(u,S,r)} + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${S.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${S.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:j})}},Se=(e,t)=>{Mc(e.inputs,t);let r=x(e.inputs,t);e.compute(Oe(e.inputs,r),{inputs:[0]})},Ye=e=>{let t=e.starts,r=e.ends,n=e.axes;return it({starts:t,ends:r,axes:n})}}),mt,Tt,Lt,Ut,Dt=w(()=>{zt(),Bt(),Pt(),Ws(),Qt(),mt=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Tt=(e,t)=>{let r=e.inputs[0],n=r.dims,o=$e.size(n),a=n.length,i=$e.normalizeAxis(t.axis,a),d=iGe),h[i]=a-1,h[a-1]=i,p=e.compute(ss(r,h),{inputs:[r],outputs:[-1]})[0]):p=r;let k=p.dims,S=k[a-1],u=o/S,B=yr(S),R=S/B,j=64;u===1&&(j=256);let Z=(Ie,Ge)=>Ge===4?`max(max(${Ie}.x, ${Ie}.y), max(${Ie}.z, ${Ie}.w))`:Ge===2?`max(${Ie}.x, ${Ie}.y)`:Ge===3?`max(max(${Ie}.x, ${Ie}.y), ${Ie}.z)`:Ie,te=ze("x",p.dataType,p.dims,B),X=wt("result",p.dataType,p.dims,B),_e=te.type.value,me=er(p.dataType)==="f32"?`var threadMax = ${_e}(-3.402823e+38f);`:`var threadMax = ${_e}(-65504.0h);`,ye=Ie=>` + var rowMaxShared : ${_e}; + var rowSumShared : ${_e}; + var threadShared : array<${_e}, ${j}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${_e} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${_e}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Ie.registerUniform("packedCols","i32").declareVariables(te,X)} + ${Ie.mainStart(j)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${j}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${me} + 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 = ${_e}(${Z("threadShared[0]",B)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${_e}(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 = ${_e}(${qr("threadShared[0]",B)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,Ae=e.compute({name:"Softmax",shaderCache:{hint:`${B};${j}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:R}]}),getShaderSource:ye},{inputs:[p],outputs:[d?-1:0]})[0];d&&e.compute(ss(Ae,h),{inputs:[Ae]})},Lt=(e,t)=>{mt(e.inputs),Tt(e,t)},Ut=e=>it({axis:e.axis})}),Vt,Zt,sr,qt,or,Sr=w(()=>{zt(),Bt(),Qt(),Vt=e=>Array.from(e.getBigInt64Array(),Number),Zt=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(Vt(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")},sr=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Vt(e[1]),o=sr(r,n),a=$e.size(o),i=e[0].dataType,d=ze("input",i,r.length),p=wt("output",i,o.length),h=k=>` + const inputShape = ${d.indices(...r)}; + ${k.registerUniform("output_size","u32").declareVariables(d,p)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + for (var i = 0; i < ${r.length}; i++) { + let input_dim_i = ${d.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; + + ${d.indicesSet("input_indices","i","input_dim_value")} + } + ${p.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...vt(e[0].dims,o)]}),getShaderSource:h}},or=e=>{Zt(e.inputs),e.compute(qt(e.inputs),{inputs:[0]})}}),Tr,dr,Pr,$r=w(()=>{zt(),Bt(),Qt(),Tr=(e,t,r,n,o)=>{let a=wt("output_data",o,r.length,4),i=ze("a_data",t[1].dataType,t[1].dims.length,4),d=ze("b_data",t[2].dataType,t[2].dims.length,4),p=ze("c_data",t[0].dataType,t[0].dims.length,4),h,k=(S,u,B)=>`select(${u}, ${S}, ${B})`;if(!n)h=a.setByOffset("global_idx",k(i.getByOffset("global_idx"),d.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let S=(u,B,R="")=>{let j=`a_data[index_a${B}][component_a${B}]`,Z=`b_data[index_b${B}][component_b${B}]`,te=`bool(c_data[index_c${B}] & (0xffu << (component_c${B} * 8)))`;return` + let output_indices${B} = ${a.offsetToIndices(`global_idx * 4u + ${B}u`)}; + let offset_a${B} = ${i.broadcastedIndicesToOffset(`output_indices${B}`,a)}; + let offset_b${B} = ${d.broadcastedIndicesToOffset(`output_indices${B}`,a)}; + let offset_c${B} = ${p.broadcastedIndicesToOffset(`output_indices${B}`,a)}; + let index_a${B} = offset_a${B} / 4u; + let index_b${B} = offset_b${B} / 4u; + let index_c${B} = offset_c${B} / 4u; + let component_a${B} = offset_a${B} % 4u; + let component_b${B} = offset_b${B} % 4u; + let component_c${B} = offset_c${B} % 4u; + ${u}[${B}] = ${R}(${k(j,Z,te)}); + `};o===9?h=` + var data = vec4(0); + ${S("data",0,"u32")} + ${S("data",1,"u32")} + ${S("data",2,"u32")} + ${S("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${S("output_data[global_idx]",0)} + ${S("output_data[global_idx]",1)} + ${S("output_data[global_idx]",2)} + ${S("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(p,i,d,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},dr=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,a=!($e.areEqual(t,r)&&$e.areEqual(r,n)),i=t,d=$e.size(t);if(a){let h=rr.calcShape(rr.calcShape(t,r,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,d=$e.size(i)}let p=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Tr(h,e,i,a,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:p},...vt(n,t,r,i)]})}},Pr=e=>{e.compute(dr(e.inputs))}}),Gr,Ur=w(()=>{el(),no(),zc(),cl(),Bc(),Yl(),Rc(),Vc(),Pu(),Gc(),Fu(),Kc(),Hc(),qc(),Rp(),jn(),Xc(),Yc(),Jc(),ep(),yd(),sp(),np(),op(),Np(),Wi(),up(),cp(),Hd(),hp(),mp(),ei(),jp(),Wr(),fp(),rt(),Dt(),fd(),Sr(),Ws(),bi(),$r(),Gr=new Map([["Abs",[ai]],["Acos",[hl]],["Acosh",[ml]],["Add",[Vl]],["ArgMax",[Za,si]],["ArgMin",[ri,si]],["Asin",[li]],["Asinh",[_l]],["Atan",[fl]],["Atanh",[ui]],["Attention",[ol]],["AveragePool",[Bd,zd]],["BatchNormalization",[ll]],["BiasAdd",[dl]],["BiasSplitGelu",[Nl]],["Cast",[wl,gl]],["Ceil",[Ml]],["Clip",[yl]],["Concat",[tu,Pi]],["Conv",[Di,go]],["ConvTranspose",[Eu,vu]],["Cos",[ci]],["Cosh",[bl]],["CumSum",[ku,Su]],["DepthToSpace",[Iu,Ou]],["DequantizeLinear",[Kd,pp]],["Div",[Wl]],["Einsum",[Nu,ju]],["Elu",[vl,zn]],["Equal",[Gl]],["Erf",[pi]],["Exp",[Tl]],["Expand",[Nn]],["FastGelu",[Gu]],["Floor",[xl]],["FusedConv",[Di,go]],["Gather",[qu,Hu]],["GatherElements",[sd,rd]],["GatherBlockQuantized",[ed,td]],["GatherND",[Qu,Yu]],["Gelu",[hi]],["Gemm",[id,Ri]],["GlobalAveragePool",[Nd,Rd]],["GlobalMaxPool",[Vd,Ud]],["Greater",[ql]],["GreaterOrEqual",[Xl]],["GridSample",[Po,Zc]],["GroupQueryAttention",[wd]],["HardSigmoid",[$l,Sl]],["InstanceNormalization",[vd]],["LayerNormalization",[Ed]],["LeakyRelu",[El,zn]],["Less",[xi]],["LessOrEqual",[Ql]],["Log",[Ll]],["MatMul",[Pd]],["MatMulNBits",[_r,ip]],["MaxPool",[jd,dp]],["Mul",[Kl]],["MultiHeadAttention",[md,hd]],["Neg",[mi]],["Not",[Pl]],["Pad",[lp]],["Pow",[Ti]],["QuickGelu",[Bl,zn]],["Range",[Qd]],["Reciprocal",[Cl]],["ReduceMin",[Qa]],["ReduceMean",[Qo]],["ReduceMax",[Xa]],["ReduceSum",[Ya]],["ReduceProd",[Jo]],["ReduceL1",[Ha]],["ReduceL2",[qa]],["ReduceLogSum",[Zo]],["ReduceLogSumExp",[Yo]],["ReduceSumSquare",[Ja]],["Relu",[kl]],["Resize",[gc,wc]],["RotaryEmbedding",[jr]],["ScatterND",[ec,Zd]],["Sigmoid",[_i]],["Sin",[fi]],["Sinh",[Al]],["Slice",[Se,Ye]],["SkipLayerNormalization",[_p]],["Split",[_d,qi]],["Sqrt",[Il]],["Softmax",[Lt,Ut]],["Sub",[Hl]],["Tan",[gi]],["Tanh",[Ol]],["ThresholdedRelu",[Dl,zn]],["Tile",[or]],["Transpose",[Uo,Ca]],["Where",[Pr]]])}),gs,Wn=w(()=>{Qe(),Yr(),Qt(),gs=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,r,n,o){We(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let h of t)d.push({binding:d.length,resource:{buffer:h.buffer}});for(let h of r)d.push({binding:d.length,resource:{buffer:h.buffer}});o&&d.push({binding:d.length,resource:o});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}i.setPipeline(e.computePipeline),i.setBindGroup(0,p),i.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ne(e.programInfo.name)}dispose(){}build(e,t){We(e.name);let r=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{r.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=bn(t,this.backend.device.limits),a=e.getShaderSource(o),i=`${n.join(` +`)} +${o.additionalImplementations} +${a}`,d=r.createShaderModule({code:i,label:e.name});ir("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let p=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return Ne(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&r<=o&&n<=o)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>o){if(i=Math.ceil(Math.cbrt(a)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),ua,ns,Ps,da,ko,ca=w(()=>{Qe(),zt(),Yr(),Ln(),yt(),Ur(),Wn(),ua=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{var o,a;let n=e.name;return(o=e.shaderCache)!=null&&o.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${ua(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Ps=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},da=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},ko=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let r=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r},o=a=>t.features.has(a)&&r.push(a)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new da(this.device),this.adapterInfo=new Ps(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ct(this),this.programManager=new gs(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,gn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.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;We(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=B);let j=Number(B-this.queryTimeBase),Z=Number(R-this.queryTimeBase);if(!Number.isSafeInteger(j)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:S.map(te=>({dims:te.dims,dataType:Ts(te.dataType)})),outputsMetadata:u.map(te=>({dims:te.dims,dataType:Ts(te.dataType)})),kernelId:i,kernelType:p,kernelName:h,programName:k,startTime:j,endTime:Z});else{let te="";S.forEach((_e,me)=>{te+=`input[${me}]: [${_e.dims}] | ${Ts(_e.dataType)}, `});let X="";u.forEach((_e,me)=>{X+=`output[${me}]: [${_e.dims}] | ${Ts(_e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${p}|${h}|${k}" ${te}${X}execution time: ${Z-j} ns`)}Re("GPU",`${k}::${B}::${R}`)}e.unmap(),this.pendingQueries.delete(e)}),Ne()}run(e,t,r,n,o,a){We(e.name);let i=[];for(let X=0;X_e):r;if(k.length!==d.length)throw new Error(`Output size ${k.length} must be equal to ${d.length}.`);let S=[],u=[];for(let X=0;X=a)throw new Error(`Invalid output index: ${k[X]}`);if(k[X]===-3)continue;let _e=k[X]===-1,me=k[X]===-2,ye=_e||me?o(d[X].dataType,d[X].dims):n(k[X],d[X].dataType,d[X].dims);if(S.push(ye),ye.data===0)continue;let Ae=this.gpuDataManager.get(ye.data);if(!Ae)throw new Error(`no GPU data for output: ${ye.data}`);if(_e&&this.temporaryData.push(Ae),me){let Ie=this.kernelPersistentData.get(this.currentKernelId);Ie||(Ie=[],this.kernelPersistentData.set(this.currentKernelId,Ie)),Ie.push(Ae)}u.push(Ae)}if(i.length!==t.length||u.length!==S.length){if(u.length===0)return Ne(e.name),S;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let B;if(h){let X=0,_e=[];h.forEach(Ie=>{let Ge=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(Ge.length===0)return;let lt=Ie.type===10?2:4,xt,Kt;Ie.type===10?(Kt=Ge.length>4?16:Ge.length>2?8:Ge.length*lt,xt=Ge.length>4?16:lt*Ge.length):(Kt=Ge.length<=2?Ge.length*lt:16,xt=16),X=Math.ceil(X/Kt)*Kt,_e.push(X);let Yt=Ie.type===10?8:4;X+=Ge.length>4?Math.ceil(Ge.length/Yt)*xt:Ge.length*lt});let me=16;X=Math.ceil(X/me)*me;let ye=new ArrayBuffer(X);h.forEach((Ie,Ge)=>{let lt=_e[Ge],xt=typeof Ie.data=="number"?[Ie.data]:Ie.data;if(Ie.type===6)new Int32Array(ye,lt,xt.length).set(xt);else if(Ie.type===12)new Uint32Array(ye,lt,xt.length).set(xt);else if(Ie.type===10)new Uint16Array(ye,lt,xt.length).set(xt);else if(Ie.type===1)new Float32Array(ye,lt,xt.length).set(xt);else throw new Error(`Unsupported uniform type: ${Ts(Ie.type)}`)});let Ae=this.gpuDataManager.create(X,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ae.buffer,0,ye,0,X),this.gpuDataManager.release(Ae.id),B={offset:0,size:X,buffer:Ae.buffer}}let R=this.programManager.normalizeDispatchGroupSize(p),j=R[1]===1&&R[2]===1,Z=ns(e,t,j),te=this.programManager.getArtifact(Z);if(te||(te=this.programManager.build(e,R),this.programManager.setArtifact(Z,te),ir("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&te.uniformVariablesInfo){if(h.length!==te.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${te.uniformVariablesInfo.length}, got ${h.length} in program "${te.programInfo.name}".`);for(let X=0;X`[ProgramManager] run "${e.name}" (key=${Z}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let X={kernelId:this.currentKernelId,programName:te.programInfo.name,inputTensorViews:t,outputTensorViews:S};this.pendingKernels.push(X),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(X)}return this.programManager.run(te,i,u,R,B),Ne(e.name),S}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,r,n){let o=Gr.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],r]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,a=n.kernelName,i=n.kernelEntry,d=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),ir("info",()=>`[WebGPU] Start to run kernel "[${o}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),i(t,d[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${a}" failed. ${h}`)),1}finally{p&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let a=o.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a);return o.set(t,[i,r]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,r){return async()=>{let n=await Ce(this,e,t);return wn(n.buffer,r)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ir("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(){ir("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ir("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),So,xr,Dr,Ds,Hs,ln,$o,pa,bc=w(()=>{Yr(),So=1,xr=()=>So++,Dr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ds=(e,t)=>{let r=Dr.get(e);if(!r)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*r/8):0},Hs=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ds(this.dataType,this.tensorShape)}destroy(){ir("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((r,n)=>r===t[n])}},ln=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Ds(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,!0,!0),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else ir("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},$o=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=xr();return this.tensorTrackersById.set(e,new ln(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n){ir("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){ir("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let o=xr(),a=new Hs({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(o,new ln(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,t,r,n,o){let a=this.backend.currentSessionId;for(let[p,h]of this.freeTensors.entries())if(h.sameTypeAndShape(e,t)){ir("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}let i=this.backend.currentContext;ir("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let d=await i.createTensor({dataType:e,shape:t,dimensions:t,usage:r,writable:n,readable:o});return new Hs({sessionId:a,context:i,tensor:d,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},pa=(...e)=>new $o(...e)}),Ao,gp,ha,ma=w(()=>{zt(),Ot(),Ln(),bc(),Yr(),Ao=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),gp=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,a)=>o===n[a]&&e[o]===t[o])},ha=class{constructor(e){this.tensorManager=pa(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],gn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>gp(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ir("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let o=Ao.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,r,n)}uploadTensor(e,t){if(!_t().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ir("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return wn(r,t)}}registerMLTensor(e,t,r){let n=Ao.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,r);return ir("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,r,n,o,a){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let d=a.get(i);if(!d)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=d.slice(t,t+r).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return ir("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),_a={};v(_a,{init:()=>Oo});var Io,fa,Oo,Up=w(()=>{zt(),ca(),Yr(),Bt(),ma(),Io=class p_{constructor(t,r,n,o){this.module=t,this.dataType=r,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=$e.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=$e.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=$e.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=$e.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if($e.size(t)!==$e.size(this.dims))throw new Error("Invalid new shape");return new p_(this.module,this.dataType,this.data,t)}},fa=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=r/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,a));let i=Number(e.getValue(n*o++,a));this.outputCount=Number(e.getValue(n*o++,a)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,a));let d=[];for(let p=0;ptypeof d=="number"?this.inputs[d]:d))??this.inputs,n=(t==null?void 0:t.outputs)??[],o=(d,p,h)=>new Io(this.module,p,this.output(d,h),h),a=(d,p)=>{let h=ls(d,p);if(!h)throw new Error(`Unsupported data type: ${d}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new Io(this.module,d,k,p)};return this.backend.run(e,r,n,o,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,o);for(let i=0;i{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new ko;await a.initialize(r,n),o("webgpu",[a,i=>a.alloc(Number(i)),i=>a.free(i),(i,d,p,h=!1)=>{if(h)ir("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(i)}, dst=${Number(d)}, size=${Number(p)}`),a.memcpy(Number(i),Number(d));else{ir("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(i)}, gpuDataId=${Number(d)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(i>>>0),Number(i>>>0)+Number(p));a.upload(Number(d),k)}},async(i,d,p)=>{ir("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${d}, size=${p}`),await a.download(Number(i),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+p)>>>0))},(i,d,p)=>a.createKernel(i,Number(d),p,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),i=>a.releaseKernel(i),(i,d,p,h)=>{ir("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${i}, contextDataOffset=${d}`);let k=new fa(t,a,Number(d));return a.computeKernel(Number(i),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new ha(r);o("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,d,p,h)=>a.ensureTensor(i,d,p,h),(i,d)=>{a.uploadTensor(i,d)},async(i,d)=>a.downloadTensor(i,d)])}}}),wp,vc,qs,Kr,Ch,yp,Vp,Wp,Gp,Kp,Hp,qp,kh=w(()=>{Js(),Jn(),zt(),Ot(),ts(),An(),wp=(e,t)=>{_t()._OrtInit(e,t)!==0&&tr("Can't initialize onnxruntime.")},vc=async e=>{wp(e.wasm.numThreads,Zs(e.logLevel))},qs=async(e,t)=>{{let r=(Up(),M(_a)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",_t(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",_t(),e)}}},Kr=new Map,Ch=e=>{let t=_t(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&tr("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},yp=e=>{let t=_t(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Vp=async(e,t)=>{var S,u,B;let r,n,o=_t();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=yp(e);let a=0,i=0,d=0,p=[],h=[],k=[];try{if([i,p]=$n(t),(t==null?void 0:t.externalData)&&o.mountExternalData){let ye=[];for(let Ae of t.externalData){let Ie=typeof Ae=="string"?Ae:Ae.path;ye.push(fn(typeof Ae=="string"?Ae:Ae.data).then(Ge=>{o.mountExternalData(Ie,Ge)}))}await Promise.all(ye)}for(let ye of(t==null?void 0:t.executionProviders)??[])if((typeof ye=="string"?ye:ye.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof ye!="string"){let Ae=ye,Ie=Ae==null?void 0:Ae.context,Ge=Ae==null?void 0:Ae.gpuDevice,lt=Ae==null?void 0:Ae.deviceType,xt=Ae==null?void 0:Ae.powerPreference;Ie?o.currentContext=Ie:Ge?o.currentContext=await o.jsepCreateMLContext(Ge):o.currentContext=await o.jsepCreateMLContext({deviceType:lt,powerPreference:xt})}else o.currentContext=await o.jsepCreateMLContext();break}a=await o._OrtCreateSession(r,n,i),a===0&&tr("Can't create a session."),(S=o.jsepOnCreateSession)==null||S.call(o),o.currentContext&&(o.jsepRegisterMLContext(a,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[R,j]=Ch(a),Z=!!(t!=null&&t.enableGraphCapture),te=[],X=[],_e=[];for(let ye=0;yeye==="gpu-buffer"||ye==="ml-tensor")&&(d=o._OrtCreateBinding(a),d===0&&tr("Can't create IO binding."),me={handle:d,outputPreferredLocations:_e,outputPreferredLocationsEncoded:_e.map(ye=>xs(ye))}),Kr.set(a,[a,h,k,me,Z,!1]),[a,te,X]}catch(R){throw h.forEach(j=>o._OrtFree(j)),k.forEach(j=>o._OrtFree(j)),d!==0&&o._OrtReleaseBinding(d)!==0&&tr("Can't release IO binding."),a!==0&&o._OrtReleaseSession(a)!==0&&tr("Can't release session."),R}finally{o._free(r),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&tr("Can't release session options."),p.forEach(R=>o._free(R)),(B=o.unmountExternalData)==null||B.call(o)}},Wp=e=>{var p;let t=_t(),r=Kr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,a,i,d]=r;i&&(d&&t._OrtClearBoundOutputs(i.handle)!==0&&tr("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&tr("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),o.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&tr("Can't release session."),Kr.delete(e)},Gp=(e,t,r,n,o,a=!1)=>{if(!e){t.push(0);return}let i=_t(),d=i.PTR_SIZE,p=e[0],h=e[1],k=e[3],S,u;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let j=e[2].gpuBuffer;u=ls(Us(p),h);let Z=i.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');S=Z(n,o,j,u)}else if(k==="ml-tensor"){let j=e[2].mlTensor;u=ls(Us(p),h);let Z=i.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');S=Z(j,Us(p),h)}else{let j=e[2];if(Array.isArray(j)){u=d*j.length,S=i._malloc(u),r.push(S);for(let Z=0;Zi.setValue(R+te*d,Z,d===4?"i32":"i64"));let j=i._OrtCreateTensor(Us(p),S,u,R,h.length,xs(k));j===0&&tr(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(j)}finally{i.stackRestore(B)}},Kp=async(e,t,r,n,o,a)=>{var Kt,Yt;let i=_t(),d=i.PTR_SIZE,p=Kr.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],S=p[2],u=p[3],B=p[4],R=p[5],j=t.length,Z=n.length,te=0,X=[],_e=[],me=[],ye=[],Ae=i.stackSave(),Ie=i.stackAlloc(j*d),Ge=i.stackAlloc(j*d),lt=i.stackAlloc(Z*d),xt=i.stackAlloc(Z*d);try{(Kt=i.jsepOnRunStart)==null||Kt.call(i,h),[te,X]=Rs(a);for(let $t=0;$tIr*Er,1);Cr=Ts(cr);let Lo=u==null?void 0:u.outputPreferredLocations[n[$t]];if(Cr==="string"){if(Lo==="gpu-buffer"||Lo==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ir=[];for(let Er=0;Er0){let Ir=i.jsepGetBuffer;if(!Ir)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Er=Ir(ot),Kn=ls(cr,un);if(Kn===void 0||!_n(Cr))throw new Error(`Unsupported data type: ${Cr}`);Gt=!0,Jt.push([Cr,Hr,{gpuBuffer:Er,download:i.jsepCreateDownloader(Er,Kn,Cr),dispose:()=>{i._OrtReleaseTensor(jt)!==0&&tr("Can't release tensor.")}},"gpu-buffer"])}else if(Lo==="ml-tensor"&&un>0){let Ir=i.jsepEnsureTensor;if(!Ir)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ls(cr,un)===void 0||!en(Cr))throw new Error(`Unsupported data type: ${Cr}`);let Er=await Ir(ot,cr,Hr,!1);Gt=!0,Jt.push([Cr,Hr,{mlTensor:Er,download:i.jsepCreateMLTensorDownloader(ot,Cr),dispose:()=>{i.jsepReleaseTensorId(ot),i._OrtReleaseTensor(jt)}},"ml-tensor"])}else{let Ir=mn(Cr),Er=new Ir(un);new Uint8Array(Er.buffer,Er.byteOffset,Er.byteLength).set(i.HEAPU8.subarray(ot,ot+Er.byteLength)),Jt.push([Cr,Hr,Er,"cpu"])}}finally{i.stackRestore(vr),Cr==="string"&&ot&&i._free(ot),Gt||i._OrtReleaseTensor(jt)}}return u&&!B&&(i._OrtClearBoundOutputs(u.handle)!==0&&tr("Can't clear bound outputs."),Kr.set(e,[h,k,S,u,B,!1])),Jt}finally{i.stackRestore(Ae),_e.forEach(Ct=>i._OrtReleaseTensor(Ct)),me.forEach(Ct=>i._OrtReleaseTensor(Ct)),ye.forEach(Ct=>i._free(Ct)),te!==0&&i._OrtReleaseRunOptions(te),X.forEach(Ct=>i._free(Ct))}},Hp=e=>{let t=_t(),r=Kr.get(e);if(!r)throw new Error("invalid session id");let n=r[0],o=t._OrtEndProfiling(n);o===0&&tr("Can't get an profile file name."),t._OrtFree(o)},qp=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Gn,ws,ga,Tc,xc,Mp,Xp,bp,Fo,Do,Sh,$h,Ah,Ih,Oh,Fh,Dh,Lh,zh=w(()=>{Qe(),kh(),Ot(),Ss(),Gn=()=>!!T.wasm.proxy&&typeof document<"u",ga=!1,Tc=!1,xc=!1,bp=new Map,Fo=(e,t)=>{let r=bp.get(e);r?r.push(t):bp.set(e,[t])},Do=()=>{if(ga||!Tc||xc||!ws)throw new Error("worker not ready")},Sh=e=>{switch(e.data.type){case"init-wasm":ga=!1,e.data.err?(xc=!0,Xp[1](e.data.err)):(Tc=!0,Xp[0]()),Mp&&(URL.revokeObjectURL(Mp),Mp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=bp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},$h=async()=>{if(!Tc){if(ga)throw new Error("multiple calls to 'initWasm()' detected.");if(xc)throw new Error("previous call to 'initWasm()' failed.");if(ga=!0,Gn())return new Promise((e,t)=>{ws==null||ws.terminate(),Qs().then(([r,n])=>{try{ws=n,ws.onerror=a=>t(a),ws.onmessage=Sh,Xp=[e,t];let o={type:"init-wasm",in:T};ws.postMessage(o),Mp=r}catch(o){t(o)}},t)});try{await nt(T.wasm),await vc(T),Tc=!0}catch(e){throw xc=!0,e}finally{ga=!1}}},Ah=async e=>{if(Gn())return Do(),new Promise((t,r)=>{Fo("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:T}};ws.postMessage(n)});await qs(T,e)},Ih=async e=>Gn()?(Do(),new Promise((t,r)=>{Fo("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};ws.postMessage(n,[e.buffer])})):yp(e),Oh=async(e,t)=>{if(Gn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Do(),new Promise((r,n)=>{Fo("create",[r,n]);let o={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),ws.postMessage(o,a)})}else return Vp(e,t)},Fh=async e=>{if(Gn())return Do(),new Promise((t,r)=>{Fo("release",[t,r]);let n={type:"release",in:e};ws.postMessage(n)});Wp(e)},Dh=async(e,t,r,n,o,a)=>{if(Gn()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Do(),new Promise((i,d)=>{Fo("run",[i,d]);let p=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};ws.postMessage(h,qp(p))})}else return Kp(e,t,r,n,o,a)},Lh=async e=>{if(Gn())return Do(),new Promise((t,r)=>{Fo("end-profiling",[t,r]);let n={type:"end-profiling",in:e};ws.postMessage(n)});Hp(e)}}),Qp,Bh,Rh,m_=w(()=>{Qe(),zh(),zt(),st(),An(),Qp=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Bh=e=>{switch(e[3]){case"cpu":return new ce(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!_n(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return ce.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!en(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return ce.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Rh=class{async fetchModelAndCopyToWasmMemory(e){return Ih(await fn(e))}async loadModel(e,t){We();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Oh(r,t),Ne()}async dispose(){return Fh(this.sessionId)}async run(e,t,r){We();let n=[],o=[];Object.entries(e).forEach(S=>{let u=S[0],B=S[1],R=this.inputNames.indexOf(u);if(R===-1)throw new Error(`invalid input '${u}'`);n.push(B),o.push(R)});let a=[],i=[];Object.entries(t).forEach(S=>{let u=S[0],B=S[1],R=this.outputNames.indexOf(u);if(R===-1)throw new Error(`invalid output '${u}'`);a.push(B),i.push(R)});let d=n.map((S,u)=>Qp(S,()=>`input "${this.inputNames[o[u]]}"`)),p=a.map((S,u)=>S?Qp(S,()=>`output "${this.outputNames[i[u]]}"`):null),h=await Dh(this.sessionId,o,d,i,p,r),k={};for(let S=0;SJp,initializeFlags:()=>Yp,wasmBackend:()=>jh});var Yp,Jp,jh,__=w(()=>{Qe(),zh(),m_(),Ss(),Yp=()=>{if((typeof T.wasm.initTimeout!="number"||T.wasm.initTimeout<0)&&(T.wasm.initTimeout=0),T.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 T.wasm.proxy!="boolean"&&(T.wasm.proxy=!1),typeof T.wasm.trace!="boolean"&&(T.wasm.trace=!1),typeof T.wasm.numThreads!="number"||!Number.isInteger(T.wasm.numThreads)||T.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)T.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;T.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jp=class{async init(e){Yp(),await $h(),await Ah(e)}async createInferenceSessionHandler(e,t){let r=new Rh;return await r.loadModel(e,t),Promise.resolve(r)}},jh=new Jp});Qe(),Qe(),Qe();var f_="1.21.0-dev.20241205-d27fecd3d3",g_=Fe;{let e=(__(),M(Nh)).wasmBackend;q("webgpu",e,5),q("webnn",e,5),q("cpu",e,10),q("wasm",e,10)}Object.defineProperty(T.versions,"web",{value:f_,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":(Te,A,s)=>{var f;s.r(A),s.d(A,{Tensor:()=>U.Tensor,createInferenceSession:()=>ie,deviceToExecutionProviders:()=>q,isONNXProxy:()=>Y,isONNXTensor:()=>z});var O=s("./src/env.js"),N=s("?2ce3"),Q=s("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs"),U=s("./node_modules/onnxruntime-common/dist/esm/index.js");const w=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"}}),v=[];let y,M;const b=Symbol.for("onnxruntime");if(b in globalThis)M=globalThis[b];else if(O.apis.IS_NODE_ENV){switch(M=N??(f||(f=s.t(N,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),y=["cpu"]}else M=Q,O.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),O.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),y=["wasm"];const L=M.InferenceSession;function q(D=null){if(!D)return y;switch(D){case"auto":return v;case"gpu":return v.filter($=>["webgpu","cuda","dml","webnn-gpu"].includes($))}if(v.includes(D))return[w[D]??D];throw new Error(`Unsupported device: "${D}". Should be one of: ${v.join(", ")}.`)}let se=null;async function ie(D,$,g){se&&await se;const C=L.create(D,$);se??(se=C);const T=await C;return T.config=g,T}function z(D){return D instanceof M.Tensor}const W=M==null?void 0:M.env;W!=null&&W.wasm&&(W.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${O.env.version}/dist/`,W.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(W.wasm.numThreads=1)),W!=null&&W.webgpu&&(W.webgpu.powerPreference="high-performance");function Y(){var D;return(D=W==null?void 0:W.wasm)==null?void 0:D.proxy}O.env.backends.onnx=W},"./src/base/feature_extraction_utils.js":(Te,A,s)=>{s.r(A),s.d(A,{FeatureExtractor:()=>Q,validate_audio_inputs:()=>U});var f=s("./src/utils/constants.js"),O=s("./src/utils/generic.js"),N=s("./src/utils/hub.js");class Q extends O.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,y){const M=await(0,N.getModelJSON)(v,f.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function U(w,v){var y;if(!(w instanceof Float32Array||w instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((y=w==null?void 0:w.constructor)==null?void 0:y.name)??typeof w} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(Te,A,s)=>{s.r(A),s.d(A,{ImageProcessor:()=>D,post_process_instance_segmentation:()=>Y,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>W,post_process_semantic_segmentation:()=>L});var f=s("./src/utils/generic.js"),O=s("./src/utils/tensor.js"),N=s("./src/utils/maths.js");s("./src/utils/image.js");var Q=s("./src/utils/core.js"),U=s("./src/utils/hub.js"),w=s("./src/utils/constants.js");function v($,g,C=0,T=null){const ee=$/g;let J=(0,N.bankers_round)(ee)*g;return T!==null&&J>T&&(J=Math.floor(ee)*g),Jg&&he.push(Be)}else{let Be=(0,N.max)(re.data)[1];if(Be===fe-1||(Pe=(0,N.softmax)(re.data),Pe[Be]Xe*Le[(oe+1)%2])),qe.boxes.push(et),qe.classes.push(Be),qe.scores.push(Pe[Be])}}ke.push(qe)}return ke}function L($,g=null){const C=$.logits,T=C.dims[0];if(g!==null&&g.length!==T)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ee=[];for(let J=0;JLe[he]&&(Le[he]=re[he],qe[he]=ue)}const Ue=new Array(de.dims[0]);for(let ue=0;ueue!==void 0);ee.push({segmentation:xe,labels:ut})}return ee}function q($,g,C,T){const ee=[],J=[],le=[];for(let de=0;de<$.dims[0];++de){const fe=$[de],ke=g[de],xe=(0,N.max)(fe.data)[1];if(xe===T)continue;const qe=(0,N.softmax)(fe.data)[xe];qe>C&&(ee.push(ke),J.push(qe),le.push(xe))}return[ee,J,le]}function se($,g,C,T=.5,ee=.8){const J=[];let le=0,de=0;const fe=g[C].data;for(let xe=0;xe<$.length;++xe)$[xe]===C&&(J.push(xe),++le),fe[xe]>=T&&++de;let ke=le>0&&de>0;return ke&&(ke=le/de>ee),[ke,J]}function ie($,g,C,T,ee,J=null,le=null){const[de,fe]=le??$[0].dims,ke=new O.Tensor("int32",new Int32Array(de*fe),[de,fe]),xe=[];if(le!==null)for(let ue=0;ue<$.length;++ue)$[ue]=(0,O.interpolate)($[ue],le,"bilinear",!1);const Le=new Int32Array($[0].data.length),qe=new Float32Array($[0].data.length);for(let ue=0;ue<$.length;++ue){let re=g[ue];const he=$[ue].data;for(let Pe=0;Peqe[Pe]&&(Le[Pe]=ue,qe[Pe]=he[Pe])}let Ue=0;const ut=ke.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max($,g)/Math.min($,g)}`);let J=Math.round($/C)*C,le=Math.round(g/C)*C;if(J*le>ee){const de=Math.sqrt($*g/ee);J=Math.floor($/de/C)*C,le=Math.floor(g/de/C)*C}else if(J*leJ?ke=Math.floor(J*fe/ee):J>ee&&(fe=Math.floor(ee*ke/J)),await g.resize(ke,fe,{resample:T}))}async crop_margin(g,C=200){const T=g.clone().grayscale(),ee=(0,N.min)(T.data)[0],le=(0,N.max)(T.data)[0]-ee;if(le===0)return g;const de=C/255;let fe=T.width,ke=T.height,xe=0,Le=0;const qe=T.data;for(let Ue=0;Uethis.preprocess(J)));return{pixel_values:(0,O.stack)(T.map(J=>J.pixel_values),0),original_sizes:T.map(J=>J.original_size),reshaped_input_sizes:T.map(J=>J.reshaped_input_size)}}static async from_pretrained(g,C){const T=await(0,U.getModelJSON)(g,w.IMAGE_PROCESSOR_NAME,!0,C);return new this(T)}}},"./src/base/processing_utils.js":(Te,A,s)=>{s.r(A),s.d(A,{Processor:()=>Q});var f=s("./src/utils/constants.js"),O=s("./src/utils/generic.js"),N=s("./src/utils/hub.js");class Q extends O.Callable{constructor(w,v){super(),this.config=w,this.components=v}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(w,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(w,{tokenize:!1,...v})}batch_decode(...w){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...w)}async _call(w,...v){for(const y of[this.image_processor,this.feature_extractor,this.tokenizer])if(y)return y(w,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(w,v){const[y,M]=await Promise.all([this.uses_processor_config?(0,N.getModelJSON)(w,f.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const L=await this[b].from_pretrained(w,v);return[b.replace(/_class$/,""),L]})).then(Object.fromEntries)]);return new this(y,M)}}ge(Q,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),ge(Q,"uses_processor_config",!1)},"./src/configs.js":(Te,A,s)=>{s.r(A),s.d(A,{AutoConfig:()=>v,PretrainedConfig:()=>w,getKeyValueShapes:()=>U});var f=s("./src/utils/core.js"),O=s("./src/utils/hub.js");async function N(y,M){return await(0,O.getModelJSON)(y,"config.json",!0,M)}function Q(y){const M={};let b={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=Q(y.text_config);break;case"moondream1":b=Q(y.phi_config);break;case"musicgen":b=Q(y.decoder);break;case"multi_modality":b=Q(y.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":M.num_heads="num_attention_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size",M.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.dim_kv="head_dim";break;case"openelm":M.num_heads="num_kv_heads",M.num_layers="num_transformer_layers",M.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":M.num_heads="num_heads",M.num_layers="num_layers",M.hidden_size="hidden_size";break;case"bloom":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="hidden_size";break;case"mpt":M.num_heads="n_heads",M.num_layers="n_layers",M.hidden_size="d_model";break;case"exaone":M.num_heads="num_key_value_heads",M.num_layers="num_layers",M.dim_kv="head_dim",M.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":M.num_decoder_layers="num_decoder_layers",M.num_decoder_heads="num_heads",M.decoder_dim_kv="d_kv",M.num_encoder_layers="num_layers",M.num_encoder_heads="num_heads",M.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":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="d_model",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="d_model";break;case"speecht5":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="hidden_size",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="hidden_size";break;case"trocr":M.num_encoder_layers=M.num_decoder_layers="decoder_layers",M.num_encoder_heads=M.num_decoder_heads="decoder_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":M.num_encoder_layers=M.num_decoder_layers="num_hidden_layers",M.num_encoder_heads=M.num_decoder_heads="num_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const q=Q(y.decoder),se="num_decoder_layers"in q,ie=(0,f.pick)(y,["model_type","is_encoder_decoder"]);return se?(ie.num_decoder_layers=q.num_decoder_layers,ie.num_decoder_heads=q.num_decoder_heads,ie.decoder_hidden_size=q.decoder_hidden_size,ie.num_encoder_layers=q.num_encoder_layers,ie.num_encoder_heads=q.num_encoder_heads,ie.encoder_hidden_size=q.encoder_hidden_size):(ie.num_layers=q.num_layers,ie.num_heads=q.num_heads,ie.hidden_size=q.hidden_size),ie}const L={...b,...(0,f.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const q in M)L[q]=y[M[q]];return L}function U(y,{prefix:M="past_key_values",batch_size:b=1}={}){const L={},q=y.normalized_config;if(q.is_encoder_decoder&&"num_encoder_heads"in q&&"num_decoder_heads"in q){const se=q.encoder_dim_kv??q.encoder_hidden_size/q.num_encoder_heads,ie=q.decoder_dim_kv??q.decoder_hidden_size/q.num_decoder_heads,z=[b,q.num_encoder_heads,0,se],W=[b,q.num_decoder_heads,0,ie];for(let Y=0;Y{var T,ee;s.r(A),s.d(A,{apis:()=>ie,env:()=>g});var f=s("?569f"),O=s("?3f59"),N=s("?154a");const Q="3.2.1",U=typeof window<"u"&&typeof window.document<"u",w=typeof self<"u"&&((T=self.constructor)==null?void 0:T.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,y=typeof navigator<"u"&&"gpu"in navigator,M=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",L=b&&((ee=process==null?void 0:process.release)==null?void 0:ee.name)==="node",q=!C(f),se=!C(O),ie=Object.freeze({IS_BROWSER_ENV:U,IS_WEBWORKER_ENV:w,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:L,IS_FS_AVAILABLE:q,IS_PATH_AVAILABLE:se}),z=q&&se;let W="./";if(z){const J=Object(import.meta).url;J?W=O.dirname(O.dirname(N.fileURLToPath(J))):typeof __dirname<"u"&&(W=O.dirname(__dirname))}const Y=z?O.join(W,"/.cache/"):null,D="/models/",$=z?O.join(W,D):D,g={version:Q,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(U||w),localModelPath:$,useFS:q,useBrowserCache:v,useFSCache:q,cacheDir:Y,useCustomCache:!1,customCache:null};function C(J){return Object.keys(J).length===0}},"./src/generation/configuration_utils.js":(Te,A,s)=>{s.r(A),s.d(A,{GenerationConfig:()=>O});var f=s("./src/utils/core.js");class O{constructor(Q){ge(this,"max_length",20);ge(this,"max_new_tokens",null);ge(this,"min_length",0);ge(this,"min_new_tokens",null);ge(this,"early_stopping",!1);ge(this,"max_time",null);ge(this,"do_sample",!1);ge(this,"num_beams",1);ge(this,"num_beam_groups",1);ge(this,"penalty_alpha",null);ge(this,"use_cache",!0);ge(this,"temperature",1);ge(this,"top_k",50);ge(this,"top_p",1);ge(this,"typical_p",1);ge(this,"epsilon_cutoff",0);ge(this,"eta_cutoff",0);ge(this,"diversity_penalty",0);ge(this,"repetition_penalty",1);ge(this,"encoder_repetition_penalty",1);ge(this,"length_penalty",1);ge(this,"no_repeat_ngram_size",0);ge(this,"bad_words_ids",null);ge(this,"force_words_ids",null);ge(this,"renormalize_logits",!1);ge(this,"constraints",null);ge(this,"forced_bos_token_id",null);ge(this,"forced_eos_token_id",null);ge(this,"remove_invalid_values",!1);ge(this,"exponential_decay_length_penalty",null);ge(this,"suppress_tokens",null);ge(this,"streamer",null);ge(this,"begin_suppress_tokens",null);ge(this,"forced_decoder_ids",null);ge(this,"guidance_scale",null);ge(this,"num_return_sequences",1);ge(this,"output_attentions",!1);ge(this,"output_hidden_states",!1);ge(this,"output_scores",!1);ge(this,"return_dict_in_generate",!1);ge(this,"pad_token_id",null);ge(this,"bos_token_id",null);ge(this,"eos_token_id",null);ge(this,"encoder_no_repeat_ngram_size",0);ge(this,"decoder_start_token_id",null);ge(this,"generation_kwargs",{});Object.assign(this,(0,f.pick)(Q,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Te,A,s)=>{s.r(A),s.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>z,ForcedBOSTokenLogitsProcessor:()=>w,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>N,LogitsProcessorList:()=>U,LogitsWarper:()=>Q,MinLengthLogitsProcessor:()=>q,MinNewTokensLengthLogitsProcessor:()=>se,NoBadWordsLogitsProcessor:()=>ie,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>L,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>W,TopKLogitsWarper:()=>D,TopPLogitsWarper:()=>Y,WhisperTimeStampLogitsProcessor:()=>M});var f=s("./src/utils/generic.js");s("./src/utils/tensor.js");var O=s("./src/utils/maths.js");class N extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class Q extends f.Callable{_call(g,C){throw Error("`_call` should be implemented in a subclass")}}class U extends f.Callable{constructor(){super(),this.processors=[]}push(g){this.processors.push(g)}extend(g){this.processors.push(...g)}_call(g,C){let T=C;for(const ee of this.processors)T=ee(g,T);return T}[Symbol.iterator](){return this.processors.values()}}class w extends N{constructor(g){super(),this.bos_token_id=g}_call(g,C){for(let T=0;T=1&&J[J.length-1]>=this.timestamp_begin,de=J.length<2||J[J.length-2]>=this.timestamp_begin;if(le&&(de?ee.subarray(this.timestamp_begin).fill(-1/0):ee.subarray(0,this.eos_token_id).fill(-1/0)),g[T].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Le=this.timestamp_begin+this.max_initial_timestamp_index;ee.subarray(Le+1).fill(-1/0)}const fe=(0,O.log_softmax)(ee),ke=Math.log(fe.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,qe)=>Le+qe)),xe=(0,O.max)(fe.subarray(0,this.timestamp_begin))[0];ke>xe&&ee.subarray(0,this.timestamp_begin).fill(-1/0)}return C}}class b extends N{constructor(g){super(),this.no_repeat_ngram_size=g}getNgrams(g){const C=g.length,T=[];for(let J=0;J1 to use the classifier free guidance processor, got guidance scale ${g}.`);this.guidance_scale=g}_call(g,C){if(C.dims[0]!==2*g.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 ${C.dims[0]} for the logits and ${g.length} for the input ids.`);const T=g.length,ee=C.slice([0,T],null),J=C.slice([T,C.dims[0]],null);for(let le=0;le1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${g}`);if(!Number.isInteger(T)||T<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${T}`);this.top_p=g,this.filter_value=C,this.min_tokens_to_keep=T}}class D extends Q{constructor(g,{filter_value:C=-1/0,min_tokens_to_keep:T=1}={}){if(super(),!Number.isInteger(g)||g<0)throw new Error(`\`top_k\` must be a positive integer, but is ${g}`);this.top_k=Math.max(g,T),this.filter_value=C}}},"./src/generation/logits_sampler.js":(Te,A,s)=>{s.r(A),s.d(A,{LogitsSampler:()=>Q});var f=s("./src/utils/generic.js"),O=s("./src/utils/tensor.js"),N=s("./src/utils/maths.js");s("./src/generation/configuration_utils.js");class Q extends f.Callable{constructor(M){super(),this.generation_config=M}async _call(M){return this.sample(M)}async sample(M){throw Error("sample should be implemented in subclasses.")}getLogits(M,b){let L=M.dims.at(-1),q=M.data;if(b===-1)q=q.slice(-L);else{let se=b*L;q=q.slice(se,se+L)}return q}randomSelect(M){let b=0;for(let q=0;q1)return new v(M);if(M.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${M.num_return_sequences}.`);return new U(M)}}class U extends Q{async sample(M){const b=(0,N.max)(M.data)[1];return[[BigInt(b),0]]}}class w extends Q{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[L,q]=await(0,O.topk)(M,b),se=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},()=>{const ie=this.randomSelect(se);return[q.data[ie],Math.log(se[ie])]})}}class v extends Q{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[L,q]=await(0,O.topk)(M,b),se=(0,N.softmax)(L.data);return Array.from({length:this.generation_config.num_beams},(ie,z)=>[q.data[z],Math.log(se[z])])}}},"./src/generation/stopping_criteria.js":(Te,A,s)=>{s.r(A),s.d(A,{EosTokenCriteria:()=>U,InterruptableStoppingCriteria:()=>w,MaxLengthCriteria:()=>Q,StoppingCriteria:()=>O,StoppingCriteriaList:()=>N});var f=s("./src/utils/generic.js");class O extends f.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class N extends f.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof N?y=y.criteria:y instanceof O&&(y=[y]),this.criteria.push(...y)}_call(y,M){const b=new Array(y.length).fill(!1);for(const L of this.criteria){const q=L(y,M);for(let se=0;seM.length>=this.max_length)}}class U extends O{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(b=>{const L=b.at(-1);return this.eos_token_id.some(q=>L==q)})}}class w extends O{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(y,M){return new Array(y.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Te,A,s)=>{s.r(A),s.d(A,{BaseStreamer:()=>Q,TextStreamer:()=>w,WhisperTextStreamer:()=>v});var f=s("./src/utils/core.js"),O=s("./src/tokenizers.js"),N=s("./src/env.js");class Q{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const U=N.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class w extends Q{constructor(M,{skip_prompt:b=!1,callback_function:L=null,token_callback_function:q=null,decode_kwargs:se={},...ie}={}){super(),this.tokenizer=M,this.skip_prompt=b,this.callback_function=L??U,this.token_callback_function=q,this.decode_kwargs={...se,...ie},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var se;if(M.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 b=M[0];(se=this.token_callback_function)==null||se.call(this,b),this.token_cache=(0,f.mergeArrays)(this.token_cache,b);const L=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let q;L.endsWith(` +`)?(q=L.slice(this.print_len),this.token_cache=[],this.print_len=0):L.length>0&&(0,O.is_chinese_char)(L.charCodeAt(L.length-1))?(q=L.slice(this.print_len),this.print_len+=q.length):(q=L.slice(this.print_len,L.lastIndexOf(" ")+1),this.print_len+=q.length),this.on_finalized_text(q,!1)}end(){let M;this.token_cache.length>0?(M=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):M="",this.next_tokens_are_prompt=!0,this.on_finalized_text(M,!0)}on_finalized_text(M,b){var L,q;M.length>0&&((L=this.callback_function)==null||L.call(this,M)),b&&this.callback_function===U&&N.apis.IS_PROCESS_AVAILABLE&&((q=this.callback_function)==null||q.call(this,` +`))}}class v extends w{constructor(M,{skip_prompt:b=!1,callback_function:L=null,token_callback_function:q=null,on_chunk_start:se=null,on_chunk_end:ie=null,on_finalize:z=null,time_precision:W=.02,skip_special_tokens:Y=!0,decode_kwargs:D={}}={}){super(M,{skip_prompt:b,callback_function:L,token_callback_function:q,decode_kwargs:{skip_special_tokens:Y,...D}}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=se,this.on_chunk_end=ie,this.on_finalize=z,this.time_precision=W,this.waiting_for_timestamp=!1}put(M){var L,q;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=M[0];if(b.length===1){const se=Number(b[0])-this.timestamp_begin;if(se>=0){const ie=se*this.time_precision;this.waiting_for_timestamp?(L=this.on_chunk_end)==null||L.call(this,ie):(q=this.on_chunk_start)==null||q.call(this,ie),this.waiting_for_timestamp=!this.waiting_for_timestamp,M=[[]]}}return super.put(M)}end(){var M;super.end(),(M=this.on_finalize)==null||M.call(this)}}},"./src/models.js":(Te,A,s)=>{s.r(A),s.d(A,{ASTForAudioClassification:()=>ss,ASTModel:()=>Pa,ASTPreTrainedModel:()=>jo,AlbertForMaskedLM:()=>Mn,AlbertForQuestionAnswering:()=>yn,AlbertForSequenceClassification:()=>Ln,AlbertModel:()=>wn,AlbertPreTrainedModel:()=>Yr,AutoModel:()=>Hd,AutoModelForAudioClassification:()=>dc,AutoModelForAudioFrameClassification:()=>la,AutoModelForCTC:()=>uc,AutoModelForCausalLM:()=>Zd,AutoModelForDepthEstimation:()=>_c,AutoModelForDocumentQuestionAnswering:()=>pc,AutoModelForImageClassification:()=>rc,AutoModelForImageFeatureExtraction:()=>wc,AutoModelForImageMatting:()=>hc,AutoModelForImageSegmentation:()=>sc,AutoModelForImageToImage:()=>mc,AutoModelForMaskGeneration:()=>lc,AutoModelForMaskedLM:()=>ec,AutoModelForNormalEstimation:()=>fc,AutoModelForObjectDetection:()=>ic,AutoModelForPoseEstimation:()=>gc,AutoModelForQuestionAnswering:()=>mp,AutoModelForSemanticSegmentation:()=>nc,AutoModelForSeq2SeqLM:()=>Qd,AutoModelForSequenceClassification:()=>qd,AutoModelForSpeechSeq2Seq:()=>hp,AutoModelForTextToSpectrogram:()=>Yd,AutoModelForTextToWaveform:()=>Jd,AutoModelForTokenClassification:()=>Xd,AutoModelForUniversalSegmentation:()=>oc,AutoModelForVision2Seq:()=>tc,AutoModelForXVector:()=>cc,AutoModelForZeroShotObjectDetection:()=>ac,BartForConditionalGeneration:()=>Pt,BartForSequenceClassification:()=>hr,BartModel:()=>it,BartPretrainedModel:()=>ht,BaseModelOutput:()=>De,BeitForImageClassification:()=>sn,BeitModel:()=>Rc,BeitPreTrainedModel:()=>Pi,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>Ne,BertForSequenceClassification:()=>je,BertForTokenClassification:()=>We,BertModel:()=>ve,BertPreTrainedModel:()=>ce,BlenderbotForConditionalGeneration:()=>Nr,BlenderbotModel:()=>Bt,BlenderbotPreTrainedModel:()=>Zr,BlenderbotSmallForConditionalGeneration:()=>mr,BlenderbotSmallModel:()=>er,BlenderbotSmallPreTrainedModel:()=>ps,BloomForCausalLM:()=>kl,BloomModel:()=>Cl,BloomPreTrainedModel:()=>mi,CLIPModel:()=>za,CLIPPreTrainedModel:()=>rn,CLIPSegForImageSegmentation:()=>Ga,CLIPSegModel:()=>Wa,CLIPSegPreTrainedModel:()=>qo,CLIPTextModel:()=>Fc,CLIPTextModelWithProjection:()=>Ba,CLIPVisionModel:()=>Dc,CLIPVisionModelWithProjection:()=>Lc,CamembertForMaskedLM:()=>Qs,CamembertForQuestionAnswering:()=>Ss,CamembertForSequenceClassification:()=>ks,CamembertForTokenClassification:()=>Bs,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>Ms,CausalLMOutput:()=>an,CausalLMOutputWithPast:()=>_p,ChineseCLIPModel:()=>Na,ChineseCLIPPreTrainedModel:()=>ms,ClapAudioModelWithProjection:()=>cd,ClapModel:()=>ud,ClapPreTrainedModel:()=>Eo,ClapTextModelWithProjection:()=>dd,CodeGenForCausalLM:()=>so,CodeGenModel:()=>tl,CodeGenPreTrainedModel:()=>el,CohereForCausalLM:()=>ml,CohereModel:()=>hl,CoherePreTrainedModel:()=>ai,ConvBertForMaskedLM:()=>Ft,ConvBertForQuestionAnswering:()=>gr,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>nr,ConvBertModel:()=>St,ConvBertPreTrainedModel:()=>It,ConvNextForImageClassification:()=>bu,ConvNextModel:()=>Mu,ConvNextPreTrainedModel:()=>Li,ConvNextV2ForImageClassification:()=>Tu,ConvNextV2Model:()=>vu,ConvNextV2PreTrainedModel:()=>wo,DPTForDepthEstimation:()=>mu,DPTModel:()=>hu,DPTPreTrainedModel:()=>Ii,DebertaForMaskedLM:()=>cs,DebertaForQuestionAnswering:()=>as,DebertaForSequenceClassification:()=>As,DebertaForTokenClassification:()=>Ys,DebertaModel:()=>$s,DebertaPreTrainedModel:()=>is,DebertaV2ForMaskedLM:()=>Ot,DebertaV2ForQuestionAnswering:()=>tr,DebertaV2ForSequenceClassification:()=>lr,DebertaV2ForTokenClassification:()=>bs,DebertaV2Model:()=>_t,DebertaV2PreTrainedModel:()=>nt,DecisionTransformerModel:()=>vd,DecisionTransformerPreTrainedModel:()=>bd,DeiTForImageClassification:()=>iu,DeiTModel:()=>Si,DeiTPreTrainedModel:()=>uo,DepthAnythingForDepthEstimation:()=>_u,DepthAnythingPreTrainedModel:()=>jc,DepthProForDepthEstimation:()=>fo,DepthProPreTrainedModel:()=>gu,DetrForObjectDetection:()=>Ci,DetrForSegmentation:()=>Gs,DetrModel:()=>nn,DetrObjectDetectionOutput:()=>Vr,DetrPreTrainedModel:()=>Is,DetrSegmentationOutput:()=>ru,Dinov2ForImageClassification:()=>Eu,Dinov2Model:()=>xu,Dinov2PreTrainedModel:()=>yo,DistilBertForMaskedLM:()=>Sn,DistilBertForQuestionAnswering:()=>vs,DistilBertForSequenceClassification:()=>Js,DistilBertForTokenClassification:()=>Ns,DistilBertModel:()=>Rs,DistilBertPreTrainedModel:()=>ts,DonutSwinModel:()=>Wc,DonutSwinPreTrainedModel:()=>yu,EfficientNetForImageClassification:()=>md,EfficientNetModel:()=>Un,EfficientNetPreTrainedModel:()=>Vi,ElectraForMaskedLM:()=>Qr,ElectraForQuestionAnswering:()=>zs,ElectraForSequenceClassification:()=>os,ElectraForTokenClassification:()=>Xs,ElectraModel:()=>Ar,ElectraPreTrainedModel:()=>kr,EsmForMaskedLM:()=>Jn,EsmForSequenceClassification:()=>Us,EsmForTokenClassification:()=>Ts,EsmModel:()=>$n,EsmPreTrainedModel:()=>js,ExaoneForCausalLM:()=>ol,ExaoneModel:()=>nl,ExaonePreTrainedModel:()=>vn,FalconForCausalLM:()=>ld,FalconModel:()=>ad,FalconPreTrainedModel:()=>Ks,FastViTForImageClassification:()=>Wl,FastViTModel:()=>Vl,FastViTPreTrainedModel:()=>ds,Florence2ForConditionalGeneration:()=>Oa,Florence2PreTrainedModel:()=>Ia,GLPNForDepthEstimation:()=>Vc,GLPNModel:()=>Di,GLPNPreTrainedModel:()=>Fi,GPT2LMHeadModel:()=>_s,GPT2Model:()=>Ka,GPT2PreTrainedModel:()=>Xo,GPTBigCodeForCausalLM:()=>si,GPTBigCodeModel:()=>Za,GPTBigCodePreTrainedModel:()=>ri,GPTJForCausalLM:()=>ti,GPTJModel:()=>ei,GPTJPreTrainedModel:()=>Zo,GPTNeoForCausalLM:()=>Qa,GPTNeoModel:()=>Xa,GPTNeoPreTrainedModel:()=>Yo,GPTNeoXForCausalLM:()=>Ja,GPTNeoXModel:()=>Ya,GPTNeoXPreTrainedModel:()=>Jo,Gemma2ForCausalLM:()=>wl,Gemma2Model:()=>gl,Gemma2PreTrainedModel:()=>ui,GemmaForCausalLM:()=>fl,GemmaModel:()=>_l,GemmaPreTrainedModel:()=>li,GraniteForCausalLM:()=>ur,GraniteModel:()=>pl,GranitePreTrainedModel:()=>cl,GroupViTModel:()=>Ul,GroupViTPreTrainedModel:()=>jl,HieraForImageClassification:()=>po,HieraModel:()=>au,HieraPreTrainedModel:()=>co,HubertForCTC:()=>Qu,HubertForSequenceClassification:()=>Yu,HubertModel:()=>Xu,HubertPreTrainedModel:()=>Rp,IJepaForImageClassification:()=>Fl,IJepaModel:()=>yi,IJepaPreTrainedModel:()=>io,Idefics3ForConditionalGeneration:()=>Go,Idefics3PreTrainedModel:()=>Da,ImageMattingOutput:()=>fp,JAISLMHeadModel:()=>qa,JAISModel:()=>Ha,JAISPreTrainedModel:()=>Qo,JinaCLIPModel:()=>ja,JinaCLIPPreTrainedModel:()=>ro,JinaCLIPTextModel:()=>Ua,JinaCLIPVisionModel:()=>Va,LlamaForCausalLM:()=>sl,LlamaModel:()=>rl,LlamaPreTrainedModel:()=>ni,LlavaForConditionalGeneration:()=>eo,LlavaOnevisionForConditionalGeneration:()=>$a,LlavaPreTrainedModel:()=>Sa,LongT5ForConditionalGeneration:()=>Ce,LongT5Model:()=>Me,LongT5PreTrainedModel:()=>ae,M2M100ForConditionalGeneration:()=>Rn,M2M100Model:()=>Mo,M2M100PreTrainedModel:()=>Fu,MBartForCausalLM:()=>Jr,MBartForConditionalGeneration:()=>wr,MBartForSequenceClassification:()=>Rr,MBartModel:()=>$e,MBartPreTrainedModel:()=>rr,MPNetForMaskedLM:()=>fn,MPNetForQuestionAnswering:()=>On,MPNetForSequenceClassification:()=>An,MPNetForTokenClassification:()=>In,MPNetModel:()=>zt,MPNetPreTrainedModel:()=>xs,MT5ForConditionalGeneration:()=>yt,MT5Model:()=>ct,MT5PreTrainedModel:()=>He,MarianMTModel:()=>Ou,MarianModel:()=>Iu,MarianPreTrainedModel:()=>zi,MaskFormerForInstanceSegmentation:()=>wu,MaskFormerModel:()=>Oi,MaskFormerPreTrainedModel:()=>go,MaskedLMOutput:()=>Wr,MgpstrForSceneTextRecognition:()=>np,MgpstrModelOutput:()=>xd,MgpstrPreTrainedModel:()=>Ed,MistralForCausalLM:()=>Jc,MistralModel:()=>id,MistralPreTrainedModel:()=>Ri,MobileBertForMaskedLM:()=>Zs,MobileBertForQuestionAnswering:()=>en,MobileBertForSequenceClassification:()=>_n,MobileBertModel:()=>mn,MobileBertPreTrainedModel:()=>ls,MobileLLMForCausalLM:()=>al,MobileLLMModel:()=>il,MobileLLMPreTrainedModel:()=>no,MobileNetV1ForImageClassification:()=>_d,MobileNetV1Model:()=>Hi,MobileNetV1PreTrainedModel:()=>Ki,MobileNetV2ForImageClassification:()=>gd,MobileNetV2Model:()=>fd,MobileNetV2PreTrainedModel:()=>qi,MobileNetV3ForImageClassification:()=>wd,MobileNetV3Model:()=>Qi,MobileNetV3PreTrainedModel:()=>Xi,MobileNetV4ForImageClassification:()=>Md,MobileNetV4Model:()=>Yi,MobileNetV4PreTrainedModel:()=>yd,MobileViTForImageClassification:()=>ql,MobileViTModel:()=>Hl,MobileViTPreTrainedModel:()=>Ti,MobileViTV2ForImageClassification:()=>Ql,MobileViTV2Model:()=>Xl,MobileViTV2PreTrainedModel:()=>xi,ModelOutput:()=>Je,ModernBertForMaskedLM:()=>ft,ModernBertForSequenceClassification:()=>dt,ModernBertForTokenClassification:()=>gt,ModernBertModel:()=>at,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>Aa,MoonshineForConditionalGeneration:()=>ka,MoonshineModel:()=>Oc,MoonshinePreTrainedModel:()=>Vo,MptForCausalLM:()=>$l,MptModel:()=>Sl,MptPreTrainedModel:()=>_i,MultiModalityCausalLM:()=>Td,MultiModalityPreTrainedModel:()=>sp,MusicgenForCausalLM:()=>rp,MusicgenForConditionalGeneration:()=>Gi,MusicgenModel:()=>tp,MusicgenPreTrainedModel:()=>Wi,NomicBertModel:()=>ne,NomicBertPreTrainedModel:()=>F,OPTForCausalLM:()=>Il,OPTModel:()=>Al,OPTPreTrainedModel:()=>fi,Olmo2ForCausalLM:()=>dl,Olmo2Model:()=>ul,Olmo2PreTrainedModel:()=>ii,OlmoForCausalLM:()=>zc,OlmoModel:()=>ll,OlmoPreTrainedModel:()=>oi,OpenELMForCausalLM:()=>Ml,OpenELMModel:()=>yl,OpenELMPreTrainedModel:()=>di,OwlViTForObjectDetection:()=>Zl,OwlViTModel:()=>Jl,OwlViTPreTrainedModel:()=>Yl,Owlv2ForObjectDetection:()=>tu,Owlv2Model:()=>eu,Owlv2PreTrainedModel:()=>Ei,PaliGemmaForConditionalGeneration:()=>Fa,PaliGemmaPreTrainedModel:()=>hs,PatchTSMixerForPrediction:()=>kd,PatchTSMixerModel:()=>Cd,PatchTSMixerPreTrainedModel:()=>Zi,PatchTSTForPrediction:()=>op,PatchTSTModel:()=>Pd,PatchTSTPreTrainedModel:()=>Ji,Phi3ForCausalLM:()=>Pl,Phi3Model:()=>El,Phi3PreTrainedModel:()=>hi,Phi3VForCausalLM:()=>Ko,Phi3VPreTrainedModel:()=>La,PhiForCausalLM:()=>xl,PhiModel:()=>Tl,PhiPreTrainedModel:()=>pi,PreTrainedModel:()=>oe,PretrainedMixin:()=>_r,PvtForImageClassification:()=>Bl,PvtModel:()=>zl,PvtPreTrainedModel:()=>Mi,PyAnnoteForAudioFrameClassification:()=>Nu,PyAnnoteModel:()=>Ru,PyAnnotePreTrainedModel:()=>bo,QuestionAnsweringModelOutput:()=>Xr,Qwen2ForCausalLM:()=>zn,Qwen2Model:()=>bl,Qwen2PreTrainedModel:()=>ci,Qwen2VLForConditionalGeneration:()=>oo,Qwen2VLPreTrainedModel:()=>vl,RTDetrForObjectDetection:()=>Nc,RTDetrModel:()=>su,RTDetrObjectDetectionOutput:()=>Bn,RTDetrPreTrainedModel:()=>ao,ResNetForImageClassification:()=>uu,ResNetModel:()=>lu,ResNetPreTrainedModel:()=>ho,RoFormerForMaskedLM:()=>Fe,RoFormerForQuestionAnswering:()=>pt,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>st,RoFormerModel:()=>pe,RoFormerPreTrainedModel:()=>K,RobertaForMaskedLM:()=>Es,RobertaForQuestionAnswering:()=>Mt,RobertaForSequenceClassification:()=>Fr,RobertaForTokenClassification:()=>qr,RobertaModel:()=>yr,RobertaPreTrainedModel:()=>vt,SamImageSegmentationOutput:()=>Au,SamModel:()=>$u,SamPreTrainedModel:()=>Gc,SapiensForDepthEstimation:()=>fu,SapiensForNormalEstimation:()=>_o,SapiensForSemanticSegmentation:()=>Uc,SapiensPreTrainedModel:()=>mo,SegformerForImageClassification:()=>ep,SegformerForSemanticSegmentation:()=>es,SegformerModel:()=>Zc,SegformerPreTrainedModel:()=>Po,Seq2SeqLMOutput:()=>jp,SequenceClassifierOutput:()=>Xt,SiglipModel:()=>Ra,SiglipPreTrainedModel:()=>us,SiglipTextModel:()=>to,SiglipVisionModel:()=>Ho,SpeechT5ForSpeechToText:()=>rd,SpeechT5ForTextToSpeech:()=>sd,SpeechT5HifiGan:()=>Yc,SpeechT5Model:()=>Qc,SpeechT5PreTrainedModel:()=>xo,SqueezeBertForMaskedLM:()=>gn,SqueezeBertForQuestionAnswering:()=>ir,SqueezeBertForSequenceClassification:()=>Dn,SqueezeBertModel:()=>Fn,SqueezeBertPreTrainedModel:()=>Vs,StableLmForCausalLM:()=>Ui,StableLmModel:()=>hd,StableLmPreTrainedModel:()=>ji,Starcoder2ForCausalLM:()=>on,Starcoder2Model:()=>Fs,Starcoder2PreTrainedModel:()=>fs,Swin2SRForImageSuperResolution:()=>Ai,Swin2SRModel:()=>pu,Swin2SRPreTrainedModel:()=>Tn,SwinForImageClassification:()=>$i,SwinModel:()=>cu,SwinPreTrainedModel:()=>du,T5ForConditionalGeneration:()=>H,T5Model:()=>P,T5PreTrainedModel:()=>Ee,TableTransformerForObjectDetection:()=>nu,TableTransformerModel:()=>ki,TableTransformerObjectDetectionOutput:()=>ou,TableTransformerPreTrainedModel:()=>lo,TokenClassifierOutput:()=>jr,TrOCRForCausalLM:()=>od,TrOCRPreTrainedModel:()=>nd,UniSpeechForCTC:()=>Uu,UniSpeechForSequenceClassification:()=>Vu,UniSpeechModel:()=>Bi,UniSpeechPreTrainedModel:()=>vo,UniSpeechSatForAudioFrameClassification:()=>qc,UniSpeechSatForCTC:()=>Wu,UniSpeechSatForSequenceClassification:()=>Gu,UniSpeechSatModel:()=>Hc,UniSpeechSatPreTrainedModel:()=>Nn,ViTForImageClassification:()=>Ol,ViTMAEModel:()=>Rl,ViTMAEPreTrainedModel:()=>bi,ViTMSNForImageClassification:()=>Bc,ViTMSNModel:()=>Nl,ViTMSNPreTrainedModel:()=>vi,ViTModel:()=>wi,ViTPreTrainedModel:()=>gi,VisionEncoderDecoderModel:()=>Wo,VitMatteForImageMatting:()=>Kl,VitMattePreTrainedModel:()=>Gl,VitPoseForPoseEstimation:()=>Ll,VitPosePreTrainedModel:()=>Dl,VitsModel:()=>Ni,VitsModelOutput:()=>Mc,VitsPreTrainedModel:()=>pd,Wav2Vec2BertForCTC:()=>Hu,Wav2Vec2BertForSequenceClassification:()=>qu,Wav2Vec2BertModel:()=>Ku,Wav2Vec2BertPreTrainedModel:()=>To,Wav2Vec2ForAudioFrameClassification:()=>Bu,Wav2Vec2ForCTC:()=>Lu,Wav2Vec2ForSequenceClassification:()=>zu,Wav2Vec2Model:()=>Du,Wav2Vec2PreTrainedModel:()=>Os,WavLMForAudioFrameClassification:()=>Xc,WavLMForCTC:()=>Zu,WavLMForSequenceClassification:()=>ed,WavLMForXVector:()=>td,WavLMModel:()=>Ju,WavLMPreTrainedModel:()=>jn,WeSpeakerResNetModel:()=>Kc,WeSpeakerResNetPreTrainedModel:()=>ju,WhisperForConditionalGeneration:()=>Ws,WhisperModel:()=>Ca,WhisperPreTrainedModel:()=>Uo,XLMForQuestionAnswering:()=>Zn,XLMForSequenceClassification:()=>rs,XLMForTokenClassification:()=>tn,XLMModel:()=>ze,XLMPreTrainedModel:()=>br,XLMRobertaForMaskedLM:()=>Ta,XLMRobertaForQuestionAnswering:()=>Ea,XLMRobertaForSequenceClassification:()=>No,XLMRobertaForTokenClassification:()=>xa,XLMRobertaModel:()=>Qt,XLMRobertaPreTrainedModel:()=>bn,XLMWithLMHeadModel:()=>wt,XVectorOutput:()=>yc,YolosForObjectDetection:()=>ku,YolosModel:()=>Cu,YolosObjectDetectionOutput:()=>Su,YolosPreTrainedModel:()=>Pu});var f=s("./src/configs.js"),O=s("./src/backends/onnx.js"),N=s("./src/utils/dtypes.js"),Q=s("./src/utils/generic.js"),U=s("./src/utils/core.js"),w=s("./src/utils/hub.js"),v=s("./src/utils/constants.js"),y=s("./src/generation/logits_process.js"),M=s("./src/generation/configuration_utils.js"),b=s("./src/utils/tensor.js"),L=s("./src/utils/image.js"),q=s("./src/utils/maths.js"),se=s("./src/generation/stopping_criteria.js"),ie=s("./src/generation/logits_sampler.js"),z=s("./src/env.js"),W=s("./src/models/whisper/generation_whisper.js"),Y=s("./src/models/whisper/common_whisper.js");const D={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},$=new Map,g=new Map,C=new Map;async function T(_,x,V){var Tr;const be=((Tr=V.config)==null?void 0:Tr["transformers.js_config"])??{};let Oe=V.device??be.device;Oe&&typeof Oe!="string"&&(Oe.hasOwnProperty(x)?Oe=Oe[x]:(console.warn(`device not specified for "${x}". Using the default device.`),Oe=null));const Se=Oe??(z.apis.IS_NODE_ENV?"cpu":"wasm"),Ye=(0,O.deviceToExecutionProviders)(Se);let rt=V.dtype??be.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(x)?rt=rt[x]:(rt=N.DEFAULT_DEVICE_DTYPE_MAPPING[Se]??N.DATA_TYPES.fp32,console.warn(`dtype not specified for "${x}". Using the default dtype (${rt}) for this device (${Se}).`))),rt===N.DATA_TYPES.auto){let dr=be.dtype;typeof dr!="string"&&(dr=dr[x]),dr&&dr!==N.DATA_TYPES.auto&&N.DATA_TYPES.hasOwnProperty(dr)?rt=dr:rt=N.DEFAULT_DEVICE_DTYPE_MAPPING[Se]??N.DATA_TYPES.fp32}const mt=rt;if(N.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(mt)){if(mt===N.DATA_TYPES.fp16&&Se==="webgpu"&&!await(0,N.isWebGpuFp16Supported)())throw new Error(`The device (${Se}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${mt}. Should be one of: ${Object.keys(N.DATA_TYPES).join(", ")}`);const Tt=be.kv_cache_dtype?typeof be.kv_cache_dtype=="string"?be.kv_cache_dtype:be.kv_cache_dtype[mt]??"float32":void 0;if(Tt&&!["float32","float16"].includes(Tt))throw new Error(`Invalid kv_cache_dtype: ${Tt}. Should be one of: float32, float16`);const Lt={dtype:mt,kv_cache_dtype:Tt},Ut=N.DEFAULT_DTYPE_SUFFIX_MAPPING[mt],Dt=`${V.subfolder??""}/${x}${Ut}.onnx`,Vt={...V.session_options};Vt.executionProviders??(Vt.executionProviders=Ye);const Zt=be.free_dimension_overrides;Zt?Vt.freeDimensionOverrides??(Vt.freeDimensionOverrides=Zt):Se.startsWith("webnn")&&!Vt.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const sr=(0,w.getModelFile)(_,Dt,!0,V),qt=V.use_external_data_format??be.use_external_data_format;let or=[];if(qt&&(qt===!0||typeof qt=="object"&&qt.hasOwnProperty(x)&&qt[x]===!0)){if(z.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const dr=`${x}${Ut}.onnx_data`,Pr=`${V.subfolder??""}/${dr}`;or.push(new Promise(async($r,Gr)=>{const Ur=await(0,w.getModelFile)(_,Pr,!0,V);$r({path:dr,data:Ur})}))}else Vt.externalData!==void 0&&(or=Vt.externalData.map(async dr=>{if(typeof dr.data=="string"){const Pr=await(0,w.getModelFile)(_,dr.data,!0,V);return{...dr,data:Pr}}return dr}));if(or.length>0&&(Vt.externalData=await Promise.all(or)),Se==="webgpu"){const dr=(0,f.getKeyValueShapes)(V.config,{prefix:"present"});if(Object.keys(dr).length>0&&!(0,O.isONNXProxy)()){const Pr={};for(const $r in dr)Pr[$r]="gpu-buffer";Vt.preferredOutputLocation=Pr}}return{buffer:await sr,session_options:Vt,session_config:Lt}}async function ee(_,x,V){return Object.fromEntries(await Promise.all(Object.keys(x).map(async be=>{const{buffer:Oe,session_options:Se,session_config:Ye}=await T(_,x[be],V),rt=await(0,O.createInferenceSession)(Oe,Se,Ye);return[be,rt]})))}async function J(_,x,V){return Object.fromEntries(await Promise.all(Object.keys(x).map(async be=>{const Oe=await(0,w.getModelJSON)(_,x[be],!1,V);return[be,Oe]})))}function le(_,x){const V=Object.create(null),be=[];for(const Ye of _.inputNames){const rt=x[Ye];if(!(rt instanceof b.Tensor)){be.push(Ye);continue}V[Ye]=(0,O.isONNXProxy)()?rt.clone():rt}if(be.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${be.join(", ")}.`);const Oe=Object.keys(x).length,Se=_.inputNames.length;if(Oe>Se){let Ye=Object.keys(x).filter(rt=>!_.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Oe} > ${Se}). The following inputs will be ignored: "${Ye.join(", ")}".`)}return V}async function de(_,x){const V=le(_,x);try{const be=Object.fromEntries(Object.entries(V).map(([Se,Ye])=>[Se,Ye.ort_tensor]));let Oe=await _.run(be);return Oe=fe(Oe),Oe}catch(be){const Oe=Object.fromEntries(Object.entries(V).map(([Se,{type:Ye,dims:rt,data:mt}])=>[Se,{type:Ye,dims:rt,data:mt}]));throw console.error(`An error occurred during model execution: "${be}".`),console.error("Inputs given to model:",Oe),be}}function fe(_){for(let x in _)(0,O.isONNXTensor)(_[x])?_[x]=new b.Tensor(_[x]):typeof _[x]=="object"&&fe(_[x]);return _}function ke(_){if(_ instanceof b.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(x=>x.length!==_[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(_.flat().map(x=>BigInt(x))),[_.length,_[0].length])}else return new b.Tensor("int64",BigInt64Array.from(_.map(x=>BigInt(x))),[1,_.length])}function xe(_){return new b.Tensor("bool",[_],[1])}async function Le(_,x){let{encoder_outputs:V,input_ids:be,decoder_input_ids:Oe,...Se}=x;if(!V){const rt=(0,U.pick)(x,_.sessions.model.inputNames);V=(await qe(_,rt)).last_hidden_state}return Se.input_ids=Oe,Se.encoder_hidden_states=V,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Se.encoder_attention_mask=x.attention_mask),await Ue(_,Se,!0)}async function qe(_,x){const V=_.sessions.model,be=(0,U.pick)(x,V.inputNames);if(V.inputNames.includes("inputs_embeds")&&!be.inputs_embeds){if(!x.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");be.inputs_embeds=await _.encode_text({input_ids:x.input_ids})}return V.inputNames.includes("token_type_ids")&&!be.token_type_ids&&(be.token_type_ids=new b.Tensor("int64",new BigInt64Array(be.input_ids.data.length),be.input_ids.dims)),await de(V,be)}async function Ue(_,x,V=!1){const be=_.sessions[V?"decoder_model_merged":"model"],{past_key_values:Oe,...Se}=x;if(be.inputNames.includes("use_cache_branch")&&(Se.use_cache_branch=xe(!!Oe)),be.inputNames.includes("position_ids")&&Se.attention_mask&&!Se.position_ids){const rt=_.config.model_type==="paligemma"?1:0;Se.position_ids=he(Se,Oe,rt)}_.addPastKeyValues(Se,Oe);const Ye=(0,U.pick)(Se,be.inputNames);return await de(be,Ye)}function ut({image_token_id:_,inputs_embeds:x,image_features:V,input_ids:be,attention_mask:Oe}){const Se=be.tolist().map(Tt=>Tt.reduce((Lt,Ut,Dt)=>(Ut==_&&Lt.push(Dt),Lt),[])),Ye=Se.reduce((Tt,Lt)=>Tt+Lt.length,0),rt=V.dims[0];if(Ye!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${Ye}, features ${rt}`);let mt=0;for(let Tt=0;TtSe.dims[1])){if(Oert==_.config.image_token_index)){const rt=_.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const mt=Se.dims[1]-(Oe-rt);V.input_ids=Se.slice(null,[-mt,null]),V.attention_mask=(0,b.ones)([1,Oe+mt])}}}return V}function Be(_,x,V,be){return V.past_key_values&&(x=x.map(Oe=>[Oe.at(-1)])),{...V,decoder_input_ids:ke(x)}}function et(_,...x){return _.config.is_encoder_decoder?Be(_,...x):Pe(_,...x)}function Xe(_,x,V,be){const Oe=!!V.past_key_values;return be.guidance_scale!==null&&be.guidance_scale>1&&(Oe?V.input_ids=(0,b.cat)([V.input_ids,V.input_ids],0):(V.input_ids=(0,b.cat)([V.input_ids,(0,b.full_like)(V.input_ids,BigInt(be.pad_token_id))],0),V.attention_mask=(0,b.cat)([V.attention_mask,(0,b.full_like)(V.attention_mask,0n)],0))),(Oe||!V.pixel_values)&&(V.pixel_values=(0,b.full)([0,0,3,384,384],1)),Oe&&(V.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),V.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),V}class oe extends Q.Callable{constructor(V,be,Oe){super();ge(this,"main_input_name","input_ids");ge(this,"forward_params",["input_ids","attention_mask"]);this.config=V,this.sessions=be,this.configs=Oe;const Se=C.get(this.constructor),Ye=$.get(Se);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ye){case D.DecoderOnly:this.can_generate=!0,this._forward=Ue,this._prepare_inputs_for_generation=Pe;break;case D.Seq2Seq:case D.Vision2Seq:case D.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=Be;break;case D.EncoderDecoder:this._forward=Le;break;case D.ImageTextToText:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=et;break;case D.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=et;break;case D.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Xe;break;default:this._forward=qe;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var be;const V=[];for(const Oe of Object.values(this.sessions))(be=Oe==null?void 0:Oe.handler)!=null&&be.dispose&&V.push(Oe.handler.dispose());return await Promise.all(V)}static async from_pretrained(V,{progress_callback:be=null,config:Oe=null,cache_dir:Se=null,local_files_only:Ye=!1,revision:rt="main",model_file_name:mt=null,subfolder:Tt="onnx",device:Lt=null,dtype:Ut=null,use_external_data_format:Dt=null,session_options:Vt={}}={}){let Zt={progress_callback:be,config:Oe,cache_dir:Se,local_files_only:Ye,revision:rt,model_file_name:mt,subfolder:Tt,device:Lt,dtype:Ut,use_external_data_format:Dt,session_options:Vt};const sr=C.get(this),qt=$.get(sr);Oe=Zt.config=await f.AutoConfig.from_pretrained(V,Zt);let or;if(qt===D.DecoderOnly)or=await Promise.all([ee(V,{model:Zt.model_file_name??"model"},Zt),J(V,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.Seq2Seq||qt===D.Vision2Seq)or=await Promise.all([ee(V,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt),J(V,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.MaskGeneration)or=await Promise.all([ee(V,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Zt)]);else if(qt===D.EncoderDecoder)or=await Promise.all([ee(V,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Zt)]);else if(qt===D.ImageTextToText){const Sr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Oe.is_encoder_decoder&&(Sr.model="encoder_model"),or=await Promise.all([ee(V,Sr,Zt),J(V,{generation_config:"generation_config.json"},Zt)])}else if(qt===D.Musicgen)or=await Promise.all([ee(V,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Zt),J(V,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.MultiModality)or=await Promise.all([ee(V,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},Zt),J(V,{generation_config:"generation_config.json"},Zt)]);else if(qt===D.Phi3V)or=await Promise.all([ee(V,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Zt),J(V,{generation_config:"generation_config.json"},Zt)]);else{if(qt!==D.EncoderOnly){const Sr=sr??(Oe==null?void 0:Oe.model_type);Sr!=="custom"&&console.warn(`Model type for '${Sr}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}or=await Promise.all([ee(V,{model:Zt.model_file_name??"model"},Zt)])}return new this(Oe,...or)}async _call(V){return await this.forward(V)}async forward(V){return await this._forward(this,V)}get generation_config(){var V;return((V=this.configs)==null?void 0:V.generation_config)??null}_get_logits_warper(V){const be=new y.LogitsProcessorList;return V.temperature!==null&&V.temperature!==1&&be.push(new y.TemperatureLogitsWarper(V.temperature)),V.top_k!==null&&V.top_k!==0&&be.push(new y.TopKLogitsWarper(V.top_k)),V.top_p!==null&&V.top_p<1&&be.push(new y.TopPLogitsWarper(V.top_p)),be}_get_logits_processor(V,be,Oe=null){const Se=new y.LogitsProcessorList;if(V.repetition_penalty!==null&&V.repetition_penalty!==1&&Se.push(new y.RepetitionPenaltyLogitsProcessor(V.repetition_penalty)),V.no_repeat_ngram_size!==null&&V.no_repeat_ngram_size>0&&Se.push(new y.NoRepeatNGramLogitsProcessor(V.no_repeat_ngram_size)),V.bad_words_ids!==null&&Se.push(new y.NoBadWordsLogitsProcessor(V.bad_words_ids,V.eos_token_id)),V.min_length!==null&&V.eos_token_id!==null&&V.min_length>0&&Se.push(new y.MinLengthLogitsProcessor(V.min_length,V.eos_token_id)),V.min_new_tokens!==null&&V.eos_token_id!==null&&V.min_new_tokens>0&&Se.push(new y.MinNewTokensLengthLogitsProcessor(be,V.min_new_tokens,V.eos_token_id)),V.forced_bos_token_id!==null&&Se.push(new y.ForcedBOSTokenLogitsProcessor(V.forced_bos_token_id)),V.forced_eos_token_id!==null&&Se.push(new y.ForcedEOSTokenLogitsProcessor(V.max_length,V.forced_eos_token_id)),V.begin_suppress_tokens!==null){const Ye=be>1||V.forced_bos_token_id===null?be:be+1;Se.push(new y.SuppressTokensAtBeginLogitsProcessor(V.begin_suppress_tokens,Ye))}return V.guidance_scale!==null&&V.guidance_scale>1&&Se.push(new y.ClassifierFreeGuidanceLogitsProcessor(V.guidance_scale)),Oe!==null&&Se.extend(Oe),Se}_prepare_generation_config(V,be,Oe=M.GenerationConfig){const Se={...this.config};for(const rt of["decoder","generator","text_config"])rt in Se&&Object.assign(Se,Se[rt]);const Ye=new Oe(Se);return Object.assign(Ye,this.generation_config??{}),V&&Object.assign(Ye,V),be&&Object.assign(Ye,(0,U.pick)(be,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(V,be=null){const Oe=new se.StoppingCriteriaList;return V.max_length!==null&&Oe.push(new se.MaxLengthCriteria(V.max_length,this.config.max_position_embeddings??null)),V.eos_token_id!==null&&Oe.push(new se.EosTokenCriteria(V.eos_token_id)),be&&Oe.extend(be),Oe}_validate_model_class(){if(!this.can_generate){const V=[ra,Co,ta,ea],be=C.get(this.constructor),Oe=new Set,Se=this.config.model_type;for(const rt of V){const mt=rt.get(Se);mt&&Oe.add(mt[0])}let Ye=`The current model class (${be}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Oe.size>0&&(Ye+=` Please use the following class instead: ${[...Oe].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...V){return this._prepare_inputs_for_generation(this,...V)}_update_model_kwargs_for_generation({generated_input_ids:V,outputs:be,model_inputs:Oe,is_encoder_decoder:Se}){return Oe.past_key_values=this.getPastKeyValues(be,Oe.past_key_values),Oe.input_ids=new b.Tensor("int64",V.flat(),[V.length,1]),Se||(Oe.attention_mask=(0,b.cat)([Oe.attention_mask,(0,b.ones)([Oe.attention_mask.dims[0],1])],1)),Oe.position_ids=null,Oe}_prepare_model_inputs({inputs:V,bos_token_id:be,model_kwargs:Oe}){const Se=(0,U.pick)(Oe,this.forward_params),Ye=this.main_input_name;if(Ye in Se){if(V)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Se[Ye]=V;return{inputs_tensor:Se[Ye],model_inputs:Se,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:V,model_inputs:be,model_input_name:Oe,generation_config:Se}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!be.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:mt,attention_mask:Tt,...Lt}=be,Ut=await this._prepare_inputs_embeds(be);be={...Lt,...(0,U.pick)(Ut,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await qe(this,be);if(Se.guidance_scale!==null&&Se.guidance_scale>1)Ye=(0,b.cat)([Ye,(0,b.full_like)(Ye,0)],0),"attention_mask"in be&&(be.attention_mask=(0,b.cat)([be.attention_mask,(0,b.zeros_like)(be.attention_mask)],0));else if(be.decoder_input_ids){const rt=ke(be.decoder_input_ids).dims[0];if(rt!==Ye.dims[0]){if(Ye.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ye.dims[0]}) than the decoder inputs (${rt}).`);Ye=(0,b.cat)(Array.from({length:rt},()=>Ye),0)}}return be.encoder_outputs=Ye,be}_prepare_decoder_input_ids_for_generation({batch_size:V,model_input_name:be,model_kwargs:Oe,decoder_start_token_id:Se,bos_token_id:Ye,generation_config:rt}){let{decoder_input_ids:mt,...Tt}=Oe;if(!(mt instanceof b.Tensor)){if(mt)Array.isArray(mt[0])||(mt=Array.from({length:V},()=>mt));else if(Se??(Se=Ye),this.config.model_type==="musicgen")mt=Array.from({length:V*this.config.decoder.num_codebooks},()=>[Se]);else if(Array.isArray(Se)){if(Se.length!==V)throw new Error(`\`decoder_start_token_id\` expcted to have length ${V} but got ${Se.length}`);mt=Se}else mt=Array.from({length:V},()=>[Se]);mt=ke(mt)}return Oe.decoder_attention_mask=(0,b.ones_like)(mt),{input_ids:mt,model_inputs:Tt}}async generate({inputs:V=null,generation_config:be=null,logits_processor:Oe=null,stopping_criteria:Se=null,streamer:Ye=null,...rt}){this._validate_model_class(),be=this._prepare_generation_config(be,rt);let{inputs_tensor:mt,model_inputs:Tt,model_input_name:Lt}=this._prepare_model_inputs({inputs:V,model_kwargs:rt});const Ut=this.config.is_encoder_decoder;Ut&&("encoder_outputs"in Tt||(Tt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:mt,model_inputs:Tt,model_input_name:Lt,generation_config:be})));let Dt;Ut?{input_ids:Dt,model_inputs:Tt}=this._prepare_decoder_input_ids_for_generation({batch_size:Tt[Lt].dims.at(0),model_input_name:Lt,model_kwargs:Tt,decoder_start_token_id:be.decoder_start_token_id,bos_token_id:be.bos_token_id,generation_config:be}):Dt=Tt[Lt];let Vt=Dt.dims.at(-1);be.max_new_tokens!==null&&(be.max_length=Vt+be.max_new_tokens);const Zt=this._get_logits_processor(be,Vt,Oe),sr=this._get_stopping_criteria(be,Se),qt=Tt[Lt].dims.at(0),or=ie.LogitsSampler.getSampler(be),Sr=new Array(qt).fill(0),Tr=Dt.tolist();Ye&&Ye.put(Tr);let dr,Pr={};for(;;){if(Tt=this.prepare_inputs_for_generation(Tr,Tt,be),dr=await this.forward(Tt),be.output_attentions&&be.return_dict_in_generate){const ns=this.getAttentions(dr);for(const Ps in ns)Ps in Pr||(Pr[Ps]=[]),Pr[Ps].push(ns[Ps])}const Ur=dr.logits.slice(null,-1,null),gs=Zt(Tr,Ur),Wn=[];for(let ns=0;nsns))break;Tt=this._update_model_kwargs_for_generation({generated_input_ids:Wn,outputs:dr,model_inputs:Tt,is_encoder_decoder:Ut})}Ye&&Ye.end();const $r=this.getPastKeyValues(dr,Tt.past_key_values,!0),Gr=new b.Tensor("int64",Tr.flat(),[Tr.length,Tr[0].length]);if(be.return_dict_in_generate)return{sequences:Gr,past_key_values:$r,...Pr};for(const Ur of Object.values(dr))Ur.location==="gpu-buffer"&&Ur.dispose();return Gr}getPastKeyValues(V,be,Oe=!1){const Se=Object.create(null);for(const Ye in V)if(Ye.startsWith("present")){const rt=Ye.replace("present","past_key_values"),mt=Ye.includes("encoder");if(mt&&be?Se[rt]=be[rt]:Se[rt]=V[Ye],be&&(!mt||Oe)){const Tt=be[rt];Tt.location==="gpu-buffer"&&Tt.dispose()}}return Se}getAttentions(V){const be={};for(const Oe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Se in V)Se.startsWith(Oe)&&(Oe in be||(be[Oe]=[]),be[Oe].push(V[Se]));return be}addPastKeyValues(V,be){var Oe,Se,Ye;if(be)Object.assign(V,be);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,mt=((Oe=rt==null?void 0:rt.config)==null?void 0:Oe.kv_cache_dtype)??"float32",Tt=mt==="float16"?new Uint16Array:[],Lt=((Ye=(Se=V[this.main_input_name]??V.attention_mask)==null?void 0:Se.dims)==null?void 0:Ye[0])??1,Ut=(0,f.getKeyValueShapes)(this.config,{batch_size:Lt});for(const Dt in Ut)V[Dt]=new b.Tensor(mt,Tt,Ut[Dt])}}async encode_image({pixel_values:V}){const be=(await de(this.sessions.vision_encoder,{pixel_values:V})).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 (${be.dims[1]}).`),this.config.num_image_tokens=be.dims[1]),be}async encode_text({input_ids:V}){return(await de(this.sessions.embed_tokens,{input_ids:V})).inputs_embeds}}class Je{}class De extends Je{constructor({last_hidden_state:x,hidden_states:V=null,attentions:be=null}){super(),this.last_hidden_state=x,this.hidden_states=V,this.attentions=be}}class ce extends oe{}class ve extends ce{}class Re extends ce{async _call(x){return new Wr(await super._call(x))}}class je extends ce{async _call(x){return new Xt(await super._call(x))}}class We extends ce{async _call(x){return new jr(await super._call(x))}}class Ne extends ce{async _call(x){return new Xr(await super._call(x))}}class Ze extends oe{}class at extends Ze{}class ft extends Ze{async _call(x){return new Wr(await super._call(x))}}class dt extends Ze{async _call(x){return new Xt(await super._call(x))}}class gt extends Ze{async _call(x){return new jr(await super._call(x))}}class F extends oe{}class ne extends F{}class K extends oe{}class pe extends K{}class Fe extends K{async _call(x){return new Wr(await super._call(x))}}class Qe extends K{async _call(x){return new Xt(await super._call(x))}}class st extends K{async _call(x){return new jr(await super._call(x))}}class pt extends K{async _call(x){return new Xr(await super._call(x))}}class It extends oe{}class St extends It{}class Ft extends It{async _call(x){return new Wr(await super._call(x))}}class At extends It{async _call(x){return new Xt(await super._call(x))}}class nr extends It{async _call(x){return new jr(await super._call(x))}}class gr extends It{async _call(x){return new Xr(await super._call(x))}}class kr extends oe{}class Ar extends kr{}class Qr extends kr{async _call(x){return new Wr(await super._call(x))}}class os extends kr{async _call(x){return new Xt(await super._call(x))}}class Xs extends kr{async _call(x){return new jr(await super._call(x))}}class zs extends kr{async _call(x){return new Xr(await super._call(x))}}class Ms extends oe{}class Nt extends Ms{}class Qs extends Ms{async _call(x){return new Wr(await super._call(x))}}class ks extends Ms{async _call(x){return new Xt(await super._call(x))}}class Bs extends Ms{async _call(x){return new jr(await super._call(x))}}class Ss extends Ms{async _call(x){return new Xr(await super._call(x))}}class is extends oe{}class $s extends is{}class cs extends is{async _call(x){return new Wr(await super._call(x))}}class As extends is{async _call(x){return new Xt(await super._call(x))}}class Ys extends is{async _call(x){return new jr(await super._call(x))}}class as extends is{async _call(x){return new Xr(await super._call(x))}}class nt extends oe{}class _t extends nt{}class Ot extends nt{async _call(x){return new Wr(await super._call(x))}}class lr extends nt{async _call(x){return new Xt(await super._call(x))}}class bs extends nt{async _call(x){return new jr(await super._call(x))}}class tr extends nt{async _call(x){return new Xr(await super._call(x))}}class ts extends oe{}class Rs extends ts{}class Js extends ts{async _call(x){return new Xt(await super._call(x))}}class Ns extends ts{async _call(x){return new jr(await super._call(x))}}class vs extends ts{async _call(x){return new Xr(await super._call(x))}}class Sn extends ts{async _call(x){return new Wr(await super._call(x))}}class js extends oe{}class $n extends js{}class Jn extends js{async _call(x){return new Wr(await super._call(x))}}class Us extends js{async _call(x){return new Xt(await super._call(x))}}class Ts extends js{async _call(x){return new jr(await super._call(x))}}class ls extends oe{}class mn extends ls{}class Zs extends ls{async _call(x){return new Wr(await super._call(x))}}class _n extends ls{async _call(x){return new Xt(await super._call(x))}}class en extends ls{async _call(x){return new Xr(await super._call(x))}}class xs extends oe{}class zt extends xs{}class fn extends xs{async _call(x){return new Wr(await super._call(x))}}class An extends xs{async _call(x){return new Xt(await super._call(x))}}class In extends xs{async _call(x){return new jr(await super._call(x))}}class On extends xs{async _call(x){return new Xr(await super._call(x))}}class Vs extends oe{}class Fn extends Vs{}class gn extends Vs{async _call(x){return new Wr(await super._call(x))}}class Dn extends Vs{async _call(x){return new Xt(await super._call(x))}}class ir extends Vs{async _call(x){return new Xr(await super._call(x))}}class Yr extends oe{}class wn extends Yr{}class Ln extends Yr{async _call(x){return new Xt(await super._call(x))}}class yn extends Yr{async _call(x){return new Xr(await super._call(x))}}class Mn extends Yr{async _call(x){return new Wr(await super._call(x))}}class Ee extends oe{constructor(){super(...arguments);ge(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class P extends Ee{}class H extends Ee{}class ae extends oe{}class Me extends ae{}class Ce extends ae{}class He extends oe{}class ct extends He{}class yt extends He{}class ht extends oe{}class it extends ht{}class Pt extends ht{}class hr extends ht{async _call(x){return new Xt(await super._call(x))}}class rr extends oe{}class $e extends rr{}class wr extends rr{}class Rr extends rr{async _call(x){return new Xt(await super._call(x))}}class Jr extends rr{}class Zr extends oe{}class Bt extends Zr{}class Nr extends Zr{}class ps extends oe{}class er extends ps{}class mr extends ps{}class vt extends oe{}class yr extends vt{}class Es extends vt{async _call(x){return new Wr(await super._call(x))}}class Fr extends vt{async _call(x){return new Xt(await super._call(x))}}class qr extends vt{async _call(x){return new jr(await super._call(x))}}class Mt extends vt{async _call(x){return new Xr(await super._call(x))}}class br extends oe{}class ze extends br{}class wt extends br{async _call(x){return new Wr(await super._call(x))}}class rs extends br{async _call(x){return new Xt(await super._call(x))}}class tn extends br{async _call(x){return new jr(await super._call(x))}}class Zn extends br{async _call(x){return new Xr(await super._call(x))}}class bn extends oe{}class Qt extends bn{}class Ta extends bn{async _call(x){return new Wr(await super._call(x))}}class No extends bn{async _call(x){return new Xt(await super._call(x))}}class xa extends bn{async _call(x){return new jr(await super._call(x))}}class Ea extends bn{async _call(x){return new Xr(await super._call(x))}}class jo extends oe{}class Pa extends jo{}class ss extends jo{}class Uo extends oe{constructor(){super(...arguments);ge(this,"requires_attention_mask",!1);ge(this,"main_input_name","input_features");ge(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ca extends Uo{}class Ws extends Uo{_prepare_generation_config(x,V){return super._prepare_generation_config(x,V,W.WhisperGenerationConfig)}_retrieve_init_tokens(x){const V=[x.decoder_start_token_id];let be=x.language;const Oe=x.task;if(x.is_multilingual){be||(console.warn("No language specified - defaulting to English (en)."),be="en");const Ye=`<|${(0,Y.whisper_language_to_code)(be)}|>`;V.push(x.lang_to_id[Ye]),V.push(x.task_to_id[Oe??"transcribe"])}else if(be||Oe)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!x.return_timestamps&&x.no_timestamps_token_id&&V.at(-1)!==x.no_timestamps_token_id?V.push(x.no_timestamps_token_id):x.return_timestamps&&V.at(-1)===x.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),V.pop()),V.filter(Se=>Se!=null)}async generate({inputs:x=null,generation_config:V=null,logits_processor:be=null,stopping_criteria:Oe=null,...Se}){V=this._prepare_generation_config(V,Se);const Ye=Se.decoder_input_ids??this._retrieve_init_tokens(V);if(V.return_timestamps&&(be??(be=new y.LogitsProcessorList),be.push(new y.WhisperTimeStampLogitsProcessor(V,Ye))),V.begin_suppress_tokens&&(be??(be=new y.LogitsProcessorList),be.push(new y.SuppressTokensAtBeginLogitsProcessor(V.begin_suppress_tokens,Ye.length))),V.return_token_timestamps){if(!V.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.");V.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),V.output_attentions=!0,V.return_dict_in_generate=!0}const rt=await super.generate({inputs:x,generation_config:V,logits_processor:be,decoder_input_ids:Ye,...Se});return V.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,V.alignment_heads,V.num_frames)),rt}_extract_token_timestamps(x,V,be=null,Oe=.02){if(!x.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`.");be==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 Se=this.config.median_filter_width;Se===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Se=7);const Ye=x.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(sr,qt)=>(0,b.cat)(Ye.map(or=>or[qt]),2)),mt=(0,b.stack)(V.map(([sr,qt])=>{if(sr>=rt.length)throw new Error(`Layer index ${sr} is out of bounds for cross attentions (length ${rt.length}).`);return be?rt[sr].slice(null,qt,null,[0,be]):rt[sr].slice(null,qt)})).transpose(1,0,2,3),[Tt,Lt]=(0,b.std_mean)(mt,-2,0,!0),Ut=mt.clone();for(let sr=0;sror[Gr+1]-or[Gr]),dr=(0,U.mergeArrays)([1],Tr).map($r=>!!$r),Pr=[];for(let $r=0;$rDt.findIndex(Vt=>Vt==Se)),mt=rt.every(Dt=>Dt===-1),Tt=rt.every(Dt=>Dt!==-1);if(!mt&&!Tt)throw new Error("Every input should contain either 0 or 1 image token.");if(mt)return{inputs_embeds:x,attention_mask:Oe};const Lt=[],Ut=[];for(let Dt=0;DtArray.from({length:x.dims[0]},Tr=>Array.from({length:x.dims[1]},dr=>1))),Zt=V?V.tolist():[],sr=be?be.tolist():[];let qt=0,or=0;for(let Sr=0;SrDt[Sr][Dr]==1),Pr=Tr.reduce((xr,Dr,Ds)=>(Dr==mt&&xr.push(Ds),xr),[]).map(xr=>Tr[xr+1]),$r=Pr.filter(xr=>xr==Ye).length,Gr=Pr.filter(xr=>xr==rt).length;let Ur=[],gs=0,Wn=$r,ua=Gr;for(let xr=0;xrKr>gs&&qs==Ye),Ds=Tr.findIndex((qs,Kr)=>Kr>gs&&qs==rt),Hs=Wn>0&&Dr!==-1?Dr:Tr.length+1,ln=ua>0&&Ds!==-1?Ds:Tr.length+1;let $o,pa,bc,Ao;Hs0?(0,q.max)(Ur.at(-1))[0]+1:0;Ur.push(Array.from({length:3*_a},(qs,Kr)=>Io+Kr%_a));const fa=_a+Io,Oo=gp*ha*ma,Up=Array.from({length:Oo},(qs,Kr)=>fa+Math.floor(Kr/(ha*ma))),wp=Array.from({length:Oo},(qs,Kr)=>fa+Math.floor(Kr/ma)%ha),vc=Array.from({length:Oo},(qs,Kr)=>fa+Kr%ma);Ur.push([Up,wp,vc].flat()),gs=$o+Oo}if(gs0?(0,q.max)(Ur.at(-1))[0]+1:0,Dr=Tr.length-gs;Ur.push(Array.from({length:3*Dr},(Ds,Hs)=>xr+Hs%Dr))}const ns=Ur.reduce((xr,Dr)=>xr+Dr.length,0),Ps=new Array(ns);let da=0;for(let xr=0;xr<3;++xr)for(let Dr=0;DrUt[qt%Ut.length]),Zt=Array.from({length:Dt[0]},(sr,qt)=>(0,q.max)(Ut.subarray(Dt[1]*qt,Dt[1]*(qt+1)))[0]+1+Dt[1]);return[new b.Tensor("int64",Vt,[3,...Dt]),new b.Tensor("int64",Zt,[Zt.length,1])]}else{const[Ut,Dt]=x.dims,Vt=BigInt64Array.from({length:3*Ut*Dt},(Zt,sr)=>BigInt(Math.floor(sr%Dt/Ut)));return[new b.Tensor("int64",Vt,[3,...x.dims]),(0,b.zeros)([Ut,1])]}}async encode_image({pixel_values:x,image_grid_thw:V}){return(await de(this.sessions.vision_encoder,{pixel_values:x,grid_thw:V})).image_features}_merge_input_ids_with_image_features(x){return ut({image_token_id:this.config.image_token_id,...x})}prepare_inputs_for_generation(x,V,be){if(V.attention_mask&&!V.position_ids)if(!V.past_key_values)[V.position_ids,V.rope_deltas]=this.get_rope_index(V.input_ids,V.image_grid_thw,V.video_grid_thw,V.attention_mask);else{V.pixel_values=null;const Oe=BigInt(Object.values(V.past_key_values)[0].dims.at(-2)),Se=V.rope_deltas.map(Ye=>Oe+Ye);V.position_ids=(0,b.stack)([Se,Se,Se],0)}return V}}class pi extends oe{}class Tl extends pi{}class xl extends pi{}class hi extends oe{}class El extends hi{}class Pl extends hi{}class mi extends oe{}class Cl extends mi{}class kl extends mi{}class _i extends oe{}class Sl extends _i{}class $l extends _i{}class fi extends oe{}class Al extends fi{}class Il extends fi{}class gi extends oe{}class wi extends gi{}class Ol extends gi{async _call(x){return new Xt(await super._call(x))}}class io extends oe{}class yi extends io{}class Fl extends io{async _call(x){return new Xt(await super._call(x))}}class Dl extends oe{}class Ll extends Dl{}class Mi extends oe{}class zl extends Mi{}class Bl extends Mi{async _call(x){return new Xt(await super._call(x))}}class bi extends oe{}class Rl extends bi{}class vi extends oe{}class Nl extends vi{}class Bc extends vi{async _call(x){return new Xt(await super._call(x))}}class jl extends oe{}class Ul extends jl{}class ds extends oe{}class Vl extends ds{}class Wl extends ds{async _call(x){return new Xt(await super._call(x))}}class Gl extends oe{}class Kl extends Gl{async _call(x){return new fp(await super._call(x))}}class Ti extends oe{}class Hl extends Ti{}class ql extends Ti{async _call(x){return new Xt(await super._call(x))}}class xi extends oe{}class Xl extends xi{}class Ql extends xi{async _call(x){return new Xt(await super._call(x))}}class Yl extends oe{}class Jl extends Yl{}class Zl extends Yl{}class Ei extends oe{}class eu extends Ei{}class tu extends Ei{}class Pi extends oe{}class Rc extends Pi{}class sn extends Pi{async _call(x){return new Xt(await super._call(x))}}class Is extends oe{}class nn extends Is{}class Ci extends Is{async _call(x){return new Vr(await super._call(x))}}class Gs extends Is{async _call(x){return new ru(await super._call(x))}}class Vr extends Je{constructor({logits:x,pred_boxes:V}){super(),this.logits=x,this.pred_boxes=V}}class ru extends Je{constructor({logits:x,pred_boxes:V,pred_masks:be}){super(),this.logits=x,this.pred_boxes=V,this.pred_masks=be}}class ao extends oe{}class su extends ao{}class Nc extends ao{async _call(x){return new Bn(await super._call(x))}}class Bn extends Je{constructor({logits:x,pred_boxes:V}){super(),this.logits=x,this.pred_boxes=V}}class lo extends oe{}class ki extends lo{}class nu extends lo{async _call(x){return new ou(await super._call(x))}}class ou extends Vr{}class uo extends oe{}class Si extends uo{}class iu extends uo{async _call(x){return new Xt(await super._call(x))}}class co extends oe{}class au extends co{}class po extends co{async _call(x){return new Xt(await super._call(x))}}class ho extends oe{}class lu extends ho{}class uu extends ho{async _call(x){return new Xt(await super._call(x))}}class du extends oe{}class cu extends du{}class $i extends du{async _call(x){return new Xt(await super._call(x))}}class Tn extends oe{}class pu extends Tn{}class Ai extends Tn{}class Ii extends oe{}class hu extends Ii{}class mu extends Ii{}class jc extends oe{}class _u extends jc{}class mo extends oe{}class Uc extends mo{}class fu extends mo{}class _o extends mo{}class gu extends oe{}class fo extends gu{}class go extends oe{}class Oi extends go{}class wu extends go{}class Fi extends oe{}class Di extends Fi{}class Vc extends Fi{}class yu extends oe{}class Wc extends yu{}class Li extends oe{}class Mu extends Li{}class bu extends Li{async _call(x){return new Xt(await super._call(x))}}class wo extends oe{}class vu extends wo{}class Tu extends wo{async _call(x){return new Xt(await super._call(x))}}class yo extends oe{}class xu extends yo{}class Eu extends yo{async _call(x){return new Xt(await super._call(x))}}class Pu extends oe{}class Cu extends Pu{}class ku extends Pu{async _call(x){return new Su(await super._call(x))}}class Su extends Je{constructor({logits:x,pred_boxes:V}){super(),this.logits=x,this.pred_boxes=V}}class Gc extends oe{}class $u extends Gc{async get_image_embeddings({pixel_values:x}){return await qe(this,{pixel_values:x})}async forward(x){if((!x.image_embeddings||!x.image_positional_embeddings)&&(x={...x,...await this.get_image_embeddings(x)}),!x.input_labels&&x.input_points){const be=x.input_points.dims.slice(0,-1),Oe=be.reduce((Se,Ye)=>Se*Ye,1);x.input_labels=new b.Tensor("int64",new BigInt64Array(Oe).fill(1n),be)}const V={image_embeddings:x.image_embeddings,image_positional_embeddings:x.image_positional_embeddings};return x.input_points&&(V.input_points=x.input_points),x.input_labels&&(V.input_labels=x.input_labels),x.input_boxes&&(V.input_boxes=x.input_boxes),await de(this.sessions.prompt_encoder_mask_decoder,V)}async _call(x){return new Au(await super._call(x))}}class Au extends Je{constructor({iou_scores:x,pred_masks:V}){super(),this.iou_scores=x,this.pred_masks=V}}class zi extends oe{}class Iu extends zi{}class Ou extends zi{}class Fu extends oe{}class Mo extends Fu{}class Rn extends Fu{}class Os extends oe{}class Du extends Os{}class Lu extends Os{async _call(x){return new an(await super._call(x))}}class zu extends Os{async _call(x){return new Xt(await super._call(x))}}class Bu extends Os{async _call(x){return new jr(await super._call(x))}}class bo extends oe{}class Ru extends bo{}class Nu extends bo{async _call(x){return new jr(await super._call(x))}}class ju extends oe{}class Kc extends ju{}class vo extends oe{}class Bi extends vo{}class Uu extends vo{async _call(x){return new an(await super._call(x))}}class Vu extends vo{async _call(x){return new Xt(await super._call(x))}}class Nn extends oe{}class Hc extends Nn{}class Wu extends Nn{async _call(x){return new an(await super._call(x))}}class Gu extends Nn{async _call(x){return new Xt(await super._call(x))}}class qc extends Nn{async _call(x){return new jr(await super._call(x))}}class To extends oe{}class Ku extends To{}class Hu extends To{async _call(x){return new an(await super._call(x))}}class qu extends To{async _call(x){return new Xt(await super._call(x))}}class Rp extends oe{}class Xu extends Os{}class Qu extends Os{async _call(x){return new an(await super._call(x))}}class Yu extends Os{async _call(x){return new Xt(await super._call(x))}}class jn extends oe{}class Ju extends jn{}class Zu extends jn{async _call(x){return new an(await super._call(x))}}class ed extends jn{async _call(x){return new Xt(await super._call(x))}}class td extends jn{async _call(x){return new yc(await super._call(x))}}class Xc extends jn{async _call(x){return new jr(await super._call(x))}}class xo extends oe{}class Qc extends xo{}class rd extends xo{}class sd extends xo{async generate_speech(x,V,{threshold:be=.5,minlenratio:Oe=0,maxlenratio:Se=20,vocoder:Ye=null}={}){const rt={input_ids:x},{encoder_outputs:mt,encoder_attention_mask:Tt}=await qe(this,rt),Lt=mt.dims[1]/this.config.reduction_factor,Ut=Math.floor(Lt*Se),Dt=Math.floor(Lt*Oe),Vt=this.config.num_mel_bins;let Zt=[],sr=null,qt=null,or=0;for(;;){++or;const dr=xe(!!qt);let Pr;qt?Pr=qt.output_sequence_out:Pr=new b.Tensor("float32",new Float32Array(Vt),[1,1,Vt]);let $r={use_cache_branch:dr,output_sequence:Pr,encoder_attention_mask:Tt,speaker_embeddings:V,encoder_hidden_states:mt};this.addPastKeyValues($r,sr),qt=await de(this.sessions.decoder_model_merged,$r),sr=this.getPastKeyValues(qt,sr);const{prob:Gr,spectrum:Ur}=qt;if(Zt.push(Ur),or>=Dt&&(Array.from(Gr.data).filter(gs=>gs>=be).length>0||or>=Ut))break}const Sr=(0,b.cat)(Zt),{waveform:Tr}=await de(Ye.sessions.model,{spectrogram:Sr});return{spectrogram:Sr,waveform:Tr}}}class Yc extends oe{constructor(){super(...arguments);ge(this,"main_input_name","spectrogram")}}class nd extends oe{}class od extends nd{}class Ri extends oe{}class id extends Ri{}class Jc extends Ri{}class fs extends oe{}class Fs extends fs{}class on extends fs{}class Ks extends oe{}class ad extends Ks{}class ld extends Ks{}class Eo extends oe{}class ud extends Eo{}class dd extends Eo{static async from_pretrained(x,V={}){return super.from_pretrained(x,{model_file_name:"text_model",...V})}}class cd extends Eo{static async from_pretrained(x,V={}){return super.from_pretrained(x,{model_file_name:"audio_model",...V})}}class pd extends oe{}class Ni extends pd{async _call(x){return new Mc(await super._call(x))}}class Po extends oe{}class Zc extends Po{}class ep extends Po{}class es extends Po{}class ji extends oe{}class hd extends ji{}class Ui extends ji{}class Vi extends oe{}class Un extends Vi{}class md extends Vi{async _call(x){return new Xt(await super._call(x))}}class Wi extends oe{}class tp extends Wi{}class rp extends Wi{}class Gi extends oe{constructor(){super(...arguments);ge(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(V){const[be,Oe]=V.dims,Se=this.config.decoder.num_codebooks,Ye=Oe-Se;let rt=0;for(let Lt=0;Lt0&&Vt<=Ye&&(V.data[rt++]=V.data[Lt])}const mt=Math.floor(be/Se),Tt=rt/(mt*Se);return new b.Tensor(V.type,V.data.slice(0,rt),[mt,Se,Tt])}prepare_inputs_for_generation(V,be,Oe){let Se=structuredClone(V);for(let rt=0;rt=mt&&(Se[rt][mt]=BigInt(this.config.decoder.pad_token_id));return Oe.guidance_scale!==null&&Oe.guidance_scale>1&&(Se=Se.concat(Se)),super.prepare_inputs_for_generation(Se,be,Oe)}async generate(V){const be=await super.generate(V),Oe=this._apply_and_filter_by_delay_pattern_mask(be).unsqueeze_(0),{audio_values:Se}=await de(this.sessions.encodec_decode,{audio_codes:Oe});return Se}}class Ki extends oe{}class Hi extends Ki{}class _d extends Ki{async _call(x){return new Xt(await super._call(x))}}class qi extends oe{}class fd extends qi{}class gd extends qi{async _call(x){return new Xt(await super._call(x))}}class Xi extends oe{}class Qi extends Xi{}class wd extends Xi{async _call(x){return new Xt(await super._call(x))}}class yd extends oe{}class Yi extends yd{}class Md extends yd{async _call(x){return new Xt(await super._call(x))}}class bd extends oe{}class vd extends bd{}class sp extends oe{}class Td extends sp{constructor(...V){super(...V);ge(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(V){const be=this._generation_mode??"text";let Oe;if(be==="text"||!V.past_key_values){const Tt=this.sessions.prepare_inputs_embeds,Lt=(0,U.pick)(V,Tt.inputNames);Oe=await de(Tt,Lt)}else{const Tt=this.sessions.gen_img_embeds,Lt=(0,U.pick)({image_ids:V.input_ids},Tt.inputNames);Oe=await de(Tt,Lt)}const Se={...V,...Oe},Ye=await Ue(this,Se),rt=this.sessions[be==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const mt=await de(rt,(0,U.pick)(Ye,rt.inputNames));return{...Oe,...Ye,...mt}}async generate(V){return this._generation_mode="text",super.generate(V)}async generate_images(V){this._generation_mode="image";const be=(V.inputs??V[this.main_input_name]).dims[1],Se=(await super.generate(V)).slice(null,[be,null]),Ye=this.sessions.image_decode,{decoded_image:rt}=await de(Ye,{generated_tokens:Se}),mt=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Tt=[];for(const Lt of mt){const Ut=L.RawImage.fromTensor(Lt);Tt.push(Ut)}return Tt}}class xd extends Je{constructor({char_logits:x,bpe_logits:V,wp_logits:be}){super(),this.char_logits=x,this.bpe_logits=V,this.wp_logits=be}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ed extends oe{}class np extends Ed{async _call(x){return new xd(await super._call(x))}}class Ji extends oe{}class Pd extends Ji{}class op extends Ji{}class Zi extends oe{}class Cd extends Zi{}class kd extends Zi{}class _r{static async from_pretrained(x,{progress_callback:V=null,config:be=null,cache_dir:Oe=null,local_files_only:Se=!1,revision:Ye="main",model_file_name:rt=null,subfolder:mt="onnx",device:Tt=null,dtype:Lt=null,use_external_data_format:Ut=null,session_options:Dt={}}={}){const Vt={progress_callback:V,config:be,cache_dir:Oe,local_files_only:Se,revision:Ye,model_file_name:rt,subfolder:mt,device:Tt,dtype:Lt,use_external_data_format:Ut,session_options:Dt};if(Vt.config=await f.AutoConfig.from_pretrained(x,Vt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const Zt of this.MODEL_CLASS_MAPPINGS){const sr=Zt.get(Vt.config.model_type);if(sr)return await sr[1].from_pretrained(x,Vt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Vt.config.model_type}", attempting to construct from base class.`),await oe.from_pretrained(x,Vt);throw Error(`Unsupported model type: ${Vt.config.model_type}`)}}ge(_r,"MODEL_CLASS_MAPPINGS",null),ge(_r,"BASE_IF_FAIL",!1);const ip=new Map([["bert",["BertModel",ve]],["modernbert",["ModernBertModel",at]],["nomic_bert",["NomicBertModel",ne]],["roformer",["RoFormerModel",pe]],["electra",["ElectraModel",Ar]],["esm",["EsmModel",$n]],["convbert",["ConvBertModel",St]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",$s]],["deberta-v2",["DebertaV2Model",_t]],["mpnet",["MPNetModel",zt]],["albert",["AlbertModel",wn]],["distilbert",["DistilBertModel",Rs]],["roberta",["RobertaModel",yr]],["xlm",["XLMModel",ze]],["xlm-roberta",["XLMRobertaModel",Qt]],["clap",["ClapModel",ud]],["clip",["CLIPModel",za]],["clipseg",["CLIPSegModel",Wa]],["chinese_clip",["ChineseCLIPModel",Na]],["siglip",["SiglipModel",Ra]],["jina_clip",["JinaCLIPModel",ja]],["mobilebert",["MobileBertModel",mn]],["squeezebert",["SqueezeBertModel",Fn]],["wav2vec2",["Wav2Vec2Model",Du]],["wav2vec2-bert",["Wav2Vec2BertModel",Ku]],["unispeech",["UniSpeechModel",Bi]],["unispeech-sat",["UniSpeechSatModel",Hc]],["hubert",["HubertModel",Xu]],["wavlm",["WavLMModel",Ju]],["audio-spectrogram-transformer",["ASTModel",Pa]],["vits",["VitsModel",Ni]],["pyannote",["PyAnnoteModel",Ru]],["wespeaker-resnet",["WeSpeakerResNetModel",Kc]],["detr",["DetrModel",nn]],["rt_detr",["RTDetrModel",su]],["table-transformer",["TableTransformerModel",ki]],["vit",["ViTModel",wi]],["ijepa",["IJepaModel",yi]],["pvt",["PvtModel",zl]],["vit_msn",["ViTMSNModel",Nl]],["vit_mae",["ViTMAEModel",Rl]],["groupvit",["GroupViTModel",Ul]],["fastvit",["FastViTModel",Vl]],["mobilevit",["MobileViTModel",Hl]],["mobilevitv2",["MobileViTV2Model",Xl]],["owlvit",["OwlViTModel",Jl]],["owlv2",["Owlv2Model",eu]],["beit",["BeitModel",Rc]],["deit",["DeiTModel",Si]],["hiera",["HieraModel",au]],["convnext",["ConvNextModel",Mu]],["convnextv2",["ConvNextV2Model",vu]],["dinov2",["Dinov2Model",xu]],["resnet",["ResNetModel",lu]],["swin",["SwinModel",cu]],["swin2sr",["Swin2SRModel",pu]],["donut-swin",["DonutSwinModel",Wc]],["yolos",["YolosModel",Cu]],["dpt",["DPTModel",hu]],["glpn",["GLPNModel",Di]],["hifigan",["SpeechT5HifiGan",Yc]],["efficientnet",["EfficientNetModel",Un]],["decision_transformer",["DecisionTransformerModel",vd]],["patchtst",["PatchTSTForPrediction",Pd]],["patchtsmixer",["PatchTSMixerForPrediction",Cd]],["mobilenet_v1",["MobileNetV1Model",Hi]],["mobilenet_v2",["MobileNetV2Model",fd]],["mobilenet_v3",["MobileNetV3Model",Qi]],["mobilenet_v4",["MobileNetV4Model",Yi]],["maskformer",["MaskFormerModel",Oi]],["mgp-str",["MgpstrForSceneTextRecognition",np]]]),Np=new Map([["t5",["T5Model",P]],["longt5",["LongT5Model",Me]],["mt5",["MT5Model",ct]],["bart",["BartModel",it]],["mbart",["MBartModel",$e]],["marian",["MarianModel",Iu]],["whisper",["WhisperModel",Ca]],["m2m_100",["M2M100Model",Mo]],["blenderbot",["BlenderbotModel",Bt]],["blenderbot-small",["BlenderbotSmallModel",er]]]),ap=new Map([["bloom",["BloomModel",Cl]],["jais",["JAISModel",Ha]],["gpt2",["GPT2Model",Ka]],["gptj",["GPTJModel",ei]],["gpt_bigcode",["GPTBigCodeModel",Za]],["gpt_neo",["GPTNeoModel",Xa]],["gpt_neox",["GPTNeoXModel",Ya]],["codegen",["CodeGenModel",tl]],["llama",["LlamaModel",rl]],["exaone",["ExaoneModel",nl]],["olmo",["OlmoModel",ll]],["olmo2",["Olmo2Model",ul]],["mobilellm",["MobileLLMModel",il]],["granite",["GraniteModel",pl]],["cohere",["CohereModel",hl]],["gemma",["GemmaModel",_l]],["gemma2",["Gemma2Model",gl]],["openelm",["OpenELMModel",yl]],["qwen2",["Qwen2Model",bl]],["phi",["PhiModel",Tl]],["phi3",["Phi3Model",El]],["mpt",["MptModel",Sl]],["opt",["OPTModel",Al]],["mistral",["MistralModel",id]],["starcoder2",["Starcoder2Model",Fs]],["falcon",["FalconModel",ad]],["stablelm",["StableLmModel",hd]]]),ea=new Map([["speecht5",["SpeechT5ForSpeechToText",rd]],["whisper",["WhisperForConditionalGeneration",Ws]],["moonshine",["MoonshineForConditionalGeneration",ka]]]),Sd=new Map([["speecht5",["SpeechT5ForTextToSpeech",sd]]]),$d=new Map([["vits",["VitsModel",Ni]],["musicgen",["MusicgenForConditionalGeneration",Gi]]]),Ad=new Map([["bert",["BertForSequenceClassification",je]],["modernbert",["ModernBertForSequenceClassification",dt]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",os]],["esm",["EsmForSequenceClassification",Us]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",ks]],["deberta",["DebertaForSequenceClassification",As]],["deberta-v2",["DebertaV2ForSequenceClassification",lr]],["mpnet",["MPNetForSequenceClassification",An]],["albert",["AlbertForSequenceClassification",Ln]],["distilbert",["DistilBertForSequenceClassification",Js]],["roberta",["RobertaForSequenceClassification",Fr]],["xlm",["XLMForSequenceClassification",rs]],["xlm-roberta",["XLMRobertaForSequenceClassification",No]],["bart",["BartForSequenceClassification",hr]],["mbart",["MBartForSequenceClassification",Rr]],["mobilebert",["MobileBertForSequenceClassification",_n]],["squeezebert",["SqueezeBertForSequenceClassification",Dn]]]),Id=new Map([["bert",["BertForTokenClassification",We]],["modernbert",["ModernBertForTokenClassification",gt]],["roformer",["RoFormerForTokenClassification",st]],["electra",["ElectraForTokenClassification",Xs]],["esm",["EsmForTokenClassification",Ts]],["convbert",["ConvBertForTokenClassification",nr]],["camembert",["CamembertForTokenClassification",Bs]],["deberta",["DebertaForTokenClassification",Ys]],["deberta-v2",["DebertaV2ForTokenClassification",bs]],["mpnet",["MPNetForTokenClassification",In]],["distilbert",["DistilBertForTokenClassification",Ns]],["roberta",["RobertaForTokenClassification",qr]],["xlm",["XLMForTokenClassification",tn]],["xlm-roberta",["XLMRobertaForTokenClassification",xa]]]),ta=new Map([["t5",["T5ForConditionalGeneration",H]],["longt5",["LongT5ForConditionalGeneration",Ce]],["mt5",["MT5ForConditionalGeneration",yt]],["bart",["BartForConditionalGeneration",Pt]],["mbart",["MBartForConditionalGeneration",wr]],["marian",["MarianMTModel",Ou]],["m2m_100",["M2M100ForConditionalGeneration",Rn]],["blenderbot",["BlenderbotForConditionalGeneration",Nr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",mr]]]),ra=new Map([["bloom",["BloomForCausalLM",kl]],["gpt2",["GPT2LMHeadModel",_s]],["jais",["JAISLMHeadModel",qa]],["gptj",["GPTJForCausalLM",ti]],["gpt_bigcode",["GPTBigCodeForCausalLM",si]],["gpt_neo",["GPTNeoForCausalLM",Qa]],["gpt_neox",["GPTNeoXForCausalLM",Ja]],["codegen",["CodeGenForCausalLM",so]],["llama",["LlamaForCausalLM",sl]],["exaone",["ExaoneForCausalLM",ol]],["olmo",["OlmoForCausalLM",zc]],["olmo2",["Olmo2ForCausalLM",dl]],["mobilellm",["MobileLLMForCausalLM",al]],["granite",["GraniteForCausalLM",ur]],["cohere",["CohereForCausalLM",ml]],["gemma",["GemmaForCausalLM",fl]],["gemma2",["Gemma2ForCausalLM",wl]],["openelm",["OpenELMForCausalLM",Ml]],["qwen2",["Qwen2ForCausalLM",zn]],["phi",["PhiForCausalLM",xl]],["phi3",["Phi3ForCausalLM",Pl]],["mpt",["MptForCausalLM",$l]],["opt",["OPTForCausalLM",Il]],["mbart",["MBartForCausalLM",Jr]],["mistral",["MistralForCausalLM",Jc]],["starcoder2",["Starcoder2ForCausalLM",on]],["falcon",["FalconForCausalLM",ld]],["trocr",["TrOCRForCausalLM",od]],["stablelm",["StableLmForCausalLM",Ui]],["phi3_v",["Phi3VForCausalLM",Ko]]]),lp=new Map([["multi_modality",["MultiModalityCausalLM",Td]]]),up=new Map([["bert",["BertForMaskedLM",Re]],["modernbert",["ModernBertForMaskedLM",ft]],["roformer",["RoFormerForMaskedLM",Fe]],["electra",["ElectraForMaskedLM",Qr]],["esm",["EsmForMaskedLM",Jn]],["convbert",["ConvBertForMaskedLM",Ft]],["camembert",["CamembertForMaskedLM",Qs]],["deberta",["DebertaForMaskedLM",cs]],["deberta-v2",["DebertaV2ForMaskedLM",Ot]],["mpnet",["MPNetForMaskedLM",fn]],["albert",["AlbertForMaskedLM",Mn]],["distilbert",["DistilBertForMaskedLM",Sn]],["roberta",["RobertaForMaskedLM",Es]],["xlm",["XLMWithLMHeadModel",wt]],["xlm-roberta",["XLMRobertaForMaskedLM",Ta]],["mobilebert",["MobileBertForMaskedLM",Zs]],["squeezebert",["SqueezeBertForMaskedLM",gn]]]),Vn=new Map([["bert",["BertForQuestionAnswering",Ne]],["roformer",["RoFormerForQuestionAnswering",pt]],["electra",["ElectraForQuestionAnswering",zs]],["convbert",["ConvBertForQuestionAnswering",gr]],["camembert",["CamembertForQuestionAnswering",Ss]],["deberta",["DebertaForQuestionAnswering",as]],["deberta-v2",["DebertaV2ForQuestionAnswering",tr]],["mpnet",["MPNetForQuestionAnswering",On]],["albert",["AlbertForQuestionAnswering",yn]],["distilbert",["DistilBertForQuestionAnswering",vs]],["roberta",["RobertaForQuestionAnswering",Mt]],["xlm",["XLMForQuestionAnswering",Zn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ea]],["mobilebert",["MobileBertForQuestionAnswering",en]],["squeezebert",["SqueezeBertForQuestionAnswering",ir]]]),Co=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Wo]],["idefics3",["Idefics3ForConditionalGeneration",Go]]]),Od=new Map([["llava",["LlavaForConditionalGeneration",eo]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",$a]],["moondream1",["Moondream1ForConditionalGeneration",Aa]],["florence2",["Florence2ForConditionalGeneration",Oa]],["qwen2-vl",["Qwen2VLForConditionalGeneration",oo]],["idefics3",["Idefics3ForConditionalGeneration",Go]],["paligemma",["PaliGemmaForConditionalGeneration",Fa]]]),Fd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Wo]]]),sa=new Map([["vit",["ViTForImageClassification",Ol]],["ijepa",["IJepaForImageClassification",Fl]],["pvt",["PvtForImageClassification",Bl]],["vit_msn",["ViTMSNForImageClassification",Bc]],["fastvit",["FastViTForImageClassification",Wl]],["mobilevit",["MobileViTForImageClassification",ql]],["mobilevitv2",["MobileViTV2ForImageClassification",Ql]],["beit",["BeitForImageClassification",sn]],["deit",["DeiTForImageClassification",iu]],["hiera",["HieraForImageClassification",po]],["convnext",["ConvNextForImageClassification",bu]],["convnextv2",["ConvNextV2ForImageClassification",Tu]],["dinov2",["Dinov2ForImageClassification",Eu]],["resnet",["ResNetForImageClassification",uu]],["swin",["SwinForImageClassification",$i]],["segformer",["SegformerForImageClassification",ep]],["efficientnet",["EfficientNetForImageClassification",md]],["mobilenet_v1",["MobileNetV1ForImageClassification",_d]],["mobilenet_v2",["MobileNetV2ForImageClassification",gd]],["mobilenet_v3",["MobileNetV3ForImageClassification",wd]],["mobilenet_v4",["MobileNetV4ForImageClassification",Md]]]),Dd=new Map([["detr",["DetrForObjectDetection",Ci]],["rt_detr",["RTDetrForObjectDetection",Nc]],["table-transformer",["TableTransformerForObjectDetection",nu]],["yolos",["YolosForObjectDetection",ku]]]),Ld=new Map([["owlvit",["OwlViTForObjectDetection",Zl]],["owlv2",["Owlv2ForObjectDetection",tu]]]),na=new Map([["detr",["DetrForSegmentation",Gs]],["clipseg",["CLIPSegForImageSegmentation",Ga]]]),oa=new Map([["segformer",["SegformerForSemanticSegmentation",es]],["sapiens",["SapiensForSemanticSegmentation",Uc]]]),zd=new Map([["detr",["DetrForSegmentation",Gs]],["maskformer",["MaskFormerForInstanceSegmentation",wu]]]),Bd=new Map([["sam",["SamModel",$u]]]),ia=new Map([["wav2vec2",["Wav2Vec2ForCTC",Lu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Hu]],["unispeech",["UniSpeechForCTC",Uu]],["unispeech-sat",["UniSpeechSatForCTC",Wu]],["wavlm",["WavLMForCTC",Zu]],["hubert",["HubertForCTC",Qu]]]),Rd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",zu]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",qu]],["unispeech",["UniSpeechForSequenceClassification",Vu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Gu]],["wavlm",["WavLMForSequenceClassification",ed]],["hubert",["HubertForSequenceClassification",Yu]],["audio-spectrogram-transformer",["ASTForAudioClassification",ss]]]),Nd=new Map([["wavlm",["WavLMForXVector",td]]]),aa=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",qc]],["wavlm",["WavLMForAudioFrameClassification",Xc]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Bu]],["pyannote",["PyAnnoteForAudioFrameClassification",Nu]]]),jd=new Map([["vitmatte",["VitMatteForImageMatting",Kl]]]),dp=new Map([["patchtst",["PatchTSTForPrediction",op]],["patchtsmixer",["PatchTSMixerForPrediction",kd]]]),Ud=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ai]]]),Vd=new Map([["dpt",["DPTForDepthEstimation",mu]],["depth_anything",["DepthAnythingForDepthEstimation",_u]],["glpn",["GLPNForDepthEstimation",Vc]],["sapiens",["SapiensForDepthEstimation",fu]],["depth_pro",["DepthProForDepthEstimation",fo]]]),cp=new Map([["sapiens",["SapiensForNormalEstimation",_o]]]),Wd=new Map([["vitpose",["VitPoseForPoseEstimation",Ll]]]),Gd=new Map([["clip",["CLIPVisionModelWithProjection",Lc]],["siglip",["SiglipVisionModel",Ho]],["jina_clip",["JinaCLIPVisionModel",Va]]]),Kd=[[ip,D.EncoderOnly],[Np,D.EncoderDecoder],[ap,D.DecoderOnly],[Ad,D.EncoderOnly],[Id,D.EncoderOnly],[ta,D.Seq2Seq],[ea,D.Seq2Seq],[ra,D.DecoderOnly],[lp,D.MultiModality],[up,D.EncoderOnly],[Vn,D.EncoderOnly],[Co,D.Vision2Seq],[Od,D.ImageTextToText],[sa,D.EncoderOnly],[na,D.EncoderOnly],[zd,D.EncoderOnly],[oa,D.EncoderOnly],[jd,D.EncoderOnly],[dp,D.EncoderOnly],[Ud,D.EncoderOnly],[Vd,D.EncoderOnly],[cp,D.EncoderOnly],[Wd,D.EncoderOnly],[Dd,D.EncoderOnly],[Ld,D.EncoderOnly],[Bd,D.MaskGeneration],[ia,D.EncoderOnly],[Rd,D.EncoderOnly],[Sd,D.Seq2Seq],[$d,D.EncoderOnly],[Nd,D.EncoderOnly],[aa,D.EncoderOnly],[Gd,D.EncoderOnly]];for(const[_,x]of Kd)for(const[V,be]of _.values())$.set(V,x),C.set(be,V),g.set(V,be);const pp=[["MusicgenForConditionalGeneration",Gi,D.Musicgen],["Phi3VForCausalLM",Ko,D.Phi3V],["CLIPTextModelWithProjection",Ba,D.EncoderOnly],["SiglipTextModel",to,D.EncoderOnly],["JinaCLIPTextModel",Ua,D.EncoderOnly],["ClapTextModelWithProjection",dd,D.EncoderOnly],["ClapAudioModelWithProjection",cd,D.EncoderOnly]];for(const[_,x,V]of pp)$.set(_,V),C.set(x,_),g.set(_,x);class Hd extends _r{}ge(Hd,"MODEL_CLASS_MAPPINGS",Kd.map(x=>x[0])),ge(Hd,"BASE_IF_FAIL",!0);class qd extends _r{}ge(qd,"MODEL_CLASS_MAPPINGS",[Ad]);class Xd extends _r{}ge(Xd,"MODEL_CLASS_MAPPINGS",[Id]);class Qd extends _r{}ge(Qd,"MODEL_CLASS_MAPPINGS",[ta]);class hp extends _r{}ge(hp,"MODEL_CLASS_MAPPINGS",[ea]);class Yd extends _r{}ge(Yd,"MODEL_CLASS_MAPPINGS",[Sd]);class Jd extends _r{}ge(Jd,"MODEL_CLASS_MAPPINGS",[$d]);class Zd extends _r{}ge(Zd,"MODEL_CLASS_MAPPINGS",[ra]);class ec extends _r{}ge(ec,"MODEL_CLASS_MAPPINGS",[up]);class mp extends _r{}ge(mp,"MODEL_CLASS_MAPPINGS",[Vn]);class tc extends _r{}ge(tc,"MODEL_CLASS_MAPPINGS",[Co]);class rc extends _r{}ge(rc,"MODEL_CLASS_MAPPINGS",[sa]);class sc extends _r{}ge(sc,"MODEL_CLASS_MAPPINGS",[na]);class nc extends _r{}ge(nc,"MODEL_CLASS_MAPPINGS",[oa]);class oc extends _r{}ge(oc,"MODEL_CLASS_MAPPINGS",[zd]);class ic extends _r{}ge(ic,"MODEL_CLASS_MAPPINGS",[Dd]);class ac extends _r{}ge(ac,"MODEL_CLASS_MAPPINGS",[Ld]);class lc extends _r{}ge(lc,"MODEL_CLASS_MAPPINGS",[Bd]);class uc extends _r{}ge(uc,"MODEL_CLASS_MAPPINGS",[ia]);class dc extends _r{}ge(dc,"MODEL_CLASS_MAPPINGS",[Rd]);class cc extends _r{}ge(cc,"MODEL_CLASS_MAPPINGS",[Nd]);class la extends _r{}ge(la,"MODEL_CLASS_MAPPINGS",[aa]);class pc extends _r{}ge(pc,"MODEL_CLASS_MAPPINGS",[Fd]);class hc extends _r{}ge(hc,"MODEL_CLASS_MAPPINGS",[jd]);class mc extends _r{}ge(mc,"MODEL_CLASS_MAPPINGS",[Ud]);class _c extends _r{}ge(_c,"MODEL_CLASS_MAPPINGS",[Vd]);class fc extends _r{}ge(fc,"MODEL_CLASS_MAPPINGS",[cp]);class gc extends _r{}ge(gc,"MODEL_CLASS_MAPPINGS",[Wd]);class wc extends _r{}ge(wc,"MODEL_CLASS_MAPPINGS",[Gd]);class jp extends Je{constructor({logits:x,past_key_values:V,encoder_outputs:be,decoder_attentions:Oe=null,cross_attentions:Se=null}){super(),this.logits=x,this.past_key_values=V,this.encoder_outputs=be,this.decoder_attentions=Oe,this.cross_attentions=Se}}class Xt extends Je{constructor({logits:x}){super(),this.logits=x}}class yc extends Je{constructor({logits:x,embeddings:V}){super(),this.logits=x,this.embeddings=V}}class jr extends Je{constructor({logits:x}){super(),this.logits=x}}class Wr extends Je{constructor({logits:x}){super(),this.logits=x}}class Xr extends Je{constructor({start_logits:x,end_logits:V}){super(),this.start_logits=x,this.end_logits=V}}class an extends Je{constructor({logits:x}){super(),this.logits=x}}class _p extends Je{constructor({logits:x,past_key_values:V}){super(),this.logits=x,this.past_key_values=V}}class fp extends Je{constructor({alphas:x}){super(),this.alphas=x}}class Mc extends Je{constructor({waveform:x,spectrogram:V}){super(),this.waveform=x,this.spectrogram=V}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Te,A,s)=>{s.r(A),s.d(A,{ASTFeatureExtractor:()=>N});var f=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var O=s("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U);const w=this.config.sampling_rate,v=(0,O.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;y{s.r(A),s.d(A,{AutoFeatureExtractor:()=>Q});var f=s("./src/utils/constants.js"),O=s("./src/utils/hub.js");s("./src/base/feature_extraction_utils.js");var N=s("./src/models/feature_extractors.js");class Q{static async from_pretrained(w,v={}){const y=await(0,O.getModelJSON)(w,f.FEATURE_EXTRACTOR_NAME,!0,v),M=y.feature_extractor_type,b=N[M];if(!b)throw new Error(`Unknown feature_extractor_type: '${M}'. Please report this at ${f.GITHUB_ISSUE_URL}.`);return new b(y)}}},"./src/models/auto/image_processing_auto.js":(Te,A,s)=>{s.r(A),s.d(A,{AutoImageProcessor:()=>U});var f=s("./src/utils/constants.js"),O=s("./src/utils/hub.js"),N=s("./src/base/image_processors_utils.js"),Q=s("./src/models/image_processors.js");class U{static async from_pretrained(v,y={}){const M=await(0,O.getModelJSON)(v,f.IMAGE_PROCESSOR_NAME,!0,y),b=M.image_processor_type??M.feature_extractor_type;let L=Q[b];return L||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${f.GITHUB_ISSUE_URL}.`),L=N.ImageProcessor),new L(M)}}},"./src/models/auto/processing_auto.js":(Te,A,s)=>{s.r(A),s.d(A,{AutoProcessor:()=>v});var f=s("./src/utils/constants.js"),O=s("./src/utils/hub.js"),N=s("./src/base/processing_utils.js"),Q=s("./src/models/processors.js"),U=s("./src/models/image_processors.js"),w=s("./src/models/feature_extractors.js");class v{static async from_pretrained(M,b={}){const L=await(0,O.getModelJSON)(M,f.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:q,feature_extractor_type:se,processor_class:ie}=L;if(ie&&Q[ie])return Q[ie].from_pretrained(M,b);if(!q&&!se)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const z={};if(q){const Y=U[q];if(!Y)throw new Error(`Unknown image_processor_type: '${q}'.`);z.image_processor=new Y(L)}if(se){const Y=U[se];if(Y)z.image_processor=new Y(L);else{const D=w[se];if(!D)throw new Error(`Unknown feature_extractor_type: '${se}'.`);z.feature_extractor=new D(L)}}const W={};return new N.Processor(W,z)}}},"./src/models/beit/image_processing_beit.js":(Te,A,s)=>{s.r(A),s.d(A,{BeitFeatureExtractor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Te,A,s)=>{s.r(A),s.d(A,{BitImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Te,A,s)=>{s.r(A),s.d(A,{ChineseCLIPFeatureExtractor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Te,A,s)=>{s.r(A),s.d(A,{ClapFeatureExtractor:()=>N});var f=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var O=s("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U),this.mel_filters=(0,O.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,O.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,O.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(U,w,v,y){let M;const b=U.length-w;if(b>0)if(v==="rand_trunc"){const L=Math.floor(Math.random()*(b+1));U=U.subarray(L,L+w),M=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let L=new Float64Array(w);if(L.set(U),y==="repeat")for(let q=U.length;q{s.r(A),s.d(A,{CLIPFeatureExtractor:()=>N,CLIPImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/convnext/image_processing_convnext.js":(Te,A,s)=>{s.r(A),s.d(A,{ConvNextFeatureExtractor:()=>N,ConvNextImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var v;const w=(v=this.size)==null?void 0:v.shortest_edge;if(w===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(w<384){const y=Math.floor(w/this.crop_pct),[M,b]=this.get_resize_output_image_size(U,{shortest_edge:y});U=await U.resize(M,b,{resample:this.resample}),U=await U.center_crop(w,w)}else U=await U.resize(w,w,{resample:this.resample});return U}}class N extends O{}},"./src/models/deit/image_processing_deit.js":(Te,A,s)=>{s.r(A),s.d(A,{DeiTFeatureExtractor:()=>N,DeiTImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/detr/image_processing_detr.js":(Te,A,s)=>{s.r(A),s.d(A,{DetrFeatureExtractor:()=>Q,DetrImageProcessor:()=>N});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(w){const v=await super._call(w),y=[v.pixel_values.dims[0],64,64],M=(0,O.full)(y,1n);return{...v,pixel_mask:M}}post_process_object_detection(...w){return(0,f.post_process_object_detection)(...w)}post_process_panoptic_segmentation(...w){return(0,f.post_process_panoptic_segmentation)(...w)}post_process_instance_segmentation(...w){return(0,f.post_process_instance_segmentation)(...w)}}class Q extends N{}},"./src/models/donut/image_processing_donut.js":(Te,A,s)=>{s.r(A),s.d(A,{DonutFeatureExtractor:()=>N,DonutImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{pad_image(U,w,v,y={}){const[M,b,L]=w;let q=this.image_mean;Array.isArray(this.image_mean)||(q=new Array(L).fill(q));let se=this.image_std;Array.isArray(se)||(se=new Array(L).fill(q));const ie=q.map((z,W)=>-z/se[W]);return super.pad_image(U,w,v,{center:!0,constant_values:ie,...y})}}class N extends O{}},"./src/models/dpt/image_processing_dpt.js":(Te,A,s)=>{s.r(A),s.d(A,{DPTFeatureExtractor:()=>N,DPTImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Te,A,s)=>{s.r(A),s.d(A,{EfficientNetImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{constructor(Q){super(Q),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(U=>U*U))}}},"./src/models/feature_extractors.js":(Te,A,s)=>{s.r(A),s.d(A,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ClapFeatureExtractor:()=>O.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>N.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Q.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>U.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>w.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var f=s("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),O=s("./src/models/clap/feature_extraction_clap.js"),N=s("./src/models/moonshine/feature_extraction_moonshine.js"),Q=s("./src/models/pyannote/feature_extraction_pyannote.js"),U=s("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),w=s("./src/models/speecht5/feature_extraction_speecht5.js"),v=s("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=s("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=s("./src/models/whisper/feature_extraction_whisper.js"),b=s("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Te,A,s)=>{s.r(A),s.d(A,{Florence2Processor:()=>Q});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");class Q extends f.Processor{constructor(w,v){super(w,v);const{tasks_answer_post_processing_type:y,task_prompts_without_inputs:M,task_prompts_with_input:b}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(y??{})),this.task_prompts_without_inputs=new Map(Object.entries(M??{})),this.task_prompts_with_input=new Map(Object.entries(b??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(w){typeof w=="string"&&(w=[w]);const v=[];for(const y of w)if(this.task_prompts_without_inputs.has(y))v.push(this.task_prompts_without_inputs.get(y));else{for(const[M,b]of this.task_prompts_with_input)if(y.includes(M)){v.push(b.replaceAll("{input}",y).replaceAll(M,""));break}v.length!==w.length&&v.push(y)}return v}post_process_generation(w,v,y){const M=this.tasks_answer_post_processing_type.get(v)??"pure_text";w=w.replaceAll("","").replaceAll("","");let b;switch(M){case"pure_text":b=w;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const L=M==="ocr"?"quad_boxes":"bboxes",q=w.matchAll(this.regexes[L]),se=[],ie=[];for(const[z,W,...Y]of q)se.push(W?W.trim():se.at(-1)??""),ie.push(Y.map((D,$)=>(Number(D)+.5)/this.size_per_bin*y[$%2]));b={labels:se,[L]:ie};break;default:throw new Error(`Task "${v}" (of type "${M}") not yet implemented.`)}return{[v]:b}}async _call(w,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=await this.image_processor(w,y),b=v?this.tokenizer(v,y):{};return{...M,...b}}}ge(Q,"tokenizer_class",N.AutoTokenizer),ge(Q,"image_processor_class",O.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Te,A,s)=>{s.r(A),s.d(A,{GLPNFeatureExtractor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(Te,A,s)=>{s.r(A),s.d(A,{Idefics3ImageProcessor:()=>N});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/tensor.js");class N extends f.ImageProcessor{constructor(U){super(U),this.do_image_splitting=U.do_image_splitting??!0,this.max_image_size=U.max_image_size}get_resize_for_vision_encoder(U,w){let[v,y]=U.dims.slice(-2);const M=y/v;return y>=v?(y=Math.ceil(y/w)*w,v=Math.floor(y/M),v=Math.ceil(v/w)*w):(v=Math.ceil(v/w)*w,y=Math.floor(v*M),y=Math.ceil(y/w)*w),{height:v,width:y}}async _call(U,{do_image_splitting:w=null,return_row_col_info:v=!1}={}){let y;if(!Array.isArray(U))y=[[U]];else{if(U.length===0||!U[0])throw new Error("No images provided.");Array.isArray(U[0])?y=U:y=[U]}let M=[],b=[],L=[];const q=[],se=[];for(const C of y){let T=await Promise.all(C.map(le=>this.preprocess(le)));q.push(...T.map(le=>le.original_size)),se.push(...T.map(le=>le.reshaped_input_size)),T.forEach(le=>le.pixel_values.unsqueeze_(0));const{longest_edge:ee}=this.max_image_size;let J;if(w??this.do_image_splitting){let le=new Array(T.length),de=new Array(T.length);J=await Promise.all(T.map(async(fe,ke)=>{const xe=this.get_resize_for_vision_encoder(fe.pixel_values,ee),Le=await(0,O.interpolate_4d)(fe.pixel_values,{size:[xe.height,xe.width]}),{frames:qe,num_splits_h:Ue,num_splits_w:ut}=await this.split_image(Le,this.max_image_size);return le[ke]=Ue,de[ke]=ut,(0,O.cat)(qe,0)})),b.push(le),L.push(de)}else{const le=[ee,ee];J=await Promise.all(T.map(de=>(0,O.interpolate_4d)(de.pixel_values,{size:le}))),b.push(new Array(T.length).fill(0)),L.push(new Array(T.length).fill(0))}M.push((0,O.cat)(J,0))}const ie=M.length,[z,W,Y,D]=M[0].dims;let $,g;if(ie===1)$=M[0].unsqueeze_(0),g=(0,O.full)([ie,z,Y,D],!0);else{const C=Math.max(...M.map(J=>J.dims.at(0)));g=(0,O.full)([ie,C,Y,D],!0);const T=g.data,ee=C*Y*D;for(let J=0;Jv||L>y){q=Math.ceil(b/v),se=Math.ceil(L/y);const ie=Math.ceil(b/q),z=Math.ceil(L/se);for(let D=0;D{s.r(A),s.d(A,{Idefics3Processor:()=>y});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");s("./src/utils/image.js");var Q=s("./src/utils/core.js");function U(M,b,L,q,se,ie){let z="";for(let W=0;W`+se.repeat(M);z+=` +`}return z+=` +${q}${ie}`+se.repeat(M)+`${q}`,z}function w(M,b,L,q){return`${b}${q}`+L.repeat(M)+`${b}`}function v(M,b,L,q,se,ie){return M===0&&b===0?w(L,q,se,ie):U(L,M,b,q,se,ie)}class y extends f.Processor{constructor(){super(...arguments);ge(this,"fake_image_token","");ge(this,"image_token","");ge(this,"global_img_token","")}async _call(L,q=null,se={}){se.return_row_col_info??(se.return_row_col_info=!0);let ie;q&&(ie=await this.image_processor(q,se)),Array.isArray(L)||(L=[L]);const z=ie.rows??[new Array(L.length).fill(0)],W=ie.cols??[new Array(L.length).fill(0)],Y=this.config.image_seq_len,D=[],$=[];for(let C=0;Cv(ke,J[xe],Y,this.fake_image_token,this.image_token,this.global_img_token)),de=T.split(this.image_token);if(de.length===0)throw new Error("The image token should be present in the text.");let fe=de[0];for(let ke=0;ke{s.r(A),s.d(A,{BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BitImageProcessor:()=>O.BitImageProcessor,CLIPFeatureExtractor:()=>Q.CLIPFeatureExtractor,CLIPImageProcessor:()=>Q.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>N.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>U.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>U.ConvNextImageProcessor,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTImageProcessor:()=>M.DPTImageProcessor,DeiTFeatureExtractor:()=>w.DeiTFeatureExtractor,DeiTImageProcessor:()=>w.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,EfficientNetImageProcessor:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>L.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>q.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>ie.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>W.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Y.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Y.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>$.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>$.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>g.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>g.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>T.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>T.MobileViTImageProcessor,NougatImageProcessor:()=>ee.NougatImageProcessor,OwlViTFeatureExtractor:()=>le.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>le.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,Phi3VImageProcessor:()=>de.Phi3VImageProcessor,PvtImageProcessor:()=>fe.PvtImageProcessor,Qwen2VLImageProcessor:()=>ke.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>xe.RTDetrImageProcessor,SamImageProcessor:()=>Le.SamImageProcessor,SegformerFeatureExtractor:()=>qe.SegformerFeatureExtractor,SegformerImageProcessor:()=>qe.SegformerImageProcessor,SiglipImageProcessor:()=>Ue.SiglipImageProcessor,Swin2SRImageProcessor:()=>ut.Swin2SRImageProcessor,VLMImageProcessor:()=>se.VLMImageProcessor,ViTFeatureExtractor:()=>ue.ViTFeatureExtractor,ViTImageProcessor:()=>ue.ViTImageProcessor,VitMatteImageProcessor:()=>re.VitMatteImageProcessor,VitPoseImageProcessor:()=>he.VitPoseImageProcessor,YolosFeatureExtractor:()=>Pe.YolosFeatureExtractor,YolosImageProcessor:()=>Pe.YolosImageProcessor});var f=s("./src/models/beit/image_processing_beit.js"),O=s("./src/models/bit/image_processing_bit.js"),N=s("./src/models/chinese_clip/image_processing_chinese_clip.js"),Q=s("./src/models/clip/image_processing_clip.js"),U=s("./src/models/convnext/image_processing_convnext.js"),w=s("./src/models/deit/image_processing_deit.js"),v=s("./src/models/detr/image_processing_detr.js"),y=s("./src/models/donut/image_processing_donut.js"),M=s("./src/models/dpt/image_processing_dpt.js"),b=s("./src/models/efficientnet/image_processing_efficientnet.js"),L=s("./src/models/glpn/image_processing_glpn.js"),q=s("./src/models/idefics3/image_processing_idefics3.js"),se=s("./src/models/janus/image_processing_janus.js"),ie=s("./src/models/jina_clip/image_processing_jina_clip.js"),z=s("./src/models/llava_onevision/image_processing_llava_onevision.js"),W=s("./src/models/mask2former/image_processing_mask2former.js"),Y=s("./src/models/maskformer/image_processing_maskformer.js"),D=s("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),$=s("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),g=s("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=s("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),T=s("./src/models/mobilevit/image_processing_mobilevit.js"),ee=s("./src/models/nougat/image_processing_nougat.js"),J=s("./src/models/owlv2/image_processing_owlv2.js"),le=s("./src/models/owlvit/image_processing_owlvit.js"),de=s("./src/models/phi3_v/image_processing_phi3_v.js"),fe=s("./src/models/pvt/image_processing_pvt.js"),ke=s("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),xe=s("./src/models/rt_detr/image_processing_rt_detr.js"),Le=s("./src/models/sam/image_processing_sam.js"),qe=s("./src/models/segformer/image_processing_segformer.js"),Ue=s("./src/models/siglip/image_processing_siglip.js"),ut=s("./src/models/swin2sr/image_processing_swin2sr.js"),ue=s("./src/models/vit/image_processing_vit.js"),re=s("./src/models/vitmatte/image_processing_vitmatte.js"),he=s("./src/models/vitpose/image_processing_vitpose.js"),Pe=s("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Te,A,s)=>{s.r(A),s.d(A,{VLMImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{constructor(Q){super({do_pad:!0,pad_size:{width:Q.image_size,height:Q.image_size},...Q}),this.constant_values=this.config.background_color.map(U=>U*this.rescale_factor)}pad_image(Q,U,w,v){return super.pad_image(Q,U,w,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(Te,A,s)=>{s.r(A),s.d(A,{VLChatProcessor:()=>v});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js"),Q=s("./src/utils/core.js"),U=s("./src/utils/tensor.js"),w=s("./src/utils/image.js");class v extends f.Processor{constructor(M,b){super(M,b),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(M,{images:b=null,chat_template:L="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(M.filter(J=>J.images).flatMap(J=>J.images).map(J=>w.RawImage.read(J)));const q=this.tokenizer,se=q.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:L}),ie=J=>q.encode(J,{add_special_tokens:!1}),z=se.split(this.image_tag),W=z.length-1;if(b.length!==W)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${W})`);const[Y,D,$]=q.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let g=ie(z[0]),C=new Array(g.length).fill(!1);for(let J=1;J0){const J=await this.image_processor(b);return J.pixel_values.unsqueeze_(0),{...ee,...J}}return ee}}ge(v,"image_processor_class",O.AutoImageProcessor),ge(v,"tokenizer_class",N.AutoTokenizer),ge(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Te,A,s)=>{s.r(A),s.d(A,{JinaCLIPImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{constructor(Q){const{resize_mode:U,fill_color:w,interpolation:v,size:y,...M}=Q,b=U==="squash"?{width:y,height:y}:U==="shortest"?{shortest_edge:y}:{longest_edge:y},L=v==="bicubic"?3:2;super({...M,size:b,resample:L,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Te,A,s)=>{s.r(A),s.d(A,{JinaCLIPProcessor:()=>Q});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");class Q extends f.Processor{async _call(w=null,v=null,y={}){if(!w&&!v)throw new Error("Either text or images must be provided");const M=w?this.tokenizer(w,y):{},b=v?await this.image_processor(v,y):{};return{...M,...b}}}ge(Q,"tokenizer_class",N.AutoTokenizer),ge(Q,"image_processor_class",O.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Te,A,s)=>{s.r(A),s.d(A,{LlavaOnevisionImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Te,A,s)=>{s.r(A),s.d(A,{Mask2FormerImageProcessor:()=>O});var f=s("./src/models/maskformer/image_processing_maskformer.js");class O extends f.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Te,A,s)=>{s.r(A),s.d(A,{MaskFormerFeatureExtractor:()=>N,MaskFormerImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_panoptic_segmentation(...U){return(0,f.post_process_panoptic_segmentation)(...U)}post_process_instance_segmentation(...U){return(0,f.post_process_instance_segmentation)(...U)}}class N extends O{}},"./src/models/mgp_str/processing_mgp_str.js":(Te,A,s)=>{s.r(A),s.d(A,{MgpstrProcessor:()=>w});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js"),Q=s("./src/utils/maths.js");const U={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class w extends f.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(y,M){if(!U.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[b,L]=U[M],q=this[b].bind(this),[se,ie]=y.dims,z=[],W=[],Y=y.tolist();for(let $=0;$0?T.reduce((J,le)=>J*le,1):0;W.push(C),z.push(ee)}return[q(W),z]}char_decode(y){return this.char_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}bpe_decode(y){return this.bpe_tokenizer.batch_decode(y)}wp_decode(y){return this.wp_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}batch_decode([y,M,b]){const[L,q]=this._decode_helper(y,"char"),[se,ie]=this._decode_helper(M,"bpe"),[z,W]=this._decode_helper(b,"wp"),Y=[],D=[];for(let $=0;${s.r(A),s.d(A,{MobileNetV1FeatureExtractor:()=>N,MobileNetV1ImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Te,A,s)=>{s.r(A),s.d(A,{MobileNetV2FeatureExtractor:()=>N,MobileNetV2ImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Te,A,s)=>{s.r(A),s.d(A,{MobileNetV3FeatureExtractor:()=>N,MobileNetV3ImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Te,A,s)=>{s.r(A),s.d(A,{MobileNetV4FeatureExtractor:()=>N,MobileNetV4ImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Te,A,s)=>{s.r(A),s.d(A,{MobileViTFeatureExtractor:()=>N,MobileViTImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/moonshine/feature_extraction_moonshine.js":(Te,A,s)=>{s.r(A),s.d(A,{MoonshineFeatureExtractor:()=>N});var f=s("./src/base/feature_extraction_utils.js"),O=s("./src/utils/tensor.js");class N extends f.FeatureExtractor{async _call(U){(0,f.validate_audio_inputs)(U,"MoonshineFeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));const w=[1,U.length];return{input_values:new O.Tensor("float32",U,w)}}}},"./src/models/moonshine/processing_moonshine.js":(Te,A,s)=>{s.r(A),s.d(A,{MoonshineProcessor:()=>Q});var f=s("./src/models/auto/feature_extraction_auto.js"),O=s("./src/tokenizers.js"),N=s("./src/base/processing_utils.js");class Q extends N.Processor{async _call(w){return await this.feature_extractor(w)}}ge(Q,"tokenizer_class",O.AutoTokenizer),ge(Q,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(Te,A,s)=>{s.r(A),s.d(A,{NougatImageProcessor:()=>O});var f=s("./src/models/donut/image_processing_donut.js");class O extends f.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Te,A,s)=>{s.r(A),s.d(A,{Owlv2ImageProcessor:()=>O});var f=s("./src/models/owlvit/image_processing_owlvit.js");class O extends f.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Te,A,s)=>{s.r(A),s.d(A,{OwlViTFeatureExtractor:()=>N,OwlViTImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_object_detection(...U){return(0,f.post_process_object_detection)(...U)}}class N extends O{}},"./src/models/owlvit/processing_owlvit.js":(Te,A,s)=>{s.r(A),s.d(A,{OwlViTProcessor:()=>Q});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");class Q extends f.Processor{}ge(Q,"tokenizer_class",N.AutoTokenizer),ge(Q,"image_processor_class",O.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(Te,A,s)=>{s.r(A),s.d(A,{PaliGemmaProcessor:()=>w});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");const Q="";function U(v,y,M,b,L){return`${b.repeat(M*L)}${y}${v} +`}class w extends f.Processor{async _call(y,M=null,b={}){M||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),M=""),Array.isArray(y)||(y=[y]),Array.isArray(M)||(M=[M]);const L=this.tokenizer.bos_token,q=this.image_processor.config.image_seq_length;let se;M.some(W=>W.includes(Q))?se=M.map(W=>{const Y=W.replaceAll(Q,Q.repeat(q)),D=Y.lastIndexOf(Q),$=D===-1?0:D+Q.length;return Y.slice(0,$)+L+Y.slice($)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),se=M.map(W=>U(W,L,q,Q,y.length)));const ie=this.tokenizer(se,b);return{...await this.image_processor(y,b),...ie}}}ge(w,"tokenizer_class",N.AutoTokenizer),ge(w,"image_processor_class",O.AutoImageProcessor),ge(w,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(Te,A,s)=>{s.r(A),s.d(A,{Phi3VImageProcessor:()=>y});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/tensor.js");const N=336,Q=[2,3],{ceil:U,floor:w,sqrt:v}=Math;class y extends f.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,L){const{num_img_tokens:q}=this.config;return w((w(L/N)*w(b/N)+1)*q+1+(w(L/N)+1)*v(q))}get_resize_output_image_size(b,L){const q=this._num_crops,[se,ie]=b.size;let z=se/ie,W=1;for(;W*Math.ceil(W/z)<=q;)W+=1;W-=1;const Y=Math.floor(W*336),D=Math.floor(Y/z);return[Y,D]}pad_image(b,L,q,se={}){const[ie,z]=L,W=N*U(ie/N),Y=N*U(z/N),D=[1,1,1].map(($,g)=>($-this.image_mean[g])/this.image_std[g]);return super.pad_image(b,L,{width:Y,height:W},{center:!0,constant_values:D,...se})}async _call(b,{num_crops:L=null}={}){if(this._num_crops=L??(L=this.config.num_crops),L<4||v(L)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const q=b.length,se=await Promise.all(b.map(C=>this.preprocess(C))),ie=se.map(C=>C.original_size),z=se.map(C=>C.reshaped_input_size),W=[];for(const{pixel_values:C}of se){C.unsqueeze_(0);const[T,ee]=C.dims.slice(-2),J=await(0,O.interpolate_4d)(C,{size:[N,N],mode:"bicubic"});if(L>0){const le=[],de=v(L),fe=w(ee/de),ke=w(T/de);for(let Le=0;LeC.map(T=>N*U(T/N))),$=new O.Tensor("int64",D.flat(),[q,2]),g=D.map(([C,T])=>this.calc_num_image_tokens_from_image_size(T,C));return{pixel_values:Y,original_sizes:ie,reshaped_input_sizes:z,image_sizes:$,num_img_tokens:g}}}},"./src/models/phi3_v/processing_phi3_v.js":(Te,A,s)=>{s.r(A),s.d(A,{Phi3VProcessor:()=>w});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");s("./src/utils/image.js");const Q="<|image|>",U=/<\|image_\d+\|>/g;class w extends f.Processor{async _call(y,M=null,{padding:b=!0,truncation:L=!0,num_crops:q=null}={}){Array.isArray(y)||(y=[y]);let se,ie;if(M){ie=await this.image_processor(M,{num_crops:q});const{num_img_tokens:z}=ie,W=y.map((D,$)=>D.split(U).join(Q.repeat(z[$])));se=this.tokenizer(W,{padding:b,truncation:L});const Y=this.tokenizer.model.convert_tokens_to_ids([Q])[0];se.input_ids.map_(D=>D==Y?-D:D)}else se=this.tokenizer(y);return{...se,...ie}}}ge(w,"image_processor_class",O.AutoImageProcessor),ge(w,"tokenizer_class",N.AutoTokenizer)},"./src/models/processors.js":(Te,A,s)=>{s.r(A),s.d(A,{Florence2Processor:()=>f.Florence2Processor,Idefics3Processor:()=>Q.Idefics3Processor,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,MgpstrProcessor:()=>O.MgpstrProcessor,MoonshineProcessor:()=>N.MoonshineProcessor,OwlViTProcessor:()=>v.OwlViTProcessor,PaliGemmaProcessor:()=>M.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,Qwen2VLProcessor:()=>L.Qwen2VLProcessor,SamProcessor:()=>q.SamProcessor,SpeechT5Processor:()=>se.SpeechT5Processor,VLChatProcessor:()=>U.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>ie.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>z.WhisperProcessor});var f=s("./src/models/florence2/processing_florence2.js"),O=s("./src/models/mgp_str/processing_mgp_str.js"),N=s("./src/models/moonshine/processing_moonshine.js"),Q=s("./src/models/idefics3/processing_idefics3.js"),U=s("./src/models/janus/processing_janus.js"),w=s("./src/models/jina_clip/processing_jina_clip.js"),v=s("./src/models/owlvit/processing_owlvit.js"),y=s("./src/models/phi3_v/processing_phi3_v.js"),M=s("./src/models/paligemma/processing_paligemma.js"),b=s("./src/models/pyannote/processing_pyannote.js"),L=s("./src/models/qwen2_vl/processing_qwen2_vl.js"),q=s("./src/models/sam/processing_sam.js"),se=s("./src/models/speecht5/processing_speecht5.js"),ie=s("./src/models/wav2vec2/processing_wav2vec2.js"),z=s("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Te,A,s)=>{s.r(A),s.d(A,{PvtImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Te,A,s)=>{s.r(A),s.d(A,{PyAnnoteFeatureExtractor:()=>Q});var f=s("./src/base/feature_extraction_utils.js"),O=s("./src/utils/tensor.js"),N=s("./src/utils/maths.js");class Q extends f.FeatureExtractor{async _call(w){(0,f.validate_audio_inputs)(w,"PyAnnoteFeatureExtractor"),w instanceof Float64Array&&(w=new Float32Array(w));const v=[1,1,w.length];return{input_values:new O.Tensor("float32",w,v)}}samples_to_frames(w){return(w-this.config.offset)/this.config.step}post_process_speaker_diarization(w,v){const y=v/this.samples_to_frames(v)/this.config.sampling_rate,M=[];for(const b of w.tolist()){const L=[];let q=-1;for(let se=0;se({id:se,start:ie*y,end:z*y,confidence:W/(z-ie)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(Te,A,s)=>{s.r(A),s.d(A,{PyAnnoteProcessor:()=>N});var f=s("./src/base/processing_utils.js"),O=s("./src/models/pyannote/feature_extraction_pyannote.js");class N extends f.Processor{async _call(U){return await this.feature_extractor(U)}post_process_speaker_diarization(...U){return this.feature_extractor.post_process_speaker_diarization(...U)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}ge(N,"feature_extractor_class",O.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Te,A,s)=>{s.r(A),s.d(A,{Qwen2VLImageProcessor:()=>N});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(U,...w){const{pixel_values:v,original_sizes:y,reshaped_input_sizes:M}=await super._call(U,...w);let b=v;const{temporal_patch_size:L,merge_size:q,patch_size:se}=this.config;b.dims[0]===1&&(b=(0,O.cat)(Array.from({length:L},()=>b),0));const ie=b.dims[0]/L,z=b.dims[1],W=Math.floor(b.dims[2]/se),Y=Math.floor(b.dims[3]/se),D=b.view(ie,L,z,Math.floor(W/q),q,se,Math.floor(Y/q),q,se).permute(0,3,6,4,7,2,1,5,8).view(ie*W*Y,z*L*se*se),$=new O.Tensor("int64",[ie,W,Y],[1,3]);return{pixel_values:D,image_grid_thw:$,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Te,A,s)=>{s.r(A),s.d(A,{Qwen2VLProcessor:()=>Q});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js"),N=s("./src/tokenizers.js");s("./src/utils/image.js");class Q extends f.Processor{async _call(w,v=null,...y){Array.isArray(w)||(w=[w]);let M,b;if(v&&(M=await this.image_processor(v),b=M.image_grid_thw),b){let q=this.image_processor.config.merge_size**2,se=0;const ie=b.tolist();w=w.map(z=>{for(;z.includes("<|image_pad|>");){const W=Number(ie[se++].reduce((Y,D)=>Y*D,1n));z=z.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(W/q)))}return z.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(w),...M}}}ge(Q,"image_processor_class",O.AutoImageProcessor),ge(Q,"tokenizer_class",N.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Te,A,s)=>{s.r(A),s.d(A,{RTDetrImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_object_detection(...Q){return(0,f.post_process_object_detection)(...Q)}}},"./src/models/sam/image_processing_sam.js":(Te,A,s)=>{s.r(A),s.d(A,{SamImageProcessor:()=>Q});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/core.js"),N=s("./src/utils/tensor.js");class Q extends f.ImageProcessor{reshape_input_points(w,v,y,M=!1){w=structuredClone(w);let b=(0,O.calculateDimensions)(w);if(b.length===3)M||(b=[1,...b]),w=[w];else if(b.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let L=0;LM!==v.dims[b]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N.Tensor("int64",w.flat(1/0).map(BigInt),y)}async _call(w,{input_points:v=null,input_labels:y=null,input_boxes:M=null}={}){const b=await super._call(w);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),y){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(y,b.input_points)}return M&&(b.input_boxes=this.reshape_input_points(M,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(w,v,y,{mask_threshold:M=0,binarize:b=!0,pad_size:L=null}={}){const q=[];L=L??this.pad_size;const se=[L.height,L.width];for(let ie=0;ieM&&($[g]=1);Y=new N.Tensor("bool",$,Y.dims)}q.push(Y)}return q}generate_crop_boxes(w,v,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:L=1}={}){}}},"./src/models/sam/processing_sam.js":(Te,A,s)=>{s.r(A),s.d(A,{SamProcessor:()=>N});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/image_processing_auto.js");class N extends f.Processor{async _call(...U){return await this.image_processor(...U)}post_process_masks(...U){return this.image_processor.post_process_masks(...U)}reshape_input_points(...U){return this.image_processor.reshape_input_points(...U)}}ge(N,"image_processor_class",O.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Te,A,s)=>{s.r(A),s.d(A,{SeamlessM4TFeatureExtractor:()=>Q});var f=s("./src/base/feature_extraction_utils.js"),O=s("./src/utils/tensor.js"),N=s("./src/utils/audio.js");class Q extends f.FeatureExtractor{constructor(w){super(w);const v=this.config.sampling_rate,y=(0,N.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let M=0;My*32768),(0,N.spectrogram)(w,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:v,transpose:!0})}async _call(w,{padding:v=!0,pad_to_multiple_of:y=2,do_normalize_per_mel_bins:M=!0,return_attention_mask:b=!0}={}){(0,f.validate_audio_inputs)(w,"SeamlessM4TFeatureExtractor");let L=await this._extract_fbank_features(w,this.config.max_length);if(M){const[$,g]=L.dims,C=L.data;for(let T=0;T0){const ee=new Float32Array(g*($+T));ee.set(C),ee.fill(this.config.padding_value,C.length);const J=$+T;L=new O.Tensor(L.type,ee,[J,g]),b&&(q=new O.Tensor("int64",new BigInt64Array(J),[1,J]),q.data.fill(1n,0,$))}}const[se,ie]=L.dims,z=this.config.stride;if(se%z!==0)throw new Error(`The number of frames (${se}) must be a multiple of the stride (${z}).`);const Y=L.view(1,Math.floor(se/z),ie*z),D={input_features:Y};if(b){const $=Y.dims[1],g=new BigInt64Array($);if(q){const C=q.data;for(let T=1,ee=0;T{s.r(A),s.d(A,{SegformerFeatureExtractor:()=>N,SegformerImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_semantic_segmentation(...U){return(0,f.post_process_semantic_segmentation)(...U)}}class N extends O{}},"./src/models/siglip/image_processing_siglip.js":(Te,A,s)=>{s.r(A),s.d(A,{SiglipImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Te,A,s)=>{s.r(A),s.d(A,{SpeechT5FeatureExtractor:()=>O});var f=s("./src/base/feature_extraction_utils.js");class O extends f.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Te,A,s)=>{s.r(A),s.d(A,{SpeechT5Processor:()=>Q});var f=s("./src/base/processing_utils.js"),O=s("./src/tokenizers.js"),N=s("./src/models/auto/feature_extraction_auto.js");class Q extends f.Processor{async _call(w){return await this.feature_extractor(w)}}ge(Q,"tokenizer_class",O.AutoTokenizer),ge(Q,"feature_extractor_class",N.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Te,A,s)=>{s.r(A),s.d(A,{Swin2SRImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{pad_image(Q,U,w,v={}){const[y,M,b]=U;return super.pad_image(Q,U,{width:M+(w-M%w)%w,height:y+(w-y%w)%w},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(Te,A,s)=>{s.r(A),s.d(A,{ViTFeatureExtractor:()=>N,ViTImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{}class N extends O{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Te,A,s)=>{s.r(A),s.d(A,{VitMatteImageProcessor:()=>N});var f=s("./src/base/image_processors_utils.js"),O=s("./src/utils/tensor.js");class N extends f.ImageProcessor{async _call(U,w){Array.isArray(U)||(U=[U]),Array.isArray(w)||(w=[w]);const v=await Promise.all(U.map(b=>this.preprocess(b))),y=await Promise.all(w.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,O.stack)(v.map((b,L)=>(0,O.cat)([b.pixel_values,y[L].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Te,A,s)=>{s.r(A),s.d(A,{VitPoseImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_pose_estimation(Q,U,{threshold:w=null}={}){const v=Q.tolist(),[y,M,b,L]=Q.dims,q=[];for(let se=0;se{s.r(A),s.d(A,{Wav2Vec2FeatureExtractor:()=>N});var f=s("./src/base/feature_extraction_utils.js"),O=s("./src/utils/tensor.js");class N extends f.FeatureExtractor{_zero_mean_unit_var_norm(U){const v=U.reduce((M,b)=>M+b,0)/U.length,y=U.reduce((M,b)=>M+(b-v)**2,0)/U.length;return U.map(M=>(M-v)/Math.sqrt(y+1e-7))}async _call(U){(0,f.validate_audio_inputs)(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let w=U;this.config.do_normalize&&(w=this._zero_mean_unit_var_norm(w));const v=[1,w.length];return{input_values:new O.Tensor("float32",w,v),attention_mask:new O.Tensor("int64",new BigInt64Array(w.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Te,A,s)=>{s.r(A),s.d(A,{Wav2Vec2ProcessorWithLM:()=>N});var f=s("./src/base/processing_utils.js"),O=s("./src/models/auto/feature_extraction_auto.js");class N extends f.Processor{async _call(U){return await this.feature_extractor(U)}}ge(N,"feature_extractor_class",O.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Te,A,s)=>{s.r(A),s.d(A,{WeSpeakerFeatureExtractor:()=>N});var f=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var O=s("./src/utils/audio.js");class N extends f.FeatureExtractor{constructor(U){super(U);const w=this.config.sampling_rate,v=(0,O.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(w/2),w,null,"kaldi",!0);for(let y=0;yw*32768),(0,O.spectrogram)(U,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(U){(0,f.validate_audio_inputs)(U,"WeSpeakerFeatureExtractor");const w=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=w.mean(1).data,y=w.data,[M,b,L]=w.dims;for(let q=0;q{s.r(A),s.d(A,{WHISPER_LANGUAGE_MAPPING:()=>O,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>N,whisper_language_to_code:()=>Q});const f=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],O=new Map(f),N=new Map([...f.map(([U,w])=>[w,U]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Q(U){U=U.toLowerCase();let w=N.get(U);if(w===void 0)if(O.has(U))w=U;else{const y=U.length===2?O.keys():O.values();throw new Error(`Language "${U}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return w}},"./src/models/whisper/feature_extraction_whisper.js":(Te,A,s)=>{s.r(A),s.d(A,{WhisperFeatureExtractor:()=>Q});var f=s("./src/base/feature_extraction_utils.js");s("./src/utils/tensor.js");var O=s("./src/utils/audio.js"),N=s("./src/utils/maths.js");class Q extends f.FeatureExtractor{constructor(w){var v;super(w),(v=this.config).mel_filters??(v.mel_filters=(0,O.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,O.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(w){const v=await(0,O.spectrogram)(w,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}),y=v.data,M=(0,N.max)(y)[0];for(let b=0;bthis.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`."),v=w.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(w)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Te,A,s)=>{s.r(A),s.d(A,{WhisperGenerationConfig:()=>O});var f=s("./src/generation/configuration_utils.js");class O extends f.GenerationConfig{constructor(){super(...arguments);ge(this,"return_timestamps",null);ge(this,"return_token_timestamps",null);ge(this,"num_frames",null);ge(this,"alignment_heads",null);ge(this,"task",null);ge(this,"language",null);ge(this,"no_timestamps_token_id",null);ge(this,"prompt_ids",null);ge(this,"is_multilingual",null);ge(this,"lang_to_id",null);ge(this,"task_to_id",null);ge(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Te,A,s)=>{s.r(A),s.d(A,{WhisperProcessor:()=>Q});var f=s("./src/models/auto/feature_extraction_auto.js"),O=s("./src/tokenizers.js"),N=s("./src/base/processing_utils.js");class Q extends N.Processor{async _call(w){return await this.feature_extractor(w)}}ge(Q,"tokenizer_class",O.AutoTokenizer),ge(Q,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Te,A,s)=>{s.r(A),s.d(A,{YolosFeatureExtractor:()=>N,YolosImageProcessor:()=>O});var f=s("./src/base/image_processors_utils.js");class O extends f.ImageProcessor{post_process_object_detection(...U){return(0,f.post_process_object_detection)(...U)}}class N extends O{}},"./src/ops/registry.js":(Te,A,s)=>{s.r(A),s.d(A,{TensorOpRegistry:()=>Q});var f=s("./src/backends/onnx.js"),O=s("./src/utils/tensor.js");const N=async(U,w,v)=>{const y=await(0,f.createInferenceSession)(new Uint8Array(U),w);return async M=>{const b=Object.fromEntries(Object.entries(M).map(([q,se])=>[q,se.ort_tensor])),L=await y.run(b);return Array.isArray(v)?v.map(q=>new O.Tensor(L[q])):new O.Tensor(L[v])}};class Q{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=N([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=N([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=N([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=N([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=N([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=N([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=N([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}ge(Q,"session_options",{})},"./src/pipelines.js":(Te,A,s)=>{s.r(A),s.d(A,{AudioClassificationPipeline:()=>de,AutomaticSpeechRecognitionPipeline:()=>ke,DepthEstimationPipeline:()=>Be,DocumentQuestionAnsweringPipeline:()=>re,FeatureExtractionPipeline:()=>J,FillMaskPipeline:()=>Y,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>le,ImageSegmentationPipeline:()=>qe,ImageToImagePipeline:()=>Pe,ImageToTextPipeline:()=>xe,ObjectDetectionPipeline:()=>ut,Pipeline:()=>se,QuestionAnsweringPipeline:()=>W,SummarizationPipeline:()=>$,Text2TextGenerationPipeline:()=>D,TextClassificationPipeline:()=>ie,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>he,TokenClassificationPipeline:()=>z,TranslationPipeline:()=>g,ZeroShotAudioClassificationPipeline:()=>fe,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>Ue,ZeroShotObjectDetectionPipeline:()=>ue,pipeline:()=>oe});var f=s("./src/tokenizers.js"),O=s("./src/models.js"),N=s("./src/models/auto/processing_auto.js");s("./src/base/processing_utils.js");var Q=s("./src/utils/generic.js"),U=s("./src/utils/core.js"),w=s("./src/utils/maths.js"),v=s("./src/utils/audio.js"),y=s("./src/utils/tensor.js"),M=s("./src/utils/image.js");async function b(De){return Array.isArray(De)||(De=[De]),await Promise.all(De.map(ce=>M.RawImage.read(ce)))}async function L(De,ce){return Array.isArray(De)||(De=[De]),await Promise.all(De.map(ve=>typeof ve=="string"||ve instanceof URL?(0,v.read_audio)(ve,ce):ve instanceof Float64Array?new Float32Array(ve):ve))}function q(De,ce){ce&&(De=De.map(Ne=>Ne|0));const[ve,Re,je,We]=De;return{xmin:ve,ymin:Re,xmax:je,ymax:We}}class se extends Q.Callable{constructor({task:ce,model:ve,tokenizer:Re=null,processor:je=null}){super(),this.task=ce,this.model=ve,this.tokenizer=Re,this.processor=je}async dispose(){await this.model.dispose()}}class ie extends se{constructor(ce){super(ce)}async _call(ce,{top_k:ve=1}={}){const Re=this.tokenizer(ce,{padding:!0,truncation:!0}),je=await this.model(Re),We=this.model.config.problem_type==="multi_label_classification"?at=>at.sigmoid():at=>new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),Ne=this.model.config.id2label,Ze=[];for(const at of je.logits){const ft=We(at),dt=await(0,y.topk)(ft,ve),gt=dt[0].tolist(),ne=dt[1].tolist().map((K,pe)=>({label:Ne?Ne[K]:`LABEL_${K}`,score:gt[pe]}));ve===1?Ze.push(...ne):Ze.push(ne)}return Array.isArray(ce)||ve===1?Ze:Ze[0]}}class z extends se{constructor(ce){super(ce)}async _call(ce,{ignore_labels:ve=["O"]}={}){const Re=Array.isArray(ce),je=this.tokenizer(Re?ce:[ce],{padding:!0,truncation:!0}),Ne=(await this.model(je)).logits,Ze=this.model.config.id2label,at=[];for(let ft=0;ftpt==this.tokenizer.sep_token_id);at[gt].map((pt,It)=>pt==1&&(It===0||It>ne&&ft.findIndex(St=>St==F[It])===-1));const K=We[gt].tolist(),pe=Ne[gt].tolist();for(let pt=1;ptIt==F[pt])!==-1)&&(K[pt]=-1/0,pe[pt]=-1/0);const Fe=(0,w.softmax)(K).map((pt,It)=>[pt,It]),Qe=(0,w.softmax)(pe).map((pt,It)=>[pt,It]);Fe[0][0]=0,Qe[0][0]=0;const st=(0,U.product)(Fe,Qe).filter(pt=>pt[0][1]<=pt[1][1]).map(pt=>[pt[0][1],pt[1][1],pt[0][0]*pt[1][0]]).sort((pt,It)=>It[2]-pt[2]);for(let pt=0;ptK==this.tokenizer.mask_token_id);if(ft===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const dt=je[Ze][ft],gt=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(dt.data),dt.dims),ve),F=gt[0].tolist(),ne=gt[1].tolist();We.push(ne.map((K,pe)=>{const Fe=at.slice();return Fe[ft]=K,{score:F[pe],token:Number(K),token_str:this.tokenizer.decode([K]),sequence:this.tokenizer.decode(Fe,{skip_special_tokens:!0})}}))}return Array.isArray(ce)?We:We[0]}}class D extends se{constructor(ve){super(ve);ge(this,"_key","generated_text")}async _call(ve,Re={}){Array.isArray(ve)||(ve=[ve]),this.model.config.prefix&&(ve=ve.map(ft=>this.model.config.prefix+ft));const je=this.model.config.task_specific_params;je&&je[this.task]&&je[this.task].prefix&&(ve=ve.map(ft=>je[this.task].prefix+ft));const We=this.tokenizer,Ne={padding:!0,truncation:!0};let Ze;this instanceof g&&"_build_translation_inputs"in We?Ze=We._build_translation_inputs(ve,Ne,Re):Ze=We(ve,Ne);const at=await this.model.generate({...Ze,...Re});return We.batch_decode(at,{skip_special_tokens:!0}).map(ft=>({[this._key]:ft}))}}class $ extends D{constructor(ve){super(ve);ge(this,"_key","summary_text")}}class g extends D{constructor(ve){super(ve);ge(this,"_key","translation_text")}}function C(De){return Array.isArray(De)&&De.every(ce=>"role"in ce&&"content"in ce)}class T extends se{constructor(ce){super(ce)}async _call(ce,ve={}){let Re=!1,je=!1,We;if(typeof ce=="string")We=ce=[ce];else if(Array.isArray(ce)&&ce.every(ne=>typeof ne=="string"))Re=!0,We=ce;else{if(C(ce))ce=[ce];else if(Array.isArray(ce)&&ce.every(C))Re=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");je=!0,We=ce.map(ne=>this.tokenizer.apply_chat_template(ne,{tokenize:!1,add_generation_prompt:!0}))}const Ne=ve.add_special_tokens??!1,Ze=je?!1:ve.return_full_text??!0;this.tokenizer.padding_side="left";const at=this.tokenizer(We,{add_special_tokens:Ne,padding:!0,truncation:!0}),ft=await this.model.generate({...at,...ve}),dt=this.tokenizer.batch_decode(ft,{skip_special_tokens:!0});let gt;!Ze&&at.input_ids.dims.at(-1)>0&&(gt=this.tokenizer.batch_decode(at.input_ids,{skip_special_tokens:!0}).map(ne=>ne.length));const F=Array.from({length:ce.length},ne=>[]);for(let ne=0;ne[ve.toLowerCase(),Re])),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,ve,{hypothesis_template:Re="This example is {}.",multi_label:je=!1}={}){const We=Array.isArray(ce);We||(ce=[ce]),Array.isArray(ve)||(ve=[ve]);const Ne=ve.map(ft=>Re.replace("{}",ft)),Ze=je||ve.length===1,at=[];for(const ft of ce){const dt=[];for(const ne of Ne){const K=this.tokenizer(ft,{text_pair:ne,padding:!0,truncation:!0}),pe=await this.model(K);Ze?dt.push([pe.logits.data[this.contradiction_id],pe.logits.data[this.entailment_id]]):dt.push(pe.logits.data[this.entailment_id])}const F=(Ze?dt.map(ne=>(0,w.softmax)(ne)[1]):(0,w.softmax)(dt)).map((ne,K)=>[ne,K]).sort((ne,K)=>K[0]-ne[0]);at.push({sequence:ft,labels:F.map(ne=>ve[ne[1]]),scores:F.map(ne=>ne[0])})}return We?at:at[0]}}class J extends se{constructor(ce){super(ce)}async _call(ce,{pooling:ve="none",normalize:Re=!1,quantize:je=!1,precision:We="binary"}={}){const Ne=this.tokenizer(ce,{padding:!0,truncation:!0}),Ze=await this.model(Ne);let at=Ze.last_hidden_state??Ze.logits??Ze.token_embeddings;if(ve!=="none")if(ve==="mean")at=(0,y.mean_pooling)(at,Ne.attention_mask);else if(ve==="cls")at=at.slice(null,0);else throw Error(`Pooling method '${ve}' not supported.`);return Re&&(at=at.normalize(2,-1)),je&&(at=(0,y.quantize_embeddings)(at,We)),at}}class le extends se{constructor(ce){super(ce)}async _call(ce,{pool:ve=null}={}){const Re=await b(ce),{pixel_values:je}=await this.processor(Re),We=await this.model({pixel_values:je});let Ne;if(ve){if(!("pooler_output"in We))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ne=We.pooler_output}else Ne=We.last_hidden_state??We.logits??We.image_embeds;return Ne}}class de extends se{constructor(ce){super(ce)}async _call(ce,{top_k:ve=5}={}){const Re=this.processor.feature_extractor.config.sampling_rate,je=await L(ce,Re),We=this.model.config.id2label,Ne=[];for(const Ze of je){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(dt.data),dt.dims),ve),F=gt[0].tolist(),K=gt[1].tolist().map((pe,Fe)=>({label:We?We[pe]:`LABEL_${pe}`,score:F[Fe]}));Ne.push(K)}return Array.isArray(ce)?Ne:Ne[0]}}class fe extends se{constructor(ce){super(ce)}async _call(ce,ve,{hypothesis_template:Re="This is a sound of {}."}={}){const je=!Array.isArray(ce);je&&(ce=[ce]);const We=ve.map(dt=>Re.replace("{}",dt)),Ne=this.tokenizer(We,{padding:!0,truncation:!0}),Ze=this.processor.feature_extractor.config.sampling_rate,at=await L(ce,Ze),ft=[];for(const dt of at){const gt=await this.processor(dt),F=await this.model({...Ne,...gt}),ne=(0,w.softmax)(F.logits_per_audio.data);ft.push([...ne].map((K,pe)=>({score:K,label:ve[pe]})))}return je?ft[0]:ft}}class ke extends se{constructor(ce){super(ce)}async _call(ce,ve={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ce,ve);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ce,ve);case"moonshine":return this._call_moonshine(ce,ve);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ce,ve){ve.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ve.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Re=!Array.isArray(ce);Re&&(ce=[ce]);const je=this.processor.feature_extractor.config.sampling_rate,We=await L(ce,je),Ne=[];for(const Ze of We){const at=await this.processor(Ze),dt=(await this.model(at)).logits[0],gt=[];for(const ne of dt)gt.push((0,w.max)(ne.data)[1]);const F=this.tokenizer.decode(gt);Ne.push({text:F})}return Re?Ne[0]:Ne}async _call_whisper(ce,ve){const Re=ve.return_timestamps??!1,je=ve.chunk_length_s??0,We=ve.force_full_sequences??!1;let Ne=ve.stride_length_s??null;const Ze={...ve};Re==="word"&&(Ze.return_token_timestamps=!0,Ze.return_timestamps=!1);const at=!Array.isArray(ce);at&&(ce=[ce]);const ft=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,dt=this.processor.feature_extractor.config.hop_length,gt=this.processor.feature_extractor.config.sampling_rate,F=await L(ce,gt),ne=[];for(const K of F){let pe=[];if(je>0){if(Ne===null)Ne=je/6;else if(je<=Ne)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const st=gt*je,pt=gt*Ne,It=st-2*pt;let St=0;for(;;){const Ft=St+st,At=K.subarray(St,Ft),nr=await this.processor(At),gr=St===0,kr=Ft>=K.length;if(pe.push({stride:[At.length,gr?0:pt,kr?0:pt],input_features:nr.input_features,is_last:kr}),kr)break;St+=It}}else pe=[{stride:[K.length,0,0],input_features:(await this.processor(K)).input_features,is_last:!0}];for(const st of pe){Ze.num_frames=Math.floor(st.stride[0]/dt);const pt=await this.model.generate({inputs:st.input_features,...Ze});Re==="word"?(st.tokens=pt.sequences.tolist()[0],st.token_timestamps=pt.token_timestamps.tolist()[0].map(It=>(0,w.round)(It,2))):st.tokens=pt[0].tolist(),st.stride=st.stride.map(It=>It/gt)}const[Fe,Qe]=this.tokenizer._decode_asr(pe,{time_precision:ft,return_timestamps:Re,force_full_sequences:We});ne.push({text:Fe,...Qe})}return at?ne[0]:ne}async _call_moonshine(ce,ve){const Re=!Array.isArray(ce);Re&&(ce=[ce]);const je=this.processor.feature_extractor.config.sampling_rate,We=await L(ce,je),Ne=[];for(const Ze of We){const at=await this.processor(Ze),ft=Math.floor(Ze.length/je)*6,dt=await this.model.generate({max_new_tokens:ft,...ve,...at}),gt=this.processor.batch_decode(dt,{skip_special_tokens:!0})[0];Ne.push({text:gt})}return Re?Ne[0]:Ne}}class xe extends se{constructor(ce){super(ce)}async _call(ce,ve={}){const Re=Array.isArray(ce),je=await b(ce),{pixel_values:We}=await this.processor(je),Ne=[];for(const Ze of We){Ze.dims=[1,...Ze.dims];const at=await this.model.generate({inputs:Ze,...ve}),ft=this.tokenizer.batch_decode(at,{skip_special_tokens:!0}).map(dt=>({generated_text:dt.trim()}));Ne.push(ft)}return Re?Ne:Ne[0]}}class Le extends se{constructor(ce){super(ce)}async _call(ce,{top_k:ve=5}={}){const Re=await b(ce),{pixel_values:je}=await this.processor(Re),We=await this.model({pixel_values:je}),Ne=this.model.config.id2label,Ze=[];for(const at of We.logits){const ft=await(0,y.topk)(new y.Tensor("float32",(0,w.softmax)(at.data),at.dims),ve),dt=ft[0].tolist(),F=ft[1].tolist().map((ne,K)=>({label:Ne?Ne[ne]:`LABEL_${ne}`,score:dt[K]}));Ze.push(F)}return Array.isArray(ce)?Ze:Ze[0]}}class qe extends se{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:ve=.5,mask_threshold:Re=.5,overlap_mask_area_threshold:je=.8,label_ids_to_fuse:We=null,target_sizes:Ne=null,subtask:Ze=null}={}){if(Array.isArray(ce)&&ce.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ft=await b(ce),dt=ft.map(Qe=>[Qe.height,Qe.width]),{pixel_values:gt,pixel_mask:F}=await this.processor(ft),ne=await this.model({pixel_values:gt,pixel_mask:F});let K=null;if(Ze!==null)K=this.subtasks_mapping[Ze];else for(let[Qe,st]of Object.entries(this.subtasks_mapping))if(st in this.processor.image_processor){K=this.processor.image_processor[st].bind(this.processor.image_processor),Ze=Qe;break}const pe=this.model.config.id2label,Fe=[];if(Ze==="panoptic"||Ze==="instance"){const Qe=K(ne,ve,Re,je,We,Ne??dt)[0],st=Qe.segmentation;for(const pt of Qe.segments_info){const It=new Uint8ClampedArray(st.data.length);for(let Ft=0;FtRe.replace("{}",F)),Ze=this.tokenizer(Ne,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:at}=await this.processor(We),ft=await this.model({...Ze,pixel_values:at}),dt=this.model.config.model_type==="siglip"?F=>F.sigmoid().data:F=>(0,w.softmax)(F.data),gt=[];for(const F of ft.logits_per_image){const K=[...dt(F)].map((pe,Fe)=>({score:pe,label:ve[Fe]}));K.sort((pe,Fe)=>Fe.score-pe.score),gt.push(K)}return je?gt:gt[0]}}class ut extends se{constructor(ce){super(ce)}async _call(ce,{threshold:ve=.9,percentage:Re=!1}={}){const je=Array.isArray(ce);if(je&&ce.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const We=await b(ce),Ne=Re?null:We.map(ne=>[ne.height,ne.width]),{pixel_values:Ze,pixel_mask:at}=await this.processor(We),ft=await this.model({pixel_values:Ze,pixel_mask:at}),dt=this.processor.image_processor.post_process_object_detection(ft,ve,Ne),gt=this.model.config.id2label,F=dt.map(ne=>ne.boxes.map((K,pe)=>({score:ne.scores[pe],label:gt[ne.classes[pe]],box:q(K,!Re)})));return je?F:F[0]}}class ue extends se{constructor(ce){super(ce)}async _call(ce,ve,{threshold:Re=.1,top_k:je=null,percentage:We=!1}={}){const Ne=Array.isArray(ce),Ze=await b(ce),at=this.tokenizer(ve,{padding:!0,truncation:!0}),ft=await this.processor(Ze),dt=[];for(let gt=0;gt({score:Fe.scores[pt],label:ve[Fe.classes[pt]],box:q(st,!We)})).sort((st,pt)=>pt.score-st.score);je!==null&&(Qe=Qe.slice(0,je)),dt.push(Qe)}return Ne?dt:dt[0]}}class re extends se{constructor(ce){super(ce)}async _call(ce,ve,Re={}){const je=(await b(ce))[0],{pixel_values:We}=await this.processor(je),Ne=`${ve}`,Ze=this.tokenizer(Ne,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,at=await this.model.generate({inputs:We,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ze,...Re}),dt=this.tokenizer.batch_decode(at)[0].match(/(.*?)<\/s_answer>/);let gt=null;return dt&&dt.length>=2&&(gt=dt[1].trim()),[{answer:gt}]}}class he extends se{constructor(ve){super(ve);ge(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ve.vocoder??null}async _call(ve,{speaker_embeddings:Re=null}={}){return this.processor?this._call_text_to_spectrogram(ve,{speaker_embeddings:Re}):this._call_text_to_waveform(ve)}async _call_text_to_waveform(ve){const Re=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:je}=await this.model(Re),We=this.model.config.sampling_rate;return{audio:je.data,sampling_rate:We}}async _call_text_to_spectrogram(ve,{speaker_embeddings:Re}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await O.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Re=="string"||Re instanceof URL)&&(Re=new Float32Array(await(await fetch(Re)).arrayBuffer())),Re instanceof Float32Array)Re=new y.Tensor("float32",Re,[1,Re.length]);else if(!(Re instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:je}=this.tokenizer(ve,{padding:!0,truncation:!0}),{waveform:We}=await this.model.generate_speech(je,Re,{vocoder:this.vocoder}),Ne=this.processor.feature_extractor.config.sampling_rate;return{audio:We.data,sampling_rate:Ne}}}class Pe extends se{constructor(ce){super(ce)}async _call(ce){const ve=await b(ce),Re=await this.processor(ve),je=await this.model(Re),We=[];for(const Ne of je.reconstruction){const Ze=Ne.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");We.push(M.RawImage.fromTensor(Ze))}return We.length>1?We:We[0]}}class Be extends se{constructor(ce){super(ce)}async _call(ce){const ve=await b(ce),Re=await this.processor(ve),{predicted_depth:je}=await this.model(Re),We=[];for(let Ne=0;Ne1?We:We[0]}}const et=Object.freeze({"text-classification":{tokenizer:f.AutoTokenizer,pipeline:ie,model:O.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:f.AutoTokenizer,pipeline:z,model:O.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:f.AutoTokenizer,pipeline:W,model:O.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:f.AutoTokenizer,pipeline:Y,model:O.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:f.AutoTokenizer,pipeline:$,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:f.AutoTokenizer,pipeline:g,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:f.AutoTokenizer,pipeline:D,model:O.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:f.AutoTokenizer,pipeline:T,model:O.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:f.AutoTokenizer,pipeline:ee,model:O.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:de,model:O.AutoModelForAudioClassification,processor:N.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:f.AutoTokenizer,pipeline:fe,model:O.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:f.AutoTokenizer,pipeline:ke,model:[O.AutoModelForSpeechSeq2Seq,O.AutoModelForCTC],processor:N.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:f.AutoTokenizer,pipeline:he,model:[O.AutoModelForTextToWaveform,O.AutoModelForTextToSpectrogram],processor:[N.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:f.AutoTokenizer,pipeline:xe,model:O.AutoModelForVision2Seq,processor:N.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:O.AutoModelForImageClassification,processor:N.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:qe,model:[O.AutoModelForImageSegmentation,O.AutoModelForSemanticSegmentation,O.AutoModelForUniversalSegmentation],processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:f.AutoTokenizer,pipeline:Ue,model:O.AutoModel,processor:N.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ut,model:O.AutoModelForObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:f.AutoTokenizer,pipeline:ue,model:O.AutoModelForZeroShotObjectDetection,processor:N.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:f.AutoTokenizer,pipeline:re,model:O.AutoModelForDocumentQuestionAnswering,processor:N.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Pe,model:O.AutoModelForImageToImage,processor:N.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Be,model:O.AutoModelForDepthEstimation,processor:N.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:f.AutoTokenizer,pipeline:J,model:O.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:N.AutoProcessor,pipeline:le,model:[O.AutoModelForImageFeatureExtraction,O.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Xe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function oe(De,ce=null,{progress_callback:ve=null,config:Re=null,cache_dir:je=null,local_files_only:We=!1,revision:Ne="main",device:Ze=null,dtype:at=null,model_file_name:ft=null,session_options:dt={}}={}){De=Xe[De]??De;const gt=et[De.split("_",1)[0]];if(!gt)throw Error(`Unsupported pipeline: ${De}. Must be one of [${Object.keys(et)}]`);ce||(ce=gt.default.model,console.log(`No model specified. Using default model: "${ce}".`));const F={progress_callback:ve,config:Re,cache_dir:je,local_files_only:We,revision:Ne,device:Ze,dtype:at,model_file_name:ft,session_options:dt},ne=new Map([["tokenizer",gt.tokenizer],["model",gt.model],["processor",gt.processor]]),K=await Je(ne,ce,F);K.task=De,(0,U.dispatchCallback)(ve,{status:"ready",task:De,model:ce});const pe=gt.pipeline;return new pe(K)}async function Je(De,ce,ve){const Re=Object.create(null),je=[];for(const[We,Ne]of De.entries()){if(!Ne)continue;let Ze;Array.isArray(Ne)?Ze=new Promise(async(at,ft)=>{var gt,F;let dt;for(const ne of Ne){if(ne===null){at(null);return}try{at(await ne.from_pretrained(ce,ve));return}catch(K){if((gt=K.message)!=null&>.includes("Unsupported model type"))dt=K;else if((F=K.message)!=null&&F.includes("Could not locate file"))dt=K;else{ft(K);return}}}ft(dt)}):Ze=Ne.from_pretrained(ce,ve),Re[We]=Ze,je.push(Ze)}await Promise.all(je);for(const[We,Ne]of Object.entries(Re))Re[We]=await Ne;return Re}},"./src/tokenizers.js":(Te,A,s)=>{s.r(A),s.d(A,{AlbertTokenizer:()=>ks,AutoTokenizer:()=>Mn,BartTokenizer:()=>tr,BertTokenizer:()=>Qs,BlenderbotSmallTokenizer:()=>Dn,BlenderbotTokenizer:()=>gn,BloomTokenizer:()=>Ns,CLIPTokenizer:()=>In,CamembertTokenizer:()=>nt,CodeGenTokenizer:()=>An,CodeLlamaTokenizer:()=>js,CohereTokenizer:()=>Ln,ConvBertTokenizer:()=>As,DebertaTokenizer:()=>is,DebertaV2Tokenizer:()=>$s,DistilBertTokenizer:()=>as,ElectraTokenizer:()=>Ot,EsmTokenizer:()=>ls,FalconTokenizer:()=>Us,GPT2Tokenizer:()=>bs,GPTNeoXTokenizer:()=>Ts,GemmaTokenizer:()=>Zs,Grok1Tokenizer:()=>_n,HerbertTokenizer:()=>cs,LlamaTokenizer:()=>Sn,M2M100Tokenizer:()=>zt,MBart50Tokenizer:()=>Rs,MBartTokenizer:()=>ts,MPNetTokenizer:()=>Jn,MarianTokenizer:()=>Vs,MgpstrTokenizer:()=>yn,MobileBertTokenizer:()=>Bs,NllbTokenizer:()=>xs,NougatTokenizer:()=>Yr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>mn,RoFormerTokenizer:()=>Ys,RobertaTokenizer:()=>Js,SiglipTokenizer:()=>On,SpeechT5Tokenizer:()=>ir,SqueezeBertTokenizer:()=>Ss,T5Tokenizer:()=>lr,TokenizerModel:()=>le,VitsTokenizer:()=>wn,Wav2Vec2CTCTokenizer:()=>Fn,WhisperTokenizer:()=>fn,XLMRobertaTokenizer:()=>$n,XLMTokenizer:()=>_t,is_chinese_char:()=>Y});var f=s("./src/utils/generic.js"),O=s("./src/utils/core.js"),N=s("./src/utils/hub.js"),Q=s("./src/utils/maths.js"),U=s("./src/utils/tensor.js"),w=s("./src/utils/data-structures.js"),v=s("./node_modules/@huggingface/jinja/dist/index.js"),y=s("./src/models/whisper/common_whisper.js");s("./src/utils/constants.js");async function M(Ee,P){const H=await Promise.all([(0,N.getModelJSON)(Ee,"tokenizer.json",!0,P),(0,N.getModelJSON)(Ee,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(H[1].legacy=P.legacy),H}function b(Ee,P){const H=[];let ae=0;for(const Me of Ee.matchAll(P)){const Ce=Me[0];ae0&&H.push(Ce),ae=Me.index+Ce.length}return ae=19968&&Ee<=40959||Ee>=13312&&Ee<=19903||Ee>=131072&&Ee<=173791||Ee>=173824&&Ee<=177983||Ee>=177984&&Ee<=178207||Ee>=178208&&Ee<=183983||Ee>=63744&&Ee<=64255||Ee>=194560&&Ee<=195103}function D(Ee,P,H){const ae=[];let Me=0;for(;Methis.tokens_to_ids.get(H)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(H=>this.vocab[H]??this.unk_token)}}class de extends le{constructor(P){super(P),this.tokens_to_ids=q(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[H,ae]of this.tokens_to_ids)this.vocab[ae]=H}encode(P){const H=[];for(const ae of P){const Me=[...ae];if(Me.length>this.max_input_chars_per_word){H.push(this.unk_token);continue}let Ce=!1,He=0;const ct=[];for(;He0&&(it=this.config.continuing_subword_prefix+it),this.tokens_to_ids.has(it)){ht=it;break}--yt}if(ht===null){Ce=!0;break}ct.push(ht),He=yt}Ce?H.push(this.unk_token):H.push(...ct)}return H}}class fe extends le{constructor(P,H){super(P);const ae=P.vocab.length;this.vocab=new Array(ae),this.scores=new Array(ae);for(let Me=0;Me[Me,Ce])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=H.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Q.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new w.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(P){const H=P.chars,ae=1;let Me=0;for(;Me{const Ee=[...Array.from({length:94},(Me,Ce)=>Ce+33),...Array.from({length:12},(Me,Ce)=>Ce+161),...Array.from({length:82},(Me,Ce)=>Ce+174)],P=Ee.slice();let H=0;for(let Me=0;Me<256;++Me)Ee.includes(Me)||(Ee.push(Me),P.push(256+H),H+=1);const ae=P.map(Me=>String.fromCharCode(Me));return Object.fromEntries(Ee.map((Me,Ce)=>[Me,ae[Ce]]))})(),xe=(0,O.reverseDictionary)(ke);class Le extends le{constructor(P){super(P),this.tokens_to_ids=q(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ae,Me]of this.tokens_to_ids)this.vocab[Me]=ae;const H=Array.isArray(P.merges[0]);this.merges=H?P.merges:P.merges.map(ae=>ae.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ae,Me)=>[JSON.stringify(ae),Me])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.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(P){if(P.length===0)return[];const H=this.cache.get(P);if(H!==void 0)return H;const ae=Array.from(P);this.end_of_word_suffix&&(ae[ae.length-1]+=this.end_of_word_suffix);let Me=[];if(ae.length>1){const Ce=new w.PriorityQueue((yt,ht)=>yt.score`<0x${ct.toString(16).toUpperCase().padStart(2,"0")}>`);He.every(ct=>this.tokens_to_ids.has(ct))?H.push(...He):H.push(this.unk_token)}else H.push(this.unk_token)}return H}}class qe extends le{constructor(P,H){super(P),this.tokens_to_ids=q(H.target_lang?P.vocab[H.target_lang]:P.vocab),this.bos_token=H.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=H.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=H.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=H.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[ae,Me]of this.tokens_to_ids)this.vocab[Me]=ae}encode(P){return P}}class Ue extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new Je(P);case"Precompiled":return new gr(P);case"Sequence":return new oe(P);case"Replace":return new ut(P);case"NFC":return new ue(P);case"NFKC":return new re(P);case"NFKD":return new he(P);case"Strip":return new Pe(P);case"StripAccents":return new Be(P);case"Lowercase":return new et(P);case"Prepend":return new Xe(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class ut extends Ue{normalize(P){const H=L(this.config.pattern);return H===null?P:P.replaceAll(H,this.config.content)}}class ue extends Ue{normalize(P){return P=P.normalize("NFC"),P}}class re extends Ue{normalize(P){return P=P.normalize("NFKC"),P}}class he extends Ue{normalize(P){return P=P.normalize("NFKD"),P}}class Pe extends Ue{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class Be extends Ue{normalize(P){return P=z(P),P}}class et extends Ue{normalize(P){return P=P.toLowerCase(),P}}class Xe extends Ue{normalize(P){return P=this.config.prepend+P,P}}class oe extends Ue{constructor(P){super(P),this.normalizers=P.normalizers.map(H=>Ue.fromConfig(H))}normalize(P){return this.normalizers.reduce((H,ae)=>ae.normalize(H),P)}}class Je extends Ue{_tokenize_chinese_chars(P){const H=[];for(let ae=0;aethis.pre_tokenize_text(ae,H)):this.pre_tokenize_text(P,H)).flat()}_call(P,H){return this.pre_tokenize(P,H)}}class ce extends De{constructor(P){super(),this.pattern=new RegExp(`[^\\s${g}]+|[${g}]`,"gu")}pre_tokenize_text(P,H){return P.trim().match(this.pattern)||[]}}class ve extends De{constructor(P){super(),this.config=P,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=ke,this.text_encoder=new TextEncoder}pre_tokenize_text(P,H){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(Me=>Array.from(this.text_encoder.encode(Me),Ce=>this.byte_encoder[Ce]).join(""))}}class Re extends De{constructor(P){super(),this.config=P,this.pattern=L(this.config.pattern,this.config.invert)}pre_tokenize_text(P,H){var ae;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ae=this.config.behavior)==null?void 0:ae.toLowerCase())==="removed"?P.split(this.pattern).filter(Me=>Me):b(P,this.pattern)}}class je extends De{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${g}]+|[${g}]+`,"gu")}pre_tokenize_text(P,H){return P.match(this.pattern)||[]}}class We extends De{constructor(P){super(),this.config=P;const H=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(H,"gu")}pre_tokenize_text(P,H){return P.match(this.pattern)||[]}}class Ne extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new ft(P);case"ByteLevel":return new dt(P);case"RobertaProcessing":return new at(P);case"BertProcessing":return new Ze(P);case"Sequence":return new gt(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...H){throw Error("post_process should be implemented in subclass.")}_call(P,...H){return this.post_process(P,...H)}}class Ze extends Ne{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,H=null,{add_special_tokens:ae=!0}={}){ae&&(P=(0,O.mergeArrays)([this.cls],P,[this.sep]));let Me=new Array(P.length).fill(0);if(H!==null){const Ce=ae&&this instanceof at?[this.sep]:[],He=ae?[this.sep]:[];P=(0,O.mergeArrays)(P,Ce,H,He),Me=(0,O.mergeArrays)(Me,new Array(H.length+Ce.length+He.length).fill(1))}return{tokens:P,token_type_ids:Me}}}class at extends Ze{}class ft extends Ne{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,H=null,{add_special_tokens:ae=!0}={}){const Me=H===null?this.single:this.pair;let Ce=[],He=[];for(const ct of Me)"SpecialToken"in ct?ae&&(Ce.push(ct.SpecialToken.id),He.push(ct.SpecialToken.type_id)):"Sequence"in ct&&(ct.Sequence.id==="A"?(Ce=(0,O.mergeArrays)(Ce,P),He=(0,O.mergeArrays)(He,new Array(P.length).fill(ct.Sequence.type_id))):ct.Sequence.id==="B"&&(Ce=(0,O.mergeArrays)(Ce,H),He=(0,O.mergeArrays)(He,new Array(H.length).fill(ct.Sequence.type_id))));return{tokens:Ce,token_type_ids:He}}}class dt extends Ne{post_process(P,H=null){return H&&(P=(0,O.mergeArrays)(P,H)),{tokens:P}}}class gt extends Ne{constructor(P){super(P),this.processors=P.processors.map(H=>Ne.fromConfig(H))}post_process(P,H=null,ae={}){let Me;for(const Ce of this.processors)if(Ce instanceof dt)P=Ce.post_process(P).tokens,H&&(H=Ce.post_process(H).tokens);else{const He=Ce.post_process(P,H,ae);P=He.tokens,Me=He.token_type_ids}return{tokens:P,token_type_ids:Me}}}class F extends f.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new Qe(P);case"Metaspace":return new nr(P);case"ByteLevel":return new st(P);case"Replace":return new ne(P);case"ByteFallback":return new K(P);case"Fuse":return new pe(P);case"Strip":return new Fe(P);case"Sequence":return new It(P);case"CTC":return new pt(P);case"BPEDecoder":return new St(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class ne extends F{decode_chain(P){const H=L(this.config.pattern);return H===null?P:P.map(ae=>ae.replaceAll(H,this.config.content))}}class K extends F{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const H=[];let ae=[];for(const Me of P){let Ce=null;if(Me.length===6&&Me.startsWith("<0x")&&Me.endsWith(">")){const He=parseInt(Me.slice(3,5),16);isNaN(He)||(Ce=He)}if(Ce!==null)ae.push(Ce);else{if(ae.length>0){const He=this.text_decoder.decode(Uint8Array.from(ae));H.push(He),ae=[]}H.push(Me)}}if(ae.length>0){const Me=this.text_decoder.decode(Uint8Array.from(ae));H.push(Me),ae=[]}return H}}class pe extends F{decode_chain(P){return[P.join("")]}}class Fe extends F{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(H=>{let ae=0;for(let Ce=0;Ce(ae!==0&&(H.startsWith(this.config.prefix)?H=H.replace(this.config.prefix,""):H=" "+H),this.cleanup&&(H=ie(H)),H))}}class st extends F{constructor(P){super(P),this.byte_decoder=xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const H=P.join(""),ae=new Uint8Array([...H].map(Ce=>this.byte_decoder[Ce]));return this.text_decoder.decode(ae)}decode_chain(P){const H=[];let ae=[];for(const Me of P)this.added_tokens.find(Ce=>Ce.content===Me)!==void 0?(ae.length>0&&(H.push(this.convert_tokens_to_string(ae)),ae=[]),H.push(Me)):ae.push(Me);return ae.length>0&&H.push(this.convert_tokens_to_string(ae)),H}}class pt extends F{constructor(P){super(P),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(P){if(P.length===0)return"";const H=[P[0]];for(let Ce=1;CeCe!==this.pad_token).join("");return this.cleanup&&(Me=ie(Me).replaceAll(this.word_delimiter_token," ").trim()),Me}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class It extends F{constructor(P){super(P),this.decoders=P.decoders.map(H=>F.fromConfig(H))}decode_chain(P){return this.decoders.reduce((H,ae)=>ae.decode_chain(H),P)}}class St extends F{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((H,ae)=>H.replaceAll(this.suffix,ae===P.length-1?"":" "))}}class Ft extends F{decode_chain(P){let H="";for(let ae=1;aeae.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class kr extends De{constructor(P){super(),this.tokenizers=P.pretokenizers.map(H=>De.fromConfig(H))}pre_tokenize_text(P,H){return this.tokenizers.reduce((ae,Me)=>Me.pre_tokenize(ae,H),[P])}}class Ar extends De{constructor(P){super()}pre_tokenize_text(P,H){return P.match(/\w+|[^\w\s]+/g)||[]}}class Qr extends De{constructor(P){super()}pre_tokenize_text(P,H){return $(P)}}class os extends De{constructor(P){super(),this.config=P,this.pattern=L(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,H){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Xs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function zs(Ee,P,H,ae){for(const Me of Object.keys(Ee)){const Ce=P-Ee[Me].length,He=H(Me),ct=new Array(Ce).fill(He);Ee[Me]=ae==="right"?(0,O.mergeArrays)(Ee[Me],ct):(0,O.mergeArrays)(ct,Ee[Me])}}function Ms(Ee,P){for(const H of Object.keys(Ee))Ee[H].length=P}class Nt extends f.Callable{constructor(H,ae){super();ge(this,"return_token_type_ids",!1);ge(this,"padding_side","right");this._tokenizer_config=ae,this.normalizer=Ue.fromConfig(H.normalizer),this.pre_tokenizer=De.fromConfig(H.pre_tokenizer),this.model=le.fromConfig(H.model,ae),this.post_processor=Ne.fromConfig(H.post_processor),this.decoder=F.fromConfig(H.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Me of H.added_tokens){const Ce=new J(Me);this.added_tokens.push(Ce),this.model.tokens_to_ids.set(Ce.content,Ce.id),this.model.vocab[Ce.id]=Ce.content,Ce.special&&(this.special_tokens.push(Ce.content),this.all_special_ids.push(Ce.id))}if(this.additional_special_tokens=ae.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((Me,Ce)=>Ce.content.length-Me.content.length).map(Me=>`${Me.lstrip?"\\s*":""}(${(0,O.escapeRegExp)(Me.content)})${Me.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=ae.model_max_length,this.remove_space=ae.remove_space,this.clean_up_tokenization_spaces=ae.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ae.do_lowercase_and_remove_accent??!1,ae.padding_side&&(this.padding_side=ae.padding_side),this.legacy=!1,this.chat_template=ae.chat_template??null,Array.isArray(this.chat_template)){const Me=Object.create(null);for(const{name:Ce,template:He}of this.chat_template){if(typeof Ce!="string"||typeof He!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Me[Ce]=He}this.chat_template=Me}this._compiled_template_cache=new Map}getToken(...H){for(const ae of H){const Me=this._tokenizer_config[ae];if(Me)if(typeof Me=="object"){if(Me.__type==="AddedToken")return Me.content;throw Error(`Unknown token: ${Me}`)}else return Me}return null}static async from_pretrained(H,{progress_callback:ae=null,config:Me=null,cache_dir:Ce=null,local_files_only:He=!1,revision:ct="main",legacy:yt=null}={}){const ht=await M(H,{progress_callback:ae,config:Me,cache_dir:Ce,local_files_only:He,revision:ct,legacy:yt});return new this(...ht)}_call(H,{text_pair:ae=null,add_special_tokens:Me=!0,padding:Ce=!1,truncation:He=null,max_length:ct=null,return_tensor:yt=!0,return_token_type_ids:ht=null}={}){const it=Array.isArray(H);let Pt;if(it){if(H.length===0)throw Error("text array must be non-empty");if(ae!==null){if(Array.isArray(ae)){if(H.length!==ae.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Pt=H.map((rr,$e)=>this._encode_plus(rr,{text_pair:ae[$e],add_special_tokens:Me,return_token_type_ids:ht}))}else Pt=H.map(rr=>this._encode_plus(rr,{add_special_tokens:Me,return_token_type_ids:ht}))}else{if(H==null)throw Error("text may not be null or undefined");if(Array.isArray(ae))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Pt=[this._encode_plus(H,{text_pair:ae,add_special_tokens:Me,return_token_type_ids:ht})]}if(ct===null?Ce==="max_length"?ct=this.model_max_length:ct=(0,Q.max)(Pt.map(rr=>rr.input_ids.length))[0]:He||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."),ct=Math.min(ct,this.model_max_length??1/0),Ce||He)for(let rr=0;rrct?He&&Ms(Pt[rr],ct):Ce&&zs(Pt[rr],ct,$e=>$e==="input_ids"?this.pad_token_id:0,this.padding_side));const hr={};if(yt){if(!(Ce&&He)&&Pt.some($e=>{var wr;for(const Rr of Object.keys($e))if($e[Rr].length!==((wr=Pt[0][Rr])==null?void 0:wr.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 rr=[Pt.length,Pt[0].input_ids.length];for(const $e of Object.keys(Pt[0]))hr[$e]=new U.Tensor("int64",BigInt64Array.from(Pt.flatMap(wr=>wr[$e]).map(BigInt)),rr)}else{for(const rr of Object.keys(Pt[0]))hr[rr]=Pt.map($e=>$e[rr]);if(!it)for(const rr of Object.keys(hr))hr[rr]=hr[rr][0]}return hr}_encode_text(H){return H===null?null:(this.added_tokens_regex?H.split(this.added_tokens_regex).filter(Ce=>Ce):[H]).map((Ce,He)=>{if(this.added_tokens.find(yt=>yt.content===Ce)!==void 0)return Ce;{if(this.remove_space===!0&&(Ce=Ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Ce=W(Ce)),this.normalizer!==null&&(Ce=this.normalizer(Ce)),Ce.length===0)return[];const yt=this.pre_tokenizer!==null?this.pre_tokenizer(Ce,{section_index:He}):[Ce];return this.model(yt)}}).flat()}_encode_plus(H,{text_pair:ae=null,add_special_tokens:Me=!0,return_token_type_ids:Ce=null}={}){const{tokens:He,token_type_ids:ct}=this._tokenize_helper(H,{pair:ae,add_special_tokens:Me}),yt=this.model.convert_tokens_to_ids(He),ht={input_ids:yt,attention_mask:new Array(yt.length).fill(1)};return(Ce??this.return_token_type_ids)&&ct&&(ht.token_type_ids=ct),ht}_tokenize_helper(H,{pair:ae=null,add_special_tokens:Me=!1}={}){const Ce=this._encode_text(H),He=this._encode_text(ae);return this.post_processor?this.post_processor(Ce,He,{add_special_tokens:Me}):{tokens:(0,O.mergeArrays)(Ce??[],He??[])}}tokenize(H,{pair:ae=null,add_special_tokens:Me=!1}={}){return this._tokenize_helper(H,{pair:ae,add_special_tokens:Me}).tokens}encode(H,{text_pair:ae=null,add_special_tokens:Me=!0,return_token_type_ids:Ce=null}={}){return this._encode_plus(H,{text_pair:ae,add_special_tokens:Me,return_token_type_ids:Ce}).input_ids}batch_decode(H,ae={}){return H instanceof U.Tensor&&(H=H.tolist()),H.map(Me=>this.decode(Me,ae))}decode(H,ae={}){if(H instanceof U.Tensor&&(H=se(H)),!Array.isArray(H)||H.length===0||!(0,O.isIntegralNumber)(H[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(H,ae)}decode_single(H,{skip_special_tokens:ae=!1,clean_up_tokenization_spaces:Me=null}){let Ce=this.model.convert_ids_to_tokens(H);ae&&(Ce=Ce.filter(ct=>!this.special_tokens.includes(ct)));let He=this.decoder?this.decoder(Ce):Ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(He=He.replaceAll(this.decoder.end_of_word_suffix," "),ae&&(He=He.trim())),(Me??this.clean_up_tokenization_spaces)&&(He=ie(He)),He}get_chat_template({chat_template:H=null,tools:ae=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Me=this.chat_template;if(H!==null&&Object.hasOwn(Me,H))H=Me[H];else if(H===null)if(ae!==null&&"tool_use"in Me)H=Me.tool_use;else if("default"in Me)H=Me.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(Me).sort()}.`)}else if(H===null)if(this.chat_template)H=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co./docs/transformers/main/en/chat_templating");return H}apply_chat_template(H,{tools:ae=null,documents:Me=null,chat_template:Ce=null,add_generation_prompt:He=!1,tokenize:ct=!0,padding:yt=!1,truncation:ht=!1,max_length:it=null,return_tensor:Pt=!0,return_dict:hr=!1,tokenizer_kwargs:rr={},...$e}={}){if(Ce=this.get_chat_template({chat_template:Ce,tools:ae}),typeof Ce!="string")throw Error(`chat_template must be a string, but got ${typeof Ce}`);let wr=this._compiled_template_cache.get(Ce);wr===void 0&&(wr=new v.Template(Ce),this._compiled_template_cache.set(Ce,wr));const Rr=Object.create(null);for(const Zr of Xs){const Bt=this.getToken(Zr);Bt&&(Rr[Zr]=Bt)}const Jr=wr.render({messages:H,add_generation_prompt:He,tools:ae,documents:Me,...Rr,...$e});if(ct){const Zr=this._call(Jr,{add_special_tokens:!1,padding:yt,truncation:ht,max_length:it,return_tensor:Pt,...rr});return hr?Zr:Zr.input_ids}return Jr}}class Qs extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class ks extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Bs extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Ss extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class is extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class $s extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class cs extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class As extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class Ys extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class as extends Nt{}class nt extends Nt{}class _t extends Nt{constructor(H,ae){super(H,ae);ge(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 Ot extends Nt{constructor(){super(...arguments);ge(this,"return_token_type_ids",!0)}}class lr extends Nt{}class bs extends Nt{}class tr extends Nt{}class ts extends Nt{constructor(P,H){super(P,H),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,H,ae){return en(this,P,H,ae)}}class Rs extends ts{}class Js extends Nt{}class Ns extends Nt{}const vs="▁";class Sn extends Nt{constructor(H,ae){super(H,ae);ge(this,"padding_side","left");this.legacy=ae.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:vs,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(H){if(H===null)return null;if(this.legacy||H.length===0)return super._encode_text(H);let ae=super._encode_text(vs+H.replaceAll(vs," "));return ae.length>1&&ae[0]===vs&&this.special_tokens.includes(ae[1])&&(ae=ae.slice(1)),ae}}class js extends Nt{}class $n extends Nt{}class Jn extends Nt{}class Us extends Nt{}class Ts extends Nt{}class ls extends Nt{}class mn extends Nt{}class Zs extends Nt{}class _n extends Nt{}function en(Ee,P,H,ae){if(!("language_codes"in Ee)||!Array.isArray(Ee.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ee)||!(Ee.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ee)||typeof Ee.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Me=ae.src_lang,Ce=ae.tgt_lang;if(!Ee.language_codes.includes(Ce))throw new Error(`Target language code "${Ce}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);if(Me!==void 0){if(!Ee.language_codes.includes(Me))throw new Error(`Source language code "${Me}" is not valid. Must be one of: {${Ee.language_codes.join(", ")}}`);for(const He of Ee.post_processor.config.single)if("SpecialToken"in He&&Ee.languageRegex.test(He.SpecialToken.id)){He.SpecialToken.id=Ee.lang_to_token(Me);break}}return ae.forced_bos_token_id=Ee.model.convert_tokens_to_ids([Ee.lang_to_token(Ce)])[0],Ee._call(P,H)}class xs extends Nt{constructor(P,H){super(P,H),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)),this.lang_to_token=ae=>ae}_build_translation_inputs(P,H,ae){return en(this,P,H,ae)}}class zt extends Nt{constructor(P,H){super(P,H),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ae=>this.languageRegex.test(ae)).map(ae=>ae.slice(2,-2)),this.lang_to_token=ae=>`__${ae}__`}_build_translation_inputs(P,H,ae){return en(this,P,H,ae)}}class fn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:H=!1,return_language:ae=!1,time_precision:Me=null,force_full_sequences:Ce=!0}={}){if(Me===null)throw Error("Must specify time_precision");let He=null;const ct=H==="word";function yt(){return{language:He,timestamp:[null,null],text:""}}const ht=[];let it=yt(),Pt=0;const hr=this.timestamp_begin,$e=hr+1500;let wr=[],Rr=[],Jr=!1,Zr=null;const Bt=new Set(this.all_special_ids);for(const er of P){const mr=er.tokens,vt=ct?er.token_timestamps:null;let yr=null,Es=hr;if("stride"in er){const[Mt,br,ze]=er.stride;if(Pt-=br,Zr=Mt-ze,br&&(Es=br/Me+hr),ze)for(let wt=mr.length-1;wt>=0;--wt){const rs=Number(mr[wt]);if(rs>=hr){if(yr!==null&&(rs-hr)*Me=hr&&br<=$e){const ze=(br-hr)*Me+Pt,wt=(0,Q.round)(ze,2);if(yr!==null&&br>=yr)Jr=!0;else if(Jr||wr.length>0&&br0?(wr.push(Fr),ct&&Rr.push(qr)):wr.every(Mt=>Mt.length===0)&&(it=yt(),wr=[],Fr=[],Rr=[],qr=[])}if(wr.length>0){if(Ce&&H)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[er,mr]=this.findLongestCommonSequence(wr,Rr),vt=this.decode(er);it.text=vt,ct&&(it.words=this.collateWordTimestamps(er,mr,He)),ht.push(it)}let Nr=Object.create(null);const ps=ht.map(er=>er.text).join("");if(H||ae){for(let er=0;er0;let ct=He?[]:null,yt=He?H[0]:null;for(let ht=1;htbr===Es[ze]&&yt[ps+ze]<=H[ht][vt+ze]).length:Fr=mr.filter((br,ze)=>br===Es[ze]).length;const qr=Nr/1e4,Mt=Fr/Nr+qr;Fr>1&&Mt>Pt&&(Pt=Mt,hr=[ps,er,vt,yr])}const[$e,wr,Rr,Jr]=hr,Zr=Math.floor((wr+$e)/2),Bt=Math.floor((Jr+Rr)/2);Ce.push(...ae.slice(0,Zr)),ae=it.slice(Bt),Me=ae.length,He&&(ct.push(...yt.slice(0,Zr)),yt=H[ht].slice(Bt))}return Ce.push(...ae),He?(ct.push(...yt),[Ce,ct]):[Ce,[]]}collateWordTimestamps(P,H,ae){const[Me,Ce,He]=this.combineTokensIntoWords(P,ae),ct=[];for(let yt=0;yt=Me){const ct=((He-Me)*ae).toFixed(2);Ce.push(`<|${ct}|>`),Ce.push([])}else Ce[Ce.length-1].push(He);return Ce=Ce.map(He=>typeof He=="string"?He:super.decode(He,H)),Ce.join("")}splitTokensOnUnicode(P){const H=this.decode(P,{decode_with_timestamps:!0}),ae="�",Me=[],Ce=[],He=[];let ct=[],yt=[],ht=0;for(let it=0;it=this.model.tokens_to_ids.get("<|endoftext|>"),$e=it.startsWith(" "),wr=it.trim(),Rr=yt.test(wr);if(rr||$e||Rr||Ce.length===0)Ce.push(it),He.push(Pt),ct.push(hr);else{const Jr=Ce.length-1;Ce[Jr]+=it,He[Jr].push(...Pt),ct[Jr].push(...hr)}}return[Ce,He,ct]}mergePunctuations(P,H,ae,Me,Ce){const He=structuredClone(P),ct=structuredClone(H),yt=structuredClone(ae);let ht=He.length-2,it=He.length-1;for(;ht>=0;)He[ht].startsWith(" ")&&Me.includes(He[ht].trim())?(He[it]=He[ht]+He[it],ct[it]=(0,O.mergeArrays)(ct[ht],ct[it]),yt[it]=(0,O.mergeArrays)(yt[ht],yt[it]),He[ht]="",ct[ht]=[],yt[ht]=[]):it=ht,--ht;for(ht=0,it=1;itPt),ct.filter(Pt=>Pt.length>0),yt.filter(Pt=>Pt.length>0)]}}class An extends Nt{}class In extends Nt{}class On extends Nt{}class Vs extends Nt{constructor(P,H){super(P,H),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ae=>this.languageRegex.test(ae)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[H,...ae]=P.trim().split(this.languageRegex);if(ae.length===0)return super._encode_text(H);if(ae.length===2){const[Me,Ce]=ae;return this.supported_language_codes.includes(Me)||console.warn(`Unsupported language code "${Me}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,O.mergeArrays)([Me],super._encode_text(Ce))}}}class Fn extends Nt{}class gn extends Nt{}class Dn extends Nt{}class ir extends Nt{}class Yr extends Nt{}class wn extends Nt{constructor(P,H){super(P,H),this.decoder=new Ft({})}}class Ln extends Nt{}class yn extends Nt{}class Mn{static async from_pretrained(P,{progress_callback:H=null,config:ae=null,cache_dir:Me=null,local_files_only:Ce=!1,revision:He="main",legacy:ct=null}={}){var hr;const[yt,ht]=await M(P,{progress_callback:H,config:ae,cache_dir:Me,local_files_only:Ce,revision:He,legacy:ct}),it=((hr=ht.tokenizer_class)==null?void 0:hr.replace(/Fast$/,""))??"PreTrainedTokenizer";let Pt=this.TOKENIZER_CLASS_MAPPING[it];return Pt||(console.warn(`Unknown tokenizer class "${it}", attempting to construct from base class.`),Pt=Nt),new Pt(yt,ht)}}ge(Mn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:lr,DistilBertTokenizer:as,CamembertTokenizer:nt,DebertaTokenizer:is,DebertaV2Tokenizer:$s,BertTokenizer:Qs,HerbertTokenizer:cs,ConvBertTokenizer:As,RoFormerTokenizer:Ys,XLMTokenizer:_t,ElectraTokenizer:Ot,MobileBertTokenizer:Bs,SqueezeBertTokenizer:Ss,AlbertTokenizer:ks,GPT2Tokenizer:bs,BartTokenizer:tr,MBartTokenizer:ts,MBart50Tokenizer:Rs,RobertaTokenizer:Js,WhisperTokenizer:fn,CodeGenTokenizer:An,CLIPTokenizer:In,SiglipTokenizer:On,MarianTokenizer:Vs,BloomTokenizer:Ns,NllbTokenizer:xs,M2M100Tokenizer:zt,LlamaTokenizer:Sn,CodeLlamaTokenizer:js,XLMRobertaTokenizer:$n,MPNetTokenizer:Jn,FalconTokenizer:Us,GPTNeoXTokenizer:Ts,EsmTokenizer:ls,Wav2Vec2CTCTokenizer:Fn,BlenderbotTokenizer:gn,BlenderbotSmallTokenizer:Dn,SpeechT5Tokenizer:ir,NougatTokenizer:Yr,VitsTokenizer:wn,Qwen2Tokenizer:mn,GemmaTokenizer:Zs,Grok1Tokenizer:_n,CohereTokenizer:Ln,MgpstrTokenizer:yn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(Te,A,s)=>{s.r(A),s.d(A,{hamming:()=>y,hanning:()=>v,mel_filter_bank:()=>z,read_audio:()=>U,spectrogram:()=>g,window_function:()=>C});var f=s("./src/utils/hub.js"),O=s("./src/utils/maths.js"),N=s("./src/utils/core.js"),Q=s("./src/utils/tensor.js");async function U(T,ee){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 J=await(await(0,f.getFile)(T)).arrayBuffer(),le=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${le.sampleRate}Hz.`);const de=await le.decodeAudioData(J);let fe;if(de.numberOfChannels===2){const ke=Math.sqrt(2),xe=de.getChannelData(0),Le=de.getChannelData(1);fe=new Float32Array(xe.length);for(let qe=0;qe2595*Math.log10(1+T/700),kaldi:T=>1127*Math.log(1+T/700),slaney:(T,ee=1e3,J=15,le=27/Math.log(6.4))=>T>=ee?J+Math.log(T/ee)*le:3*T/200};function b(T,ee="htk"){const J=M[ee];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?J(T):T.map(le=>J(le))}const L={htk:T=>700*(10**(T/2595)-1),kaldi:T=>700*(Math.exp(T/1127)-1),slaney:(T,ee=1e3,J=15,le=Math.log(6.4)/27)=>T>=J?ee*Math.exp(le*(T-J)):200*T/3};function q(T,ee="htk"){const J=L[ee];if(!J)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof T=="number"?J(T):T.map(le=>J(le))}function se(T,ee){const J=Float64Array.from({length:ee.length-1},(ke,xe)=>ee[xe+1]-ee[xe]),le=Array.from({length:T.length},()=>new Array(ee.length));for(let ke=0;kenew Array(T.length));for(let ke=0;keT+le*fe)}function z(T,ee,J,le,de,fe=null,ke="htk",xe=!1){if(fe!==null&&fe!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=b(J,ke),qe=b(le,ke),Ue=ie(Le,qe,ee+2);let ut=q(Ue,ke),ue;if(xe){const he=de/(T*2);ue=b(Float64Array.from({length:T},(Pe,Be)=>Be*he),ke),ut=Ue}else ue=ie(0,Math.floor(de/2),T);const re=se(ue,ut);if(fe!==null&&fe==="slaney")for(let he=0;hede)throw Error(`frame_length (${J}) may not be larger than fft_length (${de})`);if(De!==J)throw new Error(`Length of the window (${De}) must equal frame_length (${J})`);if(le<=0)throw new Error("hop_length must be greater than zero");if(fe===null&&Ue!==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(ke){if(xe!=="reflect")throw new Error(`pad_mode="${xe}" not implemented yet.`);const F=Math.floor((de-1)/2)+1;T=W(T,F,F)}let ce=Math.floor(1+Math.floor((T.length-J)/le));et!==null&&cece?oe&&(je=Xe):je=Re=Xe);const We=new O.FFT(de),Ne=new Float64Array(de),Ze=new Float64Array(We.outputBufferSize),at=new Float32Array(ve*je);for(let F=0;F=1;--pe)Ne[pe]-=qe*Ne[pe-1];Ne[0]*=1-qe}for(let pe=0;peMath.pow(xe,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(J&&(ke=ke.subarray(0,T)),le===null)return ke;if(T>le)throw new Error(`Length of the window (${T}) may not be larger than frame_length (${le})`);return ke}},"./src/utils/constants.js":(Te,A,s)=>{s.r(A),s.d(A,{CHAT_TEMPLATE_NAME:()=>w,CONFIG_NAME:()=>O,FEATURE_EXTRACTOR_NAME:()=>N,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>f,IMAGE_PROCESSOR_NAME:()=>Q,PROCESSOR_NAME:()=>U});const f="https://github.com/huggingface/transformers.js/issues/new/choose",O="config.json",N="preprocessor_config.json",Q=N,U="processor_config.json",w="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(Te,A,s)=>{s.r(A),s.d(A,{calculateDimensions:()=>v,calculateReflectOffset:()=>L,count:()=>ie,dispatchCallback:()=>f,escapeRegExp:()=>N,isIntegralNumber:()=>U,isNullishDimension:()=>w,isTypedArray:()=>Q,len:()=>se,mergeArrays:()=>M,pick:()=>q,pop:()=>y,product:()=>b,reverseDictionary:()=>O});function f(z,W){z&&z(W)}function O(z){return Object.fromEntries(Object.entries(z).map(([W,Y])=>[Y,W]))}function N(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q(z){var W,Y,D;return((D=(Y=(W=z==null?void 0:z.prototype)==null?void 0:W.__proto__)==null?void 0:Y.constructor)==null?void 0:D.name)==="TypedArray"}function U(z){return Number.isInteger(z)||typeof z=="bigint"}function w(z){return z==null||z===-1}function v(z){const W=[];let Y=z;for(;Array.isArray(Y);)W.push(Y.length),Y=Y[0];return W}function y(z,W,Y=void 0){const D=z[W];if(D!==void 0)return delete z[W],D;if(Y===void 0)throw Error(`Key ${W} does not exist in object.`);return Y}function M(...z){return Array.prototype.concat.apply([],z)}function b(...z){return z.reduce((W,Y)=>W.flatMap(D=>Y.map($=>[D,$])))}function L(z,W){return Math.abs((z+W)%(2*W)-W)}function q(z,W){return Object.assign({},...W.map(Y=>{if(z[Y]!==void 0)return{[Y]:z[Y]}}))}function se(z){let W=0;for(const Y of z)++W;return W}function ie(z,W){let Y=0;for(const D of z)D===W&&++Y;return Y}},"./src/utils/data-structures.js":(Te,A,s)=>{s.r(A),s.d(A,{CharTrie:()=>O,PriorityQueue:()=>f,TokenLattice:()=>Q});class f{constructor(v=(M,b)=>M>b,y=1/0){this._heap=[],this._comparator=v,this._maxSize=y}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...v){return this.extend(v)}extend(v){for(const y of v)if(this.size0&&this._swap(0,y),this._heap.pop(),this._siftDown(),v}replace(v){const y=this.peek();return this._heap[0]=v,this._siftDown(),y}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,y){return this._comparator(this._heap[v],this._heap[y])}_swap(v,y){const M=this._heap[v];this._heap[v]=this._heap[y],this._heap[y]=M}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(v){for(;v>0&&this._greater(v,this._parent(v));)this._swap(v,this._parent(v)),v=this._parent(v)}_siftDown(){let v=0;for(;this._left(v)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const b=new U(this.bosTokenId,0,0,0,0),L=new U(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(L.clone()),this.beginNodes[this.len].push(L),this.endNodes[0].push(b)}insert(v,y,M,b){const L=this.nodes.length,q=new U(b,L,v,y,M);this.beginNodes[v].push(q),this.endNodes[v+y].push(q),this.nodes.push(q)}viterbi(){const v=this.len;let y=0;for(;y<=v;){if(this.beginNodes[y].length==0)return[];for(let se of this.beginNodes[y]){se.prev=null;let ie=0,z=null;for(let W of this.endNodes[y]){const Y=W.backtraceScore+se.score;(z===null||Y>ie)&&(z=W.clone(),ie=Y)}if(z!==null)se.prev=z,se.backtraceScore=ie;else return[]}++y}const M=[],L=this.beginNodes[v][0].prev;if(L===null)return[];let q=L.clone();for(;q.prev!==null;)M.push(q.clone()),q=q.clone().prev.clone();return M.reverse(),M}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(y=>this.piece(y))}tokenIds(){return this.viterbi().map(y=>y.tokenId)}}class U{constructor(v,y,M,b,L){this.tokenId=v,this.nodeId=y,this.pos=M,this.length=b,this.score=L,this.prev=null,this.backtraceScore=0}clone(){const v=new U(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(Te,A,s)=>{s.r(A),s.d(A,{DEVICE_TYPES:()=>f});const f=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":(Te,A,s)=>{s.r(A),s.d(A,{DATA_TYPES:()=>Q,DEFAULT_DEVICE_DTYPE_MAPPING:()=>U,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>w,isWebGpuFp16Supported:()=>N});var f=s("./src/env.js"),O=s("./src/utils/devices.js");const N=function(){let v;return async function(){if(v===void 0)if(!f.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),Q=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),U=Object.freeze({[O.DEVICE_TYPES.wasm]:Q.q8}),w=Object.freeze({[Q.fp32]:"",[Q.fp16]:"_fp16",[Q.int8]:"_int8",[Q.uint8]:"_uint8",[Q.q8]:"_quantized",[Q.q4]:"_q4",[Q.q4f16]:"_q4f16",[Q.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Te,A,s)=>{s.r(A),s.d(A,{Callable:()=>f});const f=class{constructor(){let O=function(...N){return O._call(...N)};return Object.setPrototypeOf(O,new.target.prototype)}_call(...O){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Te,A,s)=>{s.r(A),s.d(A,{getFile:()=>y,getModelFile:()=>se,getModelJSON:()=>ie});var f=s("?7a2c"),O=s("?a42a"),N=s("./src/env.js"),Q=s("./src/utils/core.js");const U={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 w{constructor(D){if(this.filePath=D,this.headers=new Headers,this.exists=f.existsSync(D),this.exists){this.status=200,this.statusText="OK";let $=f.statSync(D);this.headers.set("content-length",$.size.toString()),this.updateContentType();let g=this;this.body=new ReadableStream({start(C){g.arrayBuffer().then(T=>{C.enqueue(new Uint8Array(T)),C.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const D=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",U[D]??"application/octet-stream")}clone(){let D=new w(this.filePath);return D.exists=this.exists,D.status=this.status,D.statusText=this.statusText,D.headers=new Headers(this.headers),D}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){const D=await f.promises.readFile(this.filePath);return new Blob([D],{type:this.headers.get("content-type")})}async text(){return await f.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(Y,D=null,$=null){let g;try{g=new URL(Y)}catch{return!1}return!(D&&!D.includes(g.protocol)||$&&!$.includes(g.hostname))}async function y(Y){var D;if(N.env.useFS&&!v(Y,["http:","https:","blob:"]))return new w(Y);if(typeof process<"u"&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node"){const $=!!(Pn!=null&&Pn.TESTING_REMOTELY),g=N.env.version,C=new Headers;if(C.set("User-Agent",`transformers.js/${g}; is_ci/${$};`),v(Y,["http:","https:"],["huggingface.co","hf.co"])){const ee=(Pn==null?void 0:Pn.HF_TOKEN)??(Pn==null?void 0:Pn.HF_ACCESS_TOKEN);ee&&C.set("Authorization",`Bearer ${ee}`)}return fetch(Y,{headers:C})}else return fetch(Y)}const M={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 b(Y,D,$){if(!$)return null;const g=M[Y]??`Error (${Y}) occurred while trying to load file`;throw Error(`${g}: "${D}".`)}class L{constructor(D){this.path=D}async match(D){let $=O.join(this.path,D),g=new w($);if(g.exists)return g}async put(D,$){const g=Buffer.from(await $.arrayBuffer());let C=O.join(this.path,D);try{await f.promises.mkdir(O.dirname(C),{recursive:!0}),await f.promises.writeFile(C,g)}catch(T){console.warn("An error occurred while writing the file to cache:",T)}}}async function q(Y,...D){for(let $ of D)try{let g=await Y.match($);if(g)return g}catch{continue}}async function se(Y,D,$=!0,g={}){if(!N.env.allowLocalModels){if(g.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(!N.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,Q.dispatchCallback)(g.progress_callback,{status:"initiate",name:Y,file:D});let C;if(!C&&N.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{C=await caches.open("transformers-cache")}catch(ut){console.warn("An error occurred while opening the browser cache:",ut)}}if(!C&&N.env.useFSCache&&(C=new L(g.cache_dir??N.env.cacheDir)),!C&&N.env.useCustomCache){if(!N.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.env.customCache.match||!N.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");C=N.env.customCache}const T=g.revision??"main";let ee=W(Y,D),J=W(N.env.localModelPath,ee),le=W(N.env.remoteHost,N.env.remotePathTemplate.replaceAll("{model}",Y).replaceAll("{revision}",encodeURIComponent(T)),D),de=T==="main"?ee:W(Y,T,D),fe,ke=C instanceof L?de:le,xe=!1,Le;C&&(Le=await q(C,J,ke));const qe=Le!==void 0;if(Le===void 0){if(N.env.allowLocalModels)if(v(ee,["http:","https:"])){if(g.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!N.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{Le=await y(J),fe=J}catch(ue){console.warn(`Unable to load from local path "${J}": "${ue}"`)}if(Le===void 0||Le.status===404){if(g.local_files_only||!N.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(Le=await y(le),Le.status!==200)return b(Le.status,le,$);fe=ke}xe=C&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,Q.dispatchCallback)(g.progress_callback,{status:"download",name:Y,file:D});let Ue;return g.progress_callback?qe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ue=new Uint8Array(await Le.arrayBuffer()),(0,Q.dispatchCallback)(g.progress_callback,{status:"progress",name:Y,file:D,progress:100,loaded:Ue.length,total:Ue.length})):Ue=await z(Le,ut=>{(0,Q.dispatchCallback)(g.progress_callback,{status:"progress",name:Y,file:D,...ut})}):Ue=new Uint8Array(await Le.arrayBuffer()),xe&&fe&&await C.match(fe)===void 0&&await C.put(fe,new Response(Ue,{headers:Le.headers})).catch(ut=>{console.warn(`Unable to add response to browser cache: ${ut}.`)}),(0,Q.dispatchCallback)(g.progress_callback,{status:"done",name:Y,file:D}),Ue}async function ie(Y,D,$=!0,g={}){let C=await se(Y,D,$,g);if(C===null)return{};let ee=new TextDecoder("utf-8").decode(C);return JSON.parse(ee)}async function z(Y,D){const $=Y.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let g=parseInt($??"0"),C=new Uint8Array(g),T=0;const ee=Y.body.getReader();async function J(){const{done:le,value:de}=await ee.read();if(le)return;let fe=T+de.length;if(fe>g){g=fe;let xe=new Uint8Array(g);xe.set(C),C=xe}C.set(de,T),T=fe;const ke=T/g*100;return D({progress:ke,loaded:T,total:g}),J()}return await J(),C}function W(...Y){return Y=Y.map((D,$)=>($&&(D=D.replace(new RegExp("^/"),"")),$!==Y.length-1&&(D=D.replace(new RegExp("/$"),"")),D)),Y.join("/")}},"./src/utils/image.js":(Te,A,s)=>{s.r(A),s.d(A,{RawImage:()=>q,load_image:()=>se});var f=s("./src/utils/core.js"),O=s("./src/utils/hub.js"),N=s("./src/env.js"),Q=s("./src/utils/tensor.js"),U=s("?2b25");let w,v,y;const M=N.apis.IS_BROWSER_ENV||N.apis.IS_WEBWORKER_ENV;if(M)w=(ie,z)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ie,z)},y=self.createImageBitmap,v=self.ImageData;else if(U)y=async ie=>{const W=(await ie.metadata()).channels,{data:Y,info:D}=await ie.rotate().raw().toBuffer({resolveWithObject:!0}),$=new q(new Uint8ClampedArray(Y),D.width,D.height,D.channels);return W!==void 0&&W!==D.channels&&$.convert(W),$};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},L=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class q{constructor(z,W,Y,D){this.data=z,this.width=W,this.height=Y,this.channels=D}get size(){return[this.width,this.height]}static async read(z){if(z instanceof q)return z;if(typeof z=="string"||z instanceof URL)return await this.fromURL(z);throw new Error(`Unsupported input type: ${typeof z}`)}static fromCanvas(z){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const Y=z.getContext("2d").getImageData(0,0,z.width,z.height).data;return new q(Y,z.width,z.height,4)}static async fromURL(z){const W=await(0,O.getFile)(z);if(W.status!==200)throw new Error(`Unable to read image from "${z}" (${W.status} ${W.statusText})`);const Y=await W.blob();return this.fromBlob(Y)}static async fromBlob(z){if(M){const W=await y(z),Y=w(W.width,W.height).getContext("2d");return Y.drawImage(W,0,0),new this(Y.getImageData(0,0,W.width,W.height).data,W.width,W.height,4)}else{const W=U(await z.arrayBuffer());return await y(W)}}static fromTensor(z,W="CHW"){if(z.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${z.dims.length} dimensions.`);if(W==="CHW")z=z.transpose(1,2,0);else if(W!=="HWC")throw new Error(`Unsupported channel format: ${W}`);if(!(z.data instanceof Uint8ClampedArray||z.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${z.type}`);switch(z.dims[2]){case 1:case 2:case 3:case 4:return new q(z.data,z.dims[1],z.dims[0],z.dims[2]);default:throw new Error(`Unsupported number of channels: ${z.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const z=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let W=0,Y=0;W=0?T=Y:J=-Y,D>=0?ee=D:le=-D,C.drawImage(g,T,ee,z,W,J,le,z,W),new q(C.getImageData(0,0,z,W).data,z,W,4).convert($)}else{let $=this.toSharp();if(Y>=0&&D>=0)$=$.extract({left:Math.floor(Y),top:Math.floor(D),width:z,height:W});else if(Y<=0&&D<=0){const g=Math.floor(-D),C=Math.floor(-Y);$=$.extend({top:g,left:C,right:z-this.width-C,bottom:W-this.height-g})}else{let g=[0,0],C=0;D<0?(g[0]=Math.floor(-D),g[1]=W-this.height-g[0]):C=Math.floor(D);let T=[0,0],ee=0;Y<0?(T[0]=Math.floor(-Y),T[1]=z-this.width-T[0]):ee=Math.floor(Y),$=$.extend({top:g[0],bottom:g[1],left:T[0],right:T[1]}).extract({left:ee,top:C,width:z,height:W})}return await y($)}}async toBlob(z="image/png",W=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:z,quality:W})}toTensor(z="CHW"){let W=new Q.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(z!=="HWC")if(z==="CHW")W=W.permute(2,0,1);else throw new Error(`Unsupported channel format: ${z}`);return W}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const z=this.clone().rgba(),W=w(z.width,z.height),Y=new v(z.data,z.width,z.height);return W.getContext("2d").putImageData(Y,0,0),W}split(){const{data:z,width:W,height:Y,channels:D}=this,$=z.constructor,g=z.length/D,C=Array.from({length:D},()=>new $(g));for(let T=0;Tnew q(T,W,Y,1))}_update(z,W,Y,D=null){return this.data=z,this.width=W,this.height=Y,D!==null&&(this.channels=D),this}clone(){return new q(this.data.slice(),this.width,this.height,this.channels)}convert(z){if(this.channels===z)return this;switch(z){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(z){if(M){if(N.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const W=z.split(".").pop().toLowerCase(),Y=L.get(W)??"image/png",D=await this.toBlob(Y),$=URL.createObjectURL(D),g=document.createElement("a");g.href=$,g.download=z,g.click(),g.remove()}else{if(N.env.useFS)return await this.toSharp().toFile(z);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(M)throw new Error("toSharp() is only supported in server-side environments.");return U(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const se=q.read.bind(q)},"./src/utils/maths.js":(Te,A,s)=>{s.r(A),s.d(A,{FFT:()=>se,bankers_round:()=>W,cos_sim:()=>w,dot:()=>U,dynamic_time_warping:()=>Y,interpolate_data:()=>f,log_softmax:()=>Q,magnitude:()=>v,max:()=>M,medianFilter:()=>ie,min:()=>y,permute_data:()=>O,round:()=>z,softmax:()=>N});function f(D,[$,g,C],[T,ee],J="bilinear",le=!1){const de=ee/C,fe=T/g,ke=new D.constructor(T*ee*$),xe=g*C,Le=T*ee;for(let qe=0;qe=0;--le)T[le]=de,C[le]=$[g[le]],de*=C[le];const ee=g.map((le,de)=>T[g.indexOf(de)]),J=new D.constructor(D.length);for(let le=0;le=0;--fe)de+=ke%$[fe]*ee[fe],ke=Math.floor(ke/$[fe]);J[de]=D[le]}return[J,C]}function N(D){const $=M(D)[0],g=D.map(ee=>Math.exp(ee-$)),C=g.reduce((ee,J)=>ee+J,0);return g.map(ee=>ee/C)}function Q(D){const $=M(D)[0];let g=0;for(let ee=0;eeee-$-C)}function U(D,$){let g=0;for(let C=0;C$+g*g,0))}function y(D){if(D.length===0)throw Error("Array must not be empty");let $=D[0],g=0;for(let C=1;C$&&($=D[C],g=C);return[Number($),g]}function b(D){return D>0&&(D&D-1)===0}class L{constructor($){if(this.size=$|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=$<<1,this.table=new Float64Array(this.size*2);for(let C=0;CC;C<<=1)++g;this._width=g%2===0?g-1:g,this._bitrev=new Int32Array(1<>>T&3)<>>1);for(let T=0;T<$.length;T+=2)C[T>>>1]=$[T];return C}toComplexArray($,g){const C=g||this.createComplexArray();for(let T=0;T>>1],C[T+1]=0;return C}transform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,1)}realTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._realTransform4($,g,1)}inverseTransform($,g){if($===g)throw new Error("Input and output buffers must be different");this._transform4($,g,-1);for(let C=0;C<$.length;++C)$[C]/=this.size}_transform4($,g,C){const T=this._csize;let J=1<>=2;J>=2;J>>=2){le=T/J<<1;const Le=le>>>2;for(de=0;de>>1,J>>>1)}else for(de=0,fe=0;de>>1,J>>>1,C)}const xe=this.table;for(J>>=2;J>=2;J>>=2){le=T/J<<1;const qe=le>>>1,Ue=qe>>>1,ut=Ue>>>1;for(de=0;de>>1;for(let qe=2;qe>1;++ke){const xe=(ke+1-$)**2/2,Le=Math.sqrt(de**2+fe**2)**xe,qe=xe*Math.atan2(fe,de),Ue=2*ke;ee[Ue]=Le*Math.cos(qe),ee[Ue+1]=Le*Math.sin(qe),J[Ue]=ee[Ue],J[Ue+1]=-ee[Ue+1]}this._slicedChirpBuffer=ee.subarray(g,C),this._f=new L(T>>1),this._f.transform(this._chirpBuffer,J)}_transform($,g,C){const T=this._buffer1,ee=this._buffer2,J=this._outBuffer1,le=this._outBuffer2,de=this._chirpBuffer,fe=this._slicedChirpBuffer,ke=this._a;if(C)for(let xe=0;xe>1,Ue=g[qe];T[xe]=Ue*fe[xe],T[Le]=Ue*fe[Le]}else for(let xe=0;xe=D.length&&(de=2*(D.length-1)-de),C[J++]=D[de]}C.sort(),g[ee]=C[T]}return g}function z(D,$){const g=Math.pow(10,$);return Math.round(D*g)/g}function W(D){const $=Math.round(D);return Math.abs(D)%1===.5?$%2===0?$:$-1:$}function Y(D){const $=D.length,g=D[0].length,C=[$+1,g+1],T=Array.from({length:C[0]},()=>Array(C[1]).fill(1/0));T[0][0]=0;const ee=Array.from({length:C[0]},()=>Array(C[1]).fill(-1));for(let ke=1;ke0||le>0;)switch(de.push(J-1),fe.push(le-1),ee[J][le]){case 0:--J,--le;break;case 1:--J;break;case 2:--le;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${J}, ${le}]. Please file a bug report.`)}return de.reverse(),fe.reverse(),[de,fe]}},"./src/utils/tensor.js":(Te,A,s)=>{s.r(A),s.d(A,{Tensor:()=>U,cat:()=>g,full:()=>de,full_like:()=>fe,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>W,matmul:()=>b,mean:()=>ee,mean_pooling:()=>z,ones:()=>ke,ones_like:()=>xe,permute:()=>v,quantize_embeddings:()=>ut,rand:()=>Ue,rfft:()=>L,slice:()=>ie,stack:()=>C,std_mean:()=>T,topk:()=>q,zeros:()=>Le,zeros_like:()=>qe});var f=s("./src/utils/maths.js"),O=s("./src/backends/onnx.js"),N=s("./src/ops/registry.js");const Q=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,uint4:Uint8Array,int4:Int8Array});class U{constructor(...re){ge(this,"ort_tensor");return(0,O.isONNXTensor)(re[0])?this.ort_tensor=re[0]:this.ort_tensor=new O.Tensor(re[0],re[1],re[2]),new Proxy(this,{get:(he,Pe)=>{if(typeof Pe=="string"){let Be=Number(Pe);if(Number.isInteger(Be))return he._getitem(Be)}return he[Pe]},set:(he,Pe,Be)=>he[Pe]=Be})}get dims(){return this.ort_tensor.dims}set dims(re){this.ort_tensor.dims=re}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[re,...he]=this.dims;if(he.length>0){const Pe=he.reduce((Be,et)=>Be*et);for(let Be=0;Be0){const Be=Pe.reduce((et,Xe)=>et*Xe);return this._subarray(re,Be,Pe)}else return new U(this.type,[this.data[re]],Pe)}indexOf(re){const he=this.data;for(let Pe=0;PeRe)throw new Error(`Invalid slice: ${ce}`);const je=[Math.max(ve,0),Math.min(Re,this.dims[De])];Pe.push(je),he.push(je[1]-je[0])}else throw new Error(`Invalid slice: ${ce}`)}const Be=Pe.map(([De,ce])=>ce-De),et=Be.reduce((De,ce)=>De*ce),Xe=this.data,oe=new Xe.constructor(et),Je=this.stride();for(let De=0;De=0;--ve){const je=Be[ve];ce+=(Re%je+Pe[ve][0])*Je[ve],Re=Math.floor(Re/je)}oe[De]=Xe[ce]}return new U(this.type,oe,he)}permute(...re){return v(this,re)}transpose(...re){return this.permute(...re)}sum(re=null,he=!1){return this.norm(1,re,he)}norm(re="fro",he=null,Pe=!1){if(re==="fro")re=2;else if(typeof re=="string")throw Error(`Unsupported norm: ${re}`);const Be=this.data;if(he===null){let oe=Be.reduce((Je,De)=>Je+De**re,0)**(1/re);return new U(this.type,[oe],[])}he=$(he,this.dims.length);const et=this.dims.slice();et[he]=1;const Xe=new Be.constructor(Be.length/this.dims[he]);for(let oe=0;oe=0;--De){const Re=this.dims[De];if(De!==he){const je=ce%Re;Je+=je*ve,ve*=et[De]}ce=Math.floor(ce/Re)}Xe[Je]+=Be[oe]**re}if(re!==1)for(let oe=0;oe=0;--Je){const ve=this.dims[Je];if(Je!==he){const Re=De%ve;oe+=Re*ce,ce*=this.dims[Je]}De=Math.floor(De/ve)}Be[Xe]/=et[oe]}return this}normalize(re=2,he=1){return this.clone().normalize_(re,he)}stride(){return J(this.dims)}squeeze(re=null){return new U(this.type,this.data,Y(this.dims,re))}squeeze_(re=null){return this.dims=Y(this.dims,re),this}unsqueeze(re=null){return new U(this.type,this.data,D(this.dims,re))}unsqueeze_(re=null){return this.dims=D(this.dims,re),this}flatten_(re=0,he=-1){he=(he+this.dims.length)%this.dims.length;let Pe=this.dims.slice(0,re),Be=this.dims.slice(re,he+1),et=this.dims.slice(he+1);return this.dims=[...Pe,Be.reduce((Xe,oe)=>Xe*oe,1),...et],this}flatten(re=0,he=-1){return this.clone().flatten_(re,he)}view(...re){let he=-1;for(let Be=0;Beoe!==he?et*Xe:et,1);re[he]=Pe.length/Be}return new U(this.type,Pe,re)}neg_(){const re=this.data;for(let he=0;heet*Xe);if(he!==Pe)throw Error(`cannot reshape array of size ${he} into shape (${re})`);let Be=ue;for(let et=re.length-1;et>=0;et--)Be=Be.reduce((Xe,oe)=>{let Je=Xe[Xe.length-1];return Je.lengthnew U("int64",ue,[ue.length]);async function ie(ue,re,he,Pe,Be){return await(await N.TensorOpRegistry.slice)({x:ue,s:se(re),e:se(he),a:se(Pe),t:se(Be??new Array(Pe.length).fill(1))})}function z(ue,re){const he=ue.data,Pe=re.data,Be=[ue.dims[0],ue.dims[2]],et=new he.constructor(Be[0]*Be[1]),[Xe,oe,Je]=ue.dims;let De=0;for(let ce=0;cehe!==1):typeof re=="number"?ue[re]===1&&ue.splice(re,1):Array.isArray(re)&&(ue=ue.filter((he,Pe)=>he!==1||!re.includes(Pe))),ue}function D(ue,re){return re=$(re,ue.length+1),ue=ue.slice(),ue.splice(re,0,1),ue}function $(ue,re,he=null,Pe=!0){if(Pe&&(ue<-re||ue>=re))throw new Error(`IndexError: index ${ue} is out of bounds for dimension${he===null?"":" "+he} with size ${re}`);return ue<0&&(ue=(ue%re+re)%re),ue}function g(ue,re=0){re=$(re,ue[0].dims.length);const he=ue[0].dims.slice();he[re]=ue.reduce((Xe,oe)=>Xe+oe.dims[re],0);const Pe=he.reduce((Xe,oe)=>Xe*oe,1),Be=new ue[0].data.constructor(Pe),et=ue[0].type;if(re===0){let Xe=0;for(const oe of ue){const Je=oe.data;Be.set(Je,Xe),Xe+=Je.length}}else{let Xe=0;for(let oe=0;oe=0;--Re){const Ne=De[Re];let Ze=je%Ne;Re===re&&(Ze+=Xe),ve+=Ze*We,We*=he[Re],je=Math.floor(je/Ne)}Be[ve]=Je[ce]}Xe+=De[re]}}return new U(et,Be,he)}function C(ue,re=0){return g(ue.map(he=>he.unsqueeze(re)),re)}function T(ue,re=null,he=1,Pe=!1){const Be=ue.data,et=ue.dims;if(re===null){const Re=Be.reduce((Ze,at)=>Ze+at,0)/Be.length,je=Math.sqrt(Be.reduce((Ze,at)=>Ze+(at-Re)**2,0)/(Be.length-he)),We=new U(ue.type,[Re],[]);return[new U(ue.type,[je],[]),We]}re=$(re,et.length);const Xe=ee(ue,re,Pe),oe=Xe.data,Je=et.slice();Je[re]=1;const De=new Be.constructor(Be.length/et[re]);for(let ve=0;ve=0;--je){const Ze=et[je];if(je!==re){const at=We%Ze;Re+=at*Ne,Ne*=Je[je]}We=Math.floor(We/Ze)}De[Re]+=(Be[ve]-oe[Re])**2}for(let ve=0;veJe+De,0);return new U(ue.type,[oe/Pe.length],[])}const Be=ue.dims;re=$(re,Be.length);const et=Be.slice();et[re]=1;const Xe=new Pe.constructor(Pe.length/Be[re]);for(let oe=0;oe=0;--De){const Re=Be[De];if(De!==re){const je=ce%Re;Je+=je*ve,ve*=et[De]}ce=Math.floor(ce/Re)}Xe[Je]+=Pe[oe]}if(Be[re]!==1)for(let oe=0;oe=0;--he)re[he]=Pe,Pe*=ue[he];return re}function le(ue,re,he,Pe){const Be=ue.reduce((et,Xe)=>et*Xe,1);return new U(he,new Pe(Be).fill(re),ue)}function de(ue,re){let he,Pe;if(typeof re=="number")he="float32",Pe=Float32Array;else if(typeof re=="bigint")he="int64",Pe=BigInt64Array;else if(typeof re=="boolean")he="bool",Pe=Uint8Array;else throw new Error(`Unsupported data type: ${typeof re}`);return le(ue,re,he,Pe)}function fe(ue,re){return de(ue.dims,re)}function ke(ue){return le(ue,1n,"int64",BigInt64Array)}function xe(ue){return ke(ue.dims)}function Le(ue){return le(ue,0n,"int64",BigInt64Array)}function qe(ue){return Le(ue.dims)}function Ue(ue){const re=ue.reduce((he,Pe)=>he*Pe,1);return new U("float32",Float32Array.from({length:re},()=>Math.random()),ue)}function ut(ue,re){if(ue.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ue.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(re))throw new Error("The precision must be either 'binary' or 'ubinary'");const he=re==="binary",Pe=he?"int8":"uint8",Be=he?Int8Array:Uint8Array,et=ue.data,Xe=new Be(et.length/8);for(let oe=0;oe0?1:0,De=Math.floor(oe/8),ce=oe%8;Xe[De]|=Je<<7-ce,he&&ce===0&&(Xe[De]-=128)}return new U(Pe,Xe,[ue.dims[0],ue.dims[1]/8])}}},a_={};function fr(Te){var A=a_[Te];if(A!==void 0)return A.exports;var s=a_[Te]={exports:{}};return d_[Te](s,s.exports,fr),s.exports}fr.m=d_;(()=>{var Te=Object.getPrototypeOf?s=>Object.getPrototypeOf(s):s=>s.__proto__,A;fr.t=function(s,f){if(f&1&&(s=this(s)),f&8||typeof s=="object"&&s&&(f&4&&s.__esModule||f&16&&typeof s.then=="function"))return s;var O=Object.create(null);fr.r(O);var N={};A=A||[null,Te({}),Te([]),Te(Te)];for(var Q=f&2&&s;typeof Q=="object"&&!~A.indexOf(Q);Q=Te(Q))Object.getOwnPropertyNames(Q).forEach(U=>N[U]=()=>s[U]);return N.default=()=>s,fr.d(O,N),O}})();fr.d=(Te,A)=>{for(var s in A)fr.o(A,s)&&!fr.o(Te,s)&&Object.defineProperty(Te,s,{enumerable:!0,get:A[s]})};fr.o=(Te,A)=>Object.prototype.hasOwnProperty.call(Te,A);fr.r=Te=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Te,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Te,"__esModule",{value:!0})};(()=>{var Te;if(typeof import.meta.url=="string"&&(Te=import.meta.url),!Te)throw new Error("Automatic publicPath is not supported in this browser");Te=Te.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),fr.p=Te})();fr.b=new URL("./",import.meta.url);var c={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/fr.r(c),fr.d(c,{ASTFeatureExtractor:()=>y.ASTFeatureExtractor,ASTForAudioClassification:()=>s.ASTForAudioClassification,ASTModel:()=>s.ASTModel,ASTPreTrainedModel:()=>s.ASTPreTrainedModel,AlbertForMaskedLM:()=>s.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>s.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>s.AlbertForSequenceClassification,AlbertModel:()=>s.AlbertModel,AlbertPreTrainedModel:()=>s.AlbertPreTrainedModel,AlbertTokenizer:()=>f.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>O.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>q.AutoImageProcessor,AutoModel:()=>s.AutoModel,AutoModelForAudioClassification:()=>s.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>s.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>s.AutoModelForCTC,AutoModelForCausalLM:()=>s.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>s.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>s.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>s.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>s.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>s.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>s.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>s.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>s.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>s.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>s.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>s.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>s.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>s.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>s.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>s.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>s.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>s.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>s.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>s.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>s.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>s.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>s.AutoModelForVision2Seq,AutoModelForXVector:()=>s.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>s.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>z.AutoProcessor,AutoTokenizer:()=>f.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>s.BartForConditionalGeneration,BartForSequenceClassification:()=>s.BartForSequenceClassification,BartModel:()=>s.BartModel,BartPretrainedModel:()=>s.BartPretrainedModel,BartTokenizer:()=>f.BartTokenizer,BaseModelOutput:()=>s.BaseModelOutput,BaseStreamer:()=>W.BaseStreamer,BeitFeatureExtractor:()=>L.BeitFeatureExtractor,BeitForImageClassification:()=>s.BeitForImageClassification,BeitModel:()=>s.BeitModel,BeitPreTrainedModel:()=>s.BeitPreTrainedModel,BertForMaskedLM:()=>s.BertForMaskedLM,BertForQuestionAnswering:()=>s.BertForQuestionAnswering,BertForSequenceClassification:()=>s.BertForSequenceClassification,BertForTokenClassification:()=>s.BertForTokenClassification,BertModel:()=>s.BertModel,BertPreTrainedModel:()=>s.BertPreTrainedModel,BertTokenizer:()=>f.BertTokenizer,BitImageProcessor:()=>L.BitImageProcessor,BlenderbotForConditionalGeneration:()=>s.BlenderbotForConditionalGeneration,BlenderbotModel:()=>s.BlenderbotModel,BlenderbotPreTrainedModel:()=>s.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>s.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>s.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>s.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>f.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>f.BlenderbotTokenizer,BloomForCausalLM:()=>s.BloomForCausalLM,BloomModel:()=>s.BloomModel,BloomPreTrainedModel:()=>s.BloomPreTrainedModel,BloomTokenizer:()=>f.BloomTokenizer,CLIPFeatureExtractor:()=>L.CLIPFeatureExtractor,CLIPImageProcessor:()=>L.CLIPImageProcessor,CLIPModel:()=>s.CLIPModel,CLIPPreTrainedModel:()=>s.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>s.CLIPSegForImageSegmentation,CLIPSegModel:()=>s.CLIPSegModel,CLIPSegPreTrainedModel:()=>s.CLIPSegPreTrainedModel,CLIPTextModel:()=>s.CLIPTextModel,CLIPTextModelWithProjection:()=>s.CLIPTextModelWithProjection,CLIPTokenizer:()=>f.CLIPTokenizer,CLIPVisionModel:()=>s.CLIPVisionModel,CLIPVisionModelWithProjection:()=>s.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>s.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>s.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>s.CamembertForSequenceClassification,CamembertForTokenClassification:()=>s.CamembertForTokenClassification,CamembertModel:()=>s.CamembertModel,CamembertPreTrainedModel:()=>s.CamembertPreTrainedModel,CamembertTokenizer:()=>f.CamembertTokenizer,CausalLMOutput:()=>s.CausalLMOutput,CausalLMOutputWithPast:()=>s.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>L.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>s.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>s.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>s.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>s.ClapModel,ClapPreTrainedModel:()=>s.ClapPreTrainedModel,ClapTextModelWithProjection:()=>s.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>D.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>s.CodeGenForCausalLM,CodeGenModel:()=>s.CodeGenModel,CodeGenPreTrainedModel:()=>s.CodeGenPreTrainedModel,CodeGenTokenizer:()=>f.CodeGenTokenizer,CodeLlamaTokenizer:()=>f.CodeLlamaTokenizer,CohereForCausalLM:()=>s.CohereForCausalLM,CohereModel:()=>s.CohereModel,CoherePreTrainedModel:()=>s.CoherePreTrainedModel,CohereTokenizer:()=>f.CohereTokenizer,ConvBertForMaskedLM:()=>s.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>s.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>s.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>s.ConvBertForTokenClassification,ConvBertModel:()=>s.ConvBertModel,ConvBertPreTrainedModel:()=>s.ConvBertPreTrainedModel,ConvBertTokenizer:()=>f.ConvBertTokenizer,ConvNextFeatureExtractor:()=>L.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>s.ConvNextForImageClassification,ConvNextImageProcessor:()=>L.ConvNextImageProcessor,ConvNextModel:()=>s.ConvNextModel,ConvNextPreTrainedModel:()=>s.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>s.ConvNextV2ForImageClassification,ConvNextV2Model:()=>s.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>s.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>L.DPTFeatureExtractor,DPTForDepthEstimation:()=>s.DPTForDepthEstimation,DPTImageProcessor:()=>L.DPTImageProcessor,DPTModel:()=>s.DPTModel,DPTPreTrainedModel:()=>s.DPTPreTrainedModel,DebertaForMaskedLM:()=>s.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>s.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>s.DebertaForSequenceClassification,DebertaForTokenClassification:()=>s.DebertaForTokenClassification,DebertaModel:()=>s.DebertaModel,DebertaPreTrainedModel:()=>s.DebertaPreTrainedModel,DebertaTokenizer:()=>f.DebertaTokenizer,DebertaV2ForMaskedLM:()=>s.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>s.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>s.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>s.DebertaV2ForTokenClassification,DebertaV2Model:()=>s.DebertaV2Model,DebertaV2PreTrainedModel:()=>s.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>f.DebertaV2Tokenizer,DecisionTransformerModel:()=>s.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>s.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>L.DeiTFeatureExtractor,DeiTForImageClassification:()=>s.DeiTForImageClassification,DeiTImageProcessor:()=>L.DeiTImageProcessor,DeiTModel:()=>s.DeiTModel,DeiTPreTrainedModel:()=>s.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>s.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>s.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>s.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>s.DepthProPreTrainedModel,DetrFeatureExtractor:()=>L.DetrFeatureExtractor,DetrForObjectDetection:()=>s.DetrForObjectDetection,DetrForSegmentation:()=>s.DetrForSegmentation,DetrImageProcessor:()=>L.DetrImageProcessor,DetrModel:()=>s.DetrModel,DetrObjectDetectionOutput:()=>s.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>s.DetrPreTrainedModel,DetrSegmentationOutput:()=>s.DetrSegmentationOutput,Dinov2ForImageClassification:()=>s.Dinov2ForImageClassification,Dinov2Model:()=>s.Dinov2Model,Dinov2PreTrainedModel:()=>s.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>s.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>s.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>s.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>s.DistilBertForTokenClassification,DistilBertModel:()=>s.DistilBertModel,DistilBertPreTrainedModel:()=>s.DistilBertPreTrainedModel,DistilBertTokenizer:()=>f.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>L.DonutFeatureExtractor,DonutImageProcessor:()=>L.DonutImageProcessor,DonutSwinModel:()=>s.DonutSwinModel,DonutSwinPreTrainedModel:()=>s.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>s.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>L.EfficientNetImageProcessor,EfficientNetModel:()=>s.EfficientNetModel,EfficientNetPreTrainedModel:()=>s.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>s.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>s.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>s.ElectraForSequenceClassification,ElectraForTokenClassification:()=>s.ElectraForTokenClassification,ElectraModel:()=>s.ElectraModel,ElectraPreTrainedModel:()=>s.ElectraPreTrainedModel,ElectraTokenizer:()=>f.ElectraTokenizer,EosTokenCriteria:()=>Y.EosTokenCriteria,EsmForMaskedLM:()=>s.EsmForMaskedLM,EsmForSequenceClassification:()=>s.EsmForSequenceClassification,EsmForTokenClassification:()=>s.EsmForTokenClassification,EsmModel:()=>s.EsmModel,EsmPreTrainedModel:()=>s.EsmPreTrainedModel,EsmTokenizer:()=>f.EsmTokenizer,ExaoneForCausalLM:()=>s.ExaoneForCausalLM,ExaoneModel:()=>s.ExaoneModel,ExaonePreTrainedModel:()=>s.ExaonePreTrainedModel,FFT:()=>w.FFT,FalconForCausalLM:()=>s.FalconForCausalLM,FalconModel:()=>s.FalconModel,FalconPreTrainedModel:()=>s.FalconPreTrainedModel,FalconTokenizer:()=>f.FalconTokenizer,FastViTForImageClassification:()=>s.FastViTForImageClassification,FastViTModel:()=>s.FastViTModel,FastViTPreTrainedModel:()=>s.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>s.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>s.Florence2PreTrainedModel,Florence2Processor:()=>ie.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>D.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>D.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>L.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>s.GLPNForDepthEstimation,GLPNModel:()=>s.GLPNModel,GLPNPreTrainedModel:()=>s.GLPNPreTrainedModel,GPT2LMHeadModel:()=>s.GPT2LMHeadModel,GPT2Model:()=>s.GPT2Model,GPT2PreTrainedModel:()=>s.GPT2PreTrainedModel,GPT2Tokenizer:()=>f.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>s.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>s.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>s.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>s.GPTJForCausalLM,GPTJModel:()=>s.GPTJModel,GPTJPreTrainedModel:()=>s.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>s.GPTNeoForCausalLM,GPTNeoModel:()=>s.GPTNeoModel,GPTNeoPreTrainedModel:()=>s.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>s.GPTNeoXForCausalLM,GPTNeoXModel:()=>s.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>s.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>f.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>s.Gemma2ForCausalLM,Gemma2Model:()=>s.Gemma2Model,Gemma2PreTrainedModel:()=>s.Gemma2PreTrainedModel,GemmaForCausalLM:()=>s.GemmaForCausalLM,GemmaModel:()=>s.GemmaModel,GemmaPreTrainedModel:()=>s.GemmaPreTrainedModel,GemmaTokenizer:()=>f.GemmaTokenizer,GraniteForCausalLM:()=>s.GraniteForCausalLM,GraniteModel:()=>s.GraniteModel,GranitePreTrainedModel:()=>s.GranitePreTrainedModel,Grok1Tokenizer:()=>f.Grok1Tokenizer,GroupViTModel:()=>s.GroupViTModel,GroupViTPreTrainedModel:()=>s.GroupViTPreTrainedModel,HerbertTokenizer:()=>f.HerbertTokenizer,HieraForImageClassification:()=>s.HieraForImageClassification,HieraModel:()=>s.HieraModel,HieraPreTrainedModel:()=>s.HieraPreTrainedModel,HubertForCTC:()=>s.HubertForCTC,HubertForSequenceClassification:()=>s.HubertForSequenceClassification,HubertModel:()=>s.HubertModel,HubertPreTrainedModel:()=>s.HubertPreTrainedModel,IJepaForImageClassification:()=>s.IJepaForImageClassification,IJepaModel:()=>s.IJepaModel,IJepaPreTrainedModel:()=>s.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>s.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>L.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>s.Idefics3PreTrainedModel,Idefics3Processor:()=>ie.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>s.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Y.InterruptableStoppingCriteria,JAISLMHeadModel:()=>s.JAISLMHeadModel,JAISModel:()=>s.JAISModel,JAISPreTrainedModel:()=>s.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>L.JinaCLIPImageProcessor,JinaCLIPModel:()=>s.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>s.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ie.JinaCLIPProcessor,JinaCLIPTextModel:()=>s.JinaCLIPTextModel,JinaCLIPVisionModel:()=>s.JinaCLIPVisionModel,LlamaForCausalLM:()=>s.LlamaForCausalLM,LlamaModel:()=>s.LlamaModel,LlamaPreTrainedModel:()=>s.LlamaPreTrainedModel,LlamaTokenizer:()=>f.LlamaTokenizer,LlavaForConditionalGeneration:()=>s.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>s.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>L.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>s.LlavaPreTrainedModel,LogitsProcessor:()=>D.LogitsProcessor,LogitsProcessorList:()=>D.LogitsProcessorList,LogitsWarper:()=>D.LogitsWarper,LongT5ForConditionalGeneration:()=>s.LongT5ForConditionalGeneration,LongT5Model:()=>s.LongT5Model,LongT5PreTrainedModel:()=>s.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>s.M2M100ForConditionalGeneration,M2M100Model:()=>s.M2M100Model,M2M100PreTrainedModel:()=>s.M2M100PreTrainedModel,M2M100Tokenizer:()=>f.M2M100Tokenizer,MBart50Tokenizer:()=>f.MBart50Tokenizer,MBartForCausalLM:()=>s.MBartForCausalLM,MBartForConditionalGeneration:()=>s.MBartForConditionalGeneration,MBartForSequenceClassification:()=>s.MBartForSequenceClassification,MBartModel:()=>s.MBartModel,MBartPreTrainedModel:()=>s.MBartPreTrainedModel,MBartTokenizer:()=>f.MBartTokenizer,MPNetForMaskedLM:()=>s.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>s.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>s.MPNetForSequenceClassification,MPNetForTokenClassification:()=>s.MPNetForTokenClassification,MPNetModel:()=>s.MPNetModel,MPNetPreTrainedModel:()=>s.MPNetPreTrainedModel,MPNetTokenizer:()=>f.MPNetTokenizer,MT5ForConditionalGeneration:()=>s.MT5ForConditionalGeneration,MT5Model:()=>s.MT5Model,MT5PreTrainedModel:()=>s.MT5PreTrainedModel,MarianMTModel:()=>s.MarianMTModel,MarianModel:()=>s.MarianModel,MarianPreTrainedModel:()=>s.MarianPreTrainedModel,MarianTokenizer:()=>f.MarianTokenizer,Mask2FormerImageProcessor:()=>L.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>L.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>s.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>L.MaskFormerImageProcessor,MaskFormerModel:()=>s.MaskFormerModel,MaskFormerPreTrainedModel:()=>s.MaskFormerPreTrainedModel,MaskedLMOutput:()=>s.MaskedLMOutput,MaxLengthCriteria:()=>Y.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>s.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>s.MgpstrModelOutput,MgpstrPreTrainedModel:()=>s.MgpstrPreTrainedModel,MgpstrProcessor:()=>ie.MgpstrProcessor,MgpstrTokenizer:()=>f.MgpstrTokenizer,MinLengthLogitsProcessor:()=>D.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>D.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>s.MistralForCausalLM,MistralModel:()=>s.MistralModel,MistralPreTrainedModel:()=>s.MistralPreTrainedModel,MobileBertForMaskedLM:()=>s.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>s.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>s.MobileBertForSequenceClassification,MobileBertModel:()=>s.MobileBertModel,MobileBertPreTrainedModel:()=>s.MobileBertPreTrainedModel,MobileBertTokenizer:()=>f.MobileBertTokenizer,MobileLLMForCausalLM:()=>s.MobileLLMForCausalLM,MobileLLMModel:()=>s.MobileLLMModel,MobileLLMPreTrainedModel:()=>s.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>L.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>s.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>L.MobileNetV1ImageProcessor,MobileNetV1Model:()=>s.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>s.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>L.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>s.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>L.MobileNetV2ImageProcessor,MobileNetV2Model:()=>s.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>s.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>L.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>s.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>L.MobileNetV3ImageProcessor,MobileNetV3Model:()=>s.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>s.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>L.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>s.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>L.MobileNetV4ImageProcessor,MobileNetV4Model:()=>s.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>s.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>L.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>s.MobileViTForImageClassification,MobileViTImageProcessor:()=>L.MobileViTImageProcessor,MobileViTModel:()=>s.MobileViTModel,MobileViTPreTrainedModel:()=>s.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>s.MobileViTV2ForImageClassification,MobileViTV2Model:()=>s.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>s.MobileViTV2PreTrainedModel,ModelOutput:()=>s.ModelOutput,ModernBertForMaskedLM:()=>s.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>s.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>s.ModernBertForTokenClassification,ModernBertModel:()=>s.ModernBertModel,ModernBertPreTrainedModel:()=>s.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>s.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>y.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>s.MoonshineForConditionalGeneration,MoonshineModel:()=>s.MoonshineModel,MoonshinePreTrainedModel:()=>s.MoonshinePreTrainedModel,MoonshineProcessor:()=>ie.MoonshineProcessor,MptForCausalLM:()=>s.MptForCausalLM,MptModel:()=>s.MptModel,MptPreTrainedModel:()=>s.MptPreTrainedModel,MultiModalityCausalLM:()=>s.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>s.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>s.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>s.MusicgenForConditionalGeneration,MusicgenModel:()=>s.MusicgenModel,MusicgenPreTrainedModel:()=>s.MusicgenPreTrainedModel,NllbTokenizer:()=>f.NllbTokenizer,NoBadWordsLogitsProcessor:()=>D.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>D.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>s.NomicBertModel,NomicBertPreTrainedModel:()=>s.NomicBertPreTrainedModel,NougatImageProcessor:()=>L.NougatImageProcessor,NougatTokenizer:()=>f.NougatTokenizer,OPTForCausalLM:()=>s.OPTForCausalLM,OPTModel:()=>s.OPTModel,OPTPreTrainedModel:()=>s.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>s.Olmo2ForCausalLM,Olmo2Model:()=>s.Olmo2Model,Olmo2PreTrainedModel:()=>s.Olmo2PreTrainedModel,OlmoForCausalLM:()=>s.OlmoForCausalLM,OlmoModel:()=>s.OlmoModel,OlmoPreTrainedModel:()=>s.OlmoPreTrainedModel,OpenELMForCausalLM:()=>s.OpenELMForCausalLM,OpenELMModel:()=>s.OpenELMModel,OpenELMPreTrainedModel:()=>s.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>L.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>s.OwlViTForObjectDetection,OwlViTImageProcessor:()=>L.OwlViTImageProcessor,OwlViTModel:()=>s.OwlViTModel,OwlViTPreTrainedModel:()=>s.OwlViTPreTrainedModel,OwlViTProcessor:()=>ie.OwlViTProcessor,Owlv2ForObjectDetection:()=>s.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>L.Owlv2ImageProcessor,Owlv2Model:()=>s.Owlv2Model,Owlv2PreTrainedModel:()=>s.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>s.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>s.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ie.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>s.PatchTSMixerForPrediction,PatchTSMixerModel:()=>s.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>s.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>s.PatchTSTForPrediction,PatchTSTModel:()=>s.PatchTSTModel,PatchTSTPreTrainedModel:()=>s.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>s.Phi3ForCausalLM,Phi3Model:()=>s.Phi3Model,Phi3PreTrainedModel:()=>s.Phi3PreTrainedModel,Phi3VForCausalLM:()=>s.Phi3VForCausalLM,Phi3VImageProcessor:()=>L.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>s.Phi3VPreTrainedModel,Phi3VProcessor:()=>ie.Phi3VProcessor,PhiForCausalLM:()=>s.PhiForCausalLM,PhiModel:()=>s.PhiModel,PhiPreTrainedModel:()=>s.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>s.PreTrainedModel,PreTrainedTokenizer:()=>f.PreTrainedTokenizer,PretrainedConfig:()=>O.PretrainedConfig,PretrainedMixin:()=>s.PretrainedMixin,Processor:()=>se.Processor,PvtForImageClassification:()=>s.PvtForImageClassification,PvtImageProcessor:()=>L.PvtImageProcessor,PvtModel:()=>s.PvtModel,PvtPreTrainedModel:()=>s.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>s.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>s.PyAnnoteModel,PyAnnotePreTrainedModel:()=>s.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ie.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>s.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>s.Qwen2ForCausalLM,Qwen2Model:()=>s.Qwen2Model,Qwen2PreTrainedModel:()=>s.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>f.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>s.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>L.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>s.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ie.Qwen2VLProcessor,RTDetrForObjectDetection:()=>s.RTDetrForObjectDetection,RTDetrImageProcessor:()=>L.RTDetrImageProcessor,RTDetrModel:()=>s.RTDetrModel,RTDetrObjectDetectionOutput:()=>s.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>s.RTDetrPreTrainedModel,RawImage:()=>Q.RawImage,RepetitionPenaltyLogitsProcessor:()=>D.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>s.ResNetForImageClassification,ResNetModel:()=>s.ResNetModel,ResNetPreTrainedModel:()=>s.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>s.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>s.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>s.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>s.RoFormerForTokenClassification,RoFormerModel:()=>s.RoFormerModel,RoFormerPreTrainedModel:()=>s.RoFormerPreTrainedModel,RoFormerTokenizer:()=>f.RoFormerTokenizer,RobertaForMaskedLM:()=>s.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>s.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>s.RobertaForSequenceClassification,RobertaForTokenClassification:()=>s.RobertaForTokenClassification,RobertaModel:()=>s.RobertaModel,RobertaPreTrainedModel:()=>s.RobertaPreTrainedModel,RobertaTokenizer:()=>f.RobertaTokenizer,SamImageProcessor:()=>L.SamImageProcessor,SamImageSegmentationOutput:()=>s.SamImageSegmentationOutput,SamModel:()=>s.SamModel,SamPreTrainedModel:()=>s.SamPreTrainedModel,SamProcessor:()=>ie.SamProcessor,SapiensForDepthEstimation:()=>s.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>s.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>s.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>s.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>L.SegformerFeatureExtractor,SegformerForImageClassification:()=>s.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>s.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>L.SegformerImageProcessor,SegformerModel:()=>s.SegformerModel,SegformerPreTrainedModel:()=>s.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>s.Seq2SeqLMOutput,SequenceClassifierOutput:()=>s.SequenceClassifierOutput,SiglipImageProcessor:()=>L.SiglipImageProcessor,SiglipModel:()=>s.SiglipModel,SiglipPreTrainedModel:()=>s.SiglipPreTrainedModel,SiglipTextModel:()=>s.SiglipTextModel,SiglipTokenizer:()=>f.SiglipTokenizer,SiglipVisionModel:()=>s.SiglipVisionModel,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>s.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>s.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>s.SpeechT5HifiGan,SpeechT5Model:()=>s.SpeechT5Model,SpeechT5PreTrainedModel:()=>s.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ie.SpeechT5Processor,SpeechT5Tokenizer:()=>f.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>s.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>s.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>s.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>s.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>s.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>f.SqueezeBertTokenizer,StableLmForCausalLM:()=>s.StableLmForCausalLM,StableLmModel:()=>s.StableLmModel,StableLmPreTrainedModel:()=>s.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>s.Starcoder2ForCausalLM,Starcoder2Model:()=>s.Starcoder2Model,Starcoder2PreTrainedModel:()=>s.Starcoder2PreTrainedModel,StoppingCriteria:()=>Y.StoppingCriteria,StoppingCriteriaList:()=>Y.StoppingCriteriaList,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>D.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>s.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>L.Swin2SRImageProcessor,Swin2SRModel:()=>s.Swin2SRModel,Swin2SRPreTrainedModel:()=>s.Swin2SRPreTrainedModel,SwinForImageClassification:()=>s.SwinForImageClassification,SwinModel:()=>s.SwinModel,SwinPreTrainedModel:()=>s.SwinPreTrainedModel,T5ForConditionalGeneration:()=>s.T5ForConditionalGeneration,T5Model:()=>s.T5Model,T5PreTrainedModel:()=>s.T5PreTrainedModel,T5Tokenizer:()=>f.T5Tokenizer,TableTransformerForObjectDetection:()=>s.TableTransformerForObjectDetection,TableTransformerModel:()=>s.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>s.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>s.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>D.TemperatureLogitsWarper,Tensor:()=>U.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>W.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>s.TokenClassifierOutput,TokenizerModel:()=>f.TokenizerModel,TopKLogitsWarper:()=>D.TopKLogitsWarper,TopPLogitsWarper:()=>D.TopPLogitsWarper,TrOCRForCausalLM:()=>s.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>s.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>s.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>s.UniSpeechForSequenceClassification,UniSpeechModel:()=>s.UniSpeechModel,UniSpeechPreTrainedModel:()=>s.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>s.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>s.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>s.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>s.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>s.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ie.VLChatProcessor,VLMImageProcessor:()=>L.VLMImageProcessor,ViTFeatureExtractor:()=>L.ViTFeatureExtractor,ViTForImageClassification:()=>s.ViTForImageClassification,ViTImageProcessor:()=>L.ViTImageProcessor,ViTMAEModel:()=>s.ViTMAEModel,ViTMAEPreTrainedModel:()=>s.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>s.ViTMSNForImageClassification,ViTMSNModel:()=>s.ViTMSNModel,ViTMSNPreTrainedModel:()=>s.ViTMSNPreTrainedModel,ViTModel:()=>s.ViTModel,ViTPreTrainedModel:()=>s.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>s.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>s.VitMatteForImageMatting,VitMatteImageProcessor:()=>L.VitMatteImageProcessor,VitMattePreTrainedModel:()=>s.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>s.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>L.VitPoseImageProcessor,VitPosePreTrainedModel:()=>s.VitPosePreTrainedModel,VitsModel:()=>s.VitsModel,VitsModelOutput:()=>s.VitsModelOutput,VitsPreTrainedModel:()=>s.VitsPreTrainedModel,VitsTokenizer:()=>f.VitsTokenizer,Wav2Vec2BertForCTC:()=>s.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>s.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>s.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>s.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>f.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>y.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>s.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>s.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>s.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>s.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>s.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>ie.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>s.WavLMForAudioFrameClassification,WavLMForCTC:()=>s.WavLMForCTC,WavLMForSequenceClassification:()=>s.WavLMForSequenceClassification,WavLMForXVector:()=>s.WavLMForXVector,WavLMModel:()=>s.WavLMModel,WavLMPreTrainedModel:()=>s.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>s.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>s.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>s.WhisperForConditionalGeneration,WhisperModel:()=>s.WhisperModel,WhisperPreTrainedModel:()=>s.WhisperPreTrainedModel,WhisperProcessor:()=>ie.WhisperProcessor,WhisperTextStreamer:()=>W.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>D.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>f.WhisperTokenizer,XLMForQuestionAnswering:()=>s.XLMForQuestionAnswering,XLMForSequenceClassification:()=>s.XLMForSequenceClassification,XLMForTokenClassification:()=>s.XLMForTokenClassification,XLMModel:()=>s.XLMModel,XLMPreTrainedModel:()=>s.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>s.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>s.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>s.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>s.XLMRobertaForTokenClassification,XLMRobertaModel:()=>s.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>s.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>f.XLMRobertaTokenizer,XLMTokenizer:()=>f.XLMTokenizer,XLMWithLMHeadModel:()=>s.XLMWithLMHeadModel,XVectorOutput:()=>s.XVectorOutput,YolosFeatureExtractor:()=>L.YolosFeatureExtractor,YolosForObjectDetection:()=>s.YolosForObjectDetection,YolosImageProcessor:()=>L.YolosImageProcessor,YolosModel:()=>s.YolosModel,YolosObjectDetectionOutput:()=>s.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>s.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>w.bankers_round,cat:()=>U.cat,cos_sim:()=>w.cos_sim,dot:()=>w.dot,dynamic_time_warping:()=>w.dynamic_time_warping,env:()=>Te.env,full:()=>U.full,full_like:()=>U.full_like,getKeyValueShapes:()=>O.getKeyValueShapes,hamming:()=>N.hamming,hanning:()=>N.hanning,interpolate:()=>U.interpolate,interpolate_4d:()=>U.interpolate_4d,interpolate_data:()=>w.interpolate_data,is_chinese_char:()=>f.is_chinese_char,layer_norm:()=>U.layer_norm,load_image:()=>Q.load_image,log_softmax:()=>w.log_softmax,magnitude:()=>w.magnitude,matmul:()=>U.matmul,max:()=>w.max,mean:()=>U.mean,mean_pooling:()=>U.mean_pooling,medianFilter:()=>w.medianFilter,mel_filter_bank:()=>N.mel_filter_bank,min:()=>w.min,ones:()=>U.ones,ones_like:()=>U.ones_like,permute:()=>U.permute,permute_data:()=>w.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>U.quantize_embeddings,rand:()=>U.rand,read_audio:()=>N.read_audio,rfft:()=>U.rfft,round:()=>w.round,slice:()=>U.slice,softmax:()=>w.softmax,spectrogram:()=>N.spectrogram,stack:()=>U.stack,std_mean:()=>U.std_mean,topk:()=>U.topk,window_function:()=>N.window_function,zeros:()=>U.zeros,zeros_like:()=>U.zeros_like});var Te=fr("./src/env.js"),A=fr("./src/pipelines.js"),s=fr("./src/models.js"),f=fr("./src/tokenizers.js"),O=fr("./src/configs.js"),N=fr("./src/utils/audio.js"),Q=fr("./src/utils/image.js"),U=fr("./src/utils/tensor.js"),w=fr("./src/utils/maths.js"),v=fr("./src/base/feature_extraction_utils.js"),y=fr("./src/models/feature_extractors.js"),M=fr("./src/models/auto/feature_extraction_auto.js"),b=fr("./src/base/image_processors_utils.js"),L=fr("./src/models/image_processors.js"),q=fr("./src/models/auto/image_processing_auto.js"),se=fr("./src/base/processing_utils.js"),ie=fr("./src/models/processors.js"),z=fr("./src/models/auto/processing_auto.js"),W=fr("./src/generation/streamers.js"),Y=fr("./src/generation/stopping_criteria.js"),D=fr("./src/generation/logits_process.js")})();c.ASTFeatureExtractor;c.ASTForAudioClassification;c.ASTModel;c.ASTPreTrainedModel;c.AlbertForMaskedLM;c.AlbertForQuestionAnswering;c.AlbertForSequenceClassification;c.AlbertModel;c.AlbertPreTrainedModel;c.AlbertTokenizer;c.AudioClassificationPipeline;c.AutoConfig;c.AutoFeatureExtractor;c.AutoImageProcessor;var Rf=c.AutoModel;c.AutoModelForAudioClassification;c.AutoModelForAudioFrameClassification;c.AutoModelForCTC;c.AutoModelForCausalLM;c.AutoModelForDepthEstimation;c.AutoModelForDocumentQuestionAnswering;c.AutoModelForImageClassification;c.AutoModelForImageFeatureExtraction;c.AutoModelForImageMatting;c.AutoModelForImageSegmentation;c.AutoModelForImageToImage;c.AutoModelForMaskGeneration;c.AutoModelForMaskedLM;c.AutoModelForNormalEstimation;c.AutoModelForObjectDetection;c.AutoModelForPoseEstimation;c.AutoModelForQuestionAnswering;c.AutoModelForSemanticSegmentation;c.AutoModelForSeq2SeqLM;c.AutoModelForSequenceClassification;c.AutoModelForSpeechSeq2Seq;c.AutoModelForTextToSpectrogram;c.AutoModelForTextToWaveform;c.AutoModelForTokenClassification;c.AutoModelForUniversalSegmentation;c.AutoModelForVision2Seq;c.AutoModelForXVector;c.AutoModelForZeroShotObjectDetection;c.AutoProcessor;c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline;c.BartForConditionalGeneration;c.BartForSequenceClassification;c.BartModel;c.BartPretrainedModel;c.BartTokenizer;c.BaseModelOutput;c.BaseStreamer;c.BeitFeatureExtractor;c.BeitForImageClassification;c.BeitModel;c.BeitPreTrainedModel;c.BertForMaskedLM;c.BertForQuestionAnswering;c.BertForSequenceClassification;c.BertForTokenClassification;c.BertModel;c.BertPreTrainedModel;c.BertTokenizer;c.BitImageProcessor;c.BlenderbotForConditionalGeneration;c.BlenderbotModel;c.BlenderbotPreTrainedModel;c.BlenderbotSmallForConditionalGeneration;c.BlenderbotSmallModel;c.BlenderbotSmallPreTrainedModel;c.BlenderbotSmallTokenizer;c.BlenderbotTokenizer;c.BloomForCausalLM;c.BloomModel;c.BloomPreTrainedModel;c.BloomTokenizer;c.CLIPFeatureExtractor;c.CLIPImageProcessor;c.CLIPModel;c.CLIPPreTrainedModel;c.CLIPSegForImageSegmentation;c.CLIPSegModel;c.CLIPSegPreTrainedModel;c.CLIPTextModel;c.CLIPTextModelWithProjection;c.CLIPTokenizer;c.CLIPVisionModel;c.CLIPVisionModelWithProjection;c.CamembertForMaskedLM;c.CamembertForQuestionAnswering;c.CamembertForSequenceClassification;c.CamembertForTokenClassification;c.CamembertModel;c.CamembertPreTrainedModel;c.CamembertTokenizer;c.CausalLMOutput;c.CausalLMOutputWithPast;c.ChineseCLIPFeatureExtractor;c.ChineseCLIPModel;c.ChineseCLIPPreTrainedModel;c.ClapAudioModelWithProjection;c.ClapFeatureExtractor;c.ClapModel;c.ClapPreTrainedModel;c.ClapTextModelWithProjection;c.ClassifierFreeGuidanceLogitsProcessor;c.CodeGenForCausalLM;c.CodeGenModel;c.CodeGenPreTrainedModel;c.CodeGenTokenizer;c.CodeLlamaTokenizer;c.CohereForCausalLM;c.CohereModel;c.CoherePreTrainedModel;c.CohereTokenizer;c.ConvBertForMaskedLM;c.ConvBertForQuestionAnswering;c.ConvBertForSequenceClassification;c.ConvBertForTokenClassification;c.ConvBertModel;c.ConvBertPreTrainedModel;c.ConvBertTokenizer;c.ConvNextFeatureExtractor;c.ConvNextForImageClassification;c.ConvNextImageProcessor;c.ConvNextModel;c.ConvNextPreTrainedModel;c.ConvNextV2ForImageClassification;c.ConvNextV2Model;c.ConvNextV2PreTrainedModel;c.DPTFeatureExtractor;c.DPTForDepthEstimation;c.DPTImageProcessor;c.DPTModel;c.DPTPreTrainedModel;c.DebertaForMaskedLM;c.DebertaForQuestionAnswering;c.DebertaForSequenceClassification;c.DebertaForTokenClassification;c.DebertaModel;c.DebertaPreTrainedModel;c.DebertaTokenizer;c.DebertaV2ForMaskedLM;c.DebertaV2ForQuestionAnswering;c.DebertaV2ForSequenceClassification;c.DebertaV2ForTokenClassification;c.DebertaV2Model;c.DebertaV2PreTrainedModel;c.DebertaV2Tokenizer;c.DecisionTransformerModel;c.DecisionTransformerPreTrainedModel;c.DeiTFeatureExtractor;c.DeiTForImageClassification;c.DeiTImageProcessor;c.DeiTModel;c.DeiTPreTrainedModel;c.DepthAnythingForDepthEstimation;c.DepthAnythingPreTrainedModel;c.DepthEstimationPipeline;c.DepthProForDepthEstimation;c.DepthProPreTrainedModel;c.DetrFeatureExtractor;c.DetrForObjectDetection;c.DetrForSegmentation;c.DetrImageProcessor;c.DetrModel;c.DetrObjectDetectionOutput;c.DetrPreTrainedModel;c.DetrSegmentationOutput;c.Dinov2ForImageClassification;c.Dinov2Model;c.Dinov2PreTrainedModel;c.DistilBertForMaskedLM;c.DistilBertForQuestionAnswering;c.DistilBertForSequenceClassification;c.DistilBertForTokenClassification;c.DistilBertModel;c.DistilBertPreTrainedModel;c.DistilBertTokenizer;c.DocumentQuestionAnsweringPipeline;c.DonutFeatureExtractor;c.DonutImageProcessor;c.DonutSwinModel;c.DonutSwinPreTrainedModel;c.EfficientNetForImageClassification;c.EfficientNetImageProcessor;c.EfficientNetModel;c.EfficientNetPreTrainedModel;c.ElectraForMaskedLM;c.ElectraForQuestionAnswering;c.ElectraForSequenceClassification;c.ElectraForTokenClassification;c.ElectraModel;c.ElectraPreTrainedModel;c.ElectraTokenizer;c.EosTokenCriteria;c.EsmForMaskedLM;c.EsmForSequenceClassification;c.EsmForTokenClassification;c.EsmModel;c.EsmPreTrainedModel;c.EsmTokenizer;c.ExaoneForCausalLM;c.ExaoneModel;c.ExaonePreTrainedModel;c.FFT;c.FalconForCausalLM;c.FalconModel;c.FalconPreTrainedModel;c.FalconTokenizer;c.FastViTForImageClassification;c.FastViTModel;c.FastViTPreTrainedModel;c.FeatureExtractionPipeline;c.FeatureExtractor;c.FillMaskPipeline;c.Florence2ForConditionalGeneration;c.Florence2PreTrainedModel;c.Florence2Processor;c.ForcedBOSTokenLogitsProcessor;c.ForcedEOSTokenLogitsProcessor;c.GLPNFeatureExtractor;c.GLPNForDepthEstimation;c.GLPNModel;c.GLPNPreTrainedModel;c.GPT2LMHeadModel;c.GPT2Model;c.GPT2PreTrainedModel;c.GPT2Tokenizer;c.GPTBigCodeForCausalLM;c.GPTBigCodeModel;c.GPTBigCodePreTrainedModel;c.GPTJForCausalLM;c.GPTJModel;c.GPTJPreTrainedModel;c.GPTNeoForCausalLM;c.GPTNeoModel;c.GPTNeoPreTrainedModel;c.GPTNeoXForCausalLM;c.GPTNeoXModel;c.GPTNeoXPreTrainedModel;c.GPTNeoXTokenizer;c.Gemma2ForCausalLM;c.Gemma2Model;c.Gemma2PreTrainedModel;c.GemmaForCausalLM;c.GemmaModel;c.GemmaPreTrainedModel;c.GemmaTokenizer;c.GraniteForCausalLM;c.GraniteModel;c.GranitePreTrainedModel;c.Grok1Tokenizer;c.GroupViTModel;c.GroupViTPreTrainedModel;c.HerbertTokenizer;c.HieraForImageClassification;c.HieraModel;c.HieraPreTrainedModel;c.HubertForCTC;c.HubertForSequenceClassification;c.HubertModel;c.HubertPreTrainedModel;c.IJepaForImageClassification;c.IJepaModel;c.IJepaPreTrainedModel;c.Idefics3ForConditionalGeneration;c.Idefics3ImageProcessor;c.Idefics3PreTrainedModel;c.Idefics3Processor;c.ImageClassificationPipeline;c.ImageFeatureExtractionPipeline;c.ImageFeatureExtractor;c.ImageMattingOutput;c.ImageProcessor;c.ImageSegmentationPipeline;c.ImageToImagePipeline;c.ImageToTextPipeline;c.InterruptableStoppingCriteria;c.JAISLMHeadModel;c.JAISModel;c.JAISPreTrainedModel;c.JinaCLIPImageProcessor;c.JinaCLIPModel;c.JinaCLIPPreTrainedModel;c.JinaCLIPProcessor;c.JinaCLIPTextModel;c.JinaCLIPVisionModel;c.LlamaForCausalLM;c.LlamaModel;c.LlamaPreTrainedModel;c.LlamaTokenizer;c.LlavaForConditionalGeneration;c.LlavaOnevisionForConditionalGeneration;c.LlavaOnevisionImageProcessor;c.LlavaPreTrainedModel;c.LogitsProcessor;c.LogitsProcessorList;c.LogitsWarper;c.LongT5ForConditionalGeneration;c.LongT5Model;c.LongT5PreTrainedModel;c.M2M100ForConditionalGeneration;c.M2M100Model;c.M2M100PreTrainedModel;c.M2M100Tokenizer;c.MBart50Tokenizer;c.MBartForCausalLM;c.MBartForConditionalGeneration;c.MBartForSequenceClassification;c.MBartModel;c.MBartPreTrainedModel;c.MBartTokenizer;c.MPNetForMaskedLM;c.MPNetForQuestionAnswering;c.MPNetForSequenceClassification;c.MPNetForTokenClassification;c.MPNetModel;c.MPNetPreTrainedModel;c.MPNetTokenizer;c.MT5ForConditionalGeneration;c.MT5Model;c.MT5PreTrainedModel;c.MarianMTModel;c.MarianModel;c.MarianPreTrainedModel;c.MarianTokenizer;c.Mask2FormerImageProcessor;c.MaskFormerFeatureExtractor;c.MaskFormerForInstanceSegmentation;c.MaskFormerImageProcessor;c.MaskFormerModel;c.MaskFormerPreTrainedModel;c.MaskedLMOutput;c.MaxLengthCriteria;c.MgpstrForSceneTextRecognition;c.MgpstrModelOutput;c.MgpstrPreTrainedModel;c.MgpstrProcessor;c.MgpstrTokenizer;c.MinLengthLogitsProcessor;c.MinNewTokensLengthLogitsProcessor;c.MistralForCausalLM;c.MistralModel;c.MistralPreTrainedModel;c.MobileBertForMaskedLM;c.MobileBertForQuestionAnswering;c.MobileBertForSequenceClassification;c.MobileBertModel;c.MobileBertPreTrainedModel;c.MobileBertTokenizer;c.MobileLLMForCausalLM;c.MobileLLMModel;c.MobileLLMPreTrainedModel;c.MobileNetV1FeatureExtractor;c.MobileNetV1ForImageClassification;c.MobileNetV1ImageProcessor;c.MobileNetV1Model;c.MobileNetV1PreTrainedModel;c.MobileNetV2FeatureExtractor;c.MobileNetV2ForImageClassification;c.MobileNetV2ImageProcessor;c.MobileNetV2Model;c.MobileNetV2PreTrainedModel;c.MobileNetV3FeatureExtractor;c.MobileNetV3ForImageClassification;c.MobileNetV3ImageProcessor;c.MobileNetV3Model;c.MobileNetV3PreTrainedModel;c.MobileNetV4FeatureExtractor;c.MobileNetV4ForImageClassification;c.MobileNetV4ImageProcessor;c.MobileNetV4Model;c.MobileNetV4PreTrainedModel;c.MobileViTFeatureExtractor;c.MobileViTForImageClassification;c.MobileViTImageProcessor;c.MobileViTModel;c.MobileViTPreTrainedModel;c.MobileViTV2ForImageClassification;c.MobileViTV2Model;c.MobileViTV2PreTrainedModel;c.ModelOutput;c.ModernBertForMaskedLM;c.ModernBertForSequenceClassification;c.ModernBertForTokenClassification;c.ModernBertModel;c.ModernBertPreTrainedModel;c.Moondream1ForConditionalGeneration;c.MoonshineFeatureExtractor;c.MoonshineForConditionalGeneration;c.MoonshineModel;c.MoonshinePreTrainedModel;c.MoonshineProcessor;c.MptForCausalLM;c.MptModel;c.MptPreTrainedModel;c.MultiModalityCausalLM;c.MultiModalityPreTrainedModel;c.MusicgenForCausalLM;c.MusicgenForConditionalGeneration;c.MusicgenModel;c.MusicgenPreTrainedModel;c.NllbTokenizer;c.NoBadWordsLogitsProcessor;c.NoRepeatNGramLogitsProcessor;c.NomicBertModel;c.NomicBertPreTrainedModel;c.NougatImageProcessor;c.NougatTokenizer;c.OPTForCausalLM;c.OPTModel;c.OPTPreTrainedModel;c.ObjectDetectionPipeline;c.Olmo2ForCausalLM;c.Olmo2Model;c.Olmo2PreTrainedModel;c.OlmoForCausalLM;c.OlmoModel;c.OlmoPreTrainedModel;c.OpenELMForCausalLM;c.OpenELMModel;c.OpenELMPreTrainedModel;c.OwlViTFeatureExtractor;c.OwlViTForObjectDetection;c.OwlViTImageProcessor;c.OwlViTModel;c.OwlViTPreTrainedModel;c.OwlViTProcessor;c.Owlv2ForObjectDetection;c.Owlv2ImageProcessor;c.Owlv2Model;c.Owlv2PreTrainedModel;c.PaliGemmaForConditionalGeneration;c.PaliGemmaPreTrainedModel;c.PaliGemmaProcessor;c.PatchTSMixerForPrediction;c.PatchTSMixerModel;c.PatchTSMixerPreTrainedModel;c.PatchTSTForPrediction;c.PatchTSTModel;c.PatchTSTPreTrainedModel;c.Phi3ForCausalLM;c.Phi3Model;c.Phi3PreTrainedModel;c.Phi3VForCausalLM;c.Phi3VImageProcessor;c.Phi3VPreTrainedModel;c.Phi3VProcessor;c.PhiForCausalLM;c.PhiModel;c.PhiPreTrainedModel;c.Pipeline;c.PreTrainedModel;c.PreTrainedTokenizer;c.PretrainedConfig;c.PretrainedMixin;c.Processor;c.PvtForImageClassification;c.PvtImageProcessor;c.PvtModel;c.PvtPreTrainedModel;c.PyAnnoteFeatureExtractor;c.PyAnnoteForAudioFrameClassification;c.PyAnnoteModel;c.PyAnnotePreTrainedModel;c.PyAnnoteProcessor;c.QuestionAnsweringModelOutput;c.QuestionAnsweringPipeline;c.Qwen2ForCausalLM;c.Qwen2Model;c.Qwen2PreTrainedModel;c.Qwen2Tokenizer;c.Qwen2VLForConditionalGeneration;c.Qwen2VLImageProcessor;c.Qwen2VLPreTrainedModel;c.Qwen2VLProcessor;c.RTDetrForObjectDetection;c.RTDetrImageProcessor;c.RTDetrModel;c.RTDetrObjectDetectionOutput;c.RTDetrPreTrainedModel;c.RawImage;c.RepetitionPenaltyLogitsProcessor;c.ResNetForImageClassification;c.ResNetModel;c.ResNetPreTrainedModel;c.RoFormerForMaskedLM;c.RoFormerForQuestionAnswering;c.RoFormerForSequenceClassification;c.RoFormerForTokenClassification;c.RoFormerModel;c.RoFormerPreTrainedModel;c.RoFormerTokenizer;c.RobertaForMaskedLM;c.RobertaForQuestionAnswering;c.RobertaForSequenceClassification;c.RobertaForTokenClassification;c.RobertaModel;c.RobertaPreTrainedModel;c.RobertaTokenizer;c.SamImageProcessor;c.SamImageSegmentationOutput;c.SamModel;c.SamPreTrainedModel;c.SamProcessor;c.SapiensForDepthEstimation;c.SapiensForNormalEstimation;c.SapiensForSemanticSegmentation;c.SapiensPreTrainedModel;c.SeamlessM4TFeatureExtractor;c.SegformerFeatureExtractor;c.SegformerForImageClassification;c.SegformerForSemanticSegmentation;c.SegformerImageProcessor;c.SegformerModel;c.SegformerPreTrainedModel;c.Seq2SeqLMOutput;c.SequenceClassifierOutput;c.SiglipImageProcessor;c.SiglipModel;c.SiglipPreTrainedModel;c.SiglipTextModel;c.SiglipTokenizer;c.SiglipVisionModel;c.SpeechT5FeatureExtractor;c.SpeechT5ForSpeechToText;c.SpeechT5ForTextToSpeech;c.SpeechT5HifiGan;c.SpeechT5Model;c.SpeechT5PreTrainedModel;c.SpeechT5Processor;c.SpeechT5Tokenizer;c.SqueezeBertForMaskedLM;c.SqueezeBertForQuestionAnswering;c.SqueezeBertForSequenceClassification;c.SqueezeBertModel;c.SqueezeBertPreTrainedModel;c.SqueezeBertTokenizer;c.StableLmForCausalLM;c.StableLmModel;c.StableLmPreTrainedModel;c.Starcoder2ForCausalLM;c.Starcoder2Model;c.Starcoder2PreTrainedModel;c.StoppingCriteria;c.StoppingCriteriaList;c.SummarizationPipeline;c.SuppressTokensAtBeginLogitsProcessor;c.Swin2SRForImageSuperResolution;c.Swin2SRImageProcessor;c.Swin2SRModel;c.Swin2SRPreTrainedModel;c.SwinForImageClassification;c.SwinModel;c.SwinPreTrainedModel;c.T5ForConditionalGeneration;c.T5Model;c.T5PreTrainedModel;c.T5Tokenizer;c.TableTransformerForObjectDetection;c.TableTransformerModel;c.TableTransformerObjectDetectionOutput;c.TableTransformerPreTrainedModel;c.TemperatureLogitsWarper;var xh=c.Tensor;c.Text2TextGenerationPipeline;c.TextClassificationPipeline;c.TextGenerationPipeline;c.TextStreamer;c.TextToAudioPipeline;c.TokenClassificationPipeline;c.TokenClassifierOutput;c.TokenizerModel;c.TopKLogitsWarper;c.TopPLogitsWarper;c.TrOCRForCausalLM;c.TrOCRPreTrainedModel;c.TranslationPipeline;c.UniSpeechForCTC;c.UniSpeechForSequenceClassification;c.UniSpeechModel;c.UniSpeechPreTrainedModel;c.UniSpeechSatForAudioFrameClassification;c.UniSpeechSatForCTC;c.UniSpeechSatForSequenceClassification;c.UniSpeechSatModel;c.UniSpeechSatPreTrainedModel;c.VLChatProcessor;c.VLMImageProcessor;c.ViTFeatureExtractor;c.ViTForImageClassification;c.ViTImageProcessor;c.ViTMAEModel;c.ViTMAEPreTrainedModel;c.ViTMSNForImageClassification;c.ViTMSNModel;c.ViTMSNPreTrainedModel;c.ViTModel;c.ViTPreTrainedModel;c.VisionEncoderDecoderModel;c.VitMatteForImageMatting;c.VitMatteImageProcessor;c.VitMattePreTrainedModel;c.VitPoseForPoseEstimation;c.VitPoseImageProcessor;c.VitPosePreTrainedModel;c.VitsModel;c.VitsModelOutput;c.VitsPreTrainedModel;c.VitsTokenizer;c.Wav2Vec2BertForCTC;c.Wav2Vec2BertForSequenceClassification;c.Wav2Vec2BertModel;c.Wav2Vec2BertPreTrainedModel;c.Wav2Vec2CTCTokenizer;c.Wav2Vec2FeatureExtractor;c.Wav2Vec2ForAudioFrameClassification;c.Wav2Vec2ForCTC;c.Wav2Vec2ForSequenceClassification;c.Wav2Vec2Model;c.Wav2Vec2PreTrainedModel;c.Wav2Vec2ProcessorWithLM;c.WavLMForAudioFrameClassification;c.WavLMForCTC;c.WavLMForSequenceClassification;c.WavLMForXVector;c.WavLMModel;c.WavLMPreTrainedModel;c.WeSpeakerFeatureExtractor;c.WeSpeakerResNetModel;c.WeSpeakerResNetPreTrainedModel;c.WhisperFeatureExtractor;c.WhisperForConditionalGeneration;c.WhisperModel;c.WhisperPreTrainedModel;c.WhisperProcessor;c.WhisperTextStreamer;c.WhisperTimeStampLogitsProcessor;c.WhisperTokenizer;c.XLMForQuestionAnswering;c.XLMForSequenceClassification;c.XLMForTokenClassification;c.XLMModel;c.XLMPreTrainedModel;c.XLMRobertaForMaskedLM;c.XLMRobertaForQuestionAnswering;c.XLMRobertaForSequenceClassification;c.XLMRobertaForTokenClassification;c.XLMRobertaModel;c.XLMRobertaPreTrainedModel;c.XLMRobertaTokenizer;c.XLMTokenizer;c.XLMWithLMHeadModel;c.XVectorOutput;c.YolosFeatureExtractor;c.YolosForObjectDetection;c.YolosImageProcessor;c.YolosModel;c.YolosObjectDetectionOutput;c.YolosPreTrainedModel;c.ZeroShotAudioClassificationPipeline;c.ZeroShotClassificationPipeline;c.ZeroShotImageClassificationPipeline;c.ZeroShotObjectDetectionPipeline;c.bankers_round;c.cat;c.cos_sim;c.dot;c.dynamic_time_warping;c.env;c.full;c.full_like;c.getKeyValueShapes;c.hamming;c.hanning;c.interpolate;c.interpolate_4d;c.interpolate_data;c.is_chinese_char;c.layer_norm;c.load_image;c.log_softmax;c.magnitude;c.matmul;c.max;c.mean;c.mean_pooling;c.medianFilter;c.mel_filter_bank;c.min;c.ones;c.ones_like;c.permute;c.permute_data;var Nf=c.pipeline;c.quantize_embeddings;c.rand;c.read_audio;c.rfft;c.round;c.slice;c.softmax;c.spectrogram;c.stack;c.std_mean;c.topk;c.window_function;c.zeros;c.zeros_like;const va=16e3,Eh=va/1e3,jf=.3,Uf=.1,Vf=400,Wf=Vf*Eh,Gf=80,vh=Gf*Eh,Kf=250*Eh,Hf=30,qf=512,Xf=Math.ceil(vh/qf);async function Qf(){try{return!("gpu"in navigator)||!navigator.gpu?!1:(await navigator.gpu.requestAdapter(),!0)}catch(Te){return console.error(Te),!1}}var kn=(Te=>(Te.Status="status",Te.Output="output",Te.Info="info",Te.Request="request",Te.Error="error",Te.Load="load",Te))(kn||{}),Ph=(Te=>(Te.RecordingStart="recording_start",Te.RecordingEnd="recording_end",Te.Ready="ready",Te))(Ph||{}),Lp=(Te=>(Te.UntilNext="until_next",Te))(Lp||{});let Th,zp,Bp=Promise.resolve();const ba=new Float32Array(Hf*va);let Cn=0;const Yf=new xh("int64",[va],[]);let l_=new xh("float32",new Float32Array(2*1*128),[2,1,128]),$c=!1,Ac=0;const Jf={webgpu:{encoder_model:"fp32",decoder_model_merged:"q4"},wasm:{encoder_model:"fp32",decoder_model_merged:"q8"}};async function Zf(){return await Rf.from_pretrained("onnx-community/silero-vad",{config:{model_type:"custom"},dtype:"fp32"}).catch(Te=>{throw self.postMessage({type:kn.Error,error:Te}),Te})}async function eg(Te){return await Nf("automatic-speech-recognition","onnx-community/moonshine-base-ONNX",{device:Te,dtype:Jf[Te]}).catch(A=>{throw self.postMessage({type:kn.Error,error:A}),A})}async function tg(Te){if(Th===void 0)return console.warn("VAD model not loaded yet"),!1;const A=new xh("float32",Te,[1,Te.length]),{stateN:s,output:f}=await(Bp=Bp.then(N=>Th({input:A,sr:Yf,state:l_})));l_=s;const O=f.data[0];return O>jf||$c&&O>=Uf}async function rg(Te,A){if(zp===void 0){console.warn("Transcriber model not loaded yet");return}const{text:s}=await(Bp=Bp.then(f=>zp(Te)));self.postMessage({type:kn.Output,buffer:Te,message:s,...A})}function h_(Te=0){self.postMessage({type:kn.Status,status:Ph.RecordingEnd,message:"Transcribing...",duration:Lp.UntilNext}),ba.fill(0,Te),Cn=Te,$c=!1,Ac=0}const Ic=[];function u_(Te){const s=Date.now()-(Ac+vh)/va*1e3,f=s-Cn/va*1e3,O=s-f,N=(Te==null?void 0:Te.length)??0,Q=ba.slice(0,Cn+vh),U=Ic.reduce((y,M)=>y+M.length,0),w=new Float32Array(U+Q.length);let v=0;for(const y of Ic)w.set(y,v),v+=y.length;w.set(Q,v),rg(w,{start:f,end:s,duration:O}),Te&&ba.set(Te,0),h_(N)}async function sg(){const Te=await Qf()?"webgpu":"wasm";self.postMessage({type:kn.Info,message:`Using device: "${Te}"`}),self.postMessage({type:kn.Info,message:"Loading models...",duration:Lp.UntilNext}),Th=await Zf(),zp=await eg(Te),await zp(new Float32Array(va)),self.postMessage({type:"status",status:"ready",message:"Ready!"}),self.onmessage=async A=>{const{buffer:s}=A.data,f=$c,O=await tg(s);if(!f&&!O){Ic.length>=Xf&&Ic.shift(),Ic.push(s);return}const N=ba.length-Cn;if(s.length>=N){ba.set(s.subarray(0,N),Cn),Cn+=N;const Q=s.subarray(N);u_(Q);return}else ba.set(s,Cn),Cn+=s.length;if(O){$c||self.postMessage({type:kn.Status,status:Ph.RecordingStart,message:"Listening...",duration:Lp.UntilNext}),$c=!0,Ac=0;return}if(Ac+=s.length,!(Ac{const{type:A}=Te.data;switch(A){case kn.Load:sg();break}});