var $_=Object.defineProperty;var S_=(gs,ln,lo)=>ln in gs?$_(gs,ln,{enumerable:!0,configurable:!0,writable:!0,value:lo}):gs[ln]=lo;var ve=(gs,ln,lo)=>S_(gs,typeof ln!="symbol"?ln+"":ln,lo);(function(){"use strict";var gs={},ln={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Oe,R,c)=>{Oe.exports=c.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Oe,R,c)=>{c.r(R),c.d(R,{Environment:()=>nt,Interpreter:()=>dt,Template:()=>_t,parse:()=>ke,tokenize:()=>y});var w=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"}),z=Object.freeze({set:w.Set,for:w.For,in:w.In,is:w.Is,if:w.If,else:w.Else,endif:w.EndIf,elif:w.ElseIf,endfor:w.EndFor,and:w.And,or:w.Or,not:w.Not,"not in":w.NotIn,macro:w.Macro,endmacro:w.EndMacro,true:w.BooleanLiteral,false:w.BooleanLiteral,none:w.NullLiteral,True:w.BooleanLiteral,False:w.BooleanLiteral,None:w.NullLiteral}),G=class{constructor(A,ne){this.value=A,this.type=ne}};function re(A){return/\w/.test(A)}function Q(A){return/[0-9]/.test(A)}var g=[["{%",w.OpenStatement],["%}",w.CloseStatement],["{{",w.OpenExpression],["}}",w.CloseExpression],["(",w.OpenParen],[")",w.CloseParen],["{",w.OpenCurlyBracket],["}",w.CloseCurlyBracket],["[",w.OpenSquareBracket],["]",w.CloseSquareBracket],[",",w.Comma],[".",w.Dot],[":",w.Colon],["|",w.Pipe],["<=",w.ComparisonBinaryOperator],[">=",w.ComparisonBinaryOperator],["==",w.ComparisonBinaryOperator],["!=",w.ComparisonBinaryOperator],["<",w.ComparisonBinaryOperator],[">",w.ComparisonBinaryOperator],["+",w.AdditiveBinaryOperator],["-",w.AdditiveBinaryOperator],["*",w.MultiplicativeBinaryOperator],["/",w.MultiplicativeBinaryOperator],["%",w.MultiplicativeBinaryOperator],["=",w.Equals]],v=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(A,ne={}){return A.endsWith(` `)&&(A=A.slice(0,-1)),A=A.replace(/{#.*?#}/gs,"{##}"),ne.lstrip_blocks&&(A=A.replace(/^[ \t]*({[#%])/gm,"$1")),ne.trim_blocks&&(A=A.replace(/([#%]})\n/g,"$1")),A.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(A,ne={}){var ot,ut,At;const V=[],ue=M(A,ne);let Ae=0;const Je=xt=>{let Et="";for(;xt(ue[Ae]);){if(ue[Ae]==="\\"){if(++Ae,Ae>=ue.length)throw new SyntaxError("Unexpected end of input");const Ct=ue[Ae++],ar=v.get(Ct);if(ar===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ct}`);Et+=ar;continue}if(Et+=ue[Ae++],Ae>=ue.length)throw new SyntaxError("Unexpected end of input")}return Et};e:for(;Ae0){V.push(new G(Ct,w.Text));continue}}Je(Ct=>/\s/.test(Ct));const Et=ue[Ae];if(Et==="-"||Et==="+"){const Ct=(ut=V.at(-1))==null?void 0:ut.type;if(Ct===w.Text||Ct===void 0)throw new SyntaxError(`Unexpected character: ${Et}`);switch(Ct){case w.Identifier:case w.NumericLiteral:case w.BooleanLiteral:case w.NullLiteral:case w.StringLiteral:case w.CloseParen:case w.CloseSquareBracket:break;default:{++Ae;const ar=Je(Q);V.push(new G(`${Et}${ar}`,ar.length>0?w.NumericLiteral:w.UnaryOperator));continue}}}for(const[Ct,ar]of g)if(ue.slice(Ae,Ae+Ct.length)===Ct){V.push(new G(Ct,ar)),Ae+=Ct.length;continue e}if(Et==="'"||Et==='"'){++Ae;const Ct=Je(ar=>ar!==Et);V.push(new G(Ct,w.StringLiteral)),++Ae;continue}if(Q(Et)){const Ct=Je(Q);V.push(new G(Ct,w.NumericLiteral));continue}if(re(Et)){const Ct=Je(re),ar=Object.hasOwn(z,Ct)?z[Ct]:w.Identifier;ar===w.In&&((At=V.at(-1))==null?void 0:At.type)===w.Not?(V.pop(),V.push(new G("not in",w.NotIn))):V.push(new G(Ct,ar));continue}throw new SyntaxError(`Unexpected character: ${Et}`)}return V}var C=class{constructor(){ve(this,"type","Statement")}},q=class extends C{constructor(ne){super();ve(this,"type","Program");this.body=ne}},J=class extends C{constructor(ne,V,ue){super();ve(this,"type","If");this.test=ne,this.body=V,this.alternate=ue}},ie=class extends C{constructor(ne,V,ue,Ae){super();ve(this,"type","For");this.loopvar=ne,this.iterable=V,this.body=ue,this.defaultBlock=Ae}},fe=class extends C{constructor(ne,V){super();ve(this,"type","Set");this.assignee=ne,this.value=V}},j=class extends C{constructor(ne,V,ue){super();ve(this,"type","Macro");this.name=ne,this.args=V,this.body=ue}},X=class extends C{constructor(){super(...arguments);ve(this,"type","Expression")}},Z=class extends X{constructor(ne,V,ue){super();ve(this,"type","MemberExpression");this.object=ne,this.property=V,this.computed=ue}},N=class extends X{constructor(ne,V){super();ve(this,"type","CallExpression");this.callee=ne,this.args=V}},I=class extends X{constructor(ne){super();ve(this,"type","Identifier");this.value=ne}},_=class extends X{constructor(ne){super();ve(this,"type","Literal");this.value=ne}},k=class extends _{constructor(){super(...arguments);ve(this,"type","NumericLiteral")}},E=class extends _{constructor(){super(...arguments);ve(this,"type","StringLiteral")}},ee=class extends _{constructor(){super(...arguments);ve(this,"type","BooleanLiteral")}},Y=class extends _{constructor(){super(...arguments);ve(this,"type","NullLiteral")}},de=class extends _{constructor(){super(...arguments);ve(this,"type","ArrayLiteral")}},me=class extends _{constructor(){super(...arguments);ve(this,"type","TupleLiteral")}},ye=class extends _{constructor(){super(...arguments);ve(this,"type","ObjectLiteral")}},Ce=class extends X{constructor(ne,V,ue){super();ve(this,"type","BinaryExpression");this.operator=ne,this.left=V,this.right=ue}},Ee=class extends X{constructor(ne,V){super();ve(this,"type","FilterExpression");this.operand=ne,this.filter=V}},Le=class extends X{constructor(ne,V){super();ve(this,"type","SelectExpression");this.iterable=ne,this.test=V}},_e=class extends X{constructor(ne,V,ue){super();ve(this,"type","TestExpression");this.operand=ne,this.negate=V,this.test=ue}},U=class extends X{constructor(ne,V){super();ve(this,"type","UnaryExpression");this.operator=ne,this.argument=V}},ce=class extends X{constructor(ne=void 0,V=void 0,ue=void 0){super();ve(this,"type","SliceExpression");this.start=ne,this.stop=V,this.step=ue}},he=class extends X{constructor(ne,V){super();ve(this,"type","KeywordArgumentExpression");this.key=ne,this.value=V}};function ke(A){const ne=new q([]);let V=0;function ue(it,Mt){const It=A[V++];if(!It||It.type!==it)throw new Error(`Parser Error: ${Mt}. ${It.type} !== ${it}.`);return It}function Ae(){switch(A[V].type){case w.Text:return ut();case w.OpenStatement:return At();case w.OpenExpression:return xt();default:throw new SyntaxError(`Unexpected token type: ${A[V].type}`)}}function Je(...it){return V+it.length<=A.length&&it.some((Mt,It)=>Mt!==A[V+It].type)}function ot(...it){return V+it.length<=A.length&&it.every((Mt,It)=>Mt===A[V+It].type)}function ut(){return new E(ue(w.Text,"Expected text token").value)}function At(){ue(w.OpenStatement,"Expected opening statement token");let it;switch(A[V].type){case w.Set:++V,it=Et(),ue(w.CloseStatement,"Expected closing statement token");break;case w.If:++V,it=Ct(),ue(w.OpenStatement,"Expected {% token"),ue(w.EndIf,"Expected endif token"),ue(w.CloseStatement,"Expected %} token");break;case w.Macro:++V,it=ar(),ue(w.OpenStatement,"Expected {% token"),ue(w.EndMacro,"Expected endmacro token"),ue(w.CloseStatement,"Expected %} token");break;case w.For:++V,it=Nr(),ue(w.OpenStatement,"Expected {% token"),ue(w.EndFor,"Expected endfor token"),ue(w.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${A[V].type}`)}return it}function xt(){ue(w.OpenExpression,"Expected opening expression token");const it=Fr();return ue(w.CloseExpression,"Expected closing expression token"),it}function Et(){const it=Fr();if(ot(w.Equals)){++V;const Mt=Et();return new fe(it,Mt)}return it}function Ct(){var Wr,en,Bs,Sr,ts,Br,As,br;const it=Fr();ue(w.CloseStatement,"Expected closing statement token");const Mt=[],It=[];for(;!(((Wr=A[V])==null?void 0:Wr.type)===w.OpenStatement&&(((en=A[V+1])==null?void 0:en.type)===w.ElseIf||((Bs=A[V+1])==null?void 0:Bs.type)===w.Else||((Sr=A[V+1])==null?void 0:Sr.type)===w.EndIf));)Mt.push(Ae());if(((ts=A[V])==null?void 0:ts.type)===w.OpenStatement&&((Br=A[V+1])==null?void 0:Br.type)!==w.EndIf)if(++V,ot(w.ElseIf))ue(w.ElseIf,"Expected elseif token"),It.push(Ct());else for(ue(w.Else,"Expected else token"),ue(w.CloseStatement,"Expected closing statement token");!(((As=A[V])==null?void 0:As.type)===w.OpenStatement&&((br=A[V+1])==null?void 0:br.type)===w.EndIf);)It.push(Ae());return new J(it,Mt,It)}function ar(){const it=ps();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Mt=Xs();ue(w.CloseStatement,"Expected closing statement token");const It=[];for(;Je(w.OpenStatement,w.EndMacro);)It.push(Ae());return new j(it,Mt,It)}function Mr(it=!1){const Mt=it?ps:Fr,It=[Mt()],Wr=ot(w.Comma);for(;Wr&&(++V,It.push(Mt()),!!ot(w.Comma)););return Wr?new me(It):It[0]}function Nr(){const it=Mr(!0);if(!(it instanceof I||it instanceof me))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);ue(w.In,"Expected `in` keyword following loop variable");const Mt=Fr();ue(w.CloseStatement,"Expected closing statement token");const It=[];for(;Je(w.OpenStatement,w.EndFor)&&Je(w.OpenStatement,w.Else);)It.push(Ae());const Wr=[];if(ot(w.OpenStatement,w.Else))for(++V,++V,ue(w.CloseStatement,"Expected closing statement token");Je(w.OpenStatement,w.EndFor);)Wr.push(Ae());return new ie(it,Mt,It,Wr)}function Fr(){return as()}function as(){const it=qs();if(ot(w.If)){++V;const Mt=qs();if(ot(w.Else)){++V;const It=qs();return new J(Mt,[it],[It])}else return new Le(it,Mt)}return it}function qs(){let it=Qs();for(;ot(w.Or);){const Mt=A[V];++V;const It=Qs();it=new Ce(Mt,it,It)}return it}function Qs(){let it=Ds();for(;ot(w.And);){const Mt=A[V];++V;const It=Ds();it=new Ce(Mt,it,It)}return it}function Ds(){let it;for(;ot(w.Not);){const Mt=A[V];++V;const It=Ds();it=new U(Mt,It)}return it??vn()}function vn(){let it=Dt();for(;ot(w.ComparisonBinaryOperator)||ot(w.In)||ot(w.NotIn);){const Mt=A[V];++V;const It=Dt();it=new Ce(Mt,it,It)}return it}function Dt(){let it=Js();for(;ot(w.AdditiveBinaryOperator);){const Mt=A[V];++V;const It=Js();it=new Ce(Mt,it,It)}return it}function Ts(){const it=xs();return ot(w.OpenParen)?Ls(it):it}function Ls(it){let Mt=new N(it,Xs());return ot(w.OpenParen)&&(Mt=Ls(Mt)),Mt}function Xs(){ue(w.OpenParen,"Expected opening parenthesis for arguments list");const it=un();return ue(w.CloseParen,"Expected closing parenthesis for arguments list"),it}function un(){const it=[];for(;!ot(w.CloseParen);){let Mt=Fr();if(ot(w.Equals)){if(++V,!(Mt instanceof I))throw new SyntaxError("Expected identifier for keyword argument");const It=Fr();Mt=new he(Mt,It)}it.push(Mt),ot(w.Comma)&&++V}return it}function Ys(){const it=[];let Mt=!1;for(;!ot(w.CloseSquareBracket);)ot(w.Colon)?(it.push(void 0),++V,Mt=!0):(it.push(Fr()),ot(w.Colon)&&(++V,Mt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Mt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ce(...it)}return it[0]}function xs(){let it=ps();for(;ot(w.Dot)||ot(w.OpenSquareBracket);){const Mt=A[V];++V;let It;const Wr=Mt.type!==w.Dot;if(Wr)It=Ys(),ue(w.CloseSquareBracket,"Expected closing square bracket");else if(It=ps(),It.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new Z(it,It,Wr)}return it}function Js(){let it=Zs();for(;ot(w.MultiplicativeBinaryOperator);){const Mt=A[V];++V;const It=Zs();it=new Ce(Mt,it,It)}return it}function Zs(){let it=zs();for(;ot(w.Is);){++V;const Mt=ot(w.Not);Mt&&++V;let It=ps();if(It instanceof ee?It=new I(It.value.toString()):It instanceof Y&&(It=new I("none")),!(It instanceof I))throw new SyntaxError("Expected identifier for the test");it=new _e(it,Mt,It)}return it}function zs(){let it=Ts();for(;ot(w.Pipe);){++V;let Mt=ps();if(!(Mt instanceof I))throw new SyntaxError("Expected identifier for the filter");ot(w.OpenParen)&&(Mt=Ls(Mt)),it=new Ee(it,Mt)}return it}function ps(){const it=A[V];switch(it.type){case w.NumericLiteral:return++V,new k(Number(it.value));case w.StringLiteral:return++V,new E(it.value);case w.BooleanLiteral:return++V,new ee(it.value.toLowerCase()==="true");case w.NullLiteral:return++V,new Y(null);case w.Identifier:return++V,new I(it.value);case w.OpenParen:{++V;const Mt=Mr();if(A[V].type!==w.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${A[V].type} instead`);return++V,Mt}case w.OpenSquareBracket:{++V;const Mt=[];for(;!ot(w.CloseSquareBracket);)Mt.push(Fr()),ot(w.Comma)&&++V;return++V,new de(Mt)}case w.OpenCurlyBracket:{++V;const Mt=new Map;for(;!ot(w.CloseCurlyBracket);){const It=Fr();ue(w.Colon,"Expected colon between key and value in object literal");const Wr=Fr();Mt.set(It,Wr),ot(w.Comma)&&++V}return++V,new ye(Mt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;V=0?(ne=(ne??(ne=0))<0?Math.max(A.length+ne,0):Math.min(ne,A.length),V=(V??(V=A.length))<0?Math.max(A.length+V,0):Math.min(V,A.length)):(ne=(ne??(ne=A.length-1))<0?Math.max(A.length+ne,-1):Math.min(ne,A.length-1),V=(V??(V=-1))<-1?Math.max(A.length+V,-1):Math.min(V,A.length-1));const Je=[];for(let ot=ne;Ae*otne.toUpperCase())}var at=class{constructor(A=void 0){ve(this,"type","RuntimeValue");ve(this,"value");ve(this,"builtins",new Map);this.value=A}__bool__(){return new He(!!this.value)}},We=class extends at{constructor(){super(...arguments);ve(this,"type","NumericValue")}},le=class extends at{constructor(){super(...arguments);ve(this,"type","StringValue");ve(this,"builtins",new Map([["upper",new Qe(()=>new le(this.value.toUpperCase()))],["lower",new Qe(()=>new le(this.value.toLowerCase()))],["strip",new Qe(()=>new le(this.value.trim()))],["title",new Qe(()=>new le(Ye(this.value)))],["length",new We(this.value.length)],["rstrip",new Qe(()=>new le(this.value.trimEnd()))],["lstrip",new Qe(()=>new le(this.value.trimStart()))]]))}},He=class extends at{constructor(){super(...arguments);ve(this,"type","BooleanValue")}},je=class extends at{constructor(){super(...arguments);ve(this,"type","ObjectValue");ve(this,"builtins",new Map([["get",new Qe(([ne,V])=>{if(!(ne instanceof le))throw new Error(`Object key must be a string: got ${ne.type}`);return this.value.get(ne.value)??V??new qe})],["items",new Qe(()=>new $e(Array.from(this.value.entries()).map(([ne,V])=>new $e([new le(ne),V]))))]]))}__bool__(){return new He(this.value.size>0)}},we=class extends je{constructor(){super(...arguments);ve(this,"type","KeywordArgumentsValue")}},$e=class extends at{constructor(){super(...arguments);ve(this,"type","ArrayValue");ve(this,"builtins",new Map([["length",new We(this.value.length)]]))}__bool__(){return new He(this.value.length>0)}},et=class extends $e{constructor(){super(...arguments);ve(this,"type","TupleValue")}},Qe=class extends at{constructor(){super(...arguments);ve(this,"type","FunctionValue")}},qe=class extends at{constructor(){super(...arguments);ve(this,"type","NullValue")}},ze=class extends at{constructor(){super(...arguments);ve(this,"type","UndefinedValue")}},nt=class{constructor(A){ve(this,"variables",new Map([["namespace",new Qe(A=>{if(A.length===0)return new je(new Map);if(A.length!==1||!(A[0]instanceof je))throw new Error("`namespace` expects either zero arguments or a single object argument");return A[0]})]]));ve(this,"tests",new Map([["boolean",A=>A.type==="BooleanValue"],["callable",A=>A instanceof Qe],["odd",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${A.type}`);return A.value%2!==0}],["even",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${A.type}`);return A.value%2===0}],["false",A=>A.type==="BooleanValue"&&!A.value],["true",A=>A.type==="BooleanValue"&&A.value],["none",A=>A.type==="NullValue"],["string",A=>A.type==="StringValue"],["number",A=>A.type==="NumericValue"],["integer",A=>A.type==="NumericValue"&&Number.isInteger(A.value)],["iterable",A=>A.type==="ArrayValue"||A.type==="StringValue"],["mapping",A=>A.type==="ObjectValue"],["lower",A=>{const ne=A.value;return A.type==="StringValue"&&ne===ne.toLowerCase()}],["upper",A=>{const ne=A.value;return A.type==="StringValue"&&ne===ne.toUpperCase()}],["none",A=>A.type==="NullValue"],["defined",A=>A.type!=="UndefinedValue"],["undefined",A=>A.type==="UndefinedValue"],["equalto",(A,ne)=>A.value===ne.value],["eq",(A,ne)=>A.value===ne.value]]));this.parent=A}set(A,ne){return this.declareVariable(A,gt(ne))}declareVariable(A,ne){if(this.variables.has(A))throw new SyntaxError(`Variable already declared: ${A}`);return this.variables.set(A,ne),ne}setVariable(A,ne){return this.variables.set(A,ne),ne}resolve(A){if(this.variables.has(A))return this;if(this.parent)return this.parent.resolve(A);throw new Error(`Unknown variable: ${A}`)}lookupVariable(A){try{return this.resolve(A).variables.get(A)??new ze}catch{return new ze}}},dt=class{constructor(A){ve(this,"global");this.global=A??new nt}run(A){return this.evaluate(A,this.global)}evaluateBinaryExpression(A,ne){const V=this.evaluate(A.left,ne);switch(A.operator.value){case"and":return V.__bool__().value?this.evaluate(A.right,ne):V;case"or":return V.__bool__().value?V:this.evaluate(A.right,ne)}const ue=this.evaluate(A.right,ne);switch(A.operator.value){case"==":return new He(V.value==ue.value);case"!=":return new He(V.value!=ue.value)}if(V instanceof ze||ue instanceof ze)throw new Error("Cannot perform operation on undefined values");if(V instanceof qe||ue instanceof qe)throw new Error("Cannot perform operation on null values");if(V instanceof We&&ue instanceof We)switch(A.operator.value){case"+":return new We(V.value+ue.value);case"-":return new We(V.value-ue.value);case"*":return new We(V.value*ue.value);case"/":return new We(V.value/ue.value);case"%":return new We(V.value%ue.value);case"<":return new He(V.value":return new He(V.value>ue.value);case">=":return new He(V.value>=ue.value);case"<=":return new He(V.value<=ue.value)}else if(V instanceof $e&&ue instanceof $e)switch(A.operator.value){case"+":return new $e(V.value.concat(ue.value))}else if(ue instanceof $e){const Ae=ue.value.find(Je=>Je.value===V.value)!==void 0;switch(A.operator.value){case"in":return new He(Ae);case"not in":return new He(!Ae)}}if(V instanceof le||ue instanceof le)switch(A.operator.value){case"+":return new le(V.value.toString()+ue.value.toString())}if(V instanceof le&&ue instanceof le)switch(A.operator.value){case"in":return new He(ue.value.includes(V.value));case"not in":return new He(!ue.value.includes(V.value))}if(V instanceof le&&ue instanceof je)switch(A.operator.value){case"in":return new He(ue.value.has(V.value));case"not in":return new He(!ue.value.has(V.value))}throw new SyntaxError(`Unknown operator "${A.operator.value}" between ${V.type} and ${ue.type}`)}evaluateArguments(A,ne){const V=[],ue=new Map;for(const Ae of A)if(Ae.type==="KeywordArgumentExpression"){const Je=Ae;ue.set(Je.key.value,this.evaluate(Je.value,ne))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");V.push(this.evaluate(Ae,ne))}return[V,ue]}evaluateFilterExpression(A,ne){const V=this.evaluate(A.operand,ne);if(A.filter.type==="Identifier"){const ue=A.filter;if(ue.value==="tojson")return new le(ht(V));if(V instanceof $e)switch(ue.value){case"list":return V;case"first":return V.value[0];case"last":return V.value[V.value.length-1];case"length":return new We(V.value.length);case"reverse":return new $e(V.value.reverse());case"sort":return new $e(V.value.sort((Ae,Je)=>{if(Ae.type!==Je.type)throw new Error(`Cannot compare different types: ${Ae.type} and ${Je.type}`);switch(Ae.type){case"NumericValue":return Ae.value-Je.value;case"StringValue":return Ae.value.localeCompare(Je.value);default:throw new Error(`Cannot compare type: ${Ae.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ue.value}`)}else if(V instanceof le)switch(ue.value){case"length":return new We(V.value.length);case"upper":return new le(V.value.toUpperCase());case"lower":return new le(V.value.toLowerCase());case"title":return new le(Ye(V.value));case"capitalize":return new le(V.value.charAt(0).toUpperCase()+V.value.slice(1));case"trim":return new le(V.value.trim());case"indent":return new le(V.value.split(` `).map((Ae,Je)=>Je===0||Ae.length===0?Ae:" "+Ae).join(` `));case"string":return V;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(V instanceof We)switch(ue.value){case"abs":return new We(Math.abs(V.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(V instanceof je)switch(ue.value){case"items":return new $e(Array.from(V.value.entries()).map(([Ae,Je])=>new $e([new le(Ae),Je])));case"length":return new We(V.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${V.type}`)}else if(A.filter.type==="CallExpression"){const ue=A.filter;if(ue.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ue.callee.type}`);const Ae=ue.callee.value;if(Ae==="tojson"){const[,Je]=this.evaluateArguments(ue.args,ne),ot=Je.get("indent")??new qe;if(!(ot instanceof We||ot instanceof qe))throw new Error("If set, indent must be a number");return new le(ht(V,ot.value))}if(V instanceof $e){switch(Ae){case"selectattr":case"rejectattr":{const Je=Ae==="selectattr";if(V.value.some(Ct=>!(Ct instanceof je)))throw new Error(`\`${Ae}\` can only be applied to array of objects`);if(ue.args.some(Ct=>Ct.type!=="StringLiteral"))throw new Error(`arguments of \`${Ae}\` must be strings`);const[ot,ut,At]=ue.args.map(Ct=>this.evaluate(Ct,ne));let xt;if(ut){const Ct=ne.tests.get(ut.value);if(!Ct)throw new Error(`Unknown test: ${ut.value}`);xt=Ct}else xt=(...Ct)=>Ct[0].__bool__().value;const Et=V.value.filter(Ct=>{const ar=Ct.value.get(ot.value),Mr=ar?xt(ar,At):!1;return Je?Mr:!Mr});return new $e(Et)}case"map":{const[,Je]=this.evaluateArguments(ue.args,ne);if(Je.has("attribute")){const ot=Je.get("attribute");if(!(ot instanceof le))throw new Error("attribute must be a string");const ut=Je.get("default"),At=V.value.map(xt=>{if(!(xt instanceof je))throw new Error("items in map must be an object");return xt.value.get(ot.value)??ut??new ze});return new $e(At)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Ae}`)}else if(V instanceof le){switch(Ae){case"indent":{const[Je,ot]=this.evaluateArguments(ue.args,ne),ut=Je.at(0)??ot.get("width")??new We(4);if(!(ut instanceof We))throw new Error("width must be a number");const At=Je.at(1)??ot.get("first")??new He(!1),xt=Je.at(2)??ot.get("blank")??new He(!1),Et=V.value.split(` `),Ct=" ".repeat(ut.value),ar=Et.map((Mr,Nr)=>!At.value&&Nr===0||!xt.value&&Mr.length===0?Mr:Ct+Mr);return new le(ar.join(` `))}}throw new Error(`Unknown StringValue filter: ${Ae}`)}else throw new Error(`Cannot apply filter "${Ae}" to type: ${V.type}`)}throw new Error(`Unknown filter: ${A.filter.type}`)}evaluateTestExpression(A,ne){const V=this.evaluate(A.operand,ne),ue=ne.tests.get(A.test.value);if(!ue)throw new Error(`Unknown test: ${A.test.value}`);const Ae=ue(V);return new He(A.negate?!Ae:Ae)}evaluateUnaryExpression(A,ne){const V=this.evaluate(A.argument,ne);switch(A.operator.value){case"not":return new He(!V.value);default:throw new SyntaxError(`Unknown operator: ${A.operator.value}`)}}evalProgram(A,ne){return this.evaluateBlock(A.body,ne)}evaluateBlock(A,ne){let V="";for(const ue of A){const Ae=this.evaluate(ue,ne);Ae.type!=="NullValue"&&Ae.type!=="UndefinedValue"&&(V+=Ae.value)}return new le(V)}evaluateIdentifier(A,ne){return ne.lookupVariable(A.value)}evaluateCallExpression(A,ne){const[V,ue]=this.evaluateArguments(A.args,ne);ue.size>0&&V.push(new we(ue));const Ae=this.evaluate(A.callee,ne);if(Ae.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Ae.type}`);return Ae.value(V,ne)}evaluateSliceExpression(A,ne,V){if(!(A instanceof $e||A instanceof le))throw new Error("Slice object must be an array or string");const ue=this.evaluate(ne.start,V),Ae=this.evaluate(ne.stop,V),Je=this.evaluate(ne.step,V);if(!(ue instanceof We||ue instanceof ze))throw new Error("Slice start must be numeric or undefined");if(!(Ae instanceof We||Ae instanceof ze))throw new Error("Slice stop must be numeric or undefined");if(!(Je instanceof We||Je instanceof ze))throw new Error("Slice step must be numeric or undefined");return A instanceof $e?new $e(Ke(A.value,ue.value,Ae.value,Je.value)):new le(Ke(Array.from(A.value),ue.value,Ae.value,Je.value).join(""))}evaluateMemberExpression(A,ne){const V=this.evaluate(A.object,ne);let ue;if(A.computed){if(A.property.type==="SliceExpression")return this.evaluateSliceExpression(V,A.property,ne);ue=this.evaluate(A.property,ne)}else ue=new le(A.property.value);let Ae;if(V instanceof je){if(!(ue instanceof le))throw new Error(`Cannot access property with non-string: got ${ue.type}`);Ae=V.value.get(ue.value)??V.builtins.get(ue.value)}else if(V instanceof $e||V instanceof le)if(ue instanceof We)Ae=V.value.at(ue.value),V instanceof le&&(Ae=new le(V.value.at(ue.value)));else if(ue instanceof le)Ae=V.builtins.get(ue.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ue.type}`);else{if(!(ue instanceof le))throw new Error(`Cannot access property with non-string: got ${ue.type}`);Ae=V.builtins.get(ue.value)}return Ae instanceof at?Ae:new ze}evaluateSet(A,ne){const V=this.evaluate(A.value,ne);if(A.assignee.type==="Identifier"){const ue=A.assignee.value;ne.setVariable(ue,V)}else if(A.assignee.type==="MemberExpression"){const ue=A.assignee,Ae=this.evaluate(ue.object,ne);if(!(Ae instanceof je))throw new Error("Cannot assign to member of non-object");if(ue.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");Ae.value.set(ue.property.value,V)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(A.assignee)}`);return new qe}evaluateIf(A,ne){const V=this.evaluate(A.test,ne);return this.evaluateBlock(V.__bool__().value?A.body:A.alternate,ne)}evaluateFor(A,ne){const V=new nt(ne);let ue,Ae;if(A.iterable.type==="SelectExpression"){const xt=A.iterable;Ae=this.evaluate(xt.iterable,V),ue=xt.test}else Ae=this.evaluate(A.iterable,V);if(!(Ae instanceof $e))throw new Error(`Expected iterable type in for loop: got ${Ae.type}`);const Je=[],ot=[];for(let xt=0;xtMr.setVariable(A.loopvar.value,Ct);else if(A.loopvar.type==="TupleLiteral"){const Mr=A.loopvar;if(Ct.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ct.type}`);const Nr=Ct;if(Mr.value.length!==Nr.value.length)throw new Error(`Too ${Mr.value.length>Nr.value.length?"few":"many"} items to unpack`);ar=Fr=>{for(let as=0;as0?Je[xt-1]:new ze],["nextitem",xt{var ot;const Ae=new nt(ue);V=V.slice();let Je;((ot=V.at(-1))==null?void 0:ot.type)==="KeywordArgumentsValue"&&(Je=V.pop());for(let ut=0;utthis.evaluate(V,ne)));case"TupleLiteral":return new et(A.value.map(V=>this.evaluate(V,ne)));case"ObjectLiteral":{const V=new Map;for(const[ue,Ae]of A.value){const Je=this.evaluate(ue,ne);if(!(Je instanceof le))throw new Error(`Object keys must be strings: got ${Je.type}`);V.set(Je.value,this.evaluate(Ae,ne))}return new je(V)}case"Identifier":return this.evaluateIdentifier(A,ne);case"CallExpression":return this.evaluateCallExpression(A,ne);case"MemberExpression":return this.evaluateMemberExpression(A,ne);case"UnaryExpression":return this.evaluateUnaryExpression(A,ne);case"BinaryExpression":return this.evaluateBinaryExpression(A,ne);case"FilterExpression":return this.evaluateFilterExpression(A,ne);case"TestExpression":return this.evaluateTestExpression(A,ne);default:throw new SyntaxError(`Unknown node type: ${A.type}`)}}};function gt(A){switch(typeof A){case"number":return new We(A);case"string":return new le(A);case"boolean":return new He(A);case"undefined":return new ze;case"object":return A===null?new qe:Array.isArray(A)?new $e(A.map(gt)):new je(new Map(Object.entries(A).map(([ne,V])=>[ne,gt(V)])));case"function":return new Qe((ne,V)=>{const ue=A(...ne.map(Ae=>Ae.value))??null;return gt(ue)});default:throw new Error(`Cannot convert to runtime value: ${A}`)}}function ht(A,ne,V){const ue=V??0;switch(A.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(A.value);case"ArrayValue":case"ObjectValue":{const Ae=ne?" ".repeat(ne):"",Je=` `+Ae.repeat(ue),ot=Je+Ae;if(A.type==="ArrayValue"){const ut=A.value.map(At=>ht(At,ne,ue+1));return ne?`[${ot}${ut.join(`,${ot}`)}${Je}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(A.value.entries()).map(([At,xt])=>{const Et=`"${At}": ${ht(xt,ne,ue+1)}`;return ne?`${ot}${Et}`:Et});return ne?`{${ut.join(",")}${Je}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${A.type}`)}}var _t=class{constructor(A){ve(this,"parsed");const ne=y(A,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ke(ne)}render(A){const ne=new nt;ne.set("false",!1),ne.set("true",!0),ne.set("raise_exception",Ae=>{throw new Error(Ae)}),ne.set("range",Re);for(const[Ae,Je]of Object.entries(A))ne.set(Ae,Je);return new dt(ne).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{registerBackend:()=>G,resolveBackendAndExecutionProviders:()=>Q});const w=new Map,z=[],G=(g,v,M)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const y=w.get(g);if(y===void 0)w.set(g,{backend:v,priority:M});else{if(y.priority>M)return;if(y.priority===M&&y.backend!==v)throw new Error(`cannot register backend "${g}" using priority ${M}`)}if(M>=0){const C=z.indexOf(g);C!==-1&&z.splice(C,1);for(let q=0;q{const v=w.get(g);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const M=!!v.initPromise;try{return M||(v.initPromise=v.backend.init(g)),await v.initPromise,v.initialized=!0,v.backend}catch(y){return M||(v.error=`${y}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},Q=async g=>{const v=g.executionProviders||[],M=v.map(fe=>typeof fe=="string"?fe:fe.name),y=M.length===0?z:M;let C;const q=[],J=new Set;for(const fe of y){const j=await re(fe);typeof j=="string"?q.push({name:fe,err:j}):(C||(C=j),C===j&&J.add(fe))}if(!C)throw new Error(`no available backend found. ERR: ${q.map(fe=>`[${fe.name}] ${fe.err}`).join(", ")}`);for(const{name:fe,err:j}of q)M.includes(fe)&&console.warn(`removing requested execution provider "${fe}" from session options because it is not available: ${j}`);const ie=v.filter(fe=>J.has(typeof fe=="string"?fe:fe.name));return[C,new Proxy(g,{get:(fe,j)=>j==="executionProviders"?ie:Reflect.get(fe,j)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Oe,R,c)=>{c.r(R),c.d(R,{registerBackend:()=>w.registerBackend});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{env:()=>G});var w=c("./node_modules/onnxruntime-common/dist/esm/version.js");let z="warning";const G={wasm:{},webgl:{},webgpu:{},versions:{common:w.version},set logLevel(re){if(re!==void 0){if(typeof re!="string"||["verbose","info","warning","error","fatal"].indexOf(re)===-1)throw new Error(`Unsupported logging level: ${re}`);z=re}},get logLevel(){return z}};Object.defineProperty(G,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Oe,R,c)=>{c.r(R),c.d(R,{env:()=>z});var w=c("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const z=w.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Oe,R,c)=>{c.r(R),c.d(R,{InferenceSession:()=>G.InferenceSession,TRACE:()=>Q.TRACE,TRACE_FUNC_BEGIN:()=>Q.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Q.TRACE_FUNC_END,Tensor:()=>re.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>z.env,registerBackend:()=>w.registerBackend});var w=c("./node_modules/onnxruntime-common/dist/esm/backend.js"),z=c("./node_modules/onnxruntime-common/dist/esm/env.js"),G=c("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),re=c("./node_modules/onnxruntime-common/dist/esm/tensor.js");c("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),c("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Q=c("./node_modules/onnxruntime-common/dist/esm/trace.js");c("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),c("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=c("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{InferenceSession:()=>re});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),z=c("./node_modules/onnxruntime-common/dist/esm/tensor.js"),G=c("./node_modules/onnxruntime-common/dist/esm/trace.js");class re{constructor(g){this.handler=g}async run(g,v,M){(0,G.TRACE_FUNC_BEGIN)();const y={};let C={};if(typeof g!="object"||g===null||g instanceof z.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let q=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof z.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.");q=!1;for(const fe of v){if(typeof fe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(fe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${fe}.`);y[fe]=null}if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let fe=!1;const j=Object.getOwnPropertyNames(v);for(const X of this.outputNames)if(j.indexOf(X)!==-1){const Z=v[X];(Z===null||Z instanceof z.Tensor)&&(fe=!0,q=!1,y[X]=Z)}if(fe){if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else C=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const fe of this.inputNames)if(typeof g[fe]>"u")throw new Error(`input '${fe}' is missing in 'feeds'.`);if(q)for(const fe of this.outputNames)y[fe]=null;const J=await this.handler.run(g,y,C),ie={};for(const fe in J)if(Object.hasOwnProperty.call(J,fe)){const j=J[fe];j instanceof z.Tensor?ie[fe]=j:ie[fe]=new z.Tensor(j.type,j.data,j.dims)}return(0,G.TRACE_FUNC_END)(),ie}async release(){return this.handler.dispose()}static async create(g,v,M,y){(0,G.TRACE_FUNC_BEGIN)();let C,q={};if(typeof g=="string"){if(C=g,typeof v=="object"&&v!==null)q=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(C=g,typeof v=="object"&&v!==null)q=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&g instanceof SharedArrayBuffer){const j=g;let X=0,Z=g.byteLength;if(typeof v=="object"&&v!==null)q=v;else if(typeof v=="number"){if(X=v,!Number.isSafeInteger(X))throw new RangeError("'byteOffset' must be an integer.");if(X<0||X>=j.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${j.byteLength}).`);if(Z=g.byteLength-X,typeof M=="number"){if(Z=M,!Number.isSafeInteger(Z))throw new RangeError("'byteLength' must be an integer.");if(Z<=0||X+Z>j.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${j.byteLength-X}].`);if(typeof y=="object"&&y!==null)q=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");C=new Uint8Array(j,X,Z)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[J,ie]=await(0,w.resolveBackendAndExecutionProviders)(q),fe=await J.createInferenceSessionHandler(C,ie);return(0,G.TRACE_FUNC_END)(),new re(fe)}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":(Oe,R,c)=>{c.r(R),c.d(R,{InferenceSession:()=>z});var w=c("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const z=w.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Oe,R,c)=>{c.r(R)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Oe,R,c)=>{c.r(R)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{tensorToDataURL:()=>w,tensorToImageData:()=>z});const w=(G,re)=>{const Q=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Q.width=G.dims[3],Q.height=G.dims[2];const g=Q.getContext("2d");if(g!=null){let v,M;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(v=G.dims[2],M=G.dims[3]):(v=G.dims[3],M=G.dims[2]);const y=(re==null?void 0:re.format)!==void 0?re.format:"RGB",C=re==null?void 0:re.norm;let q,J;C===void 0||C.mean===void 0?q=[255,255,255,255]:typeof C.mean=="number"?q=[C.mean,C.mean,C.mean,C.mean]:(q=[C.mean[0],C.mean[1],C.mean[2],0],C.mean[3]!==void 0&&(q[3]=C.mean[3])),C===void 0||C.bias===void 0?J=[0,0,0,0]:typeof C.bias=="number"?J=[C.bias,C.bias,C.bias,C.bias]:(J=[C.bias[0],C.bias[1],C.bias[2],0],C.bias[3]!==void 0&&(J[3]=C.bias[3]));const ie=M*v;let fe=0,j=ie,X=ie*2,Z=-1;y==="RGBA"?(fe=0,j=ie,X=ie*2,Z=ie*3):y==="RGB"?(fe=0,j=ie,X=ie*2):y==="RBG"&&(fe=0,X=ie,j=ie*2);for(let N=0;N{const Q=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(Q!=null){let v,M,y;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(v=G.dims[2],M=G.dims[1],y=G.dims[3]):(v=G.dims[3],M=G.dims[2],y=G.dims[1]);const C=re!==void 0&&re.format!==void 0?re.format:"RGB",q=re==null?void 0:re.norm;let J,ie;q===void 0||q.mean===void 0?J=[255,255,255,255]:typeof q.mean=="number"?J=[q.mean,q.mean,q.mean,q.mean]:(J=[q.mean[0],q.mean[1],q.mean[2],255],q.mean[3]!==void 0&&(J[3]=q.mean[3])),q===void 0||q.bias===void 0?ie=[0,0,0,0]:typeof q.bias=="number"?ie=[q.bias,q.bias,q.bias,q.bias]:(ie=[q.bias[0],q.bias[1],q.bias[2],0],q.bias[3]!==void 0&&(ie[3]=q.bias[3]));const fe=M*v;if(re!==void 0&&(re.format!==void 0&&y===4&&re.format!=="RGBA"||y===3&&re.format!=="RGB"&&re.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const j=4;let X=0,Z=1,N=2,I=3,_=0,k=fe,E=fe*2,ee=-1;C==="RGBA"?(_=0,k=fe,E=fe*2,ee=fe*3):C==="RGB"?(_=0,k=fe,E=fe*2):C==="RBG"&&(_=0,E=fe,k=fe*2),g=Q.createImageData(v,M);for(let Y=0;Y{c.r(R)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{bufferToTensor:()=>z,tensorFromGpuBuffer:()=>Q,tensorFromImage:()=>G,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>re});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const z=(M,y)=>{if(M===void 0)throw new Error("Image buffer must be defined");if(y.height===void 0||y.width===void 0)throw new Error("Image height and width must be defined");if(y.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:C,width:q}=y,J=y.norm??{mean:255,bias:0};let ie,fe;typeof J.mean=="number"?ie=[J.mean,J.mean,J.mean,J.mean]:ie=[J.mean[0],J.mean[1],J.mean[2],J.mean[3]??255],typeof J.bias=="number"?fe=[J.bias,J.bias,J.bias,J.bias]:fe=[J.bias[0],J.bias[1],J.bias[2],J.bias[3]??0];const j=y.format!==void 0?y.format:"RGBA",X=y.tensorFormat!==void 0&&y.tensorFormat!==void 0?y.tensorFormat:"RGB",Z=C*q,N=X==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3);let I=4,_=0,k=1,E=2,ee=3,Y=0,de=Z,me=Z*2,ye=-1;j==="RGB"&&(I=3,_=0,k=1,E=2,ee=-1),X==="RGBA"?ye=Z*3:X==="RBG"?(Y=0,me=Z,de=Z*2):X==="BGR"&&(me=0,de=Z,Y=Z*2);for(let Ee=0;Ee{const C=typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement,q=typeof ImageData<"u"&&M instanceof ImageData,J=typeof ImageBitmap<"u"&&M instanceof ImageBitmap,ie=typeof M=="string";let fe,j=y??{};const X=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Z=N=>typeof HTMLCanvasElement<"u"&&N instanceof HTMLCanvasElement||N instanceof OffscreenCanvas?N.getContext("2d"):null;if(C){const N=X();N.width=M.width,N.height=M.height;const I=Z(N);if(I!=null){let _=M.height,k=M.width;if(y!==void 0&&y.resizedHeight!==void 0&&y.resizedWidth!==void 0&&(_=y.resizedHeight,k=y.resizedWidth),y!==void 0){if(j=y,y.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");j.tensorFormat="RGBA",j.height=_,j.width=k}else j.tensorFormat="RGBA",j.height=_,j.width=k;I.drawImage(M,0,0),fe=I.getImageData(0,0,k,_).data}else throw new Error("Can not access image data")}else if(q){let N,I;if(y!==void 0&&y.resizedWidth!==void 0&&y.resizedHeight!==void 0?(N=y.resizedHeight,I=y.resizedWidth):(N=M.height,I=M.width),y!==void 0&&(j=y),j.format="RGBA",j.height=N,j.width=I,y!==void 0){const _=X();_.width=I,_.height=N;const k=Z(_);if(k!=null)k.putImageData(M,0,0),fe=k.getImageData(0,0,I,N).data;else throw new Error("Can not access image data")}else fe=M.data}else if(J){if(y===void 0)throw new Error("Please provide image config with format for Imagebitmap");const N=X();N.width=M.width,N.height=M.height;const I=Z(N);if(I!=null){const _=M.height,k=M.width;return I.drawImage(M,0,0,k,_),fe=I.getImageData(0,0,k,_).data,j.height=_,j.width=k,z(fe,j)}else throw new Error("Can not access image data")}else{if(ie)return new Promise((N,I)=>{const _=X(),k=Z(_);if(!M||!k)return I();const E=new Image;E.crossOrigin="Anonymous",E.src=M,E.onload=()=>{_.width=E.width,_.height=E.height,k.drawImage(E,0,0,_.width,_.height);const ee=k.getImageData(0,0,_.width,_.height);j.height=_.height,j.width=_.width,N(z(ee.data,j))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(fe!==void 0)return z(fe,j);throw new Error("Input data provided is not supported - aborted tensor creation")},re=(M,y)=>{const{width:C,height:q,download:J,dispose:ie}=y,fe=[1,q,C,4];return new w.Tensor({location:"texture",type:"float32",texture:M,dims:fe,download:J,dispose:ie})},Q=(M,y)=>{const{dataType:C,dims:q,download:J,dispose:ie}=y;return new w.Tensor({location:"gpu-buffer",type:C??"float32",gpuBuffer:M,dims:q,download:J,dispose:ie})},g=(M,y)=>{const{dataType:C,dims:q,download:J,dispose:ie}=y;return new w.Tensor({location:"ml-tensor",type:C??"float32",mlTensor:M,dims:q,download:J,dispose:ie})},v=(M,y,C)=>new w.Tensor({location:"cpu-pinned",type:M,data:y,dims:C??[y.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Oe,R,c)=>{c.r(R)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Oe,R,c)=>{c.r(R),c.d(R,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>z,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>w,checkTypedArray:()=>re});const w=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),z=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let G=!1;const re=()=>{if(!G){G=!0;const Q=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;Q&&(w.set("int64",BigInt64Array),z.set(BigInt64Array,"int64")),g&&(w.set("uint64",BigUint64Array),z.set(BigUint64Array,"uint64")),v?(w.set("float16",Float16Array),z.set(Float16Array,"float16")):w.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{Tensor:()=>Q});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),z=c("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),G=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),re=c("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Q{constructor(v,M,y){(0,G.checkTypedArray)();let C,q;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,C=v.type,q=v.dims,v.location){case"cpu-pinned":{const ie=G.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(C);if(!ie)throw new TypeError(`unsupported type "${C}" to create tensor from pinned buffer`);if(!(v.data instanceof ie))throw new TypeError(`buffer should be of type ${ie.name}`);this.cpuData=v.data;break}case"texture":{if(C!=="float32")throw new TypeError(`unsupported type "${C}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(C!=="float32"&&C!=="float16"&&C!=="int32"&&C!=="int64"&&C!=="uint32"&&C!=="uint8"&&C!=="bool"&&C!=="uint4"&&C!=="int4")throw new TypeError(`unsupported type "${C}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(C!=="float32"&&C!=="float16"&&C!=="int32"&&C!=="int64"&&C!=="uint32"&&C!=="uint64"&&C!=="int8"&&C!=="uint8"&&C!=="bool")throw new TypeError(`unsupported type "${C}" 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 ie,fe;if(typeof v=="string")if(C=v,fe=y,v==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");ie=M}else{const j=G.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(j===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(M)){if(v==="float16"&&j===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${j.name} as data.`);v==="uint64"||v==="int64"?ie=j.from(M,BigInt):ie=j.from(M)}else if(M instanceof j)ie=M;else if(M instanceof Uint8ClampedArray)if(v==="uint8")ie=Uint8Array.from(M);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${C} tensor's data must be type of ${j}`)}else if(fe=M,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const j=typeof v[0];if(j==="string")C="string",ie=v;else if(j==="boolean")C="bool",ie=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${j}.`)}else if(v instanceof Uint8ClampedArray)C="uint8",ie=Uint8Array.from(v);else{const j=G.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(j===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);C=j,ie=v}if(fe===void 0)fe=[ie.length];else if(!Array.isArray(fe))throw new TypeError("A tensor's dims must be a number array");q=fe,this.cpuData=ie,this.dataLocation="cpu"}const J=(0,re.calculateSize)(q);if(this.cpuData&&J!==this.cpuData.length&&!((C==="uint4"||C==="int4")&&Math.ceil(J/2)===this.cpuData.length))throw new Error(`Tensor's size(${J}) does not match data length(${this.cpuData.length}).`);this.type=C,this.dims=q,this.size=J}static async fromImage(v,M){return(0,z.tensorFromImage)(v,M)}static fromTexture(v,M){return(0,z.tensorFromTexture)(v,M)}static fromGpuBuffer(v,M){return(0,z.tensorFromGpuBuffer)(v,M)}static fromMLTensor(v,M){return(0,z.tensorFromMLTensor)(v,M)}static fromPinnedBuffer(v,M,y){return(0,z.tensorFromPinnedBuffer)(v,M,y)}toDataURL(v){return(0,w.tensorToDataURL)(this,v)}toImageData(v){return(0,w.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 M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,v&&this.disposer&&(this.disposer(),this.disposer=void 0),M}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,re.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{calculateSize:()=>z,tensorReshape:()=>G});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const z=re=>{let Q=1;for(let g=0;g{switch(re.location){case"cpu":return new w.Tensor(re.type,re.data,Q);case"cpu-pinned":return new w.Tensor({location:"cpu-pinned",data:re.data,type:re.type,dims:Q});case"texture":return new w.Tensor({location:"texture",texture:re.texture,type:re.type,dims:Q});case"gpu-buffer":return new w.Tensor({location:"gpu-buffer",gpuBuffer:re.gpuBuffer,type:re.type,dims:Q});case"ml-tensor":return new w.Tensor({location:"ml-tensor",mlTensor:re.mlTensor,type:re.type,dims:Q});default:throw new Error(`tensorReshape: tensor location ${re.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Oe,R,c)=>{c.r(R),c.d(R,{Tensor:()=>z});var w=c("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const z=w.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Oe,R,c)=>{c.r(R),c.d(R,{TRACE:()=>z,TRACE_FUNC_BEGIN:()=>re,TRACE_FUNC_END:()=>Q});var w=c("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const z=(g,v)=>{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||console.timeStamp(`${g}::ORT::${v}`)},G=(g,v)=>{var C;const M=((C=new Error().stack)==null?void 0:C.split(/\r\n|\r|\n/g))||[];let y=!1;for(let q=0;q{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||G("BEGIN",g)},Q=g=>{(typeof w.env.trace>"u"?!w.env.wasm.trace:!w.env.trace)||G("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Oe,R,c)=>{c.r(R),c.d(R,{TrainingSession:()=>re});var w=c("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),z=c("./node_modules/onnxruntime-common/dist/esm/tensor.js");const G="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class re{constructor(g,v,M){this.handler=g,this.hasOptimizerModel=v,this.hasEvalModel=M}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(g,v){const M=g.evalModel||"",y=g.optimizerModel||"",C=v||{},[q,J]=await(0,w.resolveBackendAndExecutionProviders)(C);if(q.createTrainingSessionHandler){const ie=await q.createTrainingSessionHandler(g.checkpointState,g.trainModel,M,y,J);return new re(ie,!!g.optimizerModel,!!g.evalModel)}else throw new Error(G)}typeNarrowingForRunStep(g,v,M,y,C){const q={};let J={};if(typeof M!="object"||M===null||M instanceof z.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ie=!0;if(typeof y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof z.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(y)){if(y.length===0)throw new TypeError("'fetches' cannot be an empty array.");ie=!1;for(const fe of y){if(typeof fe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(fe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${fe}.`);q[fe]=null}if(typeof C=="object"&&C!==null)J=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else{let fe=!1;const j=Object.getOwnPropertyNames(y);for(const X of v)if(j.indexOf(X)!==-1){const Z=y[X];(Z===null||Z instanceof z.Tensor)&&(fe=!0,ie=!1,q[X]=Z)}if(fe){if(typeof C=="object"&&C!==null)J=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else J=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const fe of g)if(typeof M[fe]>"u")throw new Error(`input '${fe}' is missing in 'feeds'.`);if(ie)for(const fe of v)q[fe]=null;return[q,J]}convertHandlerReturnTypeToMapOfTensors(g){const v={};for(const M in g)if(Object.hasOwnProperty.call(g,M)){const y=g[M];y instanceof z.Tensor?v[M]=y:v[M]=new z.Tensor(y.type,y.data,y.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,v,M){const[y,C]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,v,M),q=await this.handler.runTrainStep(g,y,C);return this.convertHandlerReturnTypeToMapOfTensors(q)}async runOptimizerStep(g){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(g||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(g,v,M){if(this.hasEvalModel){const[y,C]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,v,M),q=await this.handler.runEvalStep(g,y,C);return this.convertHandlerReturnTypeToMapOfTensors(q)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(g=!0){return this.handler.getParametersSize(g)}async loadParametersBuffer(g,v=!0){const M=await this.getParametersSize(v);if(g.length!==4*M)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(g,v)}async getContiguousParameters(g=!0){return this.handler.getContiguousParameters(g)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Oe,R,c)=>{c.r(R),c.d(R,{TrainingSession:()=>z});var w=c("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const z=w.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Oe,R,c)=>{c.r(R),c.d(R,{version:()=>w});const w="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Oe,R,c)=>{c.r(R),c.d(R,{InferenceSession:()=>ht,TRACE:()=>et,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>ze,Tensor:()=>we,TrainingSession:()=>ut,default:()=>df,env:()=>E,registerBackend:()=>J});/*! * ONNX Runtime Web v1.20.1 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var w=Object.defineProperty,z=Object.getOwnPropertyDescriptor,G=Object.getOwnPropertyNames,re=Object.prototype.hasOwnProperty,Q=(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')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},M=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of G(t))!re.call(e,n)&&n!==r&&w(e,n,{get:()=>t[n],enumerable:!(s=z(t,n))||s.enumerable});return e},y=e=>M(w({},"__esModule",{value:!0}),e),C,q,J,ie,fe,j=g(()=>{C=new Map,q=[],J=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=C.get(e);if(s===void 0)C.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=q.indexOf(e);n!==-1&&q.splice(n,1);for(let i=0;i{let t=C.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(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},fe=async e=>{let t=e.executionProviders||[],r=t.map(p=>typeof p=="string"?p:p.name),s=r.length===0?q:r,n,i=[],o=new Set;for(let p of s){let h=await ie(p);typeof h=="string"?i.push({name:p,err:h}):(n||(n=h),n===h&&o.add(p))}if(!n)throw new Error(`no available backend found. ERR: ${i.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of i)r.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let d=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[n,new Proxy(e,{get:(p,h)=>h==="executionProviders"?d:Reflect.get(p,h)})]}}),X=g(()=>{j()}),Z,N=g(()=>{Z="1.20.1"}),I,_,k=g(()=>{N(),I="warning",_={wasm:{},webgl:{},webgpu:{},versions:{common:Z},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}`);I=e}},get logLevel(){return I}},Object.defineProperty(_,"logLevel",{enumerable:!0})}),E,ee=g(()=>{k(),E=_}),Y,de,me=g(()=>{Y=(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 s=r.getContext("2d");if(s!=null){let n,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],i=e.dims[3]):(n=e.dims[3],i=e.dims[2]);let o=(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 P=i*n,x=0,l=P,O=P*2,L=-1;o==="RGBA"?(x=0,l=P,O=P*2,L=P*3):o==="RGB"?(x=0,l=P,O=P*2):o==="RBG"&&(x=0,O=P,l=P*2);for(let B=0;B{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,i,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],i=e.dims[1],o=e.dims[3]):(n=e.dims[3],i=e.dims[2],o=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,P;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?P=[0,0,0,0]:typeof p.bias=="number"?P=[p.bias,p.bias,p.bias,p.bias]:(P=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(P[3]=p.bias[3]));let x=i*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,O=0,L=1,B=2,te=3,se=0,H=x,pe=x*2,ae=-1;d==="RGBA"?(se=0,H=x,pe=x*2,ae=x*3):d==="RGB"?(se=0,H=x,pe=x*2):d==="RBG"&&(se=0,pe=x,H=x*2),s=r.createImageData(n,i);for(let ge=0;ge{je(),ye=(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:s}=t,n=t.norm??{mean:255,bias:0},i,o;typeof n.mean=="number"?i=[n.mean,n.mean,n.mean,n.mean]:i=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.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*s,P=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),x=4,l=0,O=1,L=2,B=3,te=0,se=h,H=h*2,pe=-1;d==="RGB"&&(x=3,l=0,O=1,L=2,B=-1),p==="RGBA"?pe=h*3:p==="RBG"?(te=0,H=h,se=h*2):p==="BGR"&&(H=0,se=h,te=h*2);for(let ae=0;ae{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",o,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=P=>typeof HTMLCanvasElement<"u"&&P instanceof HTMLCanvasElement||P instanceof OffscreenCanvas?P.getContext("2d"):null;if(r){let P=p();P.width=e.width,P.height=e.height;let x=h(P);if(x!=null){let l=e.height,O=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,O=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=l,d.width=O}else d.tensorFormat="RGBA",d.height=l,d.width=O;x.drawImage(e,0,0),o=x.getImageData(0,0,O,l).data}else throw new Error("Can not access image data")}else if(s){let P,x;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(P=t.resizedHeight,x=t.resizedWidth):(P=e.height,x=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=P,d.width=x,t!==void 0){let l=p();l.width=x,l.height=P;let O=h(l);if(O!=null)O.putImageData(e,0,0),o=O.getImageData(0,0,x,P).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let P=p();P.width=e.width,P.height=e.height;let x=h(P);if(x!=null){let l=e.height,O=e.width;return x.drawImage(e,0,0,O,l),o=x.getImageData(0,0,O,l).data,d.height=l,d.width=O,ye(o,d)}else throw new Error("Can not access image data")}else{if(i)return new Promise((P,x)=>{let l=p(),O=h(l);if(!e||!O)return x();let L=new Image;L.crossOrigin="Anonymous",L.src=e,L.onload=()=>{l.width=L.width,l.height=L.height,O.drawImage(L,0,0,l.width,l.height);let B=O.getImageData(0,0,l.width,l.height);d.height=l.height,d.width=l.width,P(ye(B.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ye(o,d);throw new Error("Input data provided is not supported - aborted tensor creation")},Ee=(e,t)=>{let{width:r,height:s,download:n,dispose:i}=t,o=[1,s,r,4];return new He({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:i})},Le=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:i}=t;return new He({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:i})},_e=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:i}=t;return new He({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:i})},U=(e,t,r)=>new He({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),he,ke,Re,Ke,Ye=g(()=>{he=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ke=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Re=!1,Ke=()=>{if(!Re){Re=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(he.set("int64",BigInt64Array),ke.set(BigInt64Array,"int64")),t&&(he.set("uint64",BigUint64Array),ke.set(BigUint64Array,"uint64")),r?(he.set("float16",Float16Array),ke.set(Float16Array,"float16")):he.set("float16",Uint16Array)}}}),at,We,le=g(()=>{je(),at=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new He(e.type,e.data,t);case"cpu-pinned":return new He({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new He({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new He({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new He({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),He,je=g(()=>{me(),ce(),Ye(),le(),He=class{constructor(e,t,r){Ke();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=he.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool")throw new TypeError(`unsupported type "${s}" 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 o,d;if(typeof e=="string")if(s=e,d=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let p=he.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"?o=p.from(t,BigInt):o=p.from(t)}else if(t instanceof p)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${s} 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")s="string",o=e;else if(p==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let p=ke.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=p,o=e}if(d===void 0)d=[o.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");n=d,this.cpuData=o,this.dataLocation="cpu"}let i=at(n);if(this.cpuData&&i!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=i}static async fromImage(e,t){return Ce(e,t)}static fromTexture(e,t){return Ee(e,t)}static fromGpuBuffer(e,t){return Le(e,t)}static fromMLTensor(e,t){return _e(e,t)}static fromPinnedBuffer(e,t,r){return U(e,t,r)}toDataURL(e){return Y(this,e)}toImageData(e){return de(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 We(this,e)}}}),we,$e=g(()=>{je(),we=He}),et,Qe,qe,ze,nt=g(()=>{k(),et=(e,t)=>{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||console.timeStamp(`${e}::ORT::${t}`)},Qe=(e,t)=>{var n;let r=((n=new Error().stack)==null?void 0:n.split(/\r\n|\r|\n/g))||[],s=!1;for(let i=0;i{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||Qe("BEGIN",e)},ze=e=>{(typeof _.trace>"u"?!_.wasm.trace:!_.trace)||Qe("END",e)}}),dt,gt=g(()=>{j(),$e(),nt(),dt=class Vm{constructor(t){this.handler=t}async run(t,r,s){qe();let n={},i={};if(typeof t!="object"||t===null||t instanceof we||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof we)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.");o=!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}.`);n[h]=null}if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,P=Object.getOwnPropertyNames(r);for(let x of this.outputNames)if(P.indexOf(x)!==-1){let l=r[x];(l===null||l instanceof we)&&(h=!0,o=!1,n[x]=l)}if(h){if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(o)for(let h of this.outputNames)n[h]=null;let d=await this.handler.run(t,n,i),p={};for(let h in d)if(Object.hasOwnProperty.call(d,h)){let P=d[h];P instanceof we?p[h]=P:p[h]=new we(P.type,P.data,P.dims)}return ze(),p}async release(){return this.handler.dispose()}static async create(t,r,s,n){qe();let i,o={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)o=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 P=t,x=0,l=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(x=r,!Number.isSafeInteger(x))throw new RangeError("'byteOffset' must be an integer.");if(x<0||x>=P.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${P.byteLength}).`);if(l=t.byteLength-x,typeof s=="number"){if(l=s,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||x+l>P.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${P.byteLength-x}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(P,x,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,p]=await fe(o),h=await d.createInferenceSessionHandler(i,p);return ze(),new Vm(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ht,_t=g(()=>{gt(),ht=dt}),A=g(()=>{}),ne=g(()=>{}),V=g(()=>{}),ue=g(()=>{}),Ae,Je,ot=g(()=>{j(),$e(),Ae="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class Wm{constructor(t,r,s){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=s}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let s=t.evalModel||"",n=t.optimizerModel||"",i=r||{},[o,d]=await fe(i);if(o.createTrainingSessionHandler){let p=await o.createTrainingSessionHandler(t.checkpointState,t.trainModel,s,n,d);return new Wm(p,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Ae)}typeNarrowingForRunStep(t,r,s,n,i){let o={},d={};if(typeof s!="object"||s===null||s instanceof we||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let p=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof we)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");p=!1;for(let h of n){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof i=="object"&&i!==null)d=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,P=Object.getOwnPropertyNames(n);for(let x of r)if(P.indexOf(x)!==-1){let l=n[x];(l===null||l instanceof we)&&(h=!0,p=!1,o[x]=l)}if(h){if(typeof i=="object"&&i!==null)d=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else d=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of t)if(typeof s[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(p)for(let h of r)o[h]=null;return[o,d]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let s in t)if(Object.hasOwnProperty.call(t,s)){let n=t[s];n instanceof we?r[s]=n:r[s]=new we(n.type,n.data,n.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,s){let[n,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,s),o=await this.handler.runTrainStep(t,n,i);return this.convertHandlerReturnTypeToMapOfTensors(o)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,s){if(this.hasEvalModel){let[n,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,s),o=await this.handler.runEvalStep(t,n,i);return this.convertHandlerReturnTypeToMapOfTensors(o)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let s=await this.getParametersSize(r);if(t.length!==4*s)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),ut,At=g(()=>{ot(),ut=Je}),xt={};v(xt,{InferenceSession:()=>ht,TRACE:()=>et,TRACE_FUNC_BEGIN:()=>qe,TRACE_FUNC_END:()=>ze,Tensor:()=>we,TrainingSession:()=>ut,env:()=>E,registerBackend:()=>J});var Et=g(()=>{X(),ee(),_t(),$e(),A(),ne(),nt(),V(),ue(),At()}),Ct=g(()=>{}),ar={};v(ar,{default:()=>Fr});var Mr,Nr,Fr,as=g(()=>{var e;ch(),ts(),zs(),Mr="ort-wasm-proxy-worker",Nr=((e=globalThis.self)==null?void 0:e.name)===Mr,Nr&&(self.onmessage=t=>{let{type:r,in:s}=t.data;try{switch(r){case"init-wasm":Bs(s.wasm).then(()=>{fc(s).then(()=>{postMessage({type:r})},n=>{postMessage({type:r,err:n})})},n=>{postMessage({type:r,err:n})});break;case"init-ep":{let{epName:n,env:i}=s;an(i,n).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:n}=s,i=lp(n);postMessage({type:r,out:i});break}case"create":{let{model:n,options:i}=s;kp(n,i).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Ap(s),postMessage({type:r});break;case"run":{let{sessionId:n,inputIndices:i,inputs:o,outputIndices:d,options:p}=s;Fp(n,i,o,d,new Array(d.length).fill(null),p).then(h=>{h.some(P=>P[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:h},Dp([...o,...h]))},h=>{postMessage({type:r,err:h})});break}case"end-profiling":Op(s),postMessage({type:r});break;default:}}catch(n){postMessage({type:r,err:n})}}),Fr=Nr?null:t=>new Worker(t??Ts,{type:"module",name:Mr})}),qs={};v(qs,{default:()=>vn});var Qs,Ds,vn,Dt=g(()=>{var e;Ds=(Qs=self.location.href,async function(t={}){function r(){return nr.buffer!=Nt.buffer&&is(),Nt}function s(){return nr.buffer!=Nt.buffer&&is(),hr}function n(){return nr.buffer!=Nt.buffer&&is(),Ve}function i(){return nr.buffer!=Nt.buffer&&is(),ct}function o(){return nr.buffer!=Nt.buffer&&is(),Vt}function d(){return nr.buffer!=Nt.buffer&&is(),xr}function p(){return nr.buffer!=Nt.buffer&&is(),Hr}function h(){return nr.buffer!=Nt.buffer&&is(),cp}var P,x,l=Object.assign({},t),O=new Promise((a,m)=>{P=a,x=m}),L=typeof window=="object",B=typeof importScripts=="function",te=B&&self.name=="em-pthread";l.mountExternalData=(a,m)=>{a.startsWith("./")&&(a=a.substring(2)),(l.Fb||(l.Fb=new Map)).set(a,m)},l.unmountExternalData=()=>{delete l.Fb};var se=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let H=()=>{let a=($,F,W)=>(...be)=>{let Ge=yn,st=F==null?void 0:F();be=$(...be);let yt=F==null?void 0:F();return st!==yt&&($=yt,W(st),F=W=null),yn!=Ge?new Promise((Pt,Rt)=>{th={resolve:Pt,reject:Rt}}):be},m=$=>async(...F)=>{var W;try{if(l.Eb)throw Error("Session already started");let be=l.Eb={fc:F[0],errors:[]},Ge=await $(...F);if(l.Eb!==be)throw Error("Session mismatch");(W=l.Gb)==null||W.flush();let st=be.errors;if(0Pt),0l._OrtCreateSession,$=>l._OrtCreateSession=$),l._OrtRun=m(a(l._OrtRun,()=>l._OrtRun,$=>l._OrtRun=$)),l._OrtRunWithBinding=m(a(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,$=>l._OrtRunWithBinding=$)),l._OrtBindInput=a(l._OrtBindInput,()=>l._OrtBindInput,$=>l._OrtBindInput=$),H=void 0};l.jsepInit=(a,m)=>{if(H==null||H(),a==="webgpu"){[l.Gb,l.Ub,l.Yb,l.Nb,l.Xb,l.jb,l.Zb,l.bc,l.Vb,l.Wb,l.$b]=m;let $=l.Gb;l.jsepRegisterBuffer=(F,W,be,Ge)=>$.registerBuffer(F,W,be,Ge),l.jsepGetBuffer=F=>$.getBuffer(F),l.jsepCreateDownloader=(F,W,be)=>$.createDownloader(F,W,be),l.jsepOnReleaseSession=F=>{$.onReleaseSession(F)},l.jsepOnRunStart=F=>$.onRunStart(F),l.cc=(F,W)=>{$.upload(F,W)}}else if(a==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=m,l.jsepReleaseTensorId=l.Ob;let $=l.Gb;l.jsepOnRunStart=F=>$.onRunStart(F),l.jsepRegisterMLContext=(F,W)=>{$.registerMLContext(F,W)},l.jsepOnReleaseSession=F=>{$.onReleaseSession(F)},l.jsepCreateMLTensorDownloader=(F,W)=>$.createMLTensorDownloader(F,W),l.jsepRegisterMLTensor=(F,W,be)=>$.registerMLTensor(F,W,be)}};var pe,ae,ge=Object.assign({},l),Ne="./this.program",Fe=(a,m)=>{throw m},rt="";(L||B)&&(B?rt=self.location.href:typeof document<"u"&&document.currentScript&&(rt=document.currentScript.src),Qs&&(rt=Qs),rt=rt.startsWith("blob:")?"":rt.substr(0,rt.replace(/[?#].*/,"").lastIndexOf("/")+1),B&&(ae=a=>{var m=new XMLHttpRequest;return m.open("GET",a,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),pe=(a,m,$)=>{var F=new XMLHttpRequest;F.open("GET",a,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?m(F.response):$()},F.onerror=$,F.send(null)});var vt,$t=console.log.bind(console),Yt=console.error.bind(console),rr=$t,zt=Yt;if(Object.assign(l,ge),ge=null,te){let a=function(m){try{var $=m.data,F=$.cmd;if(F==="load"){let W=[];self.onmessage=be=>W.push(be),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let be of W)a(be);self.onmessage=a};for(let be of $.handlers)l[be]&&!l[be].proxy||(l[be]=(...Ge)=>{postMessage({Mb:"callHandler",oc:be,args:Ge})},be=="print"&&(rr=l[be]),be=="printErr"&&(zt=l[be]));nr=$.wasmMemory,is(),Tr($.wasmModule)}else if(F==="run"){oh($.pthread_ptr,0,0,1,0,0),Jp($.pthread_ptr),hf(),Oh(),Ir||(Am(),Ir=!0);try{mf($.start_routine,$.arg)}catch(W){if(W!="unwind")throw W}}else F==="cancel"?Fa()&&Tp(-1):$.target!=="setimmediate"&&(F==="checkMailbox"?Ir&&mp():F&&(zt(`worker: received unknown command ${F}`),zt($)))}catch(W){throw Im(),W}};var Tr,Ir=!1;zt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Mb:"alert",text:m.join(" "),qc:Fa()})},l.instantiateWasm=(m,$)=>new Promise(F=>{Tr=W=>{W=new WebAssembly.Instance(W,Sh()),$(W),F()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=a}l.wasmBinary&&(vt=l.wasmBinary);var nr,Er,Ft,Nt,hr,Ve,ct,Vt,xr,Hr,Qr,ro,cp,bs=!1;function is(){var a=nr.buffer;l.HEAP8=Nt=new Int8Array(a),l.HEAP16=Ve=new Int16Array(a),l.HEAPU8=hr=new Uint8Array(a),l.HEAPU16=ct=new Uint16Array(a),l.HEAP32=Vt=new Int32Array(a),l.HEAPU32=xr=new Uint32Array(a),l.HEAPF32=Hr=new Float32Array(a),l.HEAPF64=cp=new Float64Array(a),l.HEAP64=Qr=new BigInt64Array(a),l.HEAPU64=ro=new BigUint64Array(a)}if(!te){if(!((nr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof se))throw zt("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");is()}var Go=[],es=[],ds=[],Gs=0,so=null;function pp(){if(--Gs==0&&so){var a=so;so=null,a()}}function ka(a){throw zt(a="Aborted("+a+")"),bs=!0,Ft=1,a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info."),x(a),a}var jp,Eh=a=>a.startsWith("data:application/octet-stream;base64,"),Ph=a=>a.startsWith("file://");function Ch(a){if(a==jp&&vt)return new Uint8Array(vt);if(ae)return ae(a);throw"both async and sync fetching of the wasm failed"}function $h(a,m,$){return function(F){if(!vt&&(L||B)){if(typeof fetch=="function"&&!Ph(F))return fetch(F,{credentials:"same-origin"}).then(W=>{if(!W.ok)throw`failed to load wasm binary file at '${F}'`;return W.arrayBuffer()}).catch(()=>Ch(F));if(pe)return new Promise((W,be)=>{pe(F,Ge=>W(new Uint8Array(Ge)),be)})}return Promise.resolve().then(()=>Ch(F))}(a).then(F=>WebAssembly.instantiate(F,m)).then($,F=>{zt(`failed to asynchronously prepare wasm: ${F}`),ka(F)})}function Sh(){return{a:{O:pf,Aa:cf,b:_f,aa:Bh,B:Nh,qa:Uh,Y:Wh,_:Gh,ra:Kh,oa:Hh,ha:qh,na:Qh,L:Xh,Z:Yh,W:Jh,pa:Zh,X:em,wa:gf,F:wf,Q:yf,P:bf,E:Tf,u:xf,q:Ef,G:Pf,A:Ff,R:Of,ua:Df,ka:Lf,U:zf,ba:Bf,H:Rf,ja:Jp,ta:jf,t:Nf,x:Wf,o:Gf,l:Hf,c:Xp,n:qf,j:Yf,w:Jf,p:Zf,g:e_,s:t_,m:r_,e:s_,k:n_,i:o_,h:i_,d:a_,ea:l_,fa:u_,ga:d_,ca:mm,da:fm,T:c_,f:p_,D:h_,I:m_,M:f_,y:__,sa:g_,V:w_,v:gm,z:y_,N:M_,S:b_,za:v_,ya:T_,la:Mm,ma:bm,$:Gp,C:vm,K:Tm,ia:xm,J:Em,a:nr,xa:Wp,va:$m,r:P_}}}var Np={868340:(a,m,$,F,W)=>{if(l===void 0||!l.Fb)return 1;if((a=ls(a>>>0)).startsWith("./")&&(a=a.substring(2)),!(a=l.Fb.get(a)))return 2;if(F>>>=0,(m>>>=0)+($>>>=0)>a.byteLength)return 3;try{let be=a.subarray(m,m+$);switch(W){case 0:s().set(be,F>>>0);break;case 1:l.cc(F,be);break;default:return 4}return 0}catch{return 4}},869023:(a,m,$)=>{l.dc(a,s().subarray(m>>>0,m+$>>>0))},869086:()=>l.ac(),869127:a=>{l.Ob(a)},869163:()=>{l.Vb()},869194:()=>{l.Wb()},869223:()=>{l.$b()},869248:a=>l.Ub(a),869281:a=>l.Yb(a),869313:(a,m,$)=>{l.Nb(a,m,$,!0)},869352:(a,m,$)=>{l.Nb(a,m,$)},869385:()=>typeof wasmOffsetConverter<"u",869442:a=>{l.jb("Abs",a,void 0)},869493:a=>{l.jb("Neg",a,void 0)},869544:a=>{l.jb("Floor",a,void 0)},869597:a=>{l.jb("Ceil",a,void 0)},869649:a=>{l.jb("Reciprocal",a,void 0)},869707:a=>{l.jb("Sqrt",a,void 0)},869759:a=>{l.jb("Exp",a,void 0)},869810:a=>{l.jb("Erf",a,void 0)},869861:a=>{l.jb("Sigmoid",a,void 0)},869916:(a,m,$)=>{l.jb("HardSigmoid",a,{alpha:m,beta:$})},869995:a=>{l.jb("Log",a,void 0)},870046:a=>{l.jb("Sin",a,void 0)},870097:a=>{l.jb("Cos",a,void 0)},870148:a=>{l.jb("Tan",a,void 0)},870199:a=>{l.jb("Asin",a,void 0)},870251:a=>{l.jb("Acos",a,void 0)},870303:a=>{l.jb("Atan",a,void 0)},870355:a=>{l.jb("Sinh",a,void 0)},870407:a=>{l.jb("Cosh",a,void 0)},870459:a=>{l.jb("Asinh",a,void 0)},870512:a=>{l.jb("Acosh",a,void 0)},870565:a=>{l.jb("Atanh",a,void 0)},870618:a=>{l.jb("Tanh",a,void 0)},870670:a=>{l.jb("Not",a,void 0)},870721:(a,m,$)=>{l.jb("Clip",a,{min:m,max:$})},870790:a=>{l.jb("Clip",a,void 0)},870842:(a,m)=>{l.jb("Elu",a,{alpha:m})},870900:a=>{l.jb("Gelu",a,void 0)},870952:a=>{l.jb("Relu",a,void 0)},871004:(a,m)=>{l.jb("LeakyRelu",a,{alpha:m})},871068:(a,m)=>{l.jb("ThresholdedRelu",a,{alpha:m})},871138:(a,m)=>{l.jb("Cast",a,{to:m})},871196:a=>{l.jb("Add",a,void 0)},871247:a=>{l.jb("Sub",a,void 0)},871298:a=>{l.jb("Mul",a,void 0)},871349:a=>{l.jb("Div",a,void 0)},871400:a=>{l.jb("Pow",a,void 0)},871451:a=>{l.jb("Equal",a,void 0)},871504:a=>{l.jb("Greater",a,void 0)},871559:a=>{l.jb("GreaterOrEqual",a,void 0)},871621:a=>{l.jb("Less",a,void 0)},871673:a=>{l.jb("LessOrEqual",a,void 0)},871732:(a,m,$,F,W)=>{l.jb("ReduceMean",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},871891:(a,m,$,F,W)=>{l.jb("ReduceMax",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872049:(a,m,$,F,W)=>{l.jb("ReduceMin",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872207:(a,m,$,F,W)=>{l.jb("ReduceProd",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872366:(a,m,$,F,W)=>{l.jb("ReduceSum",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872524:(a,m,$,F,W)=>{l.jb("ReduceL1",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872681:(a,m,$,F,W)=>{l.jb("ReduceL2",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872838:(a,m,$,F,W)=>{l.jb("ReduceLogSum",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},872999:(a,m,$,F,W)=>{l.jb("ReduceSumSquare",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},873163:(a,m,$,F,W)=>{l.jb("ReduceLogSumExp",a,{keepDims:!!m,noopWithEmptyAxes:!!$,axes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},873327:a=>{l.jb("Where",a,void 0)},873380:(a,m,$)=>{l.jb("Transpose",a,{perm:m?Array.from(o().subarray(m>>>0,$>>>0)):[]})},873488:(a,m,$,F)=>{l.jb("DepthToSpace",a,{blocksize:m,mode:ls($),format:F?"NHWC":"NCHW"})},873621:(a,m,$,F)=>{l.jb("DepthToSpace",a,{blocksize:m,mode:ls($),format:F?"NHWC":"NCHW"})},873754:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be,cr)=>{l.jb("ConvTranspose",a,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[$],group:F,kernelShape:[W],pads:[be,Ge],strides:[st],wIsConst:()=>!!r()[Pt>>>0],outputPadding:Rt?Array.from(o().subarray(Rt>>>0,mr>>>0)):[],outputShape:Pr?Array.from(o().subarray(Pr>>>0,Be>>>0)):[],activation:ls(cr)})},874155:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("ConvTranspose",a,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray($>>>0,2+($>>>0)>>>0)),group:F,kernelShape:Array.from(o().subarray(W>>>0,2+(W>>>0)>>>0)),pads:Array.from(o().subarray(be>>>0,4+(be>>>0)>>>0)),strides:Array.from(o().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[yt>>>0],outputPadding:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],outputShape:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[],activation:ls(Be)})},874720:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be,cr)=>{l.jb("ConvTranspose",a,{format:yt?"NHWC":"NCHW",autoPad:m,dilations:[$],group:F,kernelShape:[W],pads:[be,Ge],strides:[st],wIsConst:()=>!!r()[Pt>>>0],outputPadding:Rt?Array.from(o().subarray(Rt>>>0,mr>>>0)):[],outputShape:Pr?Array.from(o().subarray(Pr>>>0,Be>>>0)):[],activation:ls(cr)})},875121:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("ConvTranspose",a,{format:st?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray($>>>0,2+($>>>0)>>>0)),group:F,kernelShape:Array.from(o().subarray(W>>>0,2+(W>>>0)>>>0)),pads:Array.from(o().subarray(be>>>0,4+(be>>>0)>>>0)),strides:Array.from(o().subarray(Ge>>>0,2+(Ge>>>0)>>>0)),wIsConst:()=>!!r()[yt>>>0],outputPadding:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],outputShape:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[],activation:ls(Be)})},875686:(a,m)=>{l.jb("GlobalAveragePool",a,{format:m?"NHWC":"NCHW"})},875777:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("AveragePool",a,{format:Be?"NHWC":"NCHW",auto_pad:m,ceil_mode:$,count_include_pad:F,storage_order:W,dilations:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[],kernel_shape:st?Array.from(o().subarray(st>>>0,yt>>>0)):[],pads:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],strides:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[]})},876192:(a,m)=>{l.jb("GlobalAveragePool",a,{format:m?"NHWC":"NCHW"})},876283:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("AveragePool",a,{format:Be?"NHWC":"NCHW",auto_pad:m,ceil_mode:$,count_include_pad:F,storage_order:W,dilations:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[],kernel_shape:st?Array.from(o().subarray(st>>>0,yt>>>0)):[],pads:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],strides:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[]})},876698:(a,m)=>{l.jb("GlobalMaxPool",a,{format:m?"NHWC":"NCHW"})},876785:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("MaxPool",a,{format:Be?"NHWC":"NCHW",auto_pad:m,ceil_mode:$,count_include_pad:F,storage_order:W,dilations:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[],kernel_shape:st?Array.from(o().subarray(st>>>0,yt>>>0)):[],pads:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],strides:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[]})},877196:(a,m)=>{l.jb("GlobalMaxPool",a,{format:m?"NHWC":"NCHW"})},877283:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be)=>{l.jb("MaxPool",a,{format:Be?"NHWC":"NCHW",auto_pad:m,ceil_mode:$,count_include_pad:F,storage_order:W,dilations:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[],kernel_shape:st?Array.from(o().subarray(st>>>0,yt>>>0)):[],pads:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],strides:mr?Array.from(o().subarray(mr>>>0,Pr>>>0)):[]})},877694:(a,m,$,F,W)=>{l.jb("Gemm",a,{alpha:m,beta:$,transA:F,transB:W})},877798:a=>{l.jb("MatMul",a,void 0)},877852:(a,m,$,F)=>{l.jb("ArgMax",a,{keepDims:!!m,selectLastIndex:!!$,axis:F})},877960:(a,m,$,F)=>{l.jb("ArgMin",a,{keepDims:!!m,selectLastIndex:!!$,axis:F})},878068:(a,m)=>{l.jb("Softmax",a,{axis:m})},878131:(a,m)=>{l.jb("Concat",a,{axis:m})},878191:(a,m,$,F,W)=>{l.jb("Split",a,{axis:m,numOutputs:$,splitSizes:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},878331:a=>{l.jb("Expand",a,void 0)},878385:(a,m)=>{l.jb("Gather",a,{axis:Number(m)})},878456:(a,m)=>{l.jb("GatherElements",a,{axis:Number(m)})},878535:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt)=>{l.jb("Resize",a,{antialias:m,axes:$?Array.from(o().subarray($>>>0,F>>>0)):[],coordinateTransformMode:ls(W),cubicCoeffA:be,excludeOutside:Ge,extrapolationValue:st,keepAspectRatioPolicy:ls(yt),mode:ls(Pt),nearestMode:ls(Rt)})},878881:(a,m,$,F,W,be,Ge)=>{l.jb("Slice",a,{starts:m?Array.from(o().subarray(m>>>0,$>>>0)):[],ends:F?Array.from(o().subarray(F>>>0,W>>>0)):[],axes:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[]})},879097:a=>{l.jb("Tile",a,void 0)},879149:(a,m,$)=>{l.jb("InstanceNormalization",a,{epsilon:m,format:$?"NHWC":"NCHW"})},879263:(a,m,$)=>{l.jb("InstanceNormalization",a,{epsilon:m,format:$?"NHWC":"NCHW"})},879377:a=>{l.jb("Range",a,void 0)},879430:(a,m)=>{l.jb("Einsum",a,{equation:ls(m)})},879511:(a,m,$,F,W)=>{l.jb("Pad",a,{mode:m,value:$,pads:F?Array.from(o().subarray(F>>>0,W>>>0)):[]})},879638:(a,m,$,F,W,be)=>{l.jb("BatchNormalization",a,{epsilon:m,momentum:$,spatial:!!W,trainingMode:!!F,format:be?"NHWC":"NCHW"})},879807:(a,m,$,F,W,be)=>{l.jb("BatchNormalization",a,{epsilon:m,momentum:$,spatial:!!W,trainingMode:!!F,format:be?"NHWC":"NCHW"})},879976:(a,m,$)=>{l.jb("CumSum",a,{exclusive:Number(m),reverse:Number($)})},880073:(a,m,$)=>{l.jb("DequantizeLinear",a,{axis:m,blockSize:$})},880163:(a,m,$,F,W,be,Ge,st,yt)=>{l.jb("Attention",a,{numHeads:m,isUnidirectional:$,maskFilterValue:F,scale:W,doRotary:be,qkvHiddenSizes:Ge?Array.from(o().subarray(Number(st)>>>0,Number(st)+Ge>>>0)):[],pastPresentShareBuffer:!!yt})},880435:a=>{l.jb("BiasAdd",a,void 0)},880490:a=>{l.jb("BiasSplitGelu",a,void 0)},880551:a=>{l.jb("FastGelu",a,void 0)},880607:(a,m,$,F,W,be,Ge,st,yt,Pt,Rt,mr,Pr,Be,cr,Vr)=>{l.jb("Conv",a,{format:mr?"NHWC":"NCHW",auto_pad:m,dilations:$?Array.from(o().subarray($>>>0,F>>>0)):[],group:W,kernel_shape:be?Array.from(o().subarray(be>>>0,Ge>>>0)):[],pads:st?Array.from(o().subarray(st>>>0,yt>>>0)):[],strides:Pt?Array.from(o().subarray(Pt>>>0,Rt>>>0)):[],w_is_const:()=>!!r()[Pr>>>0],activation:ls(Be),activation_params:cr?Array.from(p().subarray(cr>>>0,Vr>>>0)):[]})},881103:a=>{l.jb("Gelu",a,void 0)},881155:(a,m,$,F)=>{l.jb("GroupQueryAttention",a,{numHeads:m,kvNumHeads:$,scale:F})},881268:(a,m,$,F)=>{l.jb("LayerNormalization",a,{axis:m,epsilon:$,simplified:!!F})},881379:(a,m,$,F)=>{l.jb("LayerNormalization",a,{axis:m,epsilon:$,simplified:!!F})},881490:(a,m,$,F,W,be)=>{l.jb("MatMulNBits",a,{k:m,n:$,accuracyLevel:F,bits:W,blockSize:be})},881617:(a,m,$,F,W,be)=>{l.jb("MultiHeadAttention",a,{numHeads:m,isUnidirectional:$,maskFilterValue:F,scale:W,doRotary:be})},881776:(a,m)=>{l.jb("QuickGelu",a,{alpha:m})},881840:(a,m,$,F,W)=>{l.jb("RotaryEmbedding",a,{interleaved:!!m,numHeads:$,rotaryEmbeddingDim:F,scale:W})},881979:(a,m,$)=>{l.jb("SkipLayerNormalization",a,{epsilon:m,simplified:!!$})},882081:(a,m,$)=>{l.jb("SkipLayerNormalization",a,{epsilon:m,simplified:!!$})},882183:(a,m,$,F)=>{l.jb("GatherBlockQuantized",a,{gatherAxis:m,quantizeAxis:$,blockSize:F})},882304:a=>{l.Zb(a)},882338:(a,m)=>l.bc(a,m,l.Eb.fc,l.Eb.errors)};function cf(a,m,$){return um(async()=>{await l.Xb(a,m,$)})}function pf(){return typeof wasmOffsetConverter<"u"}function Up(a){this.name="ExitStatus",this.message=`Program terminated with exit(${a})`,this.status=a}var Vp=a=>{a.terminate(),a.onmessage=()=>{}},kh=a=>{no.length==0&&(Lh(),Dh(no[0]));var m=no.pop();if(!m)return 6;Ho.push(m),gn[a.Ab]=m,m.Ab=a.Ab;var $={cmd:"run",start_routine:a.hc,arg:a.Qb,pthread_ptr:a.Ab};return m.postMessage($,a.mc),0},Ko=0,jr=(a,m,...$)=>{for(var F=2*$.length,W=lh(),be=ah(8*F),Ge=be>>>3,st=0;st<$.length;st++){var yt=$[st];typeof yt=="bigint"?(Qr[Ge+2*st]=1n,Qr[Ge+2*st+1]=yt):(Qr[Ge+2*st]=0n,h()[Ge+2*st+1>>>0]=yt)}return a=Fm(a,0,F,be,m),xp(W),a};function Wp(a){if(te)return jr(0,1,a);if(Ft=a,!(0{if(Ft=a,te)throw Ah(a),"unwind";Wp(a)},no=[],Ho=[],Ih=[],gn={},Fh=a=>{var m=a.Ab;delete gn[m],no.push(a),Ho.splice(Ho.indexOf(a),1),a.Ab=0,ih(m)};function Oh(){Ih.forEach(a=>a())}var Dh=a=>new Promise(m=>{a.onmessage=W=>{var be=(W=W.data).cmd;if(W.targetThread&&W.targetThread!=Fa()){var Ge=gn[W.targetThread];Ge?Ge.postMessage(W,W.transferList):zt(`Internal error! Worker sent a message "${be}" to target pthread ${W.targetThread}, but that thread no longer exists!`)}else be==="checkMailbox"?mp():be==="spawnThread"?kh(W):be==="cleanupThread"?Fh(gn[W.thread]):be==="killThread"?(W=W.thread,be=gn[W],delete gn[W],Vp(be),ih(W),Ho.splice(Ho.indexOf(be),1),be.Ab=0):be==="cancelThread"?gn[W.thread].postMessage({cmd:"cancel"}):be==="loaded"?(a.loaded=!0,m(a)):be==="alert"?alert(`Thread ${W.threadId}: ${W.text}`):W.target==="setimmediate"?a.postMessage(W):be==="callHandler"?l[W.handler](...W.args):be&&zt(`worker sent an unknown command ${be}`)},a.onerror=W=>{throw zt(`worker sent an error! ${W.filename}:${W.lineno}: ${W.message}`),W};var $,F=[];for($ of[])l.hasOwnProperty($)&&F.push($);a.postMessage({cmd:"load",handlers:F,wasmMemory:nr,wasmModule:Er})});function Lh(){var a=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});no.push(a)}var hp=a=>{for(;0{var a=Fa(),m=d()[a+52>>>2>>>0];a=d()[a+56>>>2>>>0],Dm(m,m-a),xp(m)},mf=(a,m)=>{Ko=0,a=Lm(a,m),0>>=0);throw m>>>=0,$>>>=0,d()[F.Jb+16>>>2>>>0]=0,d()[F.Jb+4>>>2>>>0]=m,d()[F.Jb+8>>>2>>>0]=$,a}function zh(a,m,$,F){return te?jr(2,1,a,m,$,F):Bh(a,m,$,F)}function Bh(a,m,$,F){if(a>>>=0,m>>>=0,$>>>=0,F>>>=0,se===void 0)return zt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var W=[];return te&&W.length===0?zh(a,m,$,F):(a={hc:$,Ab:a,Qb:F,mc:W},te?(a.Mb="spawnThread",postMessage(a,W),0):kh(a))}var Rh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,jh=(a,m,$)=>{var F=(m>>>=0)+$;for($=m;a[$]&&!($>=F);)++$;if(16<$-m&&a.buffer&&Rh)return Rh.decode(a.buffer instanceof se?a.slice(m,$):a.subarray(m,$));for(F="";m<$;){var W=a[m++];if(128&W){var be=63&a[m++];if((224&W)==192)F+=String.fromCharCode((31&W)<<6|be);else{var Ge=63&a[m++];65536>(W=(240&W)==224?(15&W)<<12|be<<6|Ge:(7&W)<<18|be<<12|Ge<<6|63&a[m++])?F+=String.fromCharCode(W):(W-=65536,F+=String.fromCharCode(55296|W>>10,56320|1023&W))}}else F+=String.fromCharCode(W)}return F},ls=(a,m)=>(a>>>=0)?jh(s(),a,m):"";function Nh(a,m,$){return te?jr(3,1,a,m,$):0}function Uh(a,m){if(te)return jr(4,1,a,m)}var Kp=a=>{for(var m=0,$=0;$=F?m++:2047>=F?m+=2:55296<=F&&57343>=F?(m+=4,++$):m+=3}return m},Vh=(a,m,$,F)=>{if(!(0>>=0;F=$+F-1;for(var be=0;be=Ge&&(Ge=65536+((1023&Ge)<<10)|1023&a.charCodeAt(++be)),127>=Ge){if($>=F)break;m[$++>>>0]=Ge}else{if(2047>=Ge){if($+1>=F)break;m[$++>>>0]=192|Ge>>6}else{if(65535>=Ge){if($+2>=F)break;m[$++>>>0]=224|Ge>>12}else{if($+3>=F)break;m[$++>>>0]=240|Ge>>18,m[$++>>>0]=128|Ge>>12&63}m[$++>>>0]=128|Ge>>6&63}m[$++>>>0]=128|63&Ge}}return m[$>>>0]=0,$-W},Aa=(a,m,$)=>Vh(a,s(),m,$);function Wh(a,m){if(te)return jr(5,1,a,m)}function Gh(a,m,$){if(te)return jr(6,1,a,m,$)}function Kh(a,m,$){return te?jr(7,1,a,m,$):0}function Hh(a,m){if(te)return jr(8,1,a,m)}function qh(a,m,$){if(te)return jr(9,1,a,m,$)}function Qh(a,m,$,F){if(te)return jr(10,1,a,m,$,F)}function Xh(a,m,$,F){if(te)return jr(11,1,a,m,$,F)}function Yh(a,m,$,F){if(te)return jr(12,1,a,m,$,F)}function Jh(a){if(te)return jr(13,1,a)}function Zh(a,m){if(te)return jr(14,1,a,m)}function em(a,m,$){if(te)return jr(15,1,a,m,$)}var tm,oo,gf=()=>{ka("")},wn=a=>{for(var m="";s()[a>>>0];)m+=tm[s()[a++>>>0]];return m},Hp={},qp={};function Fn(a,m,$={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(F,W,be={}){var Ge=W.name;if(!F)throw new oo(`type "${Ge}" must have a positive integer typeid pointer`);if(qp.hasOwnProperty(F)){if(be.Sb)return;throw new oo(`Cannot register type '${Ge}' twice`)}qp[F]=W,Hp.hasOwnProperty(F)&&(W=Hp[F],delete Hp[F],W.forEach(st=>st()))}(a,m,$)}var rm=(a,m,$)=>{switch(m){case 1:return $?F=>r()[F>>>0]:F=>s()[F>>>0];case 2:return $?F=>n()[F>>>1>>>0]:F=>i()[F>>>1>>>0];case 4:return $?F=>o()[F>>>2>>>0]:F=>d()[F>>>2>>>0];case 8:return $?F=>Qr[F>>>3]:F=>ro[F>>>3];default:throw new TypeError(`invalid integer width (${m}): ${a}`)}};function wf(a,m,$){$>>>=0,Fn(a>>>=0,{name:m=wn(m>>>0),fromWireType:F=>F,toWireType:function(F,W){if(typeof W!="bigint"&&typeof W!="number")throw W=W===null?"null":(F=typeof W)=="object"||F==="array"||F==="function"?W.toString():""+W,new TypeError(`Cannot convert "${W}" to ${this.name}`);return typeof W=="number"&&(W=BigInt(W)),W},argPackAdvance:io,readValueFromPointer:rm(m,$,m.indexOf("u")==-1),Db:null})}var io=8;function yf(a,m,$,F){Fn(a>>>=0,{name:m=wn(m>>>0),fromWireType:function(W){return!!W},toWireType:function(W,be){return be?$:F},argPackAdvance:io,readValueFromPointer:function(W){return this.fromWireType(s()[W>>>0])},Db:null})}var Qp=[],On=[];function Xp(a){9<(a>>>=0)&&--On[a+1]==0&&(On[a]=void 0,Qp.push(a))}var Ks=a=>{if(!a)throw new oo("Cannot use deleted val. handle = "+a);return On[a]},Hs=a=>{switch(a){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Qp.pop()||On.length;return On[m]=a,On[m+1]=1,m}};function Yp(a){return this.fromWireType(d()[a>>>2>>>0])}var Mf={name:"emscripten::val",fromWireType:a=>{var m=Ks(a);return Xp(a),m},toWireType:(a,m)=>Hs(m),argPackAdvance:io,readValueFromPointer:Yp,Db:null};function bf(a){return Fn(a>>>0,Mf)}var vf=(a,m)=>{switch(m){case 4:return function($){return this.fromWireType(p()[$>>>2>>>0])};case 8:return function($){return this.fromWireType(h()[$>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${a}`)}};function Tf(a,m,$){$>>>=0,Fn(a>>>=0,{name:m=wn(m>>>0),fromWireType:F=>F,toWireType:(F,W)=>W,argPackAdvance:io,readValueFromPointer:vf(m,$),Db:null})}function xf(a,m,$,F,W){if(a>>>=0,$>>>=0,m=wn(m>>>0),W===-1&&(W=4294967295),W=st=>st,F===0){var be=32-8*$;W=st=>st<>>be}var Ge=m.includes("unsigned")?function(st,yt){return yt>>>0}:function(st,yt){return yt};Fn(a,{name:m,fromWireType:W,toWireType:Ge,argPackAdvance:io,readValueFromPointer:rm(m,$,F!==0),Db:null})}function Ef(a,m,$){function F(be){var Ge=d()[be>>>2>>>0];return be=d()[be+4>>>2>>>0],new W(r().buffer,be,Ge)}var W=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Fn(a>>>=0,{name:$=wn($>>>0),fromWireType:F,argPackAdvance:io,readValueFromPointer:F},{Sb:!0})}function Pf(a,m){a>>>=0;var $=(m=wn(m>>>0))==="std::string";Fn(a,{name:m,fromWireType:function(F){var W=d()[F>>>2>>>0],be=F+4;if($)for(var Ge=be,st=0;st<=W;++st){var yt=be+st;if(st==W||s()[yt>>>0]==0){if(Ge=ls(Ge,yt-Ge),Pt===void 0)var Pt=Ge;else Pt+="\0",Pt+=Ge;Ge=yt+1}}else{for(Pt=Array(W),st=0;st>>0]);Pt=Pt.join("")}return Mn(F),Pt},toWireType:function(F,W){W instanceof ArrayBuffer&&(W=new Uint8Array(W));var be=typeof W=="string";if(!(be||W instanceof Uint8Array||W instanceof Uint8ClampedArray||W instanceof Int8Array))throw new oo("Cannot pass non-string to std::string");var Ge=$&&be?Kp(W):W.length,st=vp(4+Ge+1),yt=st+4;if(d()[st>>>2>>>0]=Ge,$&&be)Aa(W,yt,Ge+1);else if(be)for(be=0;be>>0]=Pt}else for(be=0;be>>0]=W[be];return F!==null&&F.push(Mn,st),st},argPackAdvance:io,readValueFromPointer:Yp,Db(F){Mn(F)}})}var sm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Cf=(a,m)=>{for(var $=a>>1,F=$+m/2;!($>=F)&&i()[$>>>0];)++$;if(32<($<<=1)-a&&sm)return sm.decode(s().slice(a,$));for($="",F=0;!(F>=m/2);++F){var W=n()[a+2*F>>>1>>>0];if(W==0)break;$+=String.fromCharCode(W)}return $},$f=(a,m,$)=>{if($??($=2147483647),2>$)return 0;var F=m;$=($-=2)<2*a.length?$/2:a.length;for(var W=0;W<$;++W){var be=a.charCodeAt(W);n()[m>>>1>>>0]=be,m+=2}return n()[m>>>1>>>0]=0,m-F},Sf=a=>2*a.length,kf=(a,m)=>{for(var $=0,F="";!($>=m/4);){var W=o()[a+4*$>>>2>>>0];if(W==0)break;++$,65536<=W?(W-=65536,F+=String.fromCharCode(55296|W>>10,56320|1023&W)):F+=String.fromCharCode(W)}return F},Af=(a,m,$)=>{if(m>>>=0,$??($=2147483647),4>$)return 0;var F=m;$=F+$-4;for(var W=0;W=be&&(be=65536+((1023&be)<<10)|1023&a.charCodeAt(++W)),o()[m>>>2>>>0]=be,(m+=4)+4>$)break}return o()[m>>>2>>>0]=0,m-F},If=a=>{for(var m=0,$=0;$=F&&++$,m+=4}return m};function Ff(a,m,$){if(a>>>=0,m>>>=0,$=wn($>>>=0),m===2)var F=Cf,W=$f,be=Sf,Ge=st=>i()[st>>>1>>>0];else m===4&&(F=kf,W=Af,be=If,Ge=st=>d()[st>>>2>>>0]);Fn(a,{name:$,fromWireType:st=>{for(var yt,Pt=d()[st>>>2>>>0],Rt=st+4,mr=0;mr<=Pt;++mr){var Pr=st+4+mr*m;mr!=Pt&&Ge(Pr)!=0||(Rt=F(Rt,Pr-Rt),yt===void 0?yt=Rt:(yt+="\0",yt+=Rt),Rt=Pr+m)}return Mn(st),yt},toWireType:(st,yt)=>{if(typeof yt!="string")throw new oo(`Cannot pass non-string to C++ string type ${$}`);var Pt=be(yt),Rt=vp(4+Pt+m);return d()[Rt>>>2>>>0]=Pt/m,W(yt,Rt+4,Pt+m),st!==null&&st.push(Mn,Rt),Rt},argPackAdvance:io,readValueFromPointer:Yp,Db(st){Mn(st)}})}function Of(a,m){Fn(a>>>=0,{Tb:!0,name:m=wn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Df=()=>1;function Lf(a){oh(a>>>0,!B,1,!L,131072,!1),Oh()}var nm=a=>{if(!bs)try{if(a(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(o(),a>>>2,a).value.then(mp),a+=128,Atomics.store(o(),a>>>2,1))}var mp=()=>{var a=Fa();a&&(Jp(a),nm(Om))};function zf(a,m){(a>>>=0)==m>>>0?setTimeout(mp):te?postMessage({targetThread:a,cmd:"checkMailbox"}):(a=gn[a])&&a.postMessage({cmd:"checkMailbox"})}var Zp=[];function Bf(a,m,$,F,W){for(m>>>=0,F/=2,Zp.length=F,$=W>>>0>>>3,W=0;W>>0];return(m?Np[m]:C_[a])(...Zp)}function Rf(a){a>>>=0,te?postMessage({cmd:"cleanupThread",thread:a}):Fh(gn[a])}function jf(a){}var eh=(a,m)=>{var $=qp[a];if($===void 0)throw a=km(a),$=wn(a),Mn(a),new oo(`${m} has unknown type ${$}`);return $},om=(a,m,$)=>{var F=[];return a=a.toWireType(F,$),F.length&&(d()[m>>>2>>>0]=Hs(F)),a};function Nf(a,m,$){return m>>>=0,$>>>=0,a=Ks(a>>>0),m=eh(m,"emval::as"),om(m,$,a)}var fp=a=>{try{a()}catch(m){ka(m)}},ao=0,yn=null,im=0,_p=[],am={},lm={},Uf=0,th=null,Vf=[];function um(a){return function(m){if(!bs){if(ao===0){var $=!1,F=!1;m((W=0)=>{if(!bs&&(im=W,$=!0,F)){ao=2,fp(()=>Rm(yn)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),W=!1;try{var be=function(){var yt=o()[yn+8>>>2>>>0];return yt=Bt[lm[yt]],--Ko,yt()}()}catch(yt){be=yt,W=!0}var Ge=!1;if(!yn){var st=th;st&&(th=null,(W?st.reject:st.resolve)(be),Ge=!0)}if(W&&!Ge)throw be}}),F=!0,$||(ao=1,yn=function(){var W=vp(65548),be=W+12;d()[W>>>2>>>0]=be,d()[W+4>>>2>>>0]=be+65536,be=_p[0];var Ge=am[be];return Ge===void 0&&(Ge=Uf++,am[be]=Ge,lm[Ge]=be),be=Ge,o()[W+8>>>2>>>0]=be,W}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),fp(()=>zm(yn)))}else ao===2?(ao=0,fp(jm),Mn(yn),yn=null,Vf.forEach(nm)):ka(`invalid state: ${ao}`);return im}}(m=>{a().then(m)})}function Wf(a){return a>>>=0,um(()=>(a=Ks(a)).then(Hs))}var gp=[];function Gf(a,m,$,F){return $>>>=0,F>>>=0,(a=gp[a>>>0])(null,m=Ks(m>>>0),$,F)}var Kf={},wp=a=>{var m=Kf[a];return m===void 0?wn(a):m};function Hf(a,m,$,F,W){return $>>>=0,F>>>=0,W>>>=0,(a=gp[a>>>0])(m=Ks(m>>>0),m[$=wp($)],F,W)}var dm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function qf(a){return(a>>>=0)==0?Hs(dm()):(a=wp(a),Hs(dm()[a]))}var Qf=a=>{var m=gp.length;return gp.push(a),m},Xf=(a,m)=>{for(var $=Array(a),F=0;F>>2>>>0],"parameter "+F);return $},cm=(a,m)=>Object.defineProperty(m,"name",{value:a});function Yf(a,m,$){var F=(m=Xf(a,m>>>0)).shift();a--;var W=`return function (obj, func, destructorsRef, args) { `,be=0,Ge=[];$===0&&Ge.push("obj");for(var st=["retType"],yt=[F],Pt=0;PtRt.name).join(", ")}) => ${F.name}>`,Qf(cm($,a))}function Jf(a){return a=wp(a>>>0),Hs(l[a])}function Zf(a,m){return m>>>=0,a=Ks(a>>>0),m=Ks(m),Hs(a[m])}function e_(a){9<(a>>>=0)&&(On[a+1]+=1)}function t_(){return Hs([])}function r_(a){a=Ks(a>>>0);for(var m=Array(a.length),$=0;$>>0))}function n_(){return Hs({})}function o_(a){for(var m=Ks(a>>>=0);m.length;){var $=m.pop();m.pop()($)}Xp(a)}function i_(a,m,$){m>>>=0,$>>>=0,a=Ks(a>>>0),m=Ks(m),$=Ks($),a[m]=$}function a_(a,m){return m>>>=0,a=(a=eh(a>>>0,"_emval_take_value")).readValueFromPointer(m),Hs(a)}function l_(a,m){a=-9007199254740992>a||9007199254740992>>=0,a=new Date(1e3*a),o()[m>>>2>>>0]=a.getUTCSeconds(),o()[m+4>>>2>>>0]=a.getUTCMinutes(),o()[m+8>>>2>>>0]=a.getUTCHours(),o()[m+12>>>2>>>0]=a.getUTCDate(),o()[m+16>>>2>>>0]=a.getUTCMonth(),o()[m+20>>>2>>>0]=a.getUTCFullYear()-1900,o()[m+24>>>2>>>0]=a.getUTCDay(),a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[m+28>>>2>>>0]=a}var Ia=a=>a%4==0&&(a%100!=0||a%400==0),pm=[0,31,60,91,121,152,182,213,244,274,305,335],hm=[0,31,59,90,120,151,181,212,243,273,304,334];function u_(a,m){a=-9007199254740992>a||9007199254740992>>=0,a=new Date(1e3*a),o()[m>>>2>>>0]=a.getSeconds(),o()[m+4>>>2>>>0]=a.getMinutes(),o()[m+8>>>2>>>0]=a.getHours(),o()[m+12>>>2>>>0]=a.getDate(),o()[m+16>>>2>>>0]=a.getMonth(),o()[m+20>>>2>>>0]=a.getFullYear()-1900,o()[m+24>>>2>>>0]=a.getDay();var $=(Ia(a.getFullYear())?pm:hm)[a.getMonth()]+a.getDate()-1|0;o()[m+28>>>2>>>0]=$,o()[m+36>>>2>>>0]=-60*a.getTimezoneOffset(),$=new Date(a.getFullYear(),6,1).getTimezoneOffset();var F=new Date(a.getFullYear(),0,1).getTimezoneOffset();a=0|($!=F&&a.getTimezoneOffset()==Math.min(F,$)),o()[m+32>>>2>>>0]=a}function d_(a){a>>>=0;var m=new Date(o()[a+20>>>2>>>0]+1900,o()[a+16>>>2>>>0],o()[a+12>>>2>>>0],o()[a+8>>>2>>>0],o()[a+4>>>2>>>0],o()[a>>>2>>>0],0),$=o()[a+32>>>2>>>0],F=m.getTimezoneOffset(),W=new Date(m.getFullYear(),6,1).getTimezoneOffset(),be=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Ge=Math.min(be,W);return 0>$?o()[a+32>>>2>>>0]=+(W!=be&&Ge==F):0<$!=(Ge==F)&&(W=Math.max(be,W),m.setTime(m.getTime()+6e4*((0<$?Ge:W)-F))),o()[a+24>>>2>>>0]=m.getDay(),$=(Ia(m.getFullYear())?pm:hm)[m.getMonth()]+m.getDate()-1|0,o()[a+28>>>2>>>0]=$,o()[a>>>2>>>0]=m.getSeconds(),o()[a+4>>>2>>>0]=m.getMinutes(),o()[a+8>>>2>>>0]=m.getHours(),o()[a+12>>>2>>>0]=m.getDate(),o()[a+16>>>2>>>0]=m.getMonth(),o()[a+20>>>2>>>0]=m.getYear(),a=m.getTime(),BigInt(isNaN(a)?-1:a/1e3)}function mm(a,m,$,F,W,be,Ge){return te?jr(16,1,a,m,$,F,W,be,Ge):-52}function fm(a,m,$,F,W,be){if(te)return jr(17,1,a,m,$,F,W,be)}function c_(a,m,$,F){a>>>=0,m>>>=0,$>>>=0,F>>>=0;var W=new Date().getFullYear(),be=new Date(W,0,1),Ge=new Date(W,6,1);W=be.getTimezoneOffset();var st=Ge.getTimezoneOffset(),yt=Math.max(W,st);d()[a>>>2>>>0]=60*yt,o()[m>>>2>>>0]=+(W!=st),be=(a=Pt=>Pt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(be),Ge=a(Ge),st{rh.length=0;for(var $;$=s()[a++>>>0];){var F=$!=105;m+=(F&=$!=112)&&m%8?4:0,rh.push($==112?d()[m>>>2>>>0]:$==106?Qr[m>>>3]:$==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=F?8:4}return rh};function p_(a,m,$){return a>>>=0,m=_m(m>>>0,$>>>0),Np[a](...m)}function h_(a,m,$){return a>>>=0,m=_m(m>>>0,$>>>0),Np[a](...m)}var m_=()=>{},f_=()=>Date.now();function __(a,m){return zt(ls(a>>>0,m>>>0))}var gm,g_=()=>{throw Ko+=1,"unwind"};function w_(){return 4294901760}gm=()=>performance.timeOrigin+performance.now();var y_=()=>navigator.hardwareConcurrency;function M_(){return ka("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function b_(a){a>>>=0;var m=s().length;if(a<=m||4294901760=$;$*=2){var F=m*(1+.2/$);F=Math.min(F,a+100663296);var W=Math;F=Math.max(a,F);e:{W=(W.min.call(W,4294901760,F+(65536-F%65536)%65536)-nr.buffer.byteLength+65535)/65536;try{nr.grow(W),is();var be=1;break e}catch{}be=void 0}if(be)return!0}return!1}var yp=()=>(ka("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),wc={},wm=a=>{a.forEach(m=>{yp()})};function v_(){var a=Error().stack.toString().split(` `);return a[0]=="Error"&&a.shift(),wm(a),wc.Pb=yp(),wc.ec=a,wc.Pb}function T_(a,m,$){if(a>>>=0,m>>>=0,wc.Pb==a)var F=wc.ec;else(F=Error().stack.toString().split(` `))[0]=="Error"&&F.shift(),wm(F);for(var W=3;F[W]&&yp()!=a;)++W;for(a=0;a<$&&F[a+W];++a)o()[m+4*a>>>2>>>0]=yp();return a}var sh,nh={},ym=()=>{if(!sh){var a,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",_:Ne};for(a in nh)nh[a]===void 0?delete m[a]:m[a]=nh[a];var $=[];for(a in m)$.push(`${a}=${m[a]}`);sh=$}return sh};function Mm(a,m){if(te)return jr(18,1,a,m);a>>>=0,m>>>=0;var $=0;return ym().forEach((F,W)=>{var be=m+$;for(W=d()[a+4*W>>>2>>>0]=be,be=0;be>>0]=F.charCodeAt(be);r()[W>>>0]=0,$+=F.length+1}),0}function bm(a,m){if(te)return jr(19,1,a,m);a>>>=0,m>>>=0;var $=ym();d()[a>>>2>>>0]=$.length;var F=0;return $.forEach(W=>F+=W.length+1),d()[m>>>2>>>0]=F,0}function vm(a){return te?jr(20,1,a):52}function Tm(a,m,$,F){return te?jr(21,1,a,m,$,F):52}function xm(a,m,$,F){return te?jr(22,1,a,m,$,F):70}var x_=[null,[],[]];function Em(a,m,$,F){if(te)return jr(23,1,a,m,$,F);m>>>=0,$>>>=0,F>>>=0;for(var W=0,be=0;be<$;be++){var Ge=d()[m>>>2>>>0],st=d()[m+4>>>2>>>0];m+=8;for(var yt=0;yt>>0],Rt=x_[a];Pt===0||Pt===10?((a===1?rr:zt)(jh(Rt,0)),Rt.length=0):Rt.push(Pt)}W+=st}return d()[F>>>2>>>0]=W,0}var Pm=[31,29,31,30,31,30,31,31,30,31,30,31],Cm=[31,28,31,30,31,30,31,31,30,31,30,31],E_=(a,m)=>{r().set(a,m>>>0)};function $m(a,m,$,F){function W(Be,cr,Vr){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.lengthUm?-1:0qo-Be.getDate())){Be.setDate(Be.getDate()+cr);break}cr-=qo-Be.getDate()+1,Be.setDate(1),11>Vr?Be.setMonth(Vr+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return Vr=new Date(Be.getFullYear()+1,0,4),cr=st(new Date(Be.getFullYear(),0,4)),Vr=st(Vr),0>=Ge(cr,Be)?0>=Ge(Vr,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}a>>>=0,m>>>=0,$>>>=0,F>>>=0;var Pt=d()[F+40>>>2>>>0];for(var Rt in F={kc:o()[F>>>2>>>0],jc:o()[F+4>>>2>>>0],Hb:o()[F+8>>>2>>>0],Lb:o()[F+12>>>2>>>0],Ib:o()[F+16>>>2>>>0],Cb:o()[F+20>>>2>>>0],ub:o()[F+24>>>2>>>0],Bb:o()[F+28>>>2>>>0],rc:o()[F+32>>>2>>>0],ic:o()[F+36>>>2>>>0],lc:Pt?ls(Pt):""},$=ls($),Pt={"%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"})$=$.replace(new RegExp(Rt,"g"),Pt[Rt]);var mr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Pr="January February March April May June July August September October November December".split(" ");for(Rt in Pt={"%a":Be=>mr[Be.ub].substring(0,3),"%A":Be=>mr[Be.ub],"%b":Be=>Pr[Be.Ib].substring(0,3),"%B":Be=>Pr[Be.Ib],"%C":Be=>be((Be.Cb+1900)/100|0,2),"%d":Be=>be(Be.Lb,2),"%e":Be=>W(Be.Lb,2," "),"%g":Be=>yt(Be).toString().substring(2),"%G":yt,"%H":Be=>be(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var cr=0,Vr=0;Vr<=Be.Ib-1;cr+=(Ia(Be.Cb+1900)?Pm:Cm)[Vr++]);return be(Be.Lb+cr,3)},"%m":Be=>be(Be.Ib+1,2),"%M":Be=>be(Be.jc,2),"%n":()=>` `,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>be(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>be(Math.floor((Be.Bb+7-Be.ub)/7),2),"%V":Be=>{var cr=Math.floor((Be.Bb+7-(Be.ub+6)%7)/7);if(2>=(Be.ub+371-Be.Bb-2)%7&&cr++,cr)cr==53&&((Vr=(Be.ub+371-Be.Bb)%7)==4||Vr==3&&Ia(Be.Cb)||(cr=1));else{cr=52;var Vr=(Be.ub+7-Be.Bb-1)%7;(Vr==4||Vr==5&&Ia(Be.Cb%400-1))&&cr++}return be(cr,2)},"%w":Be=>Be.ub,"%W":Be=>be(Math.floor((Be.Bb+7-(Be.ub+6)%7)/7),2),"%y":Be=>(Be.Cb+1900).toString().substring(2),"%Y":Be=>Be.Cb+1900,"%z":Be=>{var cr=0<=(Be=Be.ic);return Be=Math.abs(Be)/60,(cr?"+":"-")+("0000"+(Be/60*100+Be%60)).slice(-4)},"%Z":Be=>Be.lc,"%%":()=>"%"},$=$.replace(/%%/g,"\0\0"),Pt)$.includes(Rt)&&($=$.replace(new RegExp(Rt,"g"),Pt[Rt](F)));return Rt=function(Be){var cr=Array(Kp(Be)+1);return Vh(Be,cr,0,cr.length),cr}($=$.replace(/\0\0/g,"%")),Rt.length>m?0:(E_(Rt,a),Rt.length-1)}function P_(a,m,$,F){return $m(a>>>0,m>>>0,$>>>0,F>>>0)}te||function(){for(var a=l.numThreads-1;a--;)Lh();Go.unshift(()=>{Gs++,function(m){te?m():Promise.all(no.map(Dh)).then(m)}(()=>pp())})}();for(var Sm=Array(256),Mp=0;256>Mp;++Mp)Sm[Mp]=String.fromCharCode(Mp);tm=Sm,oo=l.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},l.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},On.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>On.length/2-5-Qp.length;var C_=[Wp,Ah,zh,Nh,Uh,Wh,Gh,Kh,Hh,qh,Qh,Xh,Yh,Jh,Zh,em,mm,fm,Mm,bm,vm,Tm,xm,Em],Bt=function(){function a($,F){return Bt=$.exports,Bt=function(){var W=Bt,be={};for(let[Ge,st]of Object.entries(W))be[Ge]=typeof st=="function"?(...yt)=>{_p.push(Ge);try{return st(...yt)}finally{bs||(_p.pop(),yn&&ao===1&&_p.length===0&&(ao=0,Ko+=1,fp(Bm),typeof Fibers<"u"&&Fibers.sc()))}}:st;return be}(),Bt=function(){var W=Bt,be=st=>yt=>st(yt)>>>0,Ge=st=>()=>st()>>>0;return(W=Object.assign({},W)).Ca=be(W.Ca),W.fb=Ge(W.fb),W.gb=be(W.gb),W.emscripten_main_runtime_thread_id=Ge(W.emscripten_main_runtime_thread_id),W.sb=be(W.sb),W.tb=Ge(W.tb),W}(),Ih.push(Bt.ib),es.unshift(Bt.Ba),Er=F,pp(),Bt}var m=Sh();if(Gs++,l.instantiateWasm)try{return l.instantiateWasm(m,a)}catch($){zt(`Module.instantiateWasm callback failed with error: ${$}`),x($)}return jp||(jp=l.locateFile?Eh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",rt):rt+"ort-wasm-simd-threaded.jsep.wasm":new URL(c("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),c.b).href),function($,F){var W=jp;return vt||typeof WebAssembly.instantiateStreaming!="function"||Eh(W)||Ph(W)||typeof fetch!="function"?$h(W,$,F):fetch(W,{credentials:"same-origin"}).then(be=>WebAssembly.instantiateStreaming(be,$).then(F,function(Ge){return zt(`wasm streaming compile failed: ${Ge}`),zt("falling back to ArrayBuffer instantiation"),$h(W,$,F)}))}(m,function($){a($.instance,$.module)}).catch(x),{}}(),km=a=>(km=Bt.Ca)(a),Am=()=>(Am=Bt.Da)();l._OrtInit=(a,m)=>(l._OrtInit=Bt.Ea)(a,m),l._OrtGetLastError=(a,m)=>(l._OrtGetLastError=Bt.Fa)(a,m),l._OrtCreateSessionOptions=(a,m,$,F,W,be,Ge,st,yt,Pt)=>(l._OrtCreateSessionOptions=Bt.Ga)(a,m,$,F,W,be,Ge,st,yt,Pt),l._OrtAppendExecutionProvider=(a,m)=>(l._OrtAppendExecutionProvider=Bt.Ha)(a,m),l._OrtAddFreeDimensionOverride=(a,m,$)=>(l._OrtAddFreeDimensionOverride=Bt.Ia)(a,m,$),l._OrtAddSessionConfigEntry=(a,m,$)=>(l._OrtAddSessionConfigEntry=Bt.Ja)(a,m,$),l._OrtReleaseSessionOptions=a=>(l._OrtReleaseSessionOptions=Bt.Ka)(a),l._OrtCreateSession=(a,m,$)=>(l._OrtCreateSession=Bt.La)(a,m,$),l._OrtReleaseSession=a=>(l._OrtReleaseSession=Bt.Ma)(a),l._OrtGetInputOutputCount=(a,m,$)=>(l._OrtGetInputOutputCount=Bt.Na)(a,m,$),l._OrtGetInputName=(a,m)=>(l._OrtGetInputName=Bt.Oa)(a,m),l._OrtGetOutputName=(a,m)=>(l._OrtGetOutputName=Bt.Pa)(a,m),l._OrtFree=a=>(l._OrtFree=Bt.Qa)(a),l._OrtCreateTensor=(a,m,$,F,W,be)=>(l._OrtCreateTensor=Bt.Ra)(a,m,$,F,W,be),l._OrtGetTensorData=(a,m,$,F,W)=>(l._OrtGetTensorData=Bt.Sa)(a,m,$,F,W),l._OrtReleaseTensor=a=>(l._OrtReleaseTensor=Bt.Ta)(a),l._OrtCreateRunOptions=(a,m,$,F)=>(l._OrtCreateRunOptions=Bt.Ua)(a,m,$,F),l._OrtAddRunConfigEntry=(a,m,$)=>(l._OrtAddRunConfigEntry=Bt.Va)(a,m,$),l._OrtReleaseRunOptions=a=>(l._OrtReleaseRunOptions=Bt.Wa)(a),l._OrtCreateBinding=a=>(l._OrtCreateBinding=Bt.Xa)(a),l._OrtBindInput=(a,m,$)=>(l._OrtBindInput=Bt.Ya)(a,m,$),l._OrtBindOutput=(a,m,$,F)=>(l._OrtBindOutput=Bt.Za)(a,m,$,F),l._OrtClearBoundOutputs=a=>(l._OrtClearBoundOutputs=Bt._a)(a),l._OrtReleaseBinding=a=>(l._OrtReleaseBinding=Bt.$a)(a),l._OrtRunWithBinding=(a,m,$,F,W)=>(l._OrtRunWithBinding=Bt.ab)(a,m,$,F,W),l._OrtRun=(a,m,$,F,W,be,Ge,st)=>(l._OrtRun=Bt.bb)(a,m,$,F,W,be,Ge,st),l._OrtEndProfiling=a=>(l._OrtEndProfiling=Bt.cb)(a),l._JsepOutput=(a,m,$)=>(l._JsepOutput=Bt.db)(a,m,$),l._JsepGetNodeName=a=>(l._JsepGetNodeName=Bt.eb)(a);var bp,Fa=()=>(Fa=Bt.fb)(),vp=l._malloc=a=>(vp=l._malloc=Bt.gb)(a),Mn=l._free=a=>(Mn=l._free=Bt.hb)(a),oh=(a,m,$,F,W,be)=>(oh=Bt.kb)(a,m,$,F,W,be),Im=()=>(Im=Bt.lb)(),Fm=(a,m,$,F,W)=>(Fm=Bt.mb)(a,m,$,F,W),ih=a=>(ih=Bt.nb)(a),Tp=a=>(Tp=Bt.ob)(a),Om=()=>(Om=Bt.pb)(),Dm=(a,m)=>(Dm=Bt.qb)(a,m),xp=a=>(xp=Bt.rb)(a),ah=a=>(ah=Bt.sb)(a),lh=()=>(lh=Bt.tb)(),Lm=l.dynCall_ii=(a,m)=>(Lm=l.dynCall_ii=Bt.vb)(a,m),zm=a=>(zm=Bt.wb)(a),Bm=()=>(Bm=Bt.xb)(),Rm=a=>(Rm=Bt.yb)(a),jm=()=>(jm=Bt.zb)();function Nm(){0lh(),l.stackRestore=a=>xp(a),l.stackAlloc=a=>ah(a),l.UTF8ToString=ls,l.stringToUTF8=Aa,l.lengthBytesUTF8=Kp,so=function a(){bp||Nm(),bp||(so=a)},Nm(),O}),vn=Ds,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Ds()}),Ts,Ls,Xs,un,Ys,xs,Js,Zs,zs=g(()=>{var e,t;Ct(),Ts=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),Ls=typeof location>"u"?void 0:location.origin,Xs=(r,s)=>{try{let n=s??Ts;return(n?new URL(r,n):new URL(r)).origin===Ls}catch{return!1}},un=async r=>{let s=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(s)},Ys=(as(),y(ar)).default,xs=async()=>{if(!Ts)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Xs(Ts))return[void 0,Ys()];let r=await un(Ts);return[r,Ys(r)]},Js=(Dt(),y(qs)).default,Zs=async(r,s,n)=>[void 0,Js]}),ps,it,Mt,It,Wr,en,Bs,Sr,ts=g(()=>{zs(),it=!1,Mt=!1,It=!1,Wr=()=>{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}},en=()=>{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}},Bs=async e=>{if(it)return Promise.resolve();if(Mt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(It)throw new Error("previous call to 'initializeWebAssembly()' failed.");Mt=!0;let t=e.initTimeout,r=e.numThreads;if(!en())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=Wr();r>1&&!s&&(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 n=e.wasmPaths,i=typeof n=="string"?n:void 0,o=n==null?void 0:n.mjs,d=(o==null?void 0:o.href)??o,p=n==null?void 0:n.wasm,h=(p==null?void 0:p.href)??p,P=e.wasmBinary,[x,l]=await Zs(d,i,r>1),O=!1,L=[];if(t>0&&L.push(new Promise(B=>{setTimeout(()=>{O=!0,B()},t)})),L.push(new Promise((B,te)=>{let se={numThreads:r};P?se.wasmBinary=P:(h||i)&&(se.locateFile=(H,pe)=>h??(i??pe)+H),l(se).then(H=>{Mt=!1,it=!0,ps=H,B(),x&&URL.revokeObjectURL(x)},H=>{Mt=!1,It=!0,te(H)})})),await Promise.race(L),O)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Sr=()=>{if(it&&ps)return ps;throw new Error("WebAssembly is not initialized yet.")}}),Br,As,br,Tn=g(()=>{ts(),Br=(e,t)=>{let r=Sr(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},As=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,i])=>{let o=t?t+n:n;if(typeof i=="object")As(i,o+".",r,s);else if(typeof i=="string"||typeof i=="number")s(o,i.toString());else if(typeof i=="boolean")s(o,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},br=e=>{let t=Sr(),r=t.stackSave();try{let s=t.stackAlloc(8);t._OrtGetLastError(s,s+4);let n=t.HEAP32[s/4],i=t.HEAPU32[s/4+1],o=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(r)}}}),tn,uo=g(()=>{ts(),Tn(),tn=e=>{let t=Sr(),r=0,s=[],n=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)n.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)n.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&&(n.terminate=!1);let i=0;return(e==null?void 0:e.tag)!==void 0&&(i=Br(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,i),r===0&&br("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&As(e.extra,"",new WeakSet,(o,d)=>{let p=Br(o,s),h=Br(d,s);t._OrtAddRunConfigEntry(r,p,h)!==0&&br(`Can't set a run config entry: ${o} - ${d}.`)}),[r,s]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),i}}}),Dn,Ln,zn,Rs,Bn,co=g(()=>{ts(),Tn(),Dn=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}`)}},Ln=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},zn=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)},Rs=(e,t,r)=>{for(let s of t){let n=typeof s=="string"?s:s.name;switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let d=Br("deviceType",r),p=Br(o,r);Sr()._OrtAddSessionConfigEntry(e,d,p)!==0&&br(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(n="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let d=Br("preferredLayout",r),p=Br(o.preferredLayout,r);Sr()._OrtAddSessionConfigEntry(e,d,p)!==0&&br(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=Br(n,r);Sr()._OrtAppendExecutionProvider(e,i)!==0&&br(`Can't append execution provider: ${n}.`)}},Bn=e=>{let t=Sr(),r=0,s=[],n=e||{};zn(n);try{let i=Dn(n.graphOptimizationLevel??"all"),o=Ln(n.executionMode??"sequential"),d=typeof n.logId=="string"?Br(n.logId,s):0,p=n.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=n.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let P=typeof n.optimizedModelFilePath=="string"?Br(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(i,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,d,p,h,P),r===0&&br("Can't create session options."),n.executionProviders&&Rs(r,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);let x=Br("enableGraphCapture",s),l=Br(n.enableGraphCapture.toString(),s);t._OrtAddSessionConfigEntry(r,x,l)!==0&&br(`Can't set a session config entry: 'enableGraphCapture' - ${n.enableGraphCapture}.`)}if(n.freeDimensionOverrides)for(let[x,l]of Object.entries(n.freeDimensionOverrides)){if(typeof x!="string")throw new Error(`free dimension override name must be a string: ${x}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let O=Br(x,s);t._OrtAddFreeDimensionOverride(r,O,l)!==0&&br(`Can't set a free dimension override: ${x} - ${l}.`)}return n.extra!==void 0&&As(n.extra,"",new WeakSet,(x,l)=>{let O=Br(x,s),L=Br(l,s);t._OrtAddSessionConfigEntry(r,O,L)!==0&&br(`Can't set a session config entry: ${x} - ${l}.`)}),[r,s]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r),s.forEach(o=>t._free(o)),i}}}),rn,Es,js,Ns,dn,xn,En,Pn,Ot=g(()=>{rn=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}`)}},Es=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}`)}},js=(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],s=typeof t=="number"?t:t.reduce((n,i)=>n*i,1);return r>0?Math.ceil(s*r):void 0},Ns=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}`)}},dn=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}`)}},xn=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",Pn=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}`)}}}),Cn,Rn=g(()=>{Ct(),Cn=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"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(s)}catch(d){if(d instanceof RangeError){let p=Math.ceil(s/65536);i=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw d}let o=0;for(;;){let{done:d,value:p}=await n.read();if(d)break;let h=p.byteLength;new Uint8Array(i,o,h).set(p),o+=h}return new Uint8Array(i,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),jn,Nn,$n,Un,Sn,kn,_r,xe=g(()=>{Ot(),jn=["V","I","W","E","F"],Nn=(e,t)=>{console.log(`[${jn[e]},${new Date().toISOString()}]${t}`)},Sn=(e,t)=>{$n=e,Un=t},kn=(e,t)=>{let r=dn(e),s=dn($n);r>=s&&Nn(r,typeof t=="function"?t():t)},_r=(...e)=>{Un&&kn(...e)}}),T,K=g(()=>{Ot(),T=(e,t)=>new(Ns(t))(e)}),oe=g(()=>{}),Me,Pe,Ue,lt,mt,pt,Tt,Wt,gr,Jt=g(()=>{xe(),oe(),Me=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]]),Pe=[],Ue=e=>Math.ceil(e/16)*16,lt=e=>{for(let t=0;tmt++,Tt=async(e,t,r,s)=>{let n=Ue(r),i=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,i,0,n),e.flush(),await i.mapAsync(GPUMapMode.READ);let d=i.getMappedRange();if(s){let p=s();return p.set(new Uint8Array(d,0,r)),p}else return new Uint8Array(d.slice(0,r))}finally{i.destroy()}},Wt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Me)Pe.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,s=t.byteOffset,n=t.byteLength,i=Ue(n),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(o.originalSize!==n)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${n}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(r,s,n)),d.unmap();let h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(d,0,o.gpuData.buffer,0,i),_r("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(d)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(t);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let n=Ue(r.originalSize),i=this.backend.getCommandEncoder();this.backend.endComputePass(),i.copyBufferToBuffer(r.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,t,r){let s;if(r){if(s=r[0],e===r[1])return _r("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, buffer is the same, skip.`),s;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 s=pt();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:t}),_r("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),_r("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=lt(e),s,n=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,i=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||i){let d=(n?this.freeBuffers:this.freeUniformBuffers).get(r);d?d.length>0?s=d.pop():s=this.backend.device.createBuffer({size:r,usage:t}):s=this.backend.device.createBuffer({size:r,usage:t})}else s=this.backend.device.createBuffer({size:r,usage:t});let o={id:pt(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:e}),_r("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return _r("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await Tt(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Me.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},gr=(...e)=>new Wt(...e)}),Cr,qt,lr=g(()=>{Cr=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}},qt=e=>new Cr(e)}),hs,Gr,De,wr,qr,ms,Ps,Ut=g(()=>{hs=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Gr=class{static calcShape(e,t,r=!1){let s=e.length,n=t.length;if(s===0)return t;if(n===0)return e;let i=Math.max(e.length,t.length),o=new Array(i);if(r){if(s<2||n<2)return;let d=hs.calcMatMulShape([e[s-2],e[s-1]],[t[n-2],t[n-1]]);if(d===void 0)return;[o[i-2],o[i-1]]=d}for(let d=r?3:1;d<=i;d++){let p=s-d<0?1:e[s-d],h=n-d<0?1:t[n-d];if(p!==h&&p>1&&h>1)return;let P=Math.max(p,h);if(p&&h)o[i-d]=Math.max(p,h);else{if(P>1)return;o[i-d]=0}}return o}static isValidBroadcast(e,t){let r=e.length,s=t.length;if(r>s)return!1;for(let n=1;n<=r;n++)if(e[r-n]!==1&&e[r-n]!==t[s-n])return!1;return!0}},De=class Ep{static size(t){return Ep.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let s=t.length;if(s===0)return[];let n=new Array(s),i=s-1;for(;i>=0;){if(t[i]%r===0){n[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");n[i]=1,r/=t[i],i--}for(i--;i>=0;i--)n[i]=t[i];return n}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 Ep.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 Ep.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,s){let n=1;for(let i=r;i=0;--n)s[n]=s[n+1]*t[n+1];return s}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(s=>this.normalizeAxis(s,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(s=>t[s]):t.slice().reverse()}static padShape(t,r){let s=t.length;return t.map((n,i)=>n+r[i]+r[i+s])}static areEqual(t,r){return t.length!==r.length?!1:t.every((s,n)=>s===r[n])}},wr=class yc{static adjustPoolAttributes(t,r,s,n,i,o){if(!t&&s.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=s.length?s.push(r[d+2]):s[d]=r[d+2];for(let d=0;d=s[d]||o[d+s.length]>=s[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,s,n,i,o,d){if(d){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{Ot(),Ut(),Rr=64,us=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},or=(e,t=1)=>{let r=us(e,t);return typeof r=="string"?r:r[0]},yr=(e,t=1)=>{let r=us(e,t);return typeof r=="string"?r:r[1]},wt=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:De.computeStrides(r)})}),t},Zt=e=>e%4===0?4:e%2===0?2:1,Dr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Is=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Fs=(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,St=(e,t,r,s)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?s==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:s==="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,po=(e,t,r,s,n)=>{let i=typeof r=="number",o=i?r:r.length,d=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=us(t,n),P=typeof h=="string"?h:h[1],x=typeof h=="string"?h:h[0],l={indices:p,value:P,storage:x,tensor:t},O=Ve=>typeof Ve=="string"?Ve:`${Ve}u`,L={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},B=i?"uniforms.":"",te=`${B}${e}_shape`,se=`${B}${e}_strides`,H="";for(let Ve=0;Ve ${l.indices} { var indices: ${l.indices}; var current = offset; ${H} return indices; }`,ae=Ve=>(L.offsetToIndices=!0,o<2?Ve:`o2i_${e}(${Ve})`),ge=[];if(o>=2)for(let Ve=o-1;Ve>=0;Ve--)ge.push(`${St(se,Ve,o)} * (indices[${Ve}])`);let Ne=o<2?"":` fn i2o_${e}(indices: ${l.indices}) -> u32 { return ${ge.join("+")}; }`,Fe=Ve=>(L.indicesToOffset=!0,o<2?Ve:`i2o_${e}(${Ve})`),rt=(...Ve)=>o===0?"0u":`${l.indices}(${Ve.map(O).join(",")})`,vt=(Ve,ct)=>o<2?`${Ve}`:`${St(Ve,ct,o)}`,$t=(Ve,ct,Vt)=>o<2?`${Ve}=${Vt};`:`${St(Ve,ct,o)}=${Vt};`,Yt={},rr=(Ve,ct)=>{L.broadcastedIndicesToOffset=!0;let Vt=`${ct.name}broadcastedIndicesTo${e}Offset`;if(Vt in Yt)return`${Vt}(${Ve})`;let xr=[];for(let Hr=o-1;Hr>=0;Hr--){let Qr=ct.indicesGet("outputIndices",Hr+ct.rank-o);xr.push(`${vt(se,Hr)} * (${Qr} % ${vt(te,Hr)})`)}return Yt[Vt]=`fn ${Vt}(outputIndices: ${ct.type.indices}) -> u32 { return ${xr.length>0?xr.join("+"):"0u"}; }`,`${Vt}(${Ve})`},zt=(Ve,ct)=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]=${ct};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${Ve}]=vec2(u32(${ct}), select(0u, 0xFFFFFFFFu, ${ct} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${Ve}]=vec2(u32(${ct}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${Ve}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ct}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Tr=Ve=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${Ve}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${Ve}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${Ve}] & 0xFFu), bool(${e}[${Ve}] & 0xFF00u), bool(${e}[${Ve}] & 0xFF0000u), bool(${e}[${Ve}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Ir=o<2?"":` fn get_${e}ByIndices(indices: ${l.indices}) -> ${P} { return ${Tr(`i2o_${e}(indices)`)}; }`,nr=o<2?"":(()=>{let Ve=d.map(Vt=>`d${Vt}: u32`).join(", "),ct=d.map(Vt=>`d${Vt}`).join(", ");return` fn get_${e}(${Ve}) -> ${P} { return get_${e}ByIndices(${rt(ct)}); }`})(),Er=(...Ve)=>{if(Ve.length!==o)throw new Error(`indices length must be ${o}`);let ct=Ve.map(O).join(",");return o===0?Tr("0u"):o===1?Tr(ct[0]):(L.get=!0,L.getByIndices=!0,L.indicesToOffset=!0,`get_${e}(${ct})`)},Ft=Ve=>o<2?Tr(Ve):(L.getByIndices=!0,L.indicesToOffset=!0,`get_${e}ByIndices(${Ve})`),Nt=o<2?"":` fn set_${e}ByIndices(indices: ${l.indices}, value: ${P}) { ${zt(`i2o_${e}(indices)`,"value")} }`,hr=o<2?"":(()=>{let Ve=d.map(Vt=>`d${Vt}: u32`).join(", "),ct=d.map(Vt=>`d${Vt}`).join(", ");return` fn set_${e}(${Ve}, value: ${P}) { set_${e}ByIndices(${rt(ct)}, value); }`})();return{impl:()=>{let Ve=[],ct=!1;return L.offsetToIndices&&(Ve.push(pe),ct=!0),L.indicesToOffset&&(Ve.push(Ne),ct=!0),L.broadcastedIndicesToOffset&&(Object.values(Yt).forEach(Vt=>Ve.push(Vt)),ct=!0),L.set&&(Ve.push(hr),ct=!0),L.setByIndices&&(Ve.push(Nt),ct=!0),L.get&&(Ve.push(nr),ct=!0),L.getByIndices&&(Ve.push(Ir),ct=!0),!i&&ct&&Ve.unshift(`const ${te} = ${l.indices}(${r.join(",")});`,`const ${se} = ${l.indices}(${De.computeStrides(r).join(",")});`),Ve.join(` `)},type:l,offsetToIndices:ae,indicesToOffset:Fe,broadcastedIndicesToOffset:rr,indices:rt,indicesGet:vt,indicesSet:$t,set:(...Ve)=>{if(Ve.length!==o+1)throw new Error(`indices length must be ${o}`);let ct=Ve[o];if(typeof ct!="string")throw new Error("value must be string");let Vt=Ve.slice(0,o).map(O).join(",");return o===0?zt("0u",ct):o===1?zt(Vt[0],ct):(L.set=!0,L.setByIndices=!0,L.indicesToOffset=!0,`set_${e}(${Vt}, ${ct})`)},setByOffset:zt,setByIndices:(Ve,ct)=>o<2?zt(Ve,ct):(L.setByIndices=!0,L.indicesToOffset=!0,`set_${e}ByIndices(${Ve}, ${ct});`),get:Er,getByOffset:Tr,getByIndices:Ft,usage:s,name:e,strides:se,shape:te,rank:o}},Ze=(e,t,r,s=1)=>po(e,t,r,"input",s),kt=(e,t,r,s=1)=>po(e,t,r,"output",s),Yo=(e,t,r,s=1)=>po(e,t,r,"internal",s),Da=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=Rr){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,i=n?`@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`,o=n?`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*s}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${s}) fn main(${i}) { ${o} `}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",s=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${s}>;`}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:s}of this.uniforms)if(s&&s>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(s/8)}>`):e.push(`${t}:array, ${Math.ceil(s/4)}>`);else{let n=s==null||s===1?r:`vec${s}<${r}>`;e.push(`${t}:${n}`)}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])}},Jo=(e,t)=>new Da(e,t),Vn=(e,t)=>{let r=e.length,s=[];for(let n=0;n1&&o===1&&s.unshift(i)}return s}}),Zo,ei,ho,La,za,fs,Ba,Ra,Us=g(()=>{Ot(),Ut(),lr(),er(),Zo=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},ei=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,ho=(e,t)=>De.sortBasedOnPerm(e,ei(e.length,t)),La=(e,t,r,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`;for(let i=0;i{let r=[],s=[];for(let n=0;n{let r=e.dataType,s=e.dims.length,n=ei(s,t),i=ho(e.dims,n),{newShape:o,newPerm:d}=za(e.dims,n),p=De.areEqual(d,[2,3,1]),h=De.areEqual(d,[3,1,2]),P=o.length===2&&d[0]>d[1]||p||h,x=P?o:e.dims,l=i;P&&(x=p?[o[0],o[1]*o[2]]:h?[o[0]*o[1],o[2]]:o,l=[x[1],x[0]]);let O=Ze("a",r,x.length),L=kt("output",r,l.length),B=16,te;return P?te=se=>` ${se.registerUniform("output_size","u32").declareVariables(O,L)} var tile : array, ${B}>; ${se.mainStart([B,B,1])} let stride = (uniforms.output_shape[1] - 1) / ${B} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${B}u + local_id.x; let input_row = workgroup_id_x * ${B}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${O.getByIndices(`${O.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${B}u + local_id.x; let output_row = workgroup_id_y * ${B}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${L.setByIndices(`${L.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`:te=se=>` ${se.registerUniform("output_size","u32").declareVariables(O,L)} ${La(n,s,O,L)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${L.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${L.setByOffset("global_idx",O.getByIndices("aIndices"))} }`,{name:P?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let se=De.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:P?{x:Math.ceil(l[1]/B),y:Math.ceil(l[0]/B)}:{x:Math.ceil(se/64)},programUniforms:[{type:12,data:se},...wt(x,l)]}},getShaderSource:te}},Ba=(e,t)=>{Zo(e.inputs),e.compute(fs(e.inputs[0],t.perm))},Ra=e=>qt({perm:e.perm})}),cn,ja,bc,Na,vc,Ua,ti,Va,Wa,Ga,Cs,Ka,mo,Ha,qa,Qa,ri,Xa,Ya,si,Ja,Tc=g(()=>{Ot(),Ut(),er(),di(),Us(),cn={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"},ja={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"},bc={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Na={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},vc=(e,t)=>{let r=[];for(let s=t-e;s{let r=[],s=e.length;for(let i=0;ie[i]);return[r,n]},ti=(e,t)=>{let r=e.length+t.length,s=[],n=0;for(let i=0;i{for(let r=0;r{let r=[];if(!Va(e,t)){for(let s=0;sr.push(s))}return r},Ga=(e,t,r,s,n,i,o)=>{let d=r[0].dims,p=De.size(i),h=De.size(o),P=Ze("_A",r[0].dataType,d),x=kt("output",n,i),l=32,O=` var aBestValues : array; `;return{name:e,shaderCache:t,getShaderSource:L=>` ${L.registerUniform("reduceSize","u32").declareVariables(P,x)} ${O} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${L.mainStart(l)} let outputIndex = global_idx / ${l}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${bc[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${l}) { let candidate = f32(${P.getByOffset("offset + k")}); bestValue = ${cn[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${l}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${ja[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${x.setByOffset("outputIndex",`${s==="mean"?`${x.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${x.type.storage}(${Na[s]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},Cs=(e,t,r,s)=>{let n=e.inputs.length===1?r:_o(e.inputs,r),i=n.axes;i.length===0&&!n.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((O,L)=>L));let o=De.normalizeAxes(i,e.inputs[0].dims.length),d=o,p=e.inputs[0],h=Wa(d,e.inputs[0].dims.length);h.length>0&&(p=e.compute(fs(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],d=vc(d.length,p.dims.length));let[P,x]=Ua(p.dims,d),l=P;n.keepDims&&(l=ti(P,o)),e.compute(Ga(t,{hint:n.cacheKey,inputDependencies:["type"]},[p],s,e.inputs[0].dataType,l,x),{inputs:[p]})},Ka=(e,t)=>{Cs(e,"ReduceMeanShared",t,"mean")},mo=(e,t)=>{Cs(e,"ReduceL1Shared",t,"l1")},Ha=(e,t)=>{Cs(e,"ReduceL2Shared",t,"l2")},qa=(e,t)=>{Cs(e,"ReduceLogSumExpShared",t,"logSumExp")},Qa=(e,t)=>{Cs(e,"ReduceMaxShared",t,"max")},ri=(e,t)=>{Cs(e,"ReduceMinShared",t,"min")},Xa=(e,t)=>{Cs(e,"ReduceProdShared",t,"prod")},Ya=(e,t)=>{Cs(e,"ReduceSumShared",t,"sum")},si=(e,t)=>{Cs(e,"ReduceSumSquareShared",t,"sumSquare")},Ja=(e,t)=>{Cs(e,"ReduceLogSumShared",t,"logSum")}}),ws,Za,fo,_o,$s,el,ni,tl,rl,oi,sl,nl,ii,ol,il,ys,al,ll,ai,ul,dl,li,cl,pl,ui,hl,di=g(()=>{Ot(),Ut(),lr(),er(),Tc(),ws=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.")},Za=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fo=(e,t,r,s,n,i,o=!1,d=!1)=>{let p=[],h=r[0].dims,P=h.length,x=De.normalizeAxes(n,P),l=!d&&x.length===0;h.forEach((B,te)=>{l||x.indexOf(te)>=0?o&&p.push(1):p.push(B)});let O=p.length,L=De.size(p);return{name:e,shaderCache:t,getShaderSource:B=>{let te=[],se=Ze("_A",r[0].dataType,P),H=kt("output",i,O),pe=s(se,H,x),ae=pe[2];for(let ge=0,Ne=0;ge=0?(o&&Ne++,ae=`for(var j${ge}: u32 = 0; j${ge} < ${h[ge]}; j${ge}++) { ${pe[2].includes("last_index")?`let last_index = j${ge};`:""} ${se.indicesSet("input_indices",ge,`j${ge}`)} ${ae} }`):(te.push(`${se.indicesSet("input_indices",ge,H.indicesGet("output_indices",Ne))};`),Ne++);return` ${B.registerUniform("output_size","u32").declareVariables(se,H)} ${B.mainStart()} ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${se.type.indices}; let output_indices = ${H.offsetToIndices("global_idx")}; ${te.join(` `)} ${pe[0]} // init ops for reduce max/min ${pe[1]} ${ae} ${pe[3]} ${pe.length===4?H.setByOffset("global_idx","value"):pe.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(L/64)},programUniforms:[{type:12,data:L},...wt(h,p)]})}},_o=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),qt({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},$s=(e,t,r,s)=>{let n=e.inputs,i=n.length===1?r:_o(n,r);e.compute(fo(t,{hint:i.cacheKey,inputDependencies:["rank"]},[n[0]],i.noopWithEmptyAxes&&i.axes.length===0?Za:s,i.axes,n[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},el=(e,t)=>{ws(e.inputs),$s(e,"ReduceLogSum",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},ni=(e,t)=>{ws(e.inputs),$s(e,"ReduceL1",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},tl=(e,t)=>{ws(e.inputs),$s(e,"ReduceL2",t,(r,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},rl=(e,t)=>{ws(e.inputs),$s(e,"ReduceLogSumExp",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},oi=(e,t)=>{ws(e.inputs),$s(e,"ReduceMax",t,(r,s,n)=>{let i=[];for(let o=0;o=0||n.length===0)&&i.push(r.indicesSet("input_indices",o,0));return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},sl=(e,t)=>{ws(e.inputs),$s(e,"ReduceMean",t,(r,s,n)=>{let i=1;for(let o=0;o=0||n.length===0)&&(i*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${i});`]})},nl=(e,t)=>{ws(e.inputs),$s(e,"ReduceMin",t,(r,s,n)=>{let i=[];for(let o=0;o=0||n.length===0)&&i.push(`input_indices[${o}] = 0;`);return[`${i.join(` `)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ii=(e,t)=>{ws(e.inputs),$s(e,"ReduceProd",t,(r,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},ol=(e,t)=>{ws(e.inputs),$s(e,"ReduceSum",t,(r,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},il=(e,t)=>{ws(e.inputs),$s(e,"ReduceSumSquare",t,(r,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},ys=(e,t,r)=>{if(t.length===0)return r;let s=1,n=1;for(let i=0;i1024},al=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?sl(e,t):Ka(e,t)},ll=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ni(e,t):mo(e,t)},ai=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tl(e,t):Ha(e,t)},ul=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rl(e,t):qa(e,t)},dl=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?oi(e,t):Qa(e,t)},li=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?nl(e,t):ri(e,t)},cl=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ii(e,t):Xa(e,t)},pl=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ol(e,t):Ya(e,t)},ui=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):si(e,t)},hl=(e,t)=>{ys(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?el(e,t):Ja(e,t)}}),go,ml,fl,wo,xc=g(()=>{Ot(),lr(),di(),go=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.")},ml=(e,t)=>{go(e.inputs);let r=(s,n,i)=>{let o=[];for(let d=0;d=0||i.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(fo("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},fl=(e,t)=>{go(e.inputs);let r=(s,n,i)=>{let o=[];for(let d=0;d=0||i.length===0)&&o.push(`input_indices[${d}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(fo("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},wo=e=>qt(e)}),_l,ci,gl,wl,An,yl,Ml,yo=g(()=>{Ot(),Ut(),oe(),er(),_l=(e,t)=>{let r=e[0],s=e[1],n=e[2],i=e[3],o=e[4],d=e[5];if(o&&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],P=r.dims[2];if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==P)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let x=n.dims[0]/3,l=x,O=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let pe of t.qkvHiddenSizes)if(pe%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");x=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],O=t.qkvHiddenSizes[2]}let L=h;if(x!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==x+l+O)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let B=0;if(o){if(l!==O)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(B=o.dims[3])}let te=L+B,se=-1,H=0;if(i)throw new Error("Mask not supported");if(o)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]!==te)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:B,kvSequenceLength:L,totalSequenceLength:te,maxSequenceLength:se,inputHiddenSize:P,hiddenSize:x,vHiddenSize:O,headSize:Math.floor(x/t.numHeads),vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:H,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ci=(e,t,r)=>{let s=Zt(r),n=64,i=r/s;i{let O=kt("x",e.dataType,e.dims,s),L=yr(e.dataType),B=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${l.registerUniforms(B).declareVariables(O)} ${l.mainStart([n,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${n}) * uniforms.d_comp + local_offset; var thread_max_vector = ${h}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${h}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(s){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${s}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${n}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${h}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${h}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(s){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${s}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${n}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${O.type.value}(${L}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${h}(x[offset + i]); x[offset + i] = ${O.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${n};${p};${s}`,inputDependencies:P},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:d})}},gl=(e,t,r,s,n,i,o,d)=>{let p=d+i.kvSequenceLength,h=[i.batchSize,i.numHeads,i.sequenceLength,p],P=i.kvNumHeads===void 0&&e>1&&s,x=P?[i.batchSize,i.numHeads,p,i.headSize]:void 0,l=o.scale===0?1/Math.sqrt(i.headSize):o.scale,O=Zt(i.headSize),L=i.headSize/O,B=12,te={x:Math.ceil(p/B),y:Math.ceil(i.sequenceLength/B),z:i.batchSize*i.numHeads},se=[{type:12,data:i.sequenceLength},{type:12,data:L},{type:12,data:p},{type:12,data:i.numHeads},{type:1,data:l},{type:12,data:d},{type:12,data:i.kvSequenceLength}],H=P&&s&&De.size(s.dims)>0,pe=["type","type"];H&&pe.push("type"),n&&pe.push("type");let ae=[{dims:h,dataType:t.dataType,gpuDataType:0}];P&&ae.push({dims:x,dataType:t.dataType,gpuDataType:0});let ge=Ne=>{let Fe=Ze("q",t.dataType,t.dims,O),rt=Ze("key",r.dataType,r.dims,O),vt=[Fe,rt];if(H){let Tr=Ze("past_key",s.dataType,s.dims,O);vt.push(Tr)}n&&vt.push(Ze("attention_bias",n.dataType,n.dims));let $t=kt("output",t.dataType,h),Yt=[$t];P&&Yt.push(kt("present_key",t.dataType,x,O));let rr=yr(1,O),zt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${B}u; var tileQ: array<${Fe.type.storage}, ${B*B}>; var tileK: array<${Fe.type.storage}, ${B*B}>; ${Ne.registerUniforms(zt).declareVariables(...vt,...Yt)} ${Ne.mainStart([B,B,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${H&&P?` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} ${P?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${rr}(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; ${H&&P?` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} ${P?"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 += ${rr}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(O){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: ${O}`)}})()}; output[outputIdx] = ${$t.type.value} (sum * uniforms.alpha) + ${n?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${O};${n!==void 0};${s!==void 0};${e}`,inputDependencies:pe},getRunData:()=>({outputs:ae,dispatchGroup:te,programUniforms:se}),getShaderSource:ge}},wl=(e,t,r,s,n,i)=>{let o=i+n.kvSequenceLength,d=n.nReps?n.nReps:1,p=n.vHiddenSize*d,h=n.kvNumHeads==null&&e>1&&s,P=h?[n.batchSize,n.numHeads,o,n.headSize]:void 0,x=[n.batchSize,n.sequenceLength,p],l=12,O={x:Math.ceil(n.vHeadSize/l),y:Math.ceil(n.sequenceLength/l),z:n.batchSize*n.numHeads},L=[{type:12,data:n.sequenceLength},{type:12,data:o},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:p},{type:12,data:i},{type:12,data:n.kvSequenceLength}],B=h&&s&&De.size(s.dims)>0,te=["type","type"];B&&te.push("type");let se=[{dims:x,dataType:t.dataType,gpuDataType:0}];h&&se.push({dims:P,dataType:t.dataType,gpuDataType:0});let H=pe=>{let ae=Ze("probs",t.dataType,t.dims),ge=Ze("v",r.dataType,r.dims),Ne=[ae,ge];B&&Ne.push(Ze("past_value",s.dataType,s.dims));let Fe=[kt("output",t.dataType,x)];h&&Fe.push(kt("present_value",t.dataType,P));let rt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${l}u; var tileQ: array<${ae.type.value}, ${l*l}>; var tileK: array<${ae.type.value}, ${l*l}>; ${pe.registerUniforms(rt).declareVariables(...Ne,...Fe)} ${pe.mainStart([l,l,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${B&&h?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${h?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${ae.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${B&&h?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${h?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:te},getRunData:()=>({outputs:se,dispatchGroup:O,programUniforms:L}),getShaderSource:H}},An=(e,t,r,s,n,i,o,d,p,h,P)=>{let x=Math.min(e.outputCount,1+(o?1:0)+(d?1:0)),l=h.kvNumHeads!==void 0||x>1?h.pastSequenceLength:0,O=l+h.kvSequenceLength,L=p&&De.size(p.dims)>0?p:void 0,B=[t,r];h.kvNumHeads===void 0&&x>1&&o&&De.size(o.dims)>0&&B.push(o),L&&B.push(L);let te=e.compute(gl(x,t,r,o,L,h,P,l),{inputs:B,outputs:h.kvNumHeads===void 0&&x>1?[-1,1]:[-1]})[0];e.compute(ci(te,h.batchSize*h.numHeads*h.sequenceLength,O),{inputs:[te],outputs:[]});let se=[te,s];h.kvNumHeads===void 0&&x>1&&d&&De.size(d.dims)>0&&se.push(d),e.compute(wl(x,te,s,d,h,l),{inputs:se,outputs:h.kvNumHeads===void 0&&x>1?[0,2]:[0]})},yl=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],s=t.sequenceLength,n=t.inputHiddenSize,i=t.headSize,o=12,d={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:s},{type:12,data:n},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],P=x=>{let l=kt("output_q",p[0].dataType,r),O=kt("output_k",p[0].dataType,r),L=kt("output_v",p[0].dataType,r),B=Ze("input",p[0].dataType,p[0].dims),te=Ze("weight",p[1].dataType,p[1].dims),se=Ze("bias",p[2].dataType,p[2].dims),H=B.type.storage,pe=[{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 = ${o}u; var tileInput: array<${H}, ${o*o}>; var tileWeightQ: array<${H}, ${o*o}>; var tileWeightK: array<${H}, ${o*o}>; var tileWeightV: array<${H}, ${o*o}>; ${x.registerUniforms(pe).declareVariables(B,te,se,l,O,L)} ${x.mainStart([o,o,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 = ${H}(0); var valueK = ${H}(0); var valueV = ${H}(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:P},{inputs:p,outputs:[-1,-1,-1]})},Ml=(e,t)=>{let r=_l(e.inputs,t),[s,n,i]=yl(e,r);return An(e,s,n,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),bl,vl,pi,Tl,Ec=g(()=>{Et(),Ot(),Ut(),lr(),er(),bl=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(s,n,i)=>{let o=n.length;if(o!==s.length)throw new Error(`${i}: num dimensions != ${o}`);n.forEach((d,p)=>{if(d!==s[p])throw new Error(`${i}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let s=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,s,"Invalid input scale"),r(e[2].dims,s,"Invalid input B"),r(e[3].dims,s,"Invalid input mean"),r(e[4].dims,s,"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")},vl=(e,t)=>{let{epsilon:r,spatial:s,format:n}=t,i=e[0].dims,o=s?Zt(i[i.length-1]):1,d=n==="NHWC"&&i.length>1?o:1,p=De.size(i)/o,h=s,P=h?i.length:i,x=Ze("x",e[0].dataType,e[0].dims,o),l=Ze("scale",e[1].dataType,e[1].dims,d),O=Ze("bias",e[2].dataType,e[2].dims,d),L=Ze("inputMean",e[3].dataType,e[3].dims,d),B=Ze("inputVar",e[4].dataType,e[4].dims,d),te=kt("y",e[0].dataType,P,o),se=()=>{let pe="";if(s)pe=`let cOffset = ${i.length===1?"0u":n==="NHWC"?`outputIndices[${i.length-1}] / ${o}`:"outputIndices[1]"};`;else if(n==="NCHW")pe=` ${te.indicesSet("outputIndices","0","0")} let cOffset = ${te.indicesToOffset("outputIndices")};`;else{pe=`var cIndices = ${l.type.indices}(0); cIndices[0] = outputIndices[${i.length-1}];`;for(let ae=1;ae` const epsilon = ${r}; ${pe.registerUniform("outputSize","u32").declareVariables(x,l,O,L,B,te)} ${pe.mainStart()} ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${te.offsetToIndices(`global_idx * ${o}`)}; ${se()} let scale = ${l.getByOffset("cOffset")}; let bias = ${O.getByOffset("cOffset")}; let inputMean = ${L.getByOffset("cOffset")}; let inputVar = ${B.getByOffset("cOffset")}; let x = ${x.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${te.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${s}_${o}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:H,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...wt(i)]:[{type:12,data:p}]})}},pi=e=>qt(e),Tl=(e,t)=>{let{inputs:r,outputCount:s}=e,n=pi({...t,outputCount:s});if(E.webgpu.validateInputContent&&bl(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(vl(r,n))}}),xl,El,hi,Pc=g(()=>{Ut(),er(),xl=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")},El=e=>{let t=e[0].dims,r=e[0].dims[2],s=De.size(t)/4,n=e[0].dataType,i=Ze("input",n,t,4),o=Ze("bias",n,[r],4),d=Ze("residual",n,t,4),p=kt("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:h=>` const channels = ${r}u / 4; ${h.declareVariables(i,o,d,p)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes(s)} let value = ${i.getByOffset("global_idx")} + ${o.getByOffset("global_idx % channels")} + ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx","value")} }`}},hi=e=>{xl(e.inputs),e.compute(El(e.inputs))}}),Pl,ur,Cl,$l,mi,Sl,kl,fi,Al,Il,_i,Fl,Ol,gi,Dl,Ll,Wn,zl,Gn,Bl,Rl,jl,Nl,wi,Ul,Vl,Wl,Gl,yi,Kl,Hl,ql,Ql,Mi,Xl,bi,vi,Ti,xi,Ei,Yl,Jl,Pi,Zl,eu,Mo=g(()=>{Ot(),Ut(),lr(),er(),Pl=(e,t,r,s,n,i,o)=>{let d=Math.ceil(t/4),p="";typeof n=="string"?p=`${n}(a)`:p=n("a");let h=Ze("inputData",r,[d],4),P=kt("outputData",s,[d],4),x=[{name:"vec_size",type:"u32"}];return o&&x.push(...o),` ${e.registerUniforms(x).declareVariables(h,P)} ${i??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${h.getByOffset("global_idx")}; ${P.setByOffset("global_idx",p)} }`},ur=(e,t,r,s,n,i=e.dataType,o,d)=>{let p=[{type:12,data:Math.ceil(De.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:h=>Pl(h,De.size(e.dims),e.dataType,i,r,s,d),getRunData:h=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(De.size(h[0].dims)/64/4)},programUniforms:p})}},Cl=e=>{e.compute(ur(e.inputs[0],"Abs","abs"))},$l=e=>{e.compute(ur(e.inputs[0],"Acos","acos"))},mi=e=>{e.compute(ur(e.inputs[0],"Acosh","acosh"))},Sl=e=>{e.compute(ur(e.inputs[0],"Asin","asin"))},kl=e=>{e.compute(ur(e.inputs[0],"Asinh","asinh"))},fi=e=>{e.compute(ur(e.inputs[0],"Atan","atan"))},Al=e=>{e.compute(ur(e.inputs[0],"Atanh","atanh"))},Il=e=>qt(e),_i=(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))},Fl=e=>{let t,r,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=s?e[1].getFloat32Array()[0]:-34028234663852886e22,r=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=s?e[1].getUint16Array()[0]:64511,r=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return qt({min:t,max:r})},Ol=(e,t)=>{let r=t||Fl(e.inputs),s=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Clip",n=>`clamp(${n}, vec4<${s}>(uniforms.min), vec4<${s}>(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:s},{name:"max",type:s}]),{inputs:[0]})},gi=e=>{e.compute(ur(e.inputs[0],"Ceil","ceil"))},Dl=e=>{e.compute(ur(e.inputs[0],"Cos","cos"))},Ll=e=>{e.compute(ur(e.inputs[0],"Cosh","cosh"))},Wn=e=>qt(e),zl=(e,t)=>{let r=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` 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))},Gn=(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)); }`,Bl=e=>{let t=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Gn(t)))},Rl=e=>{e.compute(ur(e.inputs[0],"Exp","exp"))},jl=e=>{e.compute(ur(e.inputs[0],"Floor","floor"))},Nl=e=>{let t=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Gn(t)))},wi=(e,t)=>{let r=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Ul=e=>{e.compute(ur(e.inputs[0],"Not",t=>`!${t}`))},Vl=e=>{e.compute(ur(e.inputs[0],"Neg",t=>`-${t}`))},Wl=e=>{e.compute(ur(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Gl=e=>{let t=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},yi=e=>{e.compute(ur(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Kl=e=>qt(e),Hl=(e,t)=>{let r=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"HardSigmoid",s=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${s} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},ql=e=>{e.compute(ur(e.inputs[0],"Sin","sin"))},Ql=e=>{e.compute(ur(e.inputs[0],"Sinh","sinh"))},Mi=e=>{e.compute(ur(e.inputs[0],"Sqrt","sqrt"))},Xl=e=>{e.compute(ur(e.inputs[0],"Tan","tan"))},bi=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,vi=e=>{e.compute(ur(e.inputs[0],"Tanh",bi))},Ti=(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 ${bi("v")}; } `,xi=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ei=e=>{let t=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"FastGelu",xi,Ti(t),void 0,e.inputs[0].dataType))},Yl=(e,t)=>{let r=yr(e.inputs[0].dataType);return e.compute(ur(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${r}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},Jl=e=>{e.compute(ur(e.inputs[0],"Log","log"))},Pi=(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})`,eu=(e,t)=>{let r=yr(e.inputs[0].dataType);e.compute(ur(e.inputs[0],"QuickGelu",Zl,Pi(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),tu,ru,bo,Cc=g(()=>{Ut(),er(),Mo(),tu=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")},ru=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=Ze("input",e[0].dataType,e[0].dims,4),s=Ze("bias",e[0].dataType,[e[0].dims[2]],4),n=kt("output",e[0].dataType,t,4),i=De.size(t)/4,o=or(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(r,s,n)} ${Gn(o)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${n.setByOffset("global_idx","valueLeft * geluRight")} }`}},bo=e=>{tu(e.inputs),e.compute(ru(e.inputs))}}),su,Ci,Ms,nu,$i,ou,iu,au,Si,lu,uu,du,ki,$c=g(()=>{Ot(),Ut(),er(),su=(e,t,r,s,n,i,o,d,p,h,P,x)=>{let l,O;typeof d=="string"?l=O=(H,pe)=>`${d}((${H}),(${pe}))`:typeof d=="function"?l=O=d:(l=d.scalar,O=d.vector);let L=kt("outputData",P,s.length,4),B=Ze("aData",p,t.length,4),te=Ze("bData",h,r.length,4),se;if(n)if(i){let H=De.size(t)===1,pe=De.size(r)===1,ae=t.length>0&&t[t.length-1]%4===0,ge=r.length>0&&r[r.length-1]%4===0;H||pe?se=L.setByOffset("global_idx",O(H?`${B.type.value}(${B.getByOffset("0")}.x)`:B.getByOffset("global_idx"),pe?`${te.type.value}(${te.getByOffset("0")}.x)`:te.getByOffset("global_idx"))):se=` let outputIndices = ${L.offsetToIndices("global_idx * 4u")}; let offsetA = ${B.broadcastedIndicesToOffset("outputIndices",L)}; let offsetB = ${te.broadcastedIndicesToOffset("outputIndices",L)}; ${L.setByOffset("global_idx",O(o||ae?B.getByOffset("offsetA / 4u"):`${B.type.value}(${B.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||ge?te.getByOffset("offsetB / 4u"):`${te.type.value}(${te.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else se=L.setByOffset("global_idx",O(B.getByOffset("global_idx"),te.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let H=(pe,ae,ge="")=>{let Ne=`aData[indexA${ae}][componentA${ae}]`,Fe=`bData[indexB${ae}][componentB${ae}]`;return` let outputIndices${ae} = ${L.offsetToIndices(`global_idx * 4u + ${ae}u`)}; let offsetA${ae} = ${B.broadcastedIndicesToOffset(`outputIndices${ae}`,L)}; let offsetB${ae} = ${te.broadcastedIndicesToOffset(`outputIndices${ae}`,L)}; let indexA${ae} = offsetA${ae} / 4u; let indexB${ae} = offsetB${ae} / 4u; let componentA${ae} = offsetA${ae} % 4u; let componentB${ae} = offsetB${ae} % 4u; ${pe}[${ae}] = ${ge}(${l(Ne,Fe)}); `};P===9?se=` var data = vec4(0); ${H("data",0,"u32")} ${H("data",1,"u32")} ${H("data",2,"u32")} ${H("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:se=` ${H("outputData[global_idx]",0)} ${H("outputData[global_idx]",1)} ${H("outputData[global_idx]",2)} ${H("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(B,te,L)} ${x??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${se} }`},Ci=(e,t,r,s,n,i,o=r.dataType)=>{let d=!De.areEqual(r.dims,s.dims),p=r.dims,h=De.size(r.dims),P=!1,x=!1,l=[d];if(d){let O=Gr.calcShape(r.dims,s.dims,!1);if(!O)throw new Error("Can't perform binary op on the given tensors");p=O,h=De.size(p);let L=De.size(r.dims)===1,B=De.size(s.dims)===1,te=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,se=s.dims.length>0&&s.dims[s.dims.length-1]%4===0;l.push(L),l.push(B),l.push(te),l.push(se);let H=1;for(let pe=1;peO.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:O=>su(O,r.dims,s.dims,p,P,d,x,n,r.dataType,s.dataType,o,i),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(De.size(p)/4)},...wt(r.dims,s.dims,p)]})}},Ms=(e,t,r,s,n,i)=>{e.compute(Ci(t,n??"",e.inputs[0],e.inputs[1],r,s,i))},nu=e=>{Ms(e,"Add",(t,r)=>`${t}+${r}`)},$i=e=>{Ms(e,"Div",(t,r)=>`${t}/${r}`)},ou=e=>{Ms(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},iu=e=>{Ms(e,"Mul",(t,r)=>`${t}*${r}`)},au=e=>{let t=Ze("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ms(e,"Pow",{scalar:(r,s)=>`pow_custom(${r},${s})`,vector:(r,s)=>`pow_vector_custom(${r},${s})`},` 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)); } `)},Si=e=>{Ms(e,"Sub",(t,r)=>`${t}-${r}`)},lu=e=>{Ms(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},uu=e=>{Ms(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},du=e=>{Ms(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},ki=e=>{Ms(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),cu,Ai,pu,hu,Ii,mu,Sc=g(()=>{Ot(),Ut(),lr(),er(),cu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,s=e[r],n=s.dataType,i=s.dims.length;e.forEach((o,d)=>{if(d!==r){if(o.dataType!==n)throw new Error("input tensors should be one type");if(o.dims.length!==i)throw new Error("input tensors should have the same shape");o.dims.forEach((p,h)=>{if(h!==t&&p!==s.dims[h])throw new Error("non concat dimensions must match")})}})},Ai=(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; }`,pu=(e,t)=>{let r=e.length,s=[];for(let n=0;n{let n=De.size(r),i=new Array(e.length),o=new Array(e.length),d=0,p=[],h=[],P=[{type:12,data:n}];for(let B=0;B`uniforms.sizeInConcatAxis${B}`).join(","),L=B=>` ${(()=>{B.registerUniform("outputSize","u32");for(let te=0;te(${O}); ${l} -= sizeInConcatAxis[inputIndex - 1u]; } ${pu(o,x)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:P}),getShaderSource:L}},Ii=(e,t)=>{let r=e.inputs,s=r[0].dims,n=De.normalizeAxis(t.axis,s.length);cu(r,n);let i=s.slice();i[n]=r.reduce((d,p)=>d+(p.dims.length>n?p.dims[n]:0),0);let o=r.filter(d=>De.size(d.dims)>0);e.compute(hu(o,n,i,r[0].dataType),{inputs:o})},mu=e=>qt({axis:e.axis})}),Vs,sn,nn,vo,on=g(()=>{Ot(),Ut(),Vs=(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}`)}},sn=(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"})},vo=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:s}}else if(t==="Clip"){let[r,s]=(e==null?void 0:e.activation_params)||[ms,Ps];return{activation:t,clipMax:s,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),rs,To,xo=g(()=>{rs=(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.`)}},To=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),Fi,fu=g(()=>{Fi=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)); } `}),_u,Eo,Po,Oi,gu,Co,wu,$o,So=g(()=>{Ot(),Ut(),er(),on(),xo(),_u=(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":""}); `,Eo=(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];"} }`,Po=(e,t,r="f32",s,n=!1,i=32,o=!1,d=32)=>{let p=t[1]*e[1],h=t[0]*e[0],P=n?p:i,x=n?i:p,l=P/t[0],O=i/t[1];if(!((n&&l===4&&e[1]===4||!n&&(l===3||l===4))&&P%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${l} must be 3 or 4. tileAWidth ${P} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${P/l}>, ${x}>; var mm_Bsub: array, ${h/e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${l}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${o?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${p}; let num_tiles = ${o?`${Math.ceil(d/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${O}; 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; ${_u(n,s)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${O}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Eo(n,l)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Oi=(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":""}); `,gu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Co=(e,t,r="f32",s,n=!1,i=32,o=!1,d=32,p=!1)=>{let h=e[1]*t[1],P=e[0]*t[0],x=n?h:i,l=n?i:h;if(!(l%t[1]===0&&x%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${x} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let O=l/t[1],L=x/t[0],B=i/t[1],te=p?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${h}; let globalColStart = i32(workgroupId.x) * ${P}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${x}; inputCol = inputCol + ${t[0]}) { ${Oi(n,s)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${P}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${s?", 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 = ${n?`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) * ${O}; let tileColA = i32(localId.x) * ${L}; let tileRowB = i32(localId.y) * ${B}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${O}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${L}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Oi(n,s)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${B}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${s?", 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) { ${gu(n)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${l}>; var mm_Bsub : array, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${i}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${o?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${o?`${Math.ceil(d/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${o?`i32(globalId.z) * ${d}`:"0"}; var acc : array, rowPerThread>; ${te} } `},wu=(e,t,r,s,n,i=!1)=>{let[o,d,p]=n,[h,P,x,l]=s,O=Vn(o,p),L=Vn(d,p),B=or(s[0].type.tensor),te=()=>{let H=P.rank,pe=h.rank,ae=`var aIndices: ${P.type.indices};`;for(let ge=H-2-1,Ne=pe-1;ge>=0;ge--,Ne--)ae+=` aIndices[${ge}] = ${pe>1?`batchIndices[${Ne}]`:"batchIndices"};`;return O.forEach(ge=>{ae+=` aIndices[${ge}] = 0;`}),ae+=` aIndices[${H-2}] = u32(row); aIndices[${H-1}] = u32(colIn);`,ae},se=()=>{let H=x.rank,pe=h.rank,ae=`var bIndices: ${x.type.indices};`;for(let ge=H-2-1,Ne=pe-1;ge>=0;ge--,Ne--)ae+=` bIndices[${ge}] = ${pe>1?`batchIndices[${Ne}]`:"batchIndices"};`;return L.forEach(ge=>{ae+=` bIndices[${ge}] = 0;`}),ae+=` bIndices[${H-2}] = u32(row); bIndices[${H-1}] = u32(colIn);`,ae};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${rs(e,B)} { var value = ${rs(e,B)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${te()} value = ${P.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${rs(e,B)} { var value = ${rs(e,B)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${se()} value = ${x.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${rs(e,B)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${i?"bias[colIn]":`${rs(e,B)}(bias[row])`};`:""} ${r} ${l.setByIndices("vec3(coords)","value")} } } `},$o=(e,t,r,s,n=!1,i)=>{let o=e[0].dims,d=e[1].dims,p=o.slice(0,-2),h=d.slice(0,-2),P=s?s.slice(0,-2):r.slice(0,-2),x=De.size(P),l=o[o.length-2],O=o[o.length-1],L=d[d.length-1],B=O%4===0&&L%4===0,te=l<=8?[4,1,1]:[4,4,1],se=[8,8,1],H=[Math.ceil(L/se[0]/te[0]),Math.ceil(l/se[1]/te[1]),Math.ceil(x/se[2]/te[2])],pe=B?4:1,ae=[...p,l,O/pe],ge=ae.length,Ne=[...h,O,L/pe],Fe=Ne.length,rt=[x,l,L/pe],vt=[{type:6,data:l},{type:6,data:L},{type:6,data:O}];sn(t,vt),vt.push(...wt(P,ae,Ne));let $t=["rank","rank"],Yt=e.length>2;Yt&&(vt.push(...wt(e[2].dims)),$t.push("rank")),vt.push(...wt(rt));let rr=zt=>{let Tr=P.length,Ir=Yo("batchDims",e[0].dataType,Tr,1),nr=or(e[0].dataType),Er=Ze("a",e[0].dataType,ge,pe),Ft=Ze("b",e[1].dataType,Fe,pe),Nt=kt("result",e[0].dataType,rt.length,pe),hr=[Er,Ft];if(Yt){let Hr=n?pe:1;hr.push(Ze("bias",e[2].dataType,e[2].dims.length,Hr))}let Ve=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];nn(t,Ve);let ct=or(Nt.type.tensor),Vt=Vs(t,Nt.type.value,ct),xr=wu(pe,Yt,Vt,[Ir,Er,Ft,Nt],[p,h,P],n);return` ${zt.registerUniforms(Ve).registerInternalVariables(Ir).declareVariables(...hr,Nt)} ${xr} ${B?Po(te,se,nr,Ir):Co(te,se,nr,Ir)} `};return{name:"MatMul",shaderCache:{hint:`${te};${t.activation};${B};${n}`,inputDependencies:$t},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:H[0],y:H[1],z:H[2]},programUniforms:vt}),getShaderSource:rr}}}),yu,Di,kc=g(()=>{Ot(),xe(),er(),on(),xo(),fu(),So(),yu=(e,t,r,s,n=!1,i,o=4,d=4,p=4,h="f32")=>{let P=vt=>{switch(vt){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 ${vt} is not supported.`)}},x=vt=>{switch(vt){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 ${vt} is not supported.`)}},l=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,O=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,L=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",B=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",te=e?"row":"col",se=e?"col":"row",H=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${te} / outWidth; let outCol = ${te} % outWidth; let WRow = ${se} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${se} / 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 = ${se} % inChannels; var resData = ${rs(o,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 < ${L} && xCol >= 0 && xCol < ${B}) { ${l} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${P(o)} } return resData;`,pe=e?t&&s?` let col = colIn * ${o}; ${H}`:` let col = colIn * ${o}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${H} } return ${rs(o,h)}(0.0);`:s&&r?` let col = colIn * ${o}; ${H}`:` let col = colIn * ${o}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${H} } return ${rs(o,h)}(0.0);`,ae=`${x(d)}`,ge=rs(p,h),Ne=rs(e?o:d,h),Fe=rs(e?d:o,h),rt=Vs(i,ge,h);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ne} { ${e?pe:ae} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Fe} { ${e?ae:pe} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ge}) { 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])"}; ${O} ${To(n)} ${rt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Di=(e,t,r,s,n,i,o,d,p)=>{let h=t.format==="NHWC",P=h?e[0].dims[3]:e[0].dims[1],x=r[0],l=h?r[2]:r[3],O=h?r[1]:r[2],L=h?r[3]:r[1],B=h&&(P%4===0||P%3===0)&&L%4===0,te=h?L:l*O,se=h?l*O:L,H=[8,8,1],pe=s<=8?[4,1,1]:[4,4,1],ae=[Math.ceil(te/H[0]/pe[0]),Math.ceil(se/H[1]/pe[1]),Math.ceil(x/H[2]/pe[2])];_r("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${ae}`);let ge=B?h&&P%4!==0?3:4:1,Ne=H[1]*pe[1],Fe=H[0]*pe[0],rt=Math.max(H[0]*ge,H[1]),vt=s%Ne===0,$t=n%Fe===0,Yt=i%rt===0,rr=B?[ge,4,4]:[1,1,1],zt=[{type:6,data:s},{type:6,data:n},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];sn(t,zt),zt.push(...wt(e[0].dims,e[1].dims));let Tr=["rank","rank"];o&&(zt.push(...wt(e[2].dims)),Tr.push("rank")),zt.push(...wt(r));let Ir=nr=>{let Er=[{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,Er);let Ft=B?4:1,Nt=or(e[0].dataType),hr=` fn setOutputAtIndex(flatIndex : i32, value : ${B?`vec4<${Nt}>`:Nt}) { result[flatIndex] = ${B?`vec4<${Nt}>`:Nt}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${B?`vec4<${Nt}>`:Nt}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${B?"/ 4":""}, value); }`,Ve=Ze("x",e[0].dataType,e[0].dims.length,ge===3?1:ge),ct=Ze("w",e[1].dataType,e[1].dims.length,Ft),Vt=[Ve,ct],xr=kt("result",e[0].dataType,r.length,Ft);if(o){let Hr=Ze("bias",e[2].dataType,e[2].dims.length,Ft);Vt.push(Hr),hr+=` fn getBiasByOutputCoords(coords : vec4) -> ${B?`vec4<${Nt}>`:Nt} { return bias[coords.${h?"w":"y"}${B?"/ 4":""}]; }`}return` ${Fi("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 }; ${nr.registerUniforms(Er).declareVariables(...Vt,xr)} ${hr} ${yu(h,vt,$t,Yt,o,t,rr[0],rr[1],rr[2],Nt)} ${B?Po(pe,H,Nt,void 0,!h,rt):Co(pe,H,Nt,void 0,!h,rt,!1,void 0,d)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${ge};${B};${vt};${$t};${Yt};${Ne};${Fe};${rt}`,inputDependencies:Tr},getRunData:()=>({outputs:[{dims:p?p(r):r,dataType:e[0].dataType}],dispatchGroup:{x:ae[0],y:ae[1],z:ae[2]},programUniforms:zt}),getShaderSource:Ir}}}),Mu,Li,Kn,zi,Bi,bu,Ri,vu,Ac=g(()=>{Ot(),xe(),Ut(),er(),on(),xo(),Mu=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Kn=(e,t)=>t<=1?e:e+(e-1)*(t-1),zi=(e,t,r,s=1)=>{let n=Kn(t,s);return Math.floor((e[0]*(r-1)-r+n)/2)},Bi=(e,t,r,s,n)=>{n==null&&(n=zi(e,t[0],s[0]));let i=[0,0,0,r];for(let o=0;o<3;o++)e[o]+2*n>=t[o]&&(i[o]=Math.trunc((e[o]-t[o]+2*n)/s[o]+1));return i},bu=(e,t,r,s,n,i,o,d,p,h)=>{let P,x,l,O;if(e==="VALID"&&(e=0),typeof e=="number"){P={top:e,bottom:e,left:e,right:e,front:e,back:e};let L=Bi([t,r,s,1],[d,p,h],1,[n,i,o],e);x=L[0],l=L[1],O=L[2]}else if(Array.isArray(e)){if(!e.every((B,te,se)=>B===se[0]))throw Error(`Unsupported padding parameter: ${e}`);P={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let L=Bi([t,r,s,1],[d,p,h],1,[n,i,o],e[0]);x=L[0],l=L[1],O=L[2]}else if(e==="SAME_UPPER"){x=Math.ceil(t/n),l=Math.ceil(r/i),O=Math.ceil(s/o);let L=(x-1)*n+d-t,B=(l-1)*i+p-r,te=(O-1)*o+h-s,se=Math.floor(L/2),H=L-se,pe=Math.floor(B/2),ae=B-pe,ge=Math.floor(te/2),Ne=te-ge;P={top:pe,bottom:ae,left:ge,right:Ne,front:se,back:H}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:P,outDepth:x,outHeight:l,outWidth:O}},Ri=(e,t,r,s,n,i=!1,o="channelsLast")=>{let d,p,h,P,x;if(o==="channelsLast")[d,p,h,P,x]=e;else if(o==="channelsFirst")[d,x,p,h,P]=e;else throw new Error(`Unknown dataFormat ${o}`);let[l,,O,L,B]=t,[te,se,H]=Li(r),[pe,ae,ge]=Li(s),Ne=Kn(O,pe),Fe=Kn(L,ae),rt=Kn(B,ge),{padInfo:vt,outDepth:$t,outHeight:Yt,outWidth:rr}=bu(n,p,h,P,te,se,H,Ne,Fe,rt),zt=i?l*x:l,Tr=[0,0,0,0,0];return o==="channelsFirst"?Tr=[d,zt,$t,Yt,rr]:o==="channelsLast"&&(Tr=[d,$t,Yt,rr,zt]),{batchSize:d,dataFormat:o,inDepth:p,inHeight:h,inWidth:P,inChannels:x,outDepth:$t,outHeight:Yt,outWidth:rr,outChannels:zt,padInfo:vt,strideDepth:te,strideHeight:se,strideWidth:H,filterDepth:O,filterHeight:L,filterWidth:B,effectiveFilterDepth:Ne,effectiveFilterHeight:Fe,effectiveFilterWidth:rt,dilationDepth:pe,dilationHeight:ae,dilationWidth:ge,inShape:e,outShape:Tr,filterShape:t}},vu=(e,t,r,s,n,i)=>{let o=i==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let d=[64,1,1],p={x:r.map((te,se)=>se)},h=[Math.ceil(Mu(p.x.map(te=>r[te]))/d[0]),1,1];_r("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let P=1,x=De.size(r),l=[{type:12,data:x},{type:12,data:s},{type:12,data:n},{type:12,data:t.strides},{type:12,data:t.dilations}];sn(t,l),l.push(...wt(e[0].dims,e[1].dims));let O=["rank","rank"],L=e.length===3;L&&(l.push(...wt(e[2].dims)),O.push("rank")),l.push(...wt(r));let B=te=>{let se=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];nn(t,se);let H=1,pe=or(e[0].dataType),ae=Ze("x",e[0].dataType,e[0].dims.length,P),ge=Ze("W",e[1].dataType,e[1].dims.length,H),Ne=[ae,ge],Fe=kt("result",e[0].dataType,r.length,H),rt="";if(L){let Yt=Ze("bias",e[2].dataType,e[2].dims.length,H);Ne.push(Yt),rt+=` fn getBiasByOutputCoords(coords : array) -> ${pe} { return bias[${o?St("coords",4,5):St("coords",1,5)}]; }`}let vt=rs(P,pe),$t=Vs(t,vt,pe);return` ${rt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ae.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ge.getByIndices("aIndices")}; } ${te.registerUniforms(se).declareVariables(...Ne,Fe)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${Fe.offsetToIndices("global_idx")}; let batch = ${St("coords",0,ae.rank)}; let d2 = ${o?St("coords",ae.rank-1,ae.rank):St("coords",1,ae.rank)}; let xFRCCorner = vec3(${o?St("coords",1,ae.rank):St("coords",2,ae.rank)}, ${o?St("coords",2,ae.rank):St("coords",3,ae.rank)}, ${o?St("coords",3,ae.rank):St("coords",4,ae.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${o?St("uniforms.x_shape",1,ae.rank):St("uniforms.x_shape",2,ae.rank)}; let xShapeZ = ${o?St("uniforms.x_shape",2,ae.rank):St("uniforms.x_shape",3,ae.rank)}; let xShapeW = ${o?St("uniforms.x_shape",3,ae.rank):St("uniforms.x_shape",4,ae.rank)}; let xShapeU = ${o?St("uniforms.x_shape",4,ae.rank):St("uniforms.x_shape",1,ae.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) { ${o?`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) { ${o?`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) { ${o?`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) { ${o?`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); } } } } ${L?"value = value + getBiasByOutputCoords(coords)":""}; ${$t} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${P};${L}`,inputDependencies:O},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:l}),getShaderSource:B}}}),ji,Tu,Ic=g(()=>{Ot(),Ut(),er(),on(),ji=(e,t,r,s)=>{let n=e.length>2,i=n?"value += b[output_channel];":"",o=e[0].dims,d=e[1].dims,p=t.format==="NHWC",h=p?r[3]:r[1],P=h/t.group,x=p&&P>=4?Zt(h):1,l=De.size(r)/x,O=[{type:12,data:l},{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:P}];sn(t,O),O.push(...wt(o,[d[0],d[1],d[2],d[3]/x]));let L=n?["rank","rank","rank"]:["rank","rank"];O.push(...wt([r[0],r[1],r[2],r[3]/x]));let B=te=>{let se=kt("output",e[0].dataType,r.length,x),H=or(se.type.tensor),pe=Vs(t,se.type.value,H),ae=Ze("x",e[0].dataType,o.length),ge=Ze("w",e[1].dataType,d.length,x),Ne=[ae,ge];n&&Ne.push(Ze("b",e[2].dataType,e[2].dims,x));let Fe=[{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,Fe);let rt=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 = ${ae.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${ge.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 = ${ae.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${ge.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${te.registerUniforms(Fe).declareVariables(...Ne,se)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${se.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 * ${x} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; var value: ${se.type.value} = ${se.type.value}(0); ${rt} ${i} ${pe} ${se.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${x}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:s?s(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:O}),getShaderSource:B}},Tu=(e,t,r,s)=>{let n=e.length>2,i=Zt(r[3]),o=Zt(r[2]),d=De.size(r)/i/o,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],P=[r[0],r[1],r[2],r[3]/i],x=[{type:12,data:d},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];sn(t,x),x.push(...wt(p,h,P));let l=(o-1)*t.strides[1]+h[1],O=L=>{let B=kt("output",e[0].dataType,P.length,i),te=or(B.type.tensor),se=Vs(t,B.type.value,te),H=Ze("x",e[0].dataType,p.length,i),pe=Ze("w",e[1].dataType,h.length,i),ae=[H,pe];n&&ae.push(Ze("b",e[2].dataType,e[2].dims,i));let ge=n?"value += b[output_channel];":"",Ne=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return nn(t,Ne),` ${L.registerUniforms(Ne).declareVariables(...ae,B)} ${L.mainStart()} ${L.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] / ${o}u; let col = (index1 % width1) * ${o}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<${H.type.value}, ${l}>; var values: array<${B.type.value}, ${o}>; 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 < ${l}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${H.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${H.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { let w_val = ${pe.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${o}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${o}u; i++) { var value = values[i]; ${ge} ${se} ${B.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${o};${l};${h[0]};${h[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:x}),getShaderSource:O}}}),ko,xu,Eu,Pu=g(()=>{Ot(),Ut(),So(),er(),on(),ko=(e,t,r,s,n=!1,i)=>{let o=e[0].dims,d=e[1].dims,p=o[o.length-2],h=d[d.length-1],P=o[o.length-1],x=Zt(h),l=Zt(P),O=Zt(p),L=De.size(r)/x/O,B=e.length>2,te=s?s.slice(0,-2):r.slice(0,-2),se=[De.size(te),p,h],H=[{type:12,data:L},{type:12,data:p},{type:12,data:h},{type:12,data:P}];sn(t,H),H.push(...wt(te,o,d)),B&&H.push(...wt(e[2].dims)),H.push(...wt(se));let pe=ae=>{let ge=Yo("batch_dims",e[0].dataType,te.length),Ne=Ze("a",e[0].dataType,o.length,l),Fe=Ze("b",e[1].dataType,d.length,x),rt=kt("output",e[0].dataType,se.length,x),vt=or(rt.type.tensor),$t=Vs(t,rt.type.value,vt),Yt=[Ne,Fe],rr="";if(B){let hr=n?x:1;Yt.push(Ze("bias",e[2].dataType,e[2].dims.length,hr)),rr=`${n?`value += bias[col / ${hr}];`:`value += ${rt.type.value}(bias[row + i]);`}`}let zt=o.slice(0,-2),Tr=d.slice(0,-2),Ir=Vn(zt,te),nr=Vn(Tr,te),Er=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];nn(t,Er);let Ft=(hr,Ve)=>{let ct=hr.rank,Vt=hr.name;if(ct===2)return`var ${Vt}_indices = ${hr.type.indices}(0u, 0u);`;let xr=ge.rank,Hr=`var ${Vt}_indices: ${hr.type.indices};`;for(let Qr=ct-2-1,ro=xr-1;Qr>=0;Qr--,ro--)Hr+=` ${Vt}_indices[${Qr}] = ${xr>1?`batch_indices[${ro}]`:"batch_indices"};`;return Ve.forEach(Qr=>{Hr+=` ${Vt}_indices[${Qr}] = 0;`}),Hr+=`${Vt}_indices[${ct-2}] = 0u; ${Vt}_indices[${ct-1}] = 0u;`,Hr},Nt=()=>{let hr=`var a_data: ${Ne.type.value};`;for(let Ve=0;Ve; for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { ${Nt()} } for (var i = 0u; i < ${O}u; i++) { var value = values[i]; ${rr} ${$t} let cur_indices = ${rt.type.indices}(batch, row + i, col); let offset = ${rt.indicesToOffset("cur_indices")}; ${rt.setByOffset(`offset / ${x}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${x};${l};${O};${n}`,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(L/64)},programUniforms:H}),getShaderSource:pe}},xu=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.")},Eu=e=>{xu(e.inputs);let t=Gr.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],s=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&s<8?e.compute(ko(e.inputs,{activation:""},t)):e.compute($o(e.inputs,{activation:""},t))}}),Cu,Ao,$u,Hn,Ni,Ui,Vi,Su,Wi,pn=g(()=>{Ut(),kc(),Ac(),So(),Ic(),on(),Pu(),Us(),Cu=(e,t,r,s,n,i)=>{let o=e[0],d=e.slice(i?1:2,i?3:4),p=d.length,h=t[0],P=t.slice(2).map((l,O)=>l+(l-1)*(r[O]-1)),x=d.map((l,O)=>l+s[O]+s[O+p]).map((l,O)=>Math.floor((l-P[O]+n[O])/n[O]));return x.splice(0,0,o),x.splice(i?3:1,0,h),x},Ao=[2,3,1,0],$u=(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],s=e[1].dims[1]*t.group;if(r!==s)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 n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Hn=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=vo(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,i=e.group,o=e.kernel_shape,d=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:s,format:r,dilations:n,group:i,kernelShape:o,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Ui=(e,t,r,s)=>{let n=r.format==="NHWC",i=Cu(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,n);if(r.group!==1){let Ne=[t[0]];if(n){let Fe=e.kernelCustomData.wT??e.compute(fs(t[1],Ao),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Fe),Ne.push(Fe)}else Ne.push(t[1]);t.length===3&&Ne.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(Tu(Ne,r,i,s),{inputs:Ne}):e.compute(ji(Ne,r,i,s),{inputs:Ne});return}let o=t.length===3,d=t[0].dims[n?1:2],p=t[0].dims[n?2:3],h=t[0].dims[n?3:1],P=t[1].dims[2],x=t[1].dims[3],l=i[n?1:2],O=i[n?2:3],L=i[n?3:1],B=n&&P===d&&x===p&&r.pads[0]===0&&r.pads[1]===0;if(B||P===1&&x===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 Ne=i[0],Fe,rt,vt,$t=[];if(n){let zt=e.kernelCustomData.wT??e.compute(fs(t[1],Ao),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=zt),B){let Tr=d*p*h;Fe=t[0].reshape([1,Ne,Tr]),rt=zt.reshape([1,Tr,L]),vt=[1,Ne,L]}else Fe=t[0].reshape([Ne,d*p,h]),rt=zt.reshape([1,h,L]),vt=[Ne,l*O,L];$t.push(Fe),$t.push(rt)}else Fe=t[0].reshape([Ne,h,d*p]),rt=t[1].reshape([1,L,h]),vt=[Ne,L,l*O],$t.push(rt),$t.push(Fe);o&&$t.push(t[2]);let Yt=vt[2],rr=$t[0].dims[$t[0].dims.length-1];Yt<8&&rr<8?e.compute(ko($t,r,i,vt,n,s),{inputs:$t}):e.compute($o($t,r,i,vt,n,s),{inputs:$t});return}let te=!0,se=e.kernelCustomData.wT??e.compute(fs(t[1],Ao),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se);let H=[t[0],se];o&&H.push(t[2]);let pe=n?l*O:L,ae=n?L:l*O,ge=P*x*h;e.compute(Di(H,r,i,pe,ae,ge,o,te,s),{inputs:H})},Vi=(e,t)=>{let r=t.format==="NHWC",s=[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&&s.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),o=[1].concat(t.dilations),d=[1].concat(t.kernelShape),p=Hn({...t,pads:n,strides:i,dilations:o,kernelShape:d},s);Ui(e,s,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Su=(e,t,r)=>{let s=r.format==="NHWC"?"channelsLast":"channelsFirst",n=Hn(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,o=Ri(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,s);e.compute(vu(t,n,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},Wi=(e,t)=>{if($u(e.inputs,t),e.inputs[0].dims.length===3)Vi(e,t);else if(e.inputs[0].dims.length===5)Su(e,e.inputs,t);else{let r=Hn(t,e.inputs);Ui(e,e.inputs,r)}}}),ku,Au,Fc=g(()=>{Ot(),xe(),er(),on(),xo(),fu(),So(),ku=(e,t=!1,r,s,n=4)=>{let i=te=>{switch(te){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${s}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${te} is not supported.`)}},o=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,d=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",P=e?"row":"col",x=e?"col":"row",l=` let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${P} / outWidth; let outCol = ${P} % outWidth; let WRow = ${x} / (uniforms.filter_dims[1] * inChannels); let WCol = ${x} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${p}) || fract(xR) > 0.0) { return ${s}(0.0); } if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) { return ${s}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${x} % inChannels; ${o} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${n}];`,O=e?` let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${l} } return ${s}(0.0);`:` let col = colIn * ${n}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${l} } return ${s}(0.0);`,L=` let col = colIn * ${n}; let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${i(n)} } return ${s}(0.0); `,B=Vs(r,s);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?O:L} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${s} { ${e?L:O} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${s}) { let col = colIn * ${n}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${d} ${To(t)} ${B} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${n}] = value; } }`},Au=(e,t,r,s,n,i,o,d)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],P=r[0],x=p?r[2]:r[3],l=p?r[1]:r[2],O=p?r[3]:r[1],L=p&&h%4===0&&h%3&&O%4===0,B=p?O:x*l,te=p?x*l:O,se=[8,8,1],H=s<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(B/se[0]/H[0]),Math.ceil(te/se[1]/H[1]),Math.ceil(P/se[2]/H[2])];_r("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${pe}`);let ae=L?4:1,ge=Math.max(se[0]*ae,se[1]),Ne=L?4:1,Fe=[t.kernelShape[p?1:2],t.kernelShape[p?2:3]],rt=[Fe[0]+(t.dilations[0]<=1?0:(Fe[0]-1)*(t.dilations[0]-1)),Fe[1]+(t.dilations[1]<=1?0:(Fe[1]-1)*(t.dilations[1]-1))],vt=[rt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),rt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],$t=[{type:6,data:s},{type:6,data:n},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Fe},{type:6,data:vt}];sn(t,$t),$t.push(...wt(e[0].dims,e[1].dims));let Yt=["rank","rank"];o&&($t.push(...wt(e[2].dims)),Yt.push("rank")),$t.push(...wt(r));let rr=zt=>{let Tr=Ze("x",e[0].dataType,e[0].dims.length,Ne),Ir=Ze("w",e[1].dataType,e[1].dims.length,1),nr=kt("result",e[0].dataType,r.length,Ne),Er=[Tr,Ir],Ft="";if(o){let Ve=Ze("bias",e[2].dataType,e[2].dims.length,Ne);Er.push(Ve),Ft+=` fn getBiasByOutputCoords(coords : vec4) -> ${Ve.type.value} { return bias[coords.${p?"w":"y"}${L?"/ 4":""}]; }`}let Nt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:Fe.length},{name:"pads",type:"i32",length:vt.length}];nn(t,Nt);let hr=or(e[0].dataType,1);if(hr!=="f16"&&hr!=="f32")throw new Error(`elemType ${hr} is not supported.`);return` ${Fi("uniforms.result_strides")} ${zt.registerUniforms(Nt).declareVariables(...Er,nr)}; ${Ft} ${ku(p,o,t,Tr.type.value,ae)} ${L?Po(H,se,hr,void 0,!p,ge):Co(H,se,hr,void 0,!p,ge,!1,void 0,d)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${H};${se};${L}`,inputDependencies:Yt},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:$t}),getShaderSource:rr}}}),Iu,Io,Oc=g(()=>{Ot(),xe(),Ut(),er(),Iu=(e,t,r,s,n,i=!1,o,d,p=!1)=>{let h=p?1:2,P=p?2:3,x=p?3:1,l=i?2:1,O=` fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${o}>`:o}) { result[flatIndex] = ${i?`vec4<${o}>`:o}(value); }`;s&&(O+=` fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${o}>`:o} { return bias[coords.${p?"w":"y"}${i?"/ 4":""}]; }`);let L=i?4:1,B=Ze("W",t[1].dataType,t[1].dims.length,L),te=Ze("Dy",t[0].dataType,t[0].dims.length,L),se=[te,B];s&&se.push(Ze("bias",t[2].dataType,[r[x]].length,L));let H=kt("result",t[0].dataType,r.length,L),pe=`{ let batch: u32 = ${n?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${n?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${n?"global_id.y":"workgroup_id.y"} * ${l}; let d1: u32 = ${n?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${l}>; for (var i = 0; i < ${l}; i++) { dotProd[i] = vec4<${o}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${o}(dyCorner.x) + ${o}(wR)) / ${o}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${o}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${o}(dyCorner.y) + ${o}(wC)) / ${o}(uniforms.strides.y); let dyC2 = (${o}(dyCorner.y) + 1.0 + ${o}(wC)) / ${o}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${o}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${o}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${te.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${te.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${x}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${te.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${B.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${te.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${l}; i = i + 1) { let value = dotProd[i] + ${s?"bias[c+i]":`vec4<${o}>(0.0)`}; ${H.set("batch","r","c + i","d1","value")}; } }`,ae=` let outputIndices = ${H.offsetToIndices("global_idx")}; let batch = ${H.indicesGet("outputIndices",0)}; let d1 = ${H.indicesGet("outputIndices",x)}; let r = ${H.indicesGet("outputIndices",h)}; let c = ${H.indicesGet("outputIndices",P)}; 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 = ${o}(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 = (${o}(dyRCorner) + ${o}(wR)) / ${o}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${o}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${o}(dyCCorner) + ${o}(wC)) / ${o}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${o}(uniforms.Dy_shape[${P}]) || 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 = ${p?te.get("batch","idyR","idyC","inputChannel"):te.get("batch","inputChannel","idyR","idyC")}; let wValue = ${B.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${s?"bias[d1]":`${o}(0.0)`}; ${H.setByOffset("global_idx","value")}; `;return` ${e.registerUniforms(d).declareVariables(...se,H)} ${O} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${i?pe:ae}}`},Io=(e,t,r)=>{let s=e.length>2,n=t.outputShape,i=De.size(n),o=[Math.ceil(i/64),1,1];_r("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${o}`);let d=t.format==="NHWC",p=["rank","rank"],h=[t.strides[0],t.strides[1]],P=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],x=[t.dilations[0],t.dilations[1]],l=[P[0]+(t.dilations[0]<=1?0:(t.kernelShape[d?1:2]-1)*(t.dilations[0]-1)),P[1]+(t.dilations[1]<=1?0:(t.kernelShape[d?2:3]-1)*(t.dilations[1]-1))],O=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],L=!1,B=t.group,te=e[1].dims,se=te[0]/B,H=te[1],pe=[{type:12,data:i},{type:12,data:h},{type:12,data:P},{type:12,data:x},{type:12,data:l},{type:6,data:O},{type:12,data:se},{type:12,data:H},...wt(e[0].dims,e[1].dims)];s&&(pe.push(...wt(e[2].dims)),p.push("rank")),pe.push(...wt(n));let ae=o[1]===1&&o[2]===1,ge=Ne=>{let Fe=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:P.length},{name:"dilations",type:"u32",length:P.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:O.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],rt=or(e[0].dataType);return`${Iu(Ne,e,n,s,ae,L,rt,Fe,d)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:p},getRunData:()=>({dispatchGroup:{x:o[0],y:o[1],z:o[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],programUniforms:pe}),getShaderSource:ge}}}),Fu,Ou,Du,qn,Lu,zu,Bu,Qn,Ru,ju,Dc=g(()=>{Fc(),Oc(),on(),Us(),Fu=(e,t,r,s,n,i)=>(e-1)*t+r+(s-1)*n+1-i,Ou=(e,t,r,s,n)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[s]=i,r[n]=e-i):t==="SAME_LOWER"&&(r[s]=e-i,r[n]=i)},Du=(e,t,r,s,n,i,o,d,p,h)=>{let P=e.length-2,x=h.length===0;p.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((x,l)=>x*l,1)===0){r.length=0;for(let x=2;xx+l,0)===0){let x=t[0].dims.length-2;p=new Array(x).fill(1)}let h=e.strides.slice();if(h.reduce((x,l)=>x+l,0)===0){let x=t[0].dims.length-2;h=new Array(x).fill(1)}Du(d,r,p,e.autoPad,e.group,n,h,s,o,i);let P=Object.assign({},e);return Object.assign(P,{kernelShape:r,pads:n,outputPadding:o,outputShape:i,dilations:p,strides:h}),P},Lu=e=>{let t=vo(e),r=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,i=e.group,o=e.kernelShape,d=e.pads,p=e.strides,h=e.wIsConst(),P=e.outputPadding,x=e.outputShape;return{autoPad:s,format:r,dilations:n,group:i,kernelShape:o,outputPadding:P,outputShape:x,pads:d,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},zu=(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],s=e[1].dims[0];if(r!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((o,d)=>o+d,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((o,d)=>o+d,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((o,d)=>o+d,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((o,d)=>o+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")},Bu=[2,3,1,0],Qn=(e,t,r)=>{let s=qn(r,t),n=r.format==="NHWC",i=s.outputShape,o=i[n?3:1],d=t[0].dims[n?3:1];if(s.group!==1||o===1&&d===1){e.compute(Io(t,s));return}let p=i[n?1:2],h=i[n?2:3],P=t[1].dims[2],x=t[1].dims[3],l=n?p*h:o,O=n?o:p*h,L=P*x*d,B=!0,te=e.kernelCustomData.wT??e.compute(fs(t[1],Bu),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=te);let se=[t[0],te],H=t.length===3;H&&(!n&&t[2].dims.length===1?se.push(t[2].reshape([t[2].dims[0],1,1])):se.push(t[2])),e.compute(Au(se,s,i,l,O,L,H,B),{inputs:se})},Ru=(e,t)=>{let r=t.format==="NHWC",s=[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&&s.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let d=t.pads;d.length===0&&(d=[0,0]),d=[0,d[0],0,d[1]],o=[1].concat(o),i=[1].concat(i),n=[1].concat(n);let p=qn({...t,pads:d,strides:o,dilations:i,kernelShape:n},s);e.compute(Io(s,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},ju=(e,t)=>{zu(e.inputs,t),e.inputs[0].dims.length===3?Ru(e,t):Qn(e,e.inputs,t)}}),Nu,Fo,Uu,Lc=g(()=>{Ot(),Ut(),lr(),er(),Nu=(e,t,r,s)=>{let n=De.size(t),i=t.length,o=Ze("input",e,i),d=kt("output",e,i),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=De.normalizeAxis(p,i),P=x=>{let l=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,O=St("uniforms.input_shape","uniforms.axis",i),L=s.reverse?l+(s.exclusive?" + 1":""):"0",B=s.reverse?O:l+(s.exclusive?"":" + 1");return` ${x.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,d)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${d.offsetToIndices("global_idx")}; var sum = ${d.type.value}(0); let first : i32 = ${L}; let last : i32 = ${B}; for (var i : i32 = first; i < last; i++) { ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${o.getByIndices("inputIndices")}; } ${d.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:12,data:h},...wt(t,t)]}),getShaderSource:P}},Fo=(e,t)=>{let r=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Nu(s,r,n,t),{inputs:[0]})},Uu=e=>{let t=e.exclusive===1,r=e.reverse===1;return qt({exclusive:t,reverse:r})}}),Vu,zc,Wu,Gu,Ku,Xn=g(()=>{Ot(),Ut(),lr(),er(),Vu=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.")},zc=(e,t,r,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r,s,n,i,o,d,p=t.format==="NHWC",h=t.blocksize,P=t.mode==="DCR";p?([r,s,n,i]=e.dims,o=P?[r,s,n,h,h,i/h**2]:[r,s,n,i/h**2,h,h],d=P?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,s,n,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=P?[r,h,h,i/h**2,s,n]:[r,i/h**2,h,h,s,n],d=P?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let x=e.reshape(o),l=x.dims.length,O=e.dataType,L=Ze("a",O,l),B=kt("output",O,l),te=se=>` ${se.registerUniform("output_size","u32").declareVariables(L,B)} ${zc(d,l,L,B)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${B.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${B.setByOffset("global_idx",L.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:se=>{let H=p?[r,s*h,n*h,i/h**2]:[r,i/h**2,s*h,n*h],pe=De.size(H),ae=x.dims,ge=De.sortBasedOnPerm(ae,d);return{outputs:[{dims:H,dataType:se[0].dataType}],dispatchGroup:{x:Math.ceil(pe/64)},programUniforms:[{type:12,data:pe},...wt(ae,ge)]}},getShaderSource:te}},Gu=(e,t)=>{Vu(e.inputs),e.compute(Wu(e.inputs[0],t))},Ku=e=>qt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Oo,Yn,Gi,Hu,qu,Do,Bc,Ki,Qu,Xu,Yu,Rc=g(()=>{Ot(),Ut(),lr(),er(),Oo="[a-zA-Z]|\\.\\.\\.",Yn="("+Oo+")+",Gi="^"+Yn+"$",Hu="("+Yn+",)*"+Yn,qu="^"+Hu+"$",Do=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)}},Bc=class{constructor(e,t){var n;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,s]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(qu)))throw new Error("Invalid LHS term");if(r.split(",").forEach((i,o)=>{let d=e[o].dims.slice();if(!i.match(RegExp(Gi)))throw new Error("Invalid LHS term");let p=this.processTerm(i,!0,d,o);this.lhs.push(p)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([i,o])=>o.count===1||i==="...").map(([i])=>i).join("");else if(!s.match(RegExp(Yn)))throw new Error("Invalid RHS");(n=s.match(RegExp(Oo,"g")))==null||n.forEach(i=>{if(i==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(i);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,t,r){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==t&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(r)}else s={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,s)}processTerm(e,t,r,s=-1){let n=r.length,i=!1,o=[],d=0;if(!e.match(RegExp(Gi))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(Oo,"g")),h=new Do(s);return p==null||p.forEach((P,x)=>{if(P==="..."){if(i)throw new Error("Only one ellipsis is allowed per input term");i=!0;let l=n-p.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(o=r.slice(d,d+l),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let O=0;Oe+"_max",Qu=(e,t,r,s)=>{let n=e.map(h=>h.length).map((h,P)=>Ze(`input${P}`,t,h)),i=De.size(s),o=kt("output",t,s.length),d=[...r.symbolToInfo.keys()].filter(h=>!r.rhs.symbolToIndices.has(h)),p=h=>{let P=[],x="var prod = 1.0;",l="var sum = 0.0;",O="sum += prod;",L=[],B=[],te=[],se=[],H=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((ae,ge)=>{var Ne;if(r.rhs.symbolToIndices.has(ge)){let Fe=(Ne=r.rhs.symbolToIndices.get(ge))==null?void 0:Ne[0];Fe!==void 0&&r.lhs.forEach((rt,vt)=>{if(ae.inputIndices.includes(vt)){let $t=rt.symbolToIndices.get(ge);if($t===void 0)throw new Error("Invalid symbol error");$t.forEach(Yt=>{P.push(`${n[vt].indicesSet(`input${vt}Indices`,Yt,o.indicesGet("outputIndices",Fe))}`)})}})}else r.lhs.forEach((Fe,rt)=>{if(ae.inputIndices.includes(rt)){let vt=Fe.symbolToIndices.get(ge);if(vt===void 0)throw new Error("Invalid symbol error");vt.forEach($t=>{L.push(`${n[rt].indicesSet(`input${rt}Indices`,$t,`${ge}`)}`)}),se.push(`prod *= ${n[rt].getByIndices(`input${rt}Indices`)};`)}}),B.push(`for(var ${ge}: u32 = 0; ${ge} < uniforms.${Ki(ge)}; ${ge}++) {`),te.push("}")});let pe=H?[...P,`let sum = ${n.map((ae,ge)=>ae.getByIndices(`input${ge}Indices`)).join(" * ")};`]:[...P,l,...B,...L,x,...se,O,...te];return` ${h.registerUniforms(d.map(ae=>({name:`${Ki(ae)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,o)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${o.offsetToIndices("global_idx")}; ${n.map((ae,ge)=>`var input${ge}Indices: ${n[ge].type.indices};`).join(` `)} ${pe.join(` `)}; ${o.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=d.filter(x=>r.symbolToInfo.has(x)).map(x=>{var l;return{type:12,data:((l=r.symbolToInfo.get(x))==null?void 0:l.dimValue)||0}});h.push({type:12,data:i});let P=e.map((x,l)=>[...wt(x)]).reduce((x,l)=>x.concat(l),h);return P.push(...wt(s)),{outputs:[{dims:s,dataType:t}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:P}},getShaderSource:p}},Xu=(e,t)=>{let r=new Bc(e.inputs,t.equation),s=r.outputDims,n=e.inputs.map((i,o)=>i.dims);e.compute(Qu(n,e.inputs[0].dataType,r,s))},Yu=e=>{let t=e.equation.replace(/\s+/g,"");return qt({equation:t})}}),Hi,qi,Ju,Qi,Zu,jc=g(()=>{Ot(),Ut(),er(),Hi=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),s=r.length{let r=e.length-t.length,s=[];for(let n=0;ne.length>t.length?qi(e,t):qi(t,e),Qi=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),s=Ju(t,r),n=e[0].dataType,i=n===9?4:1,o=Math.ceil(De.size(s)/i),d=h=>{let P=Ze("input",n,t.length,i),x=kt("output",n,s.length,i),l;if(n===9){let O=(L,B,te="")=>` let outputIndices${B} = ${x.offsetToIndices(`outputOffset + ${B}u`)}; let offset${B} = ${P.broadcastedIndicesToOffset(`outputIndices${B}`,x)}; let index${B} = offset${B} / 4u; let component${B} = offset${B} % 4u; ${L}[${B}] = ${te}(${P.getByOffset(`index${B}`)}[component${B}]); `;l=` let outputOffset = global_idx * ${i}; var data = vec4(0); ${O("data",0,"u32")} ${O("data",1,"u32")} ${O("data",2,"u32")} ${O("data",3,"u32")} ${x.setByOffset("global_idx","data")} }`}else l=` let outputIndices = ${x.offsetToIndices("global_idx")}; let inputOffset = ${P.broadcastedIndicesToOffset("outputIndices",x)}; ${x.setByOffset("global_idx",P.getByOffset("inputOffset"))} }`;return` ${h.registerUniform("vec_size","u32").declareVariables(P,x)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${l}`},p=[{type:12,data:o},...wt(t,s)];return{name:"Expand",shaderCache:{hint:`${s.length}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p})}},Zu=e=>{Hi(e.inputs),e.compute(Qi(e.inputs),{inputs:[0]})}}),Xi,ed,Nc=g(()=>{Ot(),Ut(),er(),Mo(),Xi=e=>{let t=e[0].dataType,r=De.size(e[0].dims),s=De.size(e[1].dims),n=s%4===0,i=o=>{let d=Ze("x",t,[1],4),p=Ze("bias",t,[1],4),h=kt("y",t,[1],4),P=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],x=O=>` let bias${O}_offset: u32 = (global_idx * 4 + ${O}) % uniforms.bias_size; let bias${O} = ${p.getByOffset(`bias${O}_offset / 4`)}[bias${O}_offset % 4];`,l=n?` let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${x(0)}${x(1)}${x(2)}${x(3)} let bias = ${d.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(P).declareVariables(d,p,h)} ${Ti(yr(t))} ${o.mainStart(Rr)} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${d.getByOffset("global_idx")}; ${l} let x_in = x + bias; ${h.setByOffset("global_idx",xi("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(r/Rr/4)}})}},ed=e=>{e.inputs.length<2||De.size(e.inputs[1].dims)===0?Ei(e):e.compute(Xi(e.inputs))}}),Lo,td,rd,sd,Uc=g(()=>{Ot(),Ut(),lr(),er(),Lo=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},td=(e,t)=>{let r=e[0].dims,s=e[1].dims,n=r.length,i=De.normalizeAxis(t.axis,n),o=r.slice(0);o.splice(i,1,...s);let d=r[i],p=e[0].dataType===9?4:1,h=Math.ceil(De.size(o)/p),P=[{type:12,data:h},{type:6,data:d},{type:12,data:i},...wt(e[0].dims,e[1].dims,o)],x=l=>{let O=Ze("data",e[0].dataType,e[0].dims.length,p),L=Ze("inputIndices",e[1].dataType,e[1].dims.length),B=kt("output",e[0].dataType,o.length,p),te=H=>{let pe=s.length,ae=`var indicesIndices${H} = ${L.type.indices}(0);`;for(let ge=0;ge1?`indicesIndices${H}[${ge}]`:`indicesIndices${H}`} = ${o.length>1?`outputIndices${H}[uniforms.axis + ${ge}]`:`outputIndices${H}`};`;ae+=` var idx${H} = ${L.getByIndices(`indicesIndices${H}`)}; if (idx${H} < 0) { idx${H} = idx${H} + uniforms.axisDimLimit; } var dataIndices${H} : ${O.type.indices}; `;for(let ge=0,Ne=0;ge1?`dataIndices${H}[${ge}]`:`dataIndices${H}`} = u32(idx${H});`,Ne+=pe):(ae+=`${n>1?`dataIndices${H}[${ge}]`:`dataIndices${H}`} = ${o.length>1?`outputIndices${H}[${Ne}]`:`outputIndices${H}`};`,Ne++);return ae},se;if(e[0].dataType===9){let H=(pe,ae,ge="")=>` let outputIndices${ae} = ${B.offsetToIndices(`outputOffset + ${ae}u`)}; ${te(ae)}; let offset${ae} = ${O.indicesToOffset(`dataIndices${ae}`)}; let index${ae} = offset${ae} / 4u; let component${ae} = offset${ae} % 4u; ${pe}[${ae}] = ${ge}(${O.getByOffset(`index${ae}`)}[component${ae}]); `;se=` let outputOffset = global_idx * ${p}; var value = vec4(0); ${H("value",0,"u32")} ${H("value",1,"u32")} ${H("value",2,"u32")} ${H("value",3,"u32")} ${B.setByOffset("global_idx","value")} `}else se=` let outputIndices = ${B.offsetToIndices("global_idx")}; ${te("")}; let value = ${O.getByIndices("dataIndices")}; ${B.setByOffset("global_idx","value")}; `;return` ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(O,L,B)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${se} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:P}),getShaderSource:x}},rd=e=>qt({axis:e.axis}),sd=(e,t)=>{let r=e.inputs;Lo(r),e.compute(td(e.inputs,t))}}),Yi,zo,Vc,nd,Wc=g(()=>{Ot(),Ut(),lr(),er(),Yi=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=De.normalizeAxis(t.quantizeAxis,e[0].dims.length),s=t.blockSize,n=e[0],i=e[2],o=e.length===4?e[3]:void 0;if(i.dims.length!==n.dims.length||!n.dims.map((d,p)=>p===r?Math.ceil(d/s)===i.dims[p]:d===i.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(o){if(o.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==i.dims.length||!o.dims.map((d,p)=>d===i.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.")}},zo=(e,t)=>{let r=e[0].dims,s=e[1].dims,n=r.length,i=De.normalizeAxis(t.gatherAxis,n),o=De.normalizeAxis(t.quantizeAxis,n),d=r.slice(0);d.splice(i,1,...s);let p=De.size(d),h=e[2].dataType,P=e[0].dataType===22,x=[{type:12,data:p},{type:12,data:o},{type:12,data:i},{type:12,data:t.blockSize},...wt(...e.map((O,L)=>O.dims),d)],l=O=>{let L=Ze("data",e[0].dataType,e[0].dims.length),B=Ze("inputIndices",e[1].dataType,e[1].dims.length),te=Ze("scales",e[2].dataType,e[2].dims.length),se=e.length>3?Ze("zeroPoint",e[3].dataType,e[3].dims.length):void 0,H=kt("output",h,d.length),pe=[L,B,te];se&&pe.push(se);let ae=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${O.registerUniforms(ae).declareVariables(...pe,H)} ${O.mainStart()} let output_indices = ${H.offsetToIndices("global_idx")}; var indices_indices = ${B.type.indices}(0); ${s.length>1?` for (var i: u32 = 0; i < ${s.length}; i++) { let index = ${H.indicesGet("output_indices","uniforms.gather_axis + i")}; ${B.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${H.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${L.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${H.indicesGet("output_indices","i")}; ${L.indicesSet("data_indices","i","index")}; } var index_from_indices = ${B.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${r[i]}; } ${L.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${d.length}; i++) { let index = ${H.indicesGet("output_indices",`i + ${s.length} - 1`)}; ${L.indicesSet("data_indices","i","index")}; } let data_offset = ${L.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${L.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${P?"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 = ${te.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${te.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${te.getByIndices("scale_indices")}; ${se?` let zero_point_indices = scale_indices; let zero_point_offset = ${se.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${se.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${P?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${yr(h)}(quantized_data - zero_point) * scale; ${H.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((O,L)=>L!==1).map(O=>O.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(O,L)=>"rank")},getRunData:()=>({outputs:[{dims:d,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:x}),getShaderSource:l}},Vc=(e,t)=>{let r=e.inputs;Yi(r,t),e.compute(zo(e.inputs,t))},nd=e=>qt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Ji,od,id,Zi,Gc=g(()=>{Ot(),Ut(),lr(),er(),Ji=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.`)},od=(e,t)=>{let r=e[0].dims,s=e[0].dataType,n=r.length,i=e[1].dims,o=e[1].dataType,d=De.normalizeAxis(t.axis,n),p=r[d],h=i.slice(0),P=De.size(h),x=Ze("input",s,n),l=Ze("indicesInput",o,i.length),O=kt("output",s,h.length),L=[{type:12,data:P},{type:6,data:p},{type:12,data:d}];return L.push(...wt(r,i,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:L}),getShaderSource:B=>` ${B.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(x,l,O)} ${B.mainStart()} ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${O.offsetToIndices("global_idx")}; var idx = ${l.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${x.type.indices}(outputIndices); ${x.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${x.getByIndices("inputIndices")}; ${O.setByOffset("global_idx","value")}; }`}},id=e=>qt({axis:e.axis}),Zi=(e,t)=>{let r=e.inputs;Ji(r),e.compute(od(e.inputs,t))}}),ad,ea,Kc,Hc,ld=g(()=>{Ot(),Ut(),er(),ad=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")},ea=(e,t)=>{let r=e[0].dims.slice(),s=e[1].dims.slice(),[n,i,o]=qr.getShapeOfGemmResult(r,t.transA,s,t.transB,e.length===3?e[2].dims:void 0),d=[n,i];if(!d)throw new Error("Can't use gemm on the given tensors");let p=De.size(d),h=[{type:12,data:p},{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],P=["type","type"];e.length===3&&(h.push(...wt(e[2].dims)),P.push("rank")),h.push(...wt(d));let x=l=>{let O="";t.transA&&t.transB?O="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?O="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?O="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(O="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let L=t.alpha===1?"":"value *= uniforms.alpha;",B=Ze("a",e[0].dataType,e[0].dims),te=Ze("b",e[1].dataType,e[1].dims),se=B.type.value,H=null,pe=[B,te];e.length===3&&(H=Ze("c",e[2].dataType,e[2].dims.length),pe.push(H));let ae=kt("output",e[0].dataType,d.length);pe.push(ae);let ge=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${l.registerUniforms(ge).declareVariables(...pe)} ${l.mainStart()} ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${se}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${O} } ${L} ${H!=null?`let cOffset = ${H.broadcastedIndicesToOffset("vec2(m, n)",ae)}; value += ${se}(uniforms.beta) * ${H.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:x}},Kc=e=>{let t=e.transA,r=e.transB,s=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Hc=(e,t)=>{ad(e.inputs),e.compute(ea(e.inputs,t))}}),ss,ud,dd,Bo,cd,Jn,ta,pd=g(()=>{Ot(),Ut(),lr(),oe(),yo(),er(),Us(),ss=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,ud=(e,t)=>{let r=e[0],s=ss(e,1),n=ss(e,2),i=ss(e,3),o=ss(e,4),d=ss(e,5),p=ss(e,6),h=ss(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 P=r.dims[0],x=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],O=x,L=0,B=0,te=Math.floor(l/t.numHeads);if(p&&h&&De.size(p.dims)&&De.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==P||p.dims[1]!==t.numHeads||p.dims[3]!==te)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==P||h.dims[1]!==t.numHeads||h.dims[3]!==te)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');L=p.dims[2],B=p.dims[2]}else if(p&&De.size(p.dims)||h&&De.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let se;if(s&&De.size(s.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');se=2,O=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==t.numHeads||s.dims[3]!==2||s.dims[4]!==te)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');se=5,O=s.dims[1]}else{if(s.dims[1]!==t.numHeads||s.dims[3]!==te)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');se=0,O=s.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');se=3}if(i&&De.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let H=L+O,pe=0;if(o&&De.size(o.dims)>0){pe=8;let Fe=o.dims;throw Fe.length===1?Fe[0]===P?pe=1:Fe[0]===3*P+2&&(pe=3):Fe.length===2&&Fe[0]===P&&Fe[1]===H&&(pe=5),pe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let ae=!1,ge=l;if(n&&De.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(O!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ge=n.dims[2]}else{if(O!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ge=n.dims[1]*n.dims[3],ae=!0}}let Ne=!1;if(o&&De.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(d&&De.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]!==P||d.dims[1]!==t.numHeads||d.dims[2]!==x||d.dims[3]!==H)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:P,sequenceLength:x,pastSequenceLength:L,kvSequenceLength:O,totalSequenceLength:H,maxSequenceLength:B,inputHiddenSize:0,hiddenSize:l,vHiddenSize:ge,headSize:te,vHeadSize:Math.floor(ge/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:pe,scale:t.scale,broadcastResPosBias:Ne,passPastInKv:ae,qkvFormat:se}},dd=e=>qt({...e}),Bo=qt({perm:[0,2,1,3]}),cd=(e,t,r,s,n,i,o)=>{let d=[s,n,i],p=De.size(d),h=[{type:12,data:p},{type:12,data:o},{type:12,data:i}],P=x=>{let l=kt("qkv_with_bias",t.dataType,d),O=Ze("qkv",t.dataType,d),L=Ze("bias",r.dataType,d),B=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${x.registerUniforms(B).declareVariables(O,L,l)} ${x.mainStart()} ${x.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:P},{inputs:[t,r],outputs:[-1]})[0]},Jn=(e,t,r,s,n,i,o,d)=>{let p=i;if(o&&De.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=cd(e,i,o,t,s,r*n,d),p=p.reshape([t,s,r,n]),r===1||s===1?p:e.compute(fs(p,Bo.perm),{inputs:[p],outputs:[-1]})[0]}else return i.dims.length===3&&(p=i.reshape([t,s,r,n])),r===1||s===1?p:e.compute(fs(p,Bo.perm),{inputs:[p],outputs:[-1]})[0]},ta=(e,t)=>{let r=ud(e.inputs,t),s=e.inputs[0],n=ss(e.inputs,1),i=ss(e.inputs,2),o=ss(e.inputs,3),d=ss(e.inputs,4),p=ss(e.inputs,5),h=ss(e.inputs,6),P=ss(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((n==null?void 0:n.dims.length)===5)throw new Error("Packed KV is not implemented");let x=n&&i&&n.dims.length===4&&i.dims.length===4,l=Jn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,s,o,0);if(x)return An(e,l,n,i,d,void 0,h,P,p,r,t);if(!n||!i)throw new Error("key and value must be provided");let O=Jn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,n,o,r.hiddenSize),L=Jn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,o,2*r.hiddenSize);An(e,l,O,L,d,void 0,h,P,p,r,t)}}),ra,sa,hd,na,md,fd=g(()=>{Ot(),Ut(),er(),ra=e=>Array.from(e.getBigInt64Array(),Number),sa=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(ra(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")},hd=(e,t)=>{let r=[];for(let s=0;s{let r=e[0].dims,s=t??ra(e[1]),n=hd(r,s),i=De.size(n),o=e[0].dataType,d=Ze("input",o,r.length),p=kt("output",o,n.length),h=P=>` const inputShape = ${d.indices(...r)}; ${P.registerUniform("output_size","u32").declareVariables(d,p)} ${P.mainStart()} ${P.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:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...wt(e[0].dims,n)]}),getShaderSource:h}},md=e=>{sa(e.inputs),e.compute(na(e.inputs),{inputs:[0]})}}),_d,oa,gd,wd,ia,aa,qc=g(()=>{Ot(),Ut(),lr(),yo(),er(),pd(),fd(),Us(),_d=(e,t)=>{let r=e[0],s=e[1],n=e[2],i=e[3],o=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let d=!1,p=r.dims[0],h=r.dims[1],P=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],x=h,l=0,O=0,L=Math.floor(P/t.numHeads),B=i&&i.dims.length!==0,te=o&&o.dims.length!==0,se=!0;if(B&&te){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=i.dims[1],O=i.dims[1]}else if(B||te)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let H;if(s){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(r.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');H=2,x=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==t.numHeads||s.dims[3]!==2||s.dims[4]!==L)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');H=5,x=s.dims[1]}else{if(s.dims[1]!==t.numHeads||s.dims[3]!==L)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');H=0,x=s.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');H=3}let pe=0,ae=!1,ge=P;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(x!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ge=n.dims[2]}else{if(x!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');ge=n.dims[1]*n.dims[3],ae=!0}}let Ne=l+x;return{batchSize:p,sequenceLength:h,pastSequenceLength:l,kvSequenceLength:x,totalSequenceLength:Ne,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:P,vHiddenSize:ge,headSize:L,vHeadSize:Math.floor(ge/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:pe,scale:t.scale,broadcastResPosBias:!1,passPastInKv:ae,qkvFormat:H,isPastkvBSNH:se}},oa=(e,t,r,s)=>{let n=[s.batchSize,s.totalSequenceLength,s.kvNumHeads,s.headSize],i=4,o=De.size(n)/i,d=s.totalSequenceLength,p=kt("present_kv",r,n.length,i),h=Ze("new_kv",e.dataType,e.dims.length,i),P=t?Ze("past_kv",t.dataType,t.dims.length,i):void 0,x=Math.ceil(s.headSize/i),l={x:d,y:e.dims[0],z:1},O=t?["rank","rank"]:["rank"],L=[{type:12,data:o},{type:12,data:s.pastSequenceLength},{type:12,data:s.kvSequenceLength},{type:12,data:s.totalSequenceLength}],B=[h];P?(L.push(...wt(e.dims),...wt(t.dims),...wt(n)),B.push(P)):L.push(...wt(e.dims),...wt(n));let te=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],se=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`,H=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`,pe=t?`if (s < past_seqlen) { ${se} } else if (s < past_seqlen + uniforms.new_seqlen) { ${H} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${H} }`,ae=ge=>` ${ge.registerUniforms(te).declareVariables(...B,p)} ${ge.mainStart([x,s.kvNumHeads,1])} ${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${p.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${s.kvNumHeads}u; let H = ${x}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${s.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${pe} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${s.kvNumHeads}${x}${!!t}`,inputDependencies:O},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:l,programUniforms:L}),getShaderSource:ae}},gd=e=>qt({...e}),wd=qt({perm:[0,2,1,3]}),ia=(e,t,r,s,n)=>{let i=t,o=s.kvNumHeads,d=s.nReps;return t.dims.length===3&&s.kvSequenceLength!==0&&(i=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize])),r?i=e.compute(oa(i,r,i.dataType,s),{inputs:[i,r],outputs:[s.isPastkvBSNH?n:-1]})[0]:i=e.compute(oa(i,void 0,i.dataType,s),{inputs:[i],outputs:[s.isPastkvBSNH?n:-1]})[0],d!==1&&(i=e.compute(na([i],[1,1,1,d]),{inputs:[i],outputs:[-1]})[0],i=i.reshape([s.batchSize,s.totalSequenceLength,o*d,s.headSize])),e.compute(fs(i,wd.perm),{inputs:[i],outputs:[-1]})[0]},aa=(e,t)=>{var p;let r=_d(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((p=e.inputs[1])==null?void 0:p.dims.length)===5)throw new Error("Packed KV is not implemented");let s=Jn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),n=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,i=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,o=ia(e,e.inputs[1],n,r,1),d=ia(e,e.inputs[2],i,r,2);An(e,s,o,d,void 0,void 0,void 0,void 0,void 0,r,t)}}),la,ua,yd,Md,vr=g(()=>{Ot(),Ut(),Us(),er(),la=(e,t,r,s,n,i,o,d)=>{let p=Zt(i),h=p===1?"f32":`vec${p}f`,P=p===1?"vec2f":`mat2x${p}f`,x=n*o,l=[n,o,i/p],O=[n,o,2],L=["rank","type","type"],B=[];B.push(...wt(l,O));let te=se=>{let H=Ze("x",t.dataType,3,p),pe=Ze("scale",r.dataType,r.dims),ae=Ze("bias",s.dataType,s.dims),ge=kt("output",1,3,2),Ne=[H,pe,ae,ge],Fe=64;return` var workgroup_shared : array<${P}, ${Fe}>; const workgroup_size = ${Fe}u; ${se.declareVariables(...Ne)} ${se.mainStart(Fe)} 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}(${H.get("batch","channel","h")}); sum += value; squared_sum += value * value; } workgroup_shared[local_idx] = ${P}(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 = ${Fs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); let squared_sum_final = ${Fs("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}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:O,dataType:1}],dispatchGroup:{x},programUniforms:B}),getShaderSource:te},{inputs:[t,r,s],outputs:[-1]})[0]},ua=(e,t,r)=>{let s=t[0].dims,n=s,i=2,o=s[0],d=s[1],p=De.sizeFromDimension(s,i),h=Zt(p),P=De.size(n)/h,x=la(e,t[0],t[1],t[2],o,p,d,r.epsilon),l=[o,d,p/h],O=[o,d],L=["type","none"],B=te=>{let se=Ze("x",t[0].dataType,l.length,h),H=Ze("scale_shift",1,O.length,2),pe=kt("output",t[0].dataType,l.length,h),ae=[se,H,pe];return` ${te.registerUniform("output_size","u32").declareVariables(...ae)} ${te.mainStart()} ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${pe.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${H.getByIndices("vec2(batch, channel)")}; let value = ${se.getByOffset("global_idx")} * ${pe.type.value}(scale_shift.x) + ${pe.type.value}(scale_shift.y); ${pe.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:[{type:12,data:P},...wt(l,O,l)]}),getShaderSource:B},{inputs:[t[0],x]})},yd=(e,t,r)=>{let s=t[0].dims,n=s,i=s[0],o=s[s.length-1],d=De.sizeFromDimension(s,1)/o,p=Zt(o),h=De.size(n)/p,P=[{type:12,data:d},{type:12,data:Math.floor(o/p)}],x=["type","type"],l=[0,s.length-1];for(let te=0;te{let se=or(t[0].dataType),H=p===1?"vec2f":`mat${p}x2f`,pe=Ne=>{let Fe=Ne===0?"x":"y",rt=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${se}(${rt}(scale.${Fe}))`;case 2:return`vec2<${se}>(${rt}(scale[0].${Fe}, scale[1].${Fe}))`;case 4:return`vec4<${se}>(${rt}(scale[0].${Fe}, scale[1].${Fe}, scale[2].${Fe}, scale[3].${Fe}))`;default:throw new Error(`Not supported compoents ${p}`)}},ae=Ze("input",t[0].dataType,t[0].dims,p),ge=kt("output",t[0].dataType,n,p);return` @group(0) @binding(0) var input : array<${ae.type.storage}>; @group(0) @binding(1) var scale_input : array<${H}>; @group(0) @binding(2) var output : array<${ge.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], ${pe(0)}, ${pe(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:P}),getShaderSource:B},{inputs:[t[0],L]})},Md=(e,t)=>{t.format==="NHWC"?yd(e,e.inputs,t):ua(e,e.inputs,t)}}),Qc,Xc,Yc,bd=g(()=>{Ot(),Ut(),er(),Qc=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Xc=(e,t,r)=>{let s=t.simplified,n=e[0].dims,i=e[1],o=!s&&e[2],d=n,p=De.normalizeAxis(t.axis,n.length),h=De.sizeToDimension(n,p),P=De.sizeFromDimension(n,p),x=De.size(i.dims),l=o?De.size(o.dims):0;if(x!==P||o&&l!==P)throw new Error(`Size of X.shape()[axis:] == ${P}. Size of scale and bias (if provided) must match this. Got scale size of ${x} and bias size of ${l}`);let O=[];for(let ge=0;ge1,H=r>2,pe=ge=>{let Ne=or(e[0].dataType),Fe=[Ze("x",e[0].dataType,e[0].dims,L),Ze("scale",i.dataType,i.dims,L)];o&&Fe.push(Ze("bias",o.dataType,o.dims,L)),Fe.push(kt("output",e[0].dataType,d,L)),se&&Fe.push(kt("mean_data_output",1,O)),H&&Fe.push(kt("inv_std_output",1,O));let rt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${ge.registerUniforms(rt).declareVariables(...Fe)} ${ge.mainStart()} ${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${Dr("f32",L)}; var mean_square_vector = ${Dr("f32",L)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Is(Ne,L,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Fs("mean_vector",L)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Fs("mean_square_vector",L)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Is(Ne,L,"x[j + offset]")}; let f32scale = ${Is(Ne,L,"scale[j]")}; output[j + offset] = ${Fe[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale ${o?`+ ${Is(Ne,L,"bias[j]")}`:""} ); } ${se?"mean_data_output[global_idx] = mean":""}; ${H?"inv_std_output[global_idx] = inv_std_dev":""}; }`},ae=[{dims:d,dataType:e[0].dataType}];return se&&ae.push({dims:O,dataType:1}),H&&ae.push({dims:O,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${L};${r};${s}`,inputDependencies:B},getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:te}),getShaderSource:pe}},Yc=(e,t)=>{Qc(e.inputs),e.compute(Xc(e.inputs,t,e.outputCount))}}),vd,Td,xd,Ed,da,Pd=g(()=>{Ot(),Ut(),lr(),er(),vd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],s=r.dims.length;if(r.dims[s-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,o=e[1];if(!De.areEqual(o.dims,[t.n,n,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(De.size(d)!==t.n*n)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*n:t.n*Math.floor((n+1)/2);if(De.size(p)!==h)throw new Error("zeroPoints input size error.")}},Td=(e,t)=>{let r=e[0].dims,s=r.length,n=r[s-2],i=t.k,o=t.n,d=r.slice(0,s-2),p=De.size(d),h=e[1].dims[2]/4,P=e[0].dataType,x=Zt(t.k),l=Zt(h),O=Zt(o),L=d.concat([n,o]),B=n>1&&o/O%2===0?2:1,te=De.size(L)/O/B,se=64,H=[],pe=[p,n,i/x],ae=De.convertShape(e[1].dims).slice();ae.splice(-1,1,h/l),H.push(...wt(pe)),H.push(...wt(ae)),H.push(...wt(e[2].dims)),e.length===4&&H.push(...wt(De.convertShape(e[3].dims)));let ge=[p,n,o/O];H.push(...wt(ge));let Ne=Fe=>{let rt=pe.length,vt=Ze("a",e[0].dataType,rt,x),$t=Ze("b",12,ae.length,l),Yt=Ze("scales",e[2].dataType,e[2].dims.length),rr=[vt,$t,Yt],zt=e.length===4?Ze("zero_points",12,e[3].dims.length):void 0;zt&&rr.push(zt);let Tr=ge.length,Ir=kt("output",e[0].dataType,Tr,O),nr=or(e[0].dataType),Er=(()=>{switch(x){case 1:return`array<${nr}, 8>`;case 2:return`mat4x2<${nr}>`;case 4:return`mat2x4<${nr}>`;default:throw new Error(`${x}-component is not supported.`)}})(),Ft=()=>{let Ve=` // reuse a data var input_offset = ${vt.indicesToOffset(`${vt.type.indices}(batch, row, word_offset)`)}; var a_data: ${Er}; for (var j: u32 = 0; j < ${8/x}; j++) { a_data[j] = ${vt.getByOffset("input_offset")}; input_offset++; } `;for(let ct=0;ct> 4) & b_mask); b_quantized_values = ${Er}(${Array.from({length:4},(Vt,xr)=>`${nr}(b_value_lower[${xr}]), ${nr}(b_value_upper[${xr}])`).join(", ")}); b_dequantized_values = ${x===1?`${Er}(${Array.from({length:8},(Vt,xr)=>`(b_quantized_values[${xr}] - ${zt?`zero_point${ct}`:"zero_point"}) * scale${ct}`).join(", ")});`:`(b_quantized_values - ${Er}(${Array(8).fill(`${zt?`zero_point${ct}`:"zero_point"}`).join(",")})) * scale${ct};`}; workgroup_shared[local_id.x * ${B} + ${Math.floor(ct/O)}]${O>1?`[${ct%O}]`:""} += ${Array.from({length:8/x},(Vt,xr)=>`${x===1?`a_data[${xr}] * b_dequantized_values[${xr}]`:`dot(a_data[${xr}], b_dequantized_values[${xr}])`}`).join(" + ")}; `;return Ve},Nt=()=>{let Ve=` var col_index = col * ${O}; ${zt?` 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 = ${nr}(8);`} `;for(let ct=0;ct> 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 = ${zt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${ct} = ${nr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return Ve},hr=()=>{let Ve=`col_index = col * ${O};`;for(let ct=0;ct; var b_value_upper: vec4; var b_quantized_values: ${Er}; var b_dequantized_values: ${Er};`,Ve};return` var workgroup_shared: array<${Ir.type.value}, ${B*se}>; ${Fe.declareVariables(...rr,Ir)} ${Fe.mainStart([se,1,1])} let output_indices = ${Ir.offsetToIndices(`(global_idx / ${se}) * ${B}`)}; 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 += ${se}) { //process one block var word_offset: u32 = block * ${t.blockSize/x}; ${Nt()} for (var word: u32 = 0; word < ${h}; word += ${l}) { ${hr()} for (var i: u32 = 0; i < ${l}; i++) { ${Ft()} word_offset += ${8/x}; } } } workgroupBarrier(); if (local_id.x < ${B}) { var output_value: ${Ir.type.value} = ${Ir.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${se}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${B}; } ${Ir.setByIndices(`${Ir.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${x};${l};${O};${B};${se}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:L,dataType:P}],dispatchGroup:{x:te},programUniforms:H}),getShaderSource:Ne}},xd=(e,t)=>{let r=e[0].dims,s=r.length,n=r[s-2],i=t.k,o=t.n,d=r.slice(0,s-2),p=De.size(d),h=e[1].dims[2]/4,P=e[0].dataType,x=Zt(t.k),l=Zt(h),O=d.concat([n,o]),L=128,B=o%8===0?8:o%4===0?4:1,te=L/B,se=te*l*8,H=se/x,pe=se/t.blockSize,ae=De.size(O)/B,ge=[],Ne=[p,n,i/x],Fe=De.convertShape(e[1].dims).slice();Fe.splice(-1,1,h/l),ge.push(...wt(Ne)),ge.push(...wt(Fe)),ge.push(...wt(e[2].dims)),e.length===4&&ge.push(...wt(De.convertShape(e[3].dims)));let rt=[p,n,o];ge.push(...wt(rt));let vt=$t=>{let Yt=Ne.length,rr=Ze("a",e[0].dataType,Yt,x),zt=Ze("b",12,Fe.length,l),Tr=Ze("scales",e[2].dataType,e[2].dims.length),Ir=[rr,zt,Tr],nr=e.length===4?Ze("zero_points",12,e[3].dims.length):void 0;nr&&Ir.push(nr);let Er=rt.length,Ft=kt("output",e[0].dataType,Er),Nt=or(e[0].dataType),hr=()=>{switch(x){case 1:return` let a_data0 = vec4<${Nt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${Nt}>(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<${Nt}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${Nt}>(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(`${x}-component is not supported.`)}};return` var sub_a: array<${rr.type.value}, ${H}>; var inter_results: array, ${B}>; ${$t.declareVariables(...Ir,Ft)} ${$t.mainStart([te,B,1])} let output_indices = ${Ft.offsetToIndices(`workgroup_index * ${B}`)}; 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) / ${pe} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${H}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${H}; a_offset += ${L}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${rr.getByIndices(`${rr.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${rr.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${pe} + local_id.x; ${nr?` 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 = ${nr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${Nt}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Nt}(8);`} let scale = ${Tr.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${zt.getByIndices(`${zt.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/x}; for (var i: u32 = 0; i < ${l}; i++) { ${hr()} let b_value = ${l===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<${Nt}>(${Array.from({length:4},(Ve,ct)=>`${Nt}(b_value_lower[${ct}]), ${Nt}(b_value_upper[${ct}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${Nt}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(Ve,ct)=>`${`dot(a_data${ct}, b_dequantized_values[${ct}])`}`).join(" + ")}; word_offset += ${8/x}; } workgroupBarrier(); } if (local_idx < ${B}) { var output_value: ${Ft.type.value} = ${Ft.type.value}(0); for (var b = 0u; b < ${te}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${Ft.setByIndices(`${Ft.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${x};${l};${te};${B}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:O,dataType:P}],dispatchGroup:{x:ae},programUniforms:ge}),getShaderSource:vt}},Ed=(e,t)=>{vd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(xd(e.inputs,t)):e.compute(Td(e.inputs,t))},da=e=>qt(e)}),Jc,Cd,$d,ca,Zc,ep,Sd,kd,Ad,tp=g(()=>{Ot(),Ut(),er(),Jc=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Cd=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${St("uniforms.pads",n,r)}; if (k < 0) { break; } if (k >= i32(${St("uniforms.x_shape",n,t)})) { break; } offset += k * i32(${St("uniforms.x_strides",n,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${s} value = x[offset]; } `},$d=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${St("uniforms.pads",n,r)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${St("uniforms.x_shape",n,t)}) - 1); k = k % _2n_1; if(k >= i32(${St("uniforms.x_shape",n,t)})) { k = _2n_1 - k; } } offset += k * i32(${St("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},ca=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${St("uniforms.pads",n,r)}; if (k < 0) { k = 0; } if (k >= i32(${St("uniforms.x_shape",n,t)})) { k = i32(${St("uniforms.x_shape",n,t)}) - 1; } offset += k * i32(${St("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Zc=(e,t,r)=>{let s="";for(let n=t-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${St("uniforms.pads",n,r)}; if (k < 0) { k += i32(${St("uniforms.x_shape",n,t)}]); } if (k >= i32(${St("uniforms.x_shape",n,t)})) { k -= i32(${St("uniforms.x_shape",n,t)}); } offset += k * i32(${St("uniforms.x_strides",n,t)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},ep=(e,t,r)=>{switch(r.mode){case 0:return Cd(e,t,r.pads.length);case 1:return $d(e,t,r.pads.length);case 2:return ca(e,t,r.pads.length);case 3:return Zc(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Sd=(e,t)=>{let r=De.padShape(e[0].dims.slice(),t.pads),s=e[0].dims,n=De.size(r),i=[{type:12,data:n},{type:6,data:t.pads}],o=e.length>=3&&e[2].data;t.mode===0&&i.push({type:o?e[2].dataType:1,data:t.value}),i.push(...wt(e[0].dims,r));let d=["rank"],p=h=>{let P=kt("output",e[0].dataType,r.length),x=Ze("x",e[0].dataType,s.length),l=x.type.value,O=ep(P,s.length,t),L=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&L.push({name:"constant_value",type:o?l:"f32"}),` ${h.registerUniforms(L).declareVariables(x,P)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${P.offsetToIndices("global_idx")}; var value = ${l}(0); ${O} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(De.size(r)/64)},programUniforms:i}),getShaderSource:p}},kd=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,n=e[0].dims.length,i=new Int32Array(2*n).fill(0);if(e.length>=4){let d=e[3].getBigInt64Array();for(let p=0;pi[Number(p)]=Number(d));let o=[];return i.forEach(d=>o.push(d)),{mode:t.mode,value:s,pads:o}}else return t},Ad=(e,t)=>{Jc(e.inputs);let r=kd(e.inputs,t);e.compute(Sd(e.inputs,r),{inputs:[0]})}}),Zn,pa,ha,ma,fa,Id,Fd,_a,Od,Dd,Ld,ga,zd,Bd,wa,rp,ya,Rd,jd,sp=g(()=>{Et(),Ot(),Ut(),er(),Zn=e=>{if(E.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},pa=(e,t,r)=>{let s=t.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let i=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),d=t.strides.slice(),p=i?t.dilations.slice():[],h=t.pads.slice();wr.adjustPoolAttributes(r,n,o,d,p,h);let P=wr.computePoolOutputShape(r,n,d,p,o,h,t.autoPad),x=Object.assign({},t);i?Object.assign(x,{kernelShape:o,strides:d,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(x,{kernelShape:o,strides:d,pads:h,cacheKey:t.cacheKey});let l=P.slice();return l.push(l.splice(1,1)[0]),[x,s?l:P]},ha=(e,t)=>{let r=t.format==="NHWC",s=De.size(e),n=De.size(t.kernelShape),i=[{type:12,data:s},{type:12,data:n}],o=[{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],P=t.pads[t.pads.length-1],x=!!(h+P);i.push({type:12,data:d},{type:12,data:p},{type:12,data:h},{type:12,data:P}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let O=t.kernelShape[t.kernelShape.length-2],L=t.strides[t.strides.length-2],B=t.pads[t.pads.length/2-2],te=t.pads[t.pads.length-2];l=!!(B+te),i.push({type:12,data:O},{type:12,data:L},{type:12,data:B},{type:12,data:te}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,o,!0,x,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let d=De.computeStrides(t.kernelShape);i.push({type:12,data:d},{type:12,data:t.pads},{type:12,data:t.strides}),o.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,P)=>h+P);return[i,o,!!p,!1,!1]}},ma=(e,t,r,s,n,i,o,d,p,h,P,x)=>{let l=n.format==="NHWC",O=t.type.value,L=kt("output",t.type.tensor,s);if(n.kernelShape.length<=2){let B="",te="",se="",H=r-(l?2:1);if(P?B=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${H}] = indices[${H}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${H}] < 0 || xIndices[${H}] >= uniforms.x_shape[${H}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:B=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${H}] = indices[${H}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`,n.kernelShape.length===2){let pe=r-(l?3:2);x?te=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${pe}] = indices[${pe}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${pe}] < 0 || xIndices[${pe}] >= uniforms.x_shape[${pe}]) { pad += i32(uniforms.kw); continue; } `:te=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${pe}] = indices[${pe}] * uniforms.sh - uniforms.phStart + j; `,se=` } `}return` ${e.registerUniforms(p).declareVariables(t,L)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${L.offsetToIndices("global_idx")}; var xIndices = ${L.offsetToIndices("global_idx")}; var value = ${O}(${d}); var pad = 0; ${te} ${B} ${se} ${o} output[global_idx] = value; }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let B=n.kernelShape.length,te=n.pads.length,se="";return h?se=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} }`:se=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${i} `,` ${e.registerUniforms(p).declareVariables(t,L)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${L.offsetToIndices("global_idx")}; var xIndices = ${L.offsetToIndices("global_idx")}; var offsets: array; var value = ${O}(${d}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${B-1}u; j++) { offsets[j] = offset / ${St("uniforms.kernelStrides","j",B)}; offset -= offsets[j] * ${St("uniforms.kernelStrides","j",B)}; } offsets[${B-1}] = offset; isPad = false; for (var j = ${r-B}u; j < ${r}u; j++) { xIndices[j] = indices[j] * ${St("uniforms.strides",`j - ${r-B}u`,B)} + offsets[j - ${r-B}u] - ${St("uniforms.pads","j - 2u",te)}; ${se} } ${o} output[global_idx] = value; }`}},fa=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Id=e=>`${fa(e)};${e.countIncludePad}`,Fd=e=>`${fa(e)};${e.storageOrder};${e.dilations}`,_a=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Od=(e,t,r,s)=>{let[n,i]=pa(t,s,r),o=Ze("x",t.dataType,t.dims.length),d=o.type.value,p="value += x_val;",h="";n.countIncludePad?h+=`value /= ${d}(uniforms.kernelSize);`:h+=`value /= ${d}(i32(uniforms.kernelSize) - pad);`;let[P,x,l,O,L]=ha(i,n);P.push(...wt(t.dims,i));let B=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${l};${O};${L}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(i)/64)},programUniforms:P}),getShaderSource:te=>ma(te,o,t.dims.length,i.length,n,p,h,0,x,l,O,L)}},Dd=e=>{let t=e.count_include_pad!==0,r=_a(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:t,...r,cacheKey:""};return{...s,cacheKey:Id(s)}},Ld=(e,t)=>{Zn(e.inputs),e.compute(Od("AveragePool",e.inputs[0],!1,t))},ga={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},zd=e=>{let t=e.format;return{format:t,...ga,cacheKey:t}},Bd=(e,t)=>{Zn(e.inputs),e.compute(Od("GlobalAveragePool",e.inputs[0],!0,t))},wa=(e,t,r,s)=>{let[n,i]=pa(t,s,r),o=` value = max(x_val, value); `,d="",p=Ze("x",t.dataType,t.dims.length),h=["rank"],[P,x,l,O,L]=ha(i,n);return P.push(...wt(t.dims,i)),{name:e,shaderCache:{hint:`${s.cacheKey};${l};${O};${L}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(De.size(i)/64)},programUniforms:P}),getShaderSource:B=>ma(B,p,t.dims.length,i.length,n,o,d,t.dataType===10?-65504:-1e5,x,l,O,L)}},rp=(e,t)=>{Zn(e.inputs),e.compute(wa("MaxPool",e.inputs[0],!1,t))},ya=e=>{let t=e.storage_order,r=e.dilations,s=_a(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...s,cacheKey:""};return{...n,cacheKey:Fd(n)}},Rd=e=>{let t=e.format;return{format:t,...ga,cacheKey:t}},jd=(e,t)=>{Zn(e.inputs),e.compute(wa("GlobalMaxPool",e.inputs[0],!0,t))}}),Nd,Ud,Vd,Wd,np=g(()=>{Ot(),Ut(),lr(),er(),Nd=(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,s)=>r===e[2].dims[s]).reduce((r,s)=>r&&s,!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((n,i)=>i===t.axis||n===e[0].dims[i]).reduce((n,i)=>n&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],s=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Ud=(e,t)=>{let r=De.normalizeAxis(t.axis,e[0].dims.length),s=e[0].dataType,n=s===3,i=e[0].dims,o=e[1].dataType,d=De.size(i),p=s===3||s===2,h=p?[Math.ceil(De.size(e[0].dims)/4)]:e[0].dims,P=e[1].dims,x=e.length>2?e[2]:void 0,l=x?p?[Math.ceil(De.size(x.dims)/4)]:x.dims:void 0,O=P.length===0||P.length===1&&P[0]===1,L=O===!1&&P.length===1,B=Zt(d),te=O&&(!p||B===4),se=te?B:1,H=te&&!p?B:1,pe=Ze("input",p?12:s,h.length,H),ae=Ze("scale",o,P.length),ge=x?Ze("zero_point",p?12:s,l.length):void 0,Ne=kt("output",o,i.length,se),Fe=[pe,ae];ge&&Fe.push(ge);let rt=[h,P];x&&rt.push(l);let vt=[{type:12,data:d/se},{type:12,data:r},{type:12,data:t.blockSize},...wt(...rt,i)],$t=Yt=>{let rr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Yt.registerUniforms(rr).declareVariables(...Fe,Ne)} ${Yt.mainStart()} ${Yt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ne.offsetToIndices("global_idx")}; // Set input x ${p?` let input = ${pe.getByOffset("global_idx / 4")}; let x_vec = ${n?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${se===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${pe.getByOffset("global_idx")};`}; // Set scale input ${O?`let scale_value= ${ae.getByOffset("0")}`:L?` let scale_index = ${Ne.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${ae.getByOffset("scale_index")};`:` var scale_indices: ${ae.type.indices} = output_indices; let index = ${ae.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${ae.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${ae.getByIndices("scale_indices")};`}; // Set zero-point input ${ge?O?p?` let zero_point_input = ${ge.getByOffset("0")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ge.getByOffset("0")}`:L?p?` let zero_point_index = ${Ne.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${ge.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ne.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${ge.getByOffset("zero_point_index")};`:p?` let zero_point_offset = ${ae.indicesToOffset("scale_indices")}; let zero_point_input = ${ge.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ge.getByIndices("scale_indices")};`:`let zero_point_value = ${p?n?"i32":"u32":pe.type.value}(0);`}; // Compute and write output ${Ne.setByOffset("global_idx",`${Ne.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:ge?["rank","rank","rank"]:["rank","rank"]},getShaderSource:$t,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(d/se/64),y:1,z:1},programUniforms:vt})}},Vd=(e,t)=>{Nd(e.inputs,t),e.compute(Ud(e.inputs,t))},Wd=e=>qt({axis:e.axis,blockSize:e.blockSize})}),Gd,Kd,Hd,op=g(()=>{Et(),Ot(),er(),Gd=(e,t,r)=>{let s=e===t,n=et&&r>0;if(s||n||i)throw new Error("Range these inputs' contents are invalid.")},Kd=(e,t,r,s)=>{let n=Math.abs(Math.ceil((t-e)/r)),i=[n],o=n,d=[{type:12,data:o},{type:s,data:e},{type:s,data:r},...wt(i)],p=h=>{let P=kt("output",s,i.length),x=P.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:x},{name:"delta",type:x}];return` ${h.registerUniforms(l).declareVariables(P)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${x}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d})}},Hd=e=>{let t=0,r=0,s=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),E.webgpu.validateInputContent&&Gd(t,r,s),e.compute(Kd(t,r,s,e.inputs[0].dataType),{inputs:[]})}}),qd,Qd,Xd,Yd,Jd,Zd,ec,tc,rc,sc,nc,Ma,oc,ic,ac,lc,ip,tr,uc,Yr=g(()=>{Ot(),Ut(),lr(),er(),qd=(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")}},Qd=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(r).fill(1);return t.forEach((n,i)=>s[n]=e[i]),s},Xd=(e,t,r,s,n,i)=>{let[o,d,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(P=>i.push(P));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(P=>s.push(P)),s.length!==0&&s.length!==h&&r>=18&&s.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");qd(s,t),t.axes.length>0&&Qd(s,t.axes,h).forEach((P,x)=>s[x]=P)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(P=>n.push(Number(P))),n.length!==0&&n.length!==h&&r>=18&&n.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(s.length!==0&&s.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(n.length!==0&&n.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 s<"u"&&typeof n<"u"&&s.length>0&&n.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Yd=(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`)}})()+"}",Jd=(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`)}})()+"}",Zd=(e,t,r)=>{let s=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?s:e.slice();return t.length>0?(t.forEach((i,o)=>{s[i]=n[o],s[o+r]=n[t.length+o]}),s):n},ec=(e,t,r,s)=>{let n=[];if(r.length>0)if(s.length>0){if(e.forEach(i=>n.push(i)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((i,o)=>n[i]=r[o])}else r.forEach(i=>n.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((i,o)=>Math.round(i*t[o]))}return n},tc=(e,t,r)=>{let s=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let n=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=s),r.axes.forEach(i=>n[i]=Math.round(e[i]*t[i]))):(t.fill(s,0,t.length),n.forEach((i,o)=>n[o]=Math.round(i*t[o]))),n},rc=(e,t,r,s,n)=>` 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 = ${St("uniforms.scales","i",s)}; var roi_low = ${St("uniforms.roi","i",n)}; var roi_hi = ${St("uniforms.roi",`i + ${t.length}`,n)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${St("uniforms.input_shape","i",t.length)}; var output_shape_i = ${St("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; }`,sc=(e,t,r,s,n,i,o)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${St("uniforms.scales","i",n)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${St("uniforms.roi","i",i)}; var roi_hi = ${St("uniforms.roi",`i + ${r.length}`,i)}; var input_shape_i = ${St("uniforms.input_shape","i",r.length)}; var output_shape_i = ${St("uniforms.output_shape","i",s.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${o} || (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; }`,nc=(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 >= ${St("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Ma=(e,t,r,s)=>e.rank>s?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; `:"",oc=(e,t,r,s,n)=>{let[i,o,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",o,`max(0, min(row, ${r[o]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; ${Ma(e,p,i,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${h} = originalIndices[${o}]; var col:${h} = originalIndices[${d}]; ${s?`if (row < 0 || row > (${r[o]} - 1) || col < 0 || col > (${r[d]} - 1)) { return ${n}; }`:""}; row = max(0, min(row, ${r[o]} - 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[${i}])`:"0"}; var x11: ${h} = getInputValue(batch, channel, row1, col1); var x12: ${h} = getInputValue(batch, channel, row1, col2); var x21: ${h} = getInputValue(batch, channel, row2, col1); var x22: ${h} = getInputValue(batch, channel, row2, col2); var dx1: ${h} = abs(row - ${h}(row1)); var dx2: ${h} = abs(${h}(row2) - row); var dy1: ${h} = abs(col - ${h}(col1)); var dy2: ${h} = abs(${h}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},ic=(e,t,r,s,n,i,o,d,p,h)=>{let P=r.length===2,[x,l]=P?[0,1]:[2,3],O=e.type.value,L=B=>{let te=B===x?"row":"col";return` fn ${te}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${O} { var output_index = ${t.indicesGet("output_indices",B)}; var originalIdx: ${O} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[B]}, ${s[B]}, ${r[B]}, ${i[B]}, ${i[B]} + ${r.length}); var fractOriginalIdx: ${O} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${d} && (originalIdx < 0 || originalIdx > (${r[B]} - 1))) { return ${p}; } var data: array<${O}, 4> = array<${O}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${te}: ${O} = originalIdx + ${O}(i); if (${te} < 0 || ${te} >= ${r[B]}) { ${h?`coefs[i + 1] = 0.0; continue;`:d?`return ${p};`:`${te} = max(0, min(${te}, ${r[B]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",B,`u32(${te})`)}; data[i + 1] = ${B===x?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${L(x)}; ${L(l)}; fn getCubicInterpolationCoefs(s: ${O}) -> array<${O}, 4> { var absS = abs(s); var coeffs: array<${O}, 4> = array<${O}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${O} = 1.0 - absS; var twoMinusAbsS: ${O} = 2.0 - absS; var onePlusAbsS: ${O} = 1.0 + absS; coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; return coeffs; } fn cubicInterpolation1D(x: array<${O}, 4>, coefs: array<${O}, 4>) -> ${O} { var coefsSum: ${O} = 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}) -> ${O} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},ac=(e,t,r,s,n)=>{let[i,o,d,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],P=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${P} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(depth, ${r[o]} - 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))`)}; ${Ma(e,h,i,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${P} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${P} = originalIndices[${o}]; var height:${P} = originalIndices[${d}]; var width:${P} = originalIndices[${p}]; ${s?`if (depth < 0 || depth > (${r[o]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) { return ${n}; }`:""}; depth = max(0, min(depth, ${r[o]} - 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[${i}])`:"0"}; var x111: ${P} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${P} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${P} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${P} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${P} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${P} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${P} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${P} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${P} = abs(depth - ${P}(depth1)); var dx2: ${P} = abs(${P}(depth2) - depth); var dy1: ${P} = abs(height - ${P}(height1)); var dy2: ${P} = abs(${P}(height2) - height); var dz1: ${P} = abs(width - ${P}(width1)); var dz2: ${P} = abs(${P}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},lc=(e,t,r,s,n,i)=>{let o=e.dims,d=Zd(i,t.axes,o.length),p=ec(o,s,n,t.axes),h=s.slice();s.length===0&&(h=o.map((H,pe)=>H===0?1:p[pe]/H),t.keepAspectRatioPolicy!=="stretch"&&(p=tc(o,h,t)));let P=kt("output",e.dataType,p.length),x=Ze("input",e.dataType,o.length),l=De.size(p),O=o.length===p.length&&o.every((H,pe)=>H===p[pe]),L=t.coordinateTransformMode==="tf_crop_and_resize",B=t.extrapolationValue,te=x.type.value,se=H=>` ${O?"":` ${Yd(t.coordinateTransformMode,te)}; ${(()=>{switch(t.mode){case"nearest":return` ${nc(x,o)}; ${Jd(t.nearestMode,r,te)}; ${sc(x,P,o,p,h.length,d.length,L)}; `;case"linear":return` ${rc(P,o,p,h.length,d.length)}; ${(()=>{if(o.length===2||o.length===4)return`${oc(x,P,o,L,B)}`;if(o.length===3||o.length===5)return`${ac(x,P,o,L,B)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(o.length===2||o.length===4)return`${ic(x,P,o,p,h,d,t.cubicCoeffA,L,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")}})()}; `} ${H.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",d.length).declareVariables(x,P)} ${H.mainStart()} ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${O?"output[global_idx] = input[global_idx];":` let output_indices = ${P.offsetToIndices("global_idx")}; var input_indices: ${x.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${x.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${o.length===2||o.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:""}|${n.length>0?n:""}|${d.length>0?d:""}|${O}|${o}`,inputDependencies:["rank"]},getShaderSource:se,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:h},{type:1,data:d},...wt(o,p)]})}},ip=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},tr=(e,t)=>{let r=[],s=[],n=[],i=ip(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Xd(e.inputs,t,i,r,s,n),e.compute(lc(e.inputs[0],t,i,r,s,n),{inputs:[0]})},uc=e=>{let t=e.antialias,r=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,i=e.excludeOutside!==0,o=e.extrapolationValue,d=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return qt({antialias:t,axes:r,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:i,extrapolationValue:o,keepAspectRatioPolicy:d,mode:p,nearestMode:h})}}),Jr,ns,hn,$p=g(()=>{Ot(),Ut(),lr(),er(),Jr=(e,t)=>{let[r,s,n,i]=e,{numHeads:o,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(!De.areEqual(s.dims,[])&&!De.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!De.areEqual(n.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(d>0&&o===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],P=n.dims[0],x=De.sizeFromDimension(r.dims,1)/h,l=d===0?n.dims[1]*2:x/o;if(d>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(p!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(h!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(l/2!==n.dims[1]&&d/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(h>P)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ns=(e,t)=>{let{interleaved:r,numHeads:s,rotaryEmbeddingDim:n,scale:i}=t,o=e[0].dims[0],d=De.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=d/p,P=e[2].dims[1],x=n===0?P*2:h/s,l=new Array(o,p,h/x,x-P),O=De.computeStrides(l),L=[{type:1,data:i},{type:12,data:l},{type:12,data:O},...e[0].dims.length===3?new Array({type:12,data:[d,h,x,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[d,x,p*x,1]}):[],...wt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],B=te=>{let se=Ze("input",e[0].dataType,e[0].dims.length),H=Ze("position_ids",e[1].dataType,e[1].dims.length),pe=Ze("cos_cache",e[2].dataType,e[2].dims.length),ae=Ze("sin_cache",e[3].dataType,e[3].dims.length),ge=kt("output",e[0].dataType,e[0].dims.length);return te.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:O.length},{name:"input_output_strides",type:"u32",length:O.length}]),` ${te.declareVariables(se,H,pe,ae,ge)} ${te.mainStart(Rr)} let half_rotary_emb_dim = uniforms.${pe.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${te.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${H.broadcastedIndicesToOffset("bsnh.xy",kt("",H.type.tensor,2))}; let position_id = u32(${H.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 = ${se.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} - ${se.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; ${ge.setByOffset("i","re")} let im = ${se.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} + ${se.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; ${ge.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${ge.setByOffset("k",se.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:qt({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(De.size(l)/Rr)},programUniforms:L})}},hn=(e,t)=>{Jr(e.inputs,t),e.compute(ns(e.inputs,t))}}),dc,cc,f,S=g(()=>{Ot(),Ut(),er(),dc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],s=e[2];if(t.dataType!==r.dataType||t.dataType!==s.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 n=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},cc=(e,t,r,s)=>{let n=t.simplified,i=e[0].dims,o=De.size(i),d=i,p=o,h=i.slice(-1)[0],P=s?i.slice(0,-1).concat(1):[],x=!n&&e.length>3,l=e.length>4,O=s&&r>1,L=s&&r>2,B=r>3,te=64,se=Zt(h),H=[{type:12,data:p},{type:12,data:se},{type:12,data:h},{type:1,data:t.epsilon}],pe=ge=>{let Ne=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Fe=[Ze("x",e[0].dataType,e[0].dims,se),Ze("skip",e[1].dataType,e[1].dims,se),Ze("gamma",e[2].dataType,e[2].dims,se)];x&&Fe.push(Ze("beta",e[3].dataType,e[3].dims,se)),l&&Fe.push(Ze("bias",e[4].dataType,e[4].dims,se)),Fe.push(kt("output",e[0].dataType,d,se)),O&&Fe.push(kt("mean_output",1,P)),L&&Fe.push(kt("inv_std_output",1,P)),B&&Fe.push(kt("input_skip_bias_sum",e[0].dataType,d,se));let rt=or(e[0].dataType),vt=or(1,se);return` ${ge.registerUniforms(Ne).declareVariables(...Fe)} var sum_shared : array<${vt}, ${te}>; var sum_squared_shared : array<${vt}, ${te}>; ${ge.mainStart([te,1,1])} let ix = local_id.x; let iy = global_id.x / ${te}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${te}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${te-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${l?"bias[offset1d + i]":rt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${B?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Is(rt,se,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${te}; 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 = ${Fs("sum",se)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Fs("square_sum",se)} / f32(uniforms.hidden_size) ${n?"":"- mean * mean"} + uniforms.epsilon); ${O?"mean_output[global_idx] = mean;":""} ${L?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${n?"":`- ${rt}(mean)`}) * ${rt}(inv_std_dev) * gamma[offset1d + i] ${x?"+ beta[offset1d + i]":""}; } }`},ae=[{dims:d,dataType:e[0].dataType}];return r>1&&ae.push({dims:P,dataType:1}),r>2&&ae.push({dims:P,dataType:1}),r>3&&ae.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${se};${O};${L};${B}`,inputDependencies:e.map((ge,Ne)=>"type")},getShaderSource:pe,getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:H})}},f=(e,t)=>{dc(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(cc(e.inputs,t,e.outputCount,!1),{outputs:r})}}),D,Te,Ie,Se,Xe,tt,ft,bt,Ht=g(()=>{Ot(),Ut(),lr(),er(),D=(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,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Te=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(s=>r.push(Number(s)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(s=>r.push(Number(s)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Ie=(e,t)=>{if(e.length>1){let r=Te(e,1),s=Te(e,2),n=Te(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),qt({starts:r,ends:s,axes:n})}else return t},Se=(e,t,r,s,n)=>{let i=e;return e<0&&(i+=r[s[t]]),n[t]<0?Math.max(0,Math.min(i,r[s[t]]-1)):Math.max(0,Math.min(i,r[s[t]]))},Xe=(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 = ${St("uniforms.input_shape","i",r.length)}; let steps_i = ${St("uniforms.steps","i",r.length)}; let signs_i = ${St("uniforms.signs","i",r.length)}; let starts_i = ${St("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; }`,tt=(e,t)=>{let r=e[0].dims,s=De.size(r),n=t.axes.length>0?De.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=Te(e,4);i.forEach(se=>se!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(n.length).fill(1));let o=t.starts.map((se,H)=>Se(se,H,r,n,i)),d=t.ends.map((se,H)=>Se(se,H,r,n,i));if(n.length!==o.length||n.length!==d.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let se=0;seMath.sign(se));i.forEach((se,H,pe)=>{if(se<0){let ae=(d[H]-o[H])/se,ge=o[H],Ne=ge+ae*i[H];o[H]=Ne,d[H]=ge,pe[H]=-se}});let h=r.slice(0);n.forEach((se,H)=>{h[se]=Math.ceil((d[se]-o[se])/i[se])});let P={dims:h,dataType:e[0].dataType},x=kt("output",e[0].dataType,h.length),l=Ze("input",e[0].dataType,e[0].dims.length),O=De.size(h),L=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:i.length}],B=[{type:12,data:O},{type:12,data:o},{type:6,data:p},{type:12,data:i},...wt(e[0].dims,h)],te=se=>` ${se.registerUniforms(L).declareVariables(l,x)} ${Xe(l,x,r)} ${se.mainStart()} ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${x.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${x.setByOffset("global_idx",l.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${o.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:te,getRunData:()=>({outputs:[P],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:B})}},ft=(e,t)=>{D(e.inputs,t);let r=Ie(e.inputs,t);e.compute(tt(e.inputs,r),{inputs:[0]})},bt=e=>{let t=e.starts,r=e.ends,s=e.axes;return qt({starts:t,ends:r,axes:s})}}),jt,Lt,Gt,sr,ir=g(()=>{Ot(),Ut(),lr(),Us(),er(),jt=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Lt=(e,t)=>{let r=e.inputs[0],s=r.dims,n=De.size(s),i=64,o=s.length,d=De.normalizeAxis(t.axis,o),p=drt),P[d]=o-1,P[o-1]=d,h=e.compute(fs(r,P),{inputs:[r],outputs:[-1]})[0]):h=r;let x=h.dims,l=x[o-1],O=n/l,L=Zt(l),B=l/L,te=(Fe,rt)=>rt===4?`max(max(${Fe}.x, ${Fe}.y), max(${Fe}.z, ${Fe}.w))`:rt===2?`max(${Fe}.x, ${Fe}.y)`:rt===3?`max(max(${Fe}.x, ${Fe}.y), ${Fe}.z)`:Fe,se=Ze("x",h.dataType,h.dims,L),H=kt("result",h.dataType,h.dims,L),pe=se.type.value,ae=or(h.dataType)==="f32"?`var threadMax = ${pe}(-3.402823e+38f);`:`var threadMax = ${pe}(-65504.0h);`,ge=Fe=>` var rowMaxShared : ${pe}; var rowSumShared : ${pe}; var threadShared : array<${pe}, ${i}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${pe} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${pe}) { let index = row * row_stride + col; result[index] = value; } ${Fe.registerUniform("packedCols","i32").declareVariables(se,H)} ${Fe.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${i}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${ae} 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 = ${pe}(${te("threadShared[0]",L)}); } workgroupBarrier(); // find the rows sum var threadSum = ${pe}(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 = ${pe}(${Fs("threadShared[0]",L)}); } 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); } }`,Ne=e.compute({name:"Softmax",shaderCache:{hint:`${L}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:x,dataType:h.dataType}],dispatchGroup:{x:O},programUniforms:[{type:6,data:B}]}),getShaderSource:ge},{inputs:[h],outputs:[p?-1:0]})[0];p&&e.compute(fs(Ne,P),{inputs:[Ne]})},Gt=(e,t)=>{jt(e.inputs),Lt(e,t)},sr=e=>qt({axis:e.axis})}),Xt,dr,Or,$r,pr,kr,Lr,os=g(()=>{Ot(),Ut(),lr(),er(),Xt=e=>{if(!e||e.length<1)throw new Error("too few inputs")},dr=(e,t)=>{let r=[],s=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),s=r.length),qt({numOutputs:s,axis:t.axis,splitSizes:r})},Or=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${St("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,$r=e=>{let t=e.length,r=[];for(let s=0;s{let r=e[0].dims,s=De.size(r),n=e[0].dataType,i=De.normalizeAxis(t.axis,r.length),o=new Array(t.numOutputs),d=Ze("input",n,r.length),p=new Array(t.numOutputs),h=[],P=[],x=0,l=[{type:12,data:s}];for(let L=0;L` ${L.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(d,...o)} ${Or(p.length)} ${$r(o)} ${L.mainStart()} ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${d.offsetToIndices("global_idx")}; var index = ${d.indicesGet("indices",i)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${St("uniforms.size_in_split_axis","output_number - 1u",p.length)}; ${d.indicesSet("indices",i,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:O,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},kr=(e,t)=>{Xt(e.inputs);let r=e.inputs.length===1?t:dr(e.inputs,t);e.compute(pr(e.inputs,r),{inputs:[0]})},Lr=e=>{let t=e.axis,r=e.splitSizes,s=e.numOutputs<0?r.length:e.numOutputs;if(s!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:t,numOutputs:s,splitSizes:r})}}),Kr,Ss,In,pc=g(()=>{Ot(),Ut(),er(),Kr=(e,t,r,s,n)=>{let i=kt("output_data",n,r.length,4),o=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,P=(x,l,O)=>`select(${l}, ${x}, ${O})`;if(!s)h=i.setByOffset("global_idx",P(o.getByOffset("global_idx"),d.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let x=(l,O,L="")=>{let B=`a_data[index_a${O}][component_a${O}]`,te=`b_data[index_b${O}][component_b${O}]`,se=`bool(c_data[index_c${O}] & (0xffu << (component_c${O} * 8)))`;return` let output_indices${O} = ${i.offsetToIndices(`global_idx * 4u + ${O}u`)}; let offset_a${O} = ${o.broadcastedIndicesToOffset(`output_indices${O}`,i)}; let offset_b${O} = ${d.broadcastedIndicesToOffset(`output_indices${O}`,i)}; let offset_c${O} = ${p.broadcastedIndicesToOffset(`output_indices${O}`,i)}; let index_a${O} = offset_a${O} / 4u; let index_b${O} = offset_b${O} / 4u; let index_c${O} = offset_c${O} / 4u; let component_a${O} = offset_a${O} % 4u; let component_b${O} = offset_b${O} % 4u; let component_c${O} = offset_c${O} % 4u; ${l}[${O}] = ${L}(${P(B,te,se)}); `};n===9?h=` var data = vec4(0); ${x("data",0,"u32")} ${x("data",1,"u32")} ${x("data",2,"u32")} ${x("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` ${x("output_data[global_idx]",0)} ${x("output_data[global_idx]",1)} ${x("output_data[global_idx]",2)} ${x("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(p,o,d,i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${h} }`},Ss=e=>{let t=e[1].dims,r=e[2].dims,s=e[0].dims,n=e[1].dataType,i=!(De.areEqual(t,r)&&De.areEqual(r,s)),o=t,d=De.size(t);if(i){let h=Gr.calcShape(Gr.calcShape(t,r,!1),s,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,d=De.size(o)}let p=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Kr(h,e,o,i,n),getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:p},...wt(s,t,r,o)]})}},In=e=>{e.compute(Ss(e.inputs))}}),_s,Ws=g(()=>{xc(),yo(),Ec(),Pc(),Cc(),$c(),Sc(),pn(),Dc(),Lc(),Xn(),Rc(),jc(),Nc(),Uc(),Wc(),Gc(),ld(),qc(),vr(),bd(),Pu(),Pd(),pd(),tp(),sp(),np(),op(),di(),Yr(),$p(),S(),Ht(),ir(),os(),fd(),Us(),Mo(),pc(),_s=new Map([["Abs",[Cl]],["Acos",[$l]],["Acosh",[mi]],["Add",[nu]],["ArgMax",[fl,wo]],["ArgMin",[ml,wo]],["Asin",[Sl]],["Asinh",[kl]],["Atan",[fi]],["Atanh",[Al]],["Attention",[Ml]],["AveragePool",[Ld,Dd]],["BatchNormalization",[Tl]],["BiasAdd",[hi]],["BiasSplitGelu",[bo]],["Cast",[_i,Il]],["Ceil",[gi]],["Clip",[Ol]],["Concat",[Ii,mu]],["Conv",[Wi,Ni]],["ConvTranspose",[ju,Lu]],["Cos",[Dl]],["Cosh",[Ll]],["CumSum",[Fo,Uu]],["DepthToSpace",[Gu,Ku]],["DequantizeLinear",[Vd,Wd]],["Div",[$i]],["Einsum",[Xu,Yu]],["Elu",[zl,Wn]],["Equal",[ou]],["Erf",[Bl]],["Exp",[Rl]],["Expand",[Zu]],["FastGelu",[ed]],["Floor",[jl]],["FusedConv",[Wi,Ni]],["Gather",[sd,rd]],["GatherElements",[Zi,id]],["GatherBlockQuantized",[Vc,nd]],["Gelu",[Nl]],["Gemm",[Hc,Kc]],["GlobalAveragePool",[Bd,zd]],["GlobalMaxPool",[jd,Rd]],["Greater",[lu]],["GreaterOrEqual",[du]],["GroupQueryAttention",[aa,gd]],["HardSigmoid",[Hl,Kl]],["InstanceNormalization",[Md]],["LayerNormalization",[Yc]],["LeakyRelu",[wi,Wn]],["Less",[uu]],["LessOrEqual",[ki]],["Log",[Jl]],["MatMul",[Eu]],["MatMulNBits",[Ed,da]],["MaxPool",[rp,ya]],["Mul",[iu]],["MultiHeadAttention",[ta,dd]],["Neg",[Vl]],["Not",[Ul]],["Pad",[Ad]],["Pow",[au]],["QuickGelu",[eu,Wn]],["Range",[Hd]],["Reciprocal",[Wl]],["ReduceMin",[li]],["ReduceMean",[al]],["ReduceMax",[dl]],["ReduceSum",[pl]],["ReduceProd",[cl]],["ReduceL1",[ll]],["ReduceL2",[ai]],["ReduceLogSum",[hl]],["ReduceLogSumExp",[ul]],["ReduceSumSquare",[ui]],["Relu",[Gl]],["Resize",[tr,uc]],["RotaryEmbedding",[hn]],["Sigmoid",[yi]],["Sin",[ql]],["Sinh",[Ql]],["Slice",[ft,bt]],["SkipLayerNormalization",[f]],["Split",[kr,Lr]],["Sqrt",[Mi]],["Softmax",[Gt,sr]],["Sub",[Si]],["Tan",[Xl]],["Tanh",[vi]],["ThresholdedRelu",[Yl,Wn]],["Tile",[md]],["Transpose",[Ba,Ra]],["Where",[In]]])}),ba,va=g(()=>{Et(),xe(),er(),ba=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,s,n){qe(e.programInfo.name);let i=this.backend.device,o=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}});n&&d.push({binding:d.length,resource:n});let p=i.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:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}o.setPipeline(e.computePipeline),o.setBindGroup(0,p),o.dispatchWorkgroups(...s),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(),ze(e.programInfo.name)}dispose(){}build(e,t){qe(e.name);let r=this.backend.device,s=[];r.features.has("shader-f16")&&s.push("enable f16;");let n=Jo(t,this.backend.device.limits),i=e.getShaderSource(n),o=`${s.join(` `)} ${n.additionalImplementations} ${i}`,d=r.createShaderModule({code:o,label:e.name});_r("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=r.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return ze(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:n.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=n&&r<=n&&s<=n)return[t,r,s];let i=t*r*s,o=Math.ceil(Math.sqrt(i));if(o>n){if(o=Math.ceil(Math.cbrt(i)),o>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),Ro,jo,Ar,Ur,mn=g(()=>{Et(),Ot(),xe(),K(),Jt(),Ws(),va(),Ro=(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 s=0;s{var n,i;let s=e.name;return(n=e.shaderCache)!=null&&n.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+r+`:${Ro(t,((i=e.shaderCache)==null?void 0:i.inputDependencies)??new Array(t.length).fill("dims"))}`,s},Ar=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ur=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=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(s),this.adapterInfo=new Ar(t.info||await t.requestAdapterInfo()),this.gpuDataManager=gr(this),this.programManager=new ba(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Sn(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;qe(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let n=0;n"u"&&(this.queryTimeBase=O);let B=Number(O-this.queryTimeBase),te=Number(L-this.queryTimeBase);if(!Number.isSafeInteger(B)||!Number.isSafeInteger(te))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:x.map(se=>({dims:se.dims,dataType:Es(se.dataType)})),outputsMetadata:l.map(se=>({dims:se.dims,dataType:Es(se.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:P,startTime:B,endTime:te});else{let se="";x.forEach((pe,ae)=>{se+=`input[${ae}]: [${pe.dims}] | ${Es(pe.dataType)}, `});let H="";l.forEach((pe,ae)=>{H+=`output[${ae}]: [${pe.dims}] | ${Es(pe.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${P}" ${se}${H}execution time: ${te-B} ns`)}et("GPU",`${P}::${O}::${L}`)}e.unmap(),this.pendingQueries.delete(e)}),ze()}run(e,t,r,s,n,i){qe(e.name);let o=[];for(let H=0;Hpe):r;if(P.length!==d.length)throw new Error(`Output size ${P.length} must be equal to ${d.length}.`);let x=[],l=[];for(let H=0;H=i)throw new Error(`Invalid output index: ${P[H]}`);if(P[H]===-3)continue;let pe=P[H]===-1,ae=P[H]===-2,ge=pe||ae?n(d[H].dataType,d[H].dims):s(P[H],d[H].dataType,d[H].dims);if(x.push(ge),ge.data===0)continue;let Ne=this.gpuDataManager.get(ge.data);if(!Ne)throw new Error(`no GPU data for output: ${ge.data}`);if(pe&&this.temporaryData.push(Ne),ae){let Fe=this.kernelPersistentData.get(this.currentKernelId);Fe||(Fe=[],this.kernelPersistentData.set(this.currentKernelId,Fe)),Fe.push(Ne)}l.push(Ne)}if(o.length!==t.length||l.length!==x.length){if(l.length===0)return ze(e.name),x;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let O;if(h){let H=0,pe=[];h.forEach(Fe=>{let rt=typeof Fe.data=="number"?[Fe.data]:Fe.data;if(rt.length===0)return;let vt=Fe.type===10?2:4,$t,Yt;Fe.type===10?(Yt=rt.length>4?16:rt.length>2?8:rt.length*vt,$t=rt.length>4?16:vt*rt.length):(Yt=rt.length<=2?rt.length*vt:16,$t=16),H=Math.ceil(H/Yt)*Yt,pe.push(H);let rr=Fe.type===10?8:4;H+=rt.length>4?Math.ceil(rt.length/rr)*$t:rt.length*vt});let ae=16;H=Math.ceil(H/ae)*ae;let ge=new ArrayBuffer(H);h.forEach((Fe,rt)=>{let vt=pe[rt],$t=typeof Fe.data=="number"?[Fe.data]:Fe.data;if(Fe.type===6)new Int32Array(ge,vt,$t.length).set($t);else if(Fe.type===12)new Uint32Array(ge,vt,$t.length).set($t);else if(Fe.type===10)new Uint16Array(ge,vt,$t.length).set($t);else if(Fe.type===1)new Float32Array(ge,vt,$t.length).set($t);else throw new Error(`Unsupported uniform type: ${Es(Fe.type)}`)});let Ne=this.gpuDataManager.create(H,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ne.buffer,0,ge,0,H),this.gpuDataManager.release(Ne.id),O={offset:0,size:H,buffer:Ne.buffer}}let L=this.programManager.normalizeDispatchGroupSize(p),B=L[1]===1&&L[2]===1,te=jo(e,t,B),se=this.programManager.getArtifact(te);if(se||(se=this.programManager.build(e,L),this.programManager.setArtifact(te,se),_r("info",()=>`[artifact] key: ${te}, programName: ${e.name}`)),h&&se.uniformVariablesInfo){if(h.length!==se.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${se.uniformVariablesInfo.length}, got ${h.length} in program "${se.programInfo.name}".`);for(let H=0;H`[ProgramManager] run "${e.name}" (key=${te}) with ${L[0]}x${L[1]}x${L[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let H={kernelId:this.currentKernelId,programName:se.programInfo.name,inputTensorViews:t,outputTensorViews:x};this.pendingKernels.push(H),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(H)}return this.programManager.run(se,o,l,L,O),ze(e.name),x}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,s){let n=_s.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let i={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],r]};this.kernels.set(t,i)}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 s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let n=s.kernelType,i=s.kernelName,o=s.kernelEntry,d=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${i}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),_r("info",()=>`[WebGPU] Start to run kernel "[${n}] ${i}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,d[1]),0}catch(h){return r.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${i}" failed. ${h}`)),1}finally{p&&r.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${n}] ${i}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let i=n.get(t),o=this.gpuDataManager.registerExternalBuffer(r,s,i);return n.set(t,[o,r]),o}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 s=await Tt(this,e,t);return T(s.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(){_r("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(){_r("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){_r("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 s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),fn,_n,eo,Ta,xa,hc=g(()=>{xe(),fn=1,_n=()=>fn++,eo=class{constructor(e,t){this.mlContext=e,this.tensorEntry=t,this.tensorCache=t?[t]:[]}get tensor(){var e;return(e=this.tensorEntry)==null?void 0:e[0]}get context(){if(!this.mlContext)throw new Error("MLContext has not been set.");return this.mlContext}set context(e){if(this.mlContext&&this.mlContext!==e)throw new Error("MLTensor in use in a different MLContext.");this.mlContext=e}destroy(){for(let[e]of this.tensorCache)e.destroy();this.tensorCache=[],this.tensorEntry=void 0}trySelectTensor(e,t){for(let[r,s,n]of this.tensorCache)if(t===r){if(this.context!==e)throw new Error("MLTensor cannot be registered with a different MLContext.");return this.tensorEntry=[r,s,n],!0}return!1}async ensureTensor(e,t,r){var i;if(this.tensorEntry){let[o,d,p]=this.tensorEntry;if(d===e&&p.every((h,P)=>h===t[P]))return o}for(let[o,d,p]of this.tensorCache)if(d===e&&p.every((h,P)=>h===t[P])){if(r&&this.tensorEntry){_r("verbose",()=>`[WebNN] Slowdown may occur, having to copy existing tensor {dataType: ${e}, shape: ${t}}`);let h=await this.context.readTensor(this.tensorEntry[0]);this.context.writeTensor(o,h)}return this.tensorEntry=[o,d,p],o}_r("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let s=MLTensorUsage.READ|MLTensorUsage.WRITE,n=await this.context.createTensor({dataType:e,shape:t,dimensions:t,usage:s});return this.tensorEntry=[n,e,t],this.tensorCache.push(this.tensorEntry),this.activeUpload&&((i=this.mlContext)==null||i.writeTensor(n,this.activeUpload),this.activeUpload=void 0),n}upload(e){var t;if(!this.tensorEntry){this.activeUpload=new Uint8Array(e);return}(t=this.mlContext)==null||t.writeTensor(this.tensorEntry[0],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.tensorEntry)throw new Error("Tensor has not been created.");return e?this.context.readTensor(this.tensorEntry[0],e):this.context.readTensor(this.tensorEntry[0])}},Ta=class{constructor(e){this.backend=e,this.tensorsById=new Map,this.tensorIdsByContext=new Map}reserveTensorId(){let e=_n();return this.tensorsById.set(e,new eo),e}releaseTensorId(e){let t=this.tensorsById.get(e);if(t){t.destroy(),this.tensorsById.delete(e);for(let[r,s]of this.tensorIdsByContext)if(s.has(e)){s.delete(e),s.size===0&&this.tensorIdsByContext.delete(r);break}}}async ensureTensor(e,t,r,s){var i;_r("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${s}}`);let n=this.tensorsById.get(e);if(!n)throw new Error("Tensor not found.");return n.context=this.backend.currentContext,this.tensorIdsByContext.has(this.backend.currentContext)||this.tensorIdsByContext.set(this.backend.currentContext,new Set),(i=this.tensorIdsByContext.get(this.backend.currentContext))==null||i.add(e),n.ensureTensor(t,r,s)}upload(e,t){this.tensorsById.get(e).upload(t)}async download(e,t){return _r("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`),this.tensorsById.get(e).download(t)}releaseTensorsForContext(e){let t=this.tensorIdsByContext.get(e);if(t){for(let r of t)this.tensorsById.get(r).destroy(),this.tensorsById.delete(r);this.tensorIdsByContext.delete(e)}}registerTensor(e,t,r,s){for(let[o,d]of this.tensorsById)if(d.trySelectTensor(e,t))return o;let n=_n();this.tensorsById.set(n,new eo(e,[t,r,s]));let i=this.tensorIdsByContext.get(e);return i||(i=new Set,this.tensorIdsByContext.set(e,i)),i.add(n),n}},xa=(...e)=>new Ta(...e)}),mc,Ea,Pa=g(()=>{Ot(),ts(),K(),hc(),xe(),mc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ea=class{constructor(e){this.tensorManager=xa(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,Sn(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}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.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&(this.sessionIdsByMLContext.delete(t),this.tensorManager.releaseTensorsForContext(t))}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){_r("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s){let n=mc.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,n,r,s)}uploadTensor(e,t){if(!Sr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");_r("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 T(r,t)}}registerMLTensor(e,t,r){let s=mc.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(this.currentContext,e,s,r);return _r("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${s}, dimensions: ${r}} -> {tensorId: ${n}}`),n}flush(){}}}),Ca={};v(Ca,{init:()=>Uo});var No,$a,Uo,Sp=g(()=>{Ot(),mn(),xe(),Ut(),Pa(),No=class Gm{constructor(t,r,s,n){this.module=t,this.dataType=r,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=De.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(De.size(t)!==De.size(this.dims))throw new Error("Invalid new shape");return new Gm(this.module,this.dataType,this.data,t)}},$a=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let s=e.HEAPU32,n=r>>>2;this.opKernelContext=s[n++];let i=s[n++];this.outputCount=s[n++],this.customDataOffset=s[n++],this.customDataSize=s[n++];let o=[];for(let d=0;dtypeof d=="number"?this.inputs[d]:d))??this.inputs,s=(t==null?void 0:t.outputs)??[],n=(d,p,h)=>new No(this.module,p,this.output(d,h),h),i=(d,p)=>{let h=js(d,p);if(!h)throw new Error(`Unsupported data type: ${d}`);let P=h>0?this.backend.gpuDataManager.create(h).id:0;return new No(this.module,d,P,p)};return this.backend.run(e,r,s,n,i,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let s=this.module.stackAlloc((1+t.length)*4),n=s>>2;this.module.HEAPU32[n++]=t.length;for(let i=0;i{let n=t.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new Ur;await i.initialize(r,s),n("webgpu",[i,o=>i.alloc(o),o=>i.free(o),(o,d,p,h=!1)=>{if(h)_r("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${o}, dst=${d}, size=${p}`),i.memcpy(o,d);else{_r("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${o}, gpuDataId=${d}, size=${p}`);let P=t.HEAPU8.subarray(o>>>0,(o>>>0)+p);i.upload(d,P)}},async(o,d,p)=>{_r("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${d}, size=${p}`),await i.download(o,()=>t.HEAPU8.subarray(d>>>0,(d>>>0)+p))},(o,d,p)=>i.createKernel(o,d,p,t.UTF8ToString(t._JsepGetNodeName(d))),o=>i.releaseKernel(o),(o,d,p,h)=>{_r("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${d}`);let P=new $a(t,i,d);return i.computeKernel(o,P,h)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new Ea(r);n("webnn",[i,()=>i.reserveTensorId(),o=>i.releaseTensorId(o),async(o,d,p,h)=>i.ensureTensor(o,d,p,h),(o,d)=>{i.uploadTensor(o,d)},async(o,d)=>i.downloadTensor(o,d)])}}}),ap,fc,an,Zr,dh,lp,kp,Ap,Ip,Fp,Op,Dp,ch=g(()=>{uo(),co(),Ot(),ts(),Tn(),Rn(),ap=(e,t)=>{Sr()._OrtInit(e,t)!==0&&br("Can't initialize onnxruntime.")},fc=async e=>{ap(e.wasm.numThreads,dn(e.logLevel))},an=async(e,t)=>{{let r=(Sp(),y(Ca)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:i}),!s)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",Sr(),e,s)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Sr(),e)}}},Zr=new Map,dh=e=>{let t=Sr(),r=t.stackSave();try{let s=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,s,s+4)!==0&&br("Can't get session input/output count."),[t.HEAP32[s/4],t.HEAP32[s/4+1]]}finally{t.stackRestore(r)}},lp=e=>{let t=Sr(),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]},kp=async(e,t)=>{var x,l;let r,s,n=Sr();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=lp(e);let i=0,o=0,d=0,p=[],h=[],P=[];try{if([o,p]=Bn(t),(t==null?void 0:t.externalData)&&n.mountExternalData){let ae=[];for(let ge of t.externalData){let Ne=typeof ge=="string"?ge:ge.path;ae.push(Cn(typeof ge=="string"?ge:ge.data).then(Fe=>{n.mountExternalData(Ne,Fe)}))}await Promise.all(ae)}for(let ae of(t==null?void 0:t.executionProviders)??[])if((typeof ae=="string"?ae:ae.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,n.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ae!="string"){let ge=ae,Ne=ge==null?void 0:ge.context,Fe=ge==null?void 0:ge.gpuDevice,rt=ge==null?void 0:ge.deviceType,vt=ge==null?void 0:ge.numThreads,$t=ge==null?void 0:ge.powerPreference;Ne?n.currentContext=Ne:Fe?n.currentContext=await navigator.ml.createContext(Fe):n.currentContext=await navigator.ml.createContext({deviceType:rt,numThreads:vt,powerPreference:$t})}else n.currentContext=await navigator.ml.createContext();break}i=await n._OrtCreateSession(r,s,o),i===0&&br("Can't create a session."),n.currentContext&&(n.jsepRegisterMLContext(i,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[O,L]=dh(i),B=!!(t!=null&&t.enableGraphCapture),te=[],se=[],H=[];for(let ae=0;aeae==="gpu-buffer"||ae==="ml-tensor")&&(d=n._OrtCreateBinding(i),d===0&&br("Can't create IO binding."),pe={handle:d,outputPreferredLocations:H,outputPreferredLocationsEncoded:H.map(ae=>Pn(ae))}),Zr.set(i,[i,h,P,pe,B,!1]),[i,te,se]}catch(O){throw h.forEach(L=>n._OrtFree(L)),P.forEach(L=>n._OrtFree(L)),d!==0&&n._OrtReleaseBinding(d),i!==0&&n._OrtReleaseSession(i),O}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o),p.forEach(O=>n._free(O)),(l=n.unmountExternalData)==null||l.call(n)}},Ap=e=>{var p;let t=Sr(),r=Zr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,i,o,d]=r;o&&(d&&t._OrtClearBoundOutputs(o.handle),t._OrtReleaseBinding(o.handle)),(p=t.jsepOnReleaseSession)==null||p.call(t,e),n.forEach(h=>t._OrtFree(h)),i.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(s),Zr.delete(e)},Ip=(e,t,r,s,n,i=!1)=>{if(!e){t.push(0);return}let o=Sr(),d=e[0],p=e[1],h=e[3],P,x;if(d==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let L=e[2].gpuBuffer;x=js(rn(d),p);let B=o.jsepRegisterBuffer;if(!B)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');P=B(s,n,L,x)}else if(h==="ml-tensor"){let L=e[2].mlTensor;x=js(rn(d),p);let B=o.jsepRegisterMLTensor;if(!B)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');P=B(L,rn(d),p)}else{let L=e[2];if(Array.isArray(L)){x=4*L.length,P=o._malloc(x),r.push(P);let B=P/4;for(let te=0;teo.HEAP32[L++]=te);let B=o._OrtCreateTensor(rn(d),P,x,O,p.length,Pn(h));B===0&&br(`Can't create tensor for input/output. session=${s}, index=${n}.`),t.push(B)}finally{o.stackRestore(l)}},Fp=async(e,t,r,s,n,i)=>{var $t,Yt;let o=Sr(),d=Zr.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=d[0],h=d[1],P=d[2],x=d[3],l=d[4],O=d[5],L=t.length,B=s.length,te=0,se=[],H=[],pe=[],ae=[],ge=o.stackSave(),Ne=o.stackAlloc(L*4),Fe=o.stackAlloc(L*4),rt=o.stackAlloc(B*4),vt=o.stackAlloc(B*4);try{($t=o.jsepOnRunStart)==null||$t.call(o,p),[te,se]=tn(i);for(let Ft=0;Ftes*ds,1);Vt=Es(Qr);let Go=x==null?void 0:x.outputPreferredLocations[s[Ft]];if(Vt==="string"){if(Go==="gpu-buffer"||Go==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let es=[],ds=xr/4;for(let Gs=0;Gs0){let es=o.jsepGetBuffer;if(!es)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ds=es(xr),Gs=js(Qr,is);if(Gs===void 0||!xn(Vt))throw new Error(`Unsupported data type: ${Vt}`);ct=!0,Er.push([Vt,bs,{gpuBuffer:ds,download:o.jsepCreateDownloader(ds,Gs,Vt),dispose:()=>{o._OrtReleaseTensor(Nt)}},"gpu-buffer"])}else if(Go==="ml-tensor"&&is>0){let es=o.jsepEnsureTensor;if(!es)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(js(Qr,is)===void 0||!En(Vt))throw new Error(`Unsupported data type: ${Vt}`);let ds=await es(xr,Qr,bs,!1);ct=!0,Er.push([Vt,bs,{mlTensor:ds,download:o.jsepCreateMLTensorDownloader(xr,Vt),dispose:()=>{o.jsepReleaseTensorId(xr),o._OrtReleaseTensor(Nt)}},"ml-tensor"])}else{let es=Ns(Vt),ds=new es(is);new Uint8Array(ds.buffer,ds.byteOffset,ds.byteLength).set(o.HEAPU8.subarray(xr,xr+ds.byteLength)),Er.push([Vt,bs,ds,"cpu"])}}finally{o.stackRestore(hr),Vt==="string"&&xr&&o._free(xr),ct||o._OrtReleaseTensor(Nt)}}return x&&!l&&(o._OrtClearBoundOutputs(x.handle),Zr.set(e,[p,h,P,x,l,!1])),Er}finally{o.stackRestore(ge),H.forEach(rr=>o._OrtReleaseTensor(rr)),pe.forEach(rr=>o._OrtReleaseTensor(rr)),ae.forEach(rr=>o._free(rr)),te!==0&&o._OrtReleaseRunOptions(te),se.forEach(rr=>o._free(rr))}},Op=e=>{let t=Sr(),r=Zr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&br("Can't get an profile file name."),t._OrtFree(n)},Dp=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),to,ks,Sa,_c,gc,up,Lp,dp,Vo,Wo,ph,hh,mh,fh,_h,gh,wh,yh,Mh=g(()=>{Et(),ch(),ts(),zs(),to=()=>!!E.wasm.proxy&&typeof document<"u",Sa=!1,_c=!1,gc=!1,dp=new Map,Vo=(e,t)=>{let r=dp.get(e);r?r.push(t):dp.set(e,[t])},Wo=()=>{if(Sa||!_c||gc||!ks)throw new Error("worker not ready")},ph=e=>{switch(e.data.type){case"init-wasm":Sa=!1,e.data.err?(gc=!0,Lp[1](e.data.err)):(_c=!0,Lp[0]()),up&&(URL.revokeObjectURL(up),up=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=dp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},hh=async()=>{if(!_c){if(Sa)throw new Error("multiple calls to 'initWasm()' detected.");if(gc)throw new Error("previous call to 'initWasm()' failed.");if(Sa=!0,to())return new Promise((e,t)=>{ks==null||ks.terminate(),xs().then(([r,s])=>{try{ks=s,ks.onerror=i=>t(i),ks.onmessage=ph,Lp=[e,t];let n={type:"init-wasm",in:E};ks.postMessage(n),up=r}catch(n){t(n)}},t)});try{await Bs(E.wasm),await fc(E),_c=!0}catch(e){throw gc=!0,e}finally{Sa=!1}}},mh=async e=>{if(to())return Wo(),new Promise((t,r)=>{Vo("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:E}};ks.postMessage(s)});await an(E,e)},fh=async e=>to()?(Wo(),new Promise((t,r)=>{Vo("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};ks.postMessage(s,[e.buffer])})):lp(e),_h=async(e,t)=>{if(to()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wo(),new Promise((r,s)=>{Vo("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),ks.postMessage(n,i)})}else return kp(e,t)},gh=async e=>{if(to())return Wo(),new Promise((t,r)=>{Vo("release",[t,r]);let s={type:"release",in:e};ks.postMessage(s)});Ap(e)},wh=async(e,t,r,s,n,i)=>{if(to()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wo(),new Promise((o,d)=>{Vo("run",[o,d]);let p=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:s,options:i}};ks.postMessage(h,Dp(p))})}else return Fp(e,t,r,s,n,i)},yh=async e=>{if(to())return Wo(),new Promise((t,r)=>{Vo("end-profiling",[t,r]);let s={type:"end-profiling",in:e};ks.postMessage(s)});Op(e)}}),zp,bh,vh,af=g(()=>{Et(),Mh(),Ot(),Ct(),Rn(),zp=(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 we(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!xn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return we.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}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:s,dispose:n}=e[2];return we.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},vh=class{async fetchModelAndCopyToWasmMemory(e){return fh(await Cn(e))}async loadModel(e,t){qe();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await _h(r,t),ze()}async dispose(){return gh(this.sessionId)}async run(e,t,r){qe();let s=[],n=[];Object.entries(e).forEach(x=>{let l=x[0],O=x[1],L=this.inputNames.indexOf(l);if(L===-1)throw new Error(`invalid input '${l}'`);s.push(O),n.push(L)});let i=[],o=[];Object.entries(t).forEach(x=>{let l=x[0],O=x[1],L=this.outputNames.indexOf(l);if(L===-1)throw new Error(`invalid output '${l}'`);i.push(O),o.push(L)});let d=s.map((x,l)=>zp(x,()=>`input "${this.inputNames[n[l]]}"`)),p=i.map((x,l)=>x?zp(x,()=>`output "${this.outputNames[o[l]]}"`):null),h=await wh(this.sessionId,n,d,o,p,r),P={};for(let x=0;xRp,initializeFlags:()=>Bp,wasmBackend:()=>xh});var Bp,Rp,xh,lf=g(()=>{Et(),Mh(),af(),zs(),Bp=()=>{if((typeof E.wasm.initTimeout!="number"||E.wasm.initTimeout<0)&&(E.wasm.initTimeout=0),E.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 E.wasm.proxy!="boolean"&&(E.wasm.proxy=!1),typeof E.wasm.trace!="boolean"&&(E.wasm.trace=!1),typeof E.wasm.numThreads!="number"||!Number.isInteger(E.wasm.numThreads)||E.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)E.wasm.numThreads=1;else{let e=typeof navigator>"u"?Q("node:os").cpus().length:navigator.hardwareConcurrency;E.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Rp=class{async init(e){Bp(),await hh(),await mh(e)}async createInferenceSessionHandler(e,t){let r=new vh;return await r.loadModel(e,t),Promise.resolve(r)}},xh=new Rp});Et(),Et(),Et();var uf="1.20.1",df=xt;{let e=(lf(),y(Th)).wasmBackend;J("webgpu",e,5),J("webnn",e,5),J("cpu",e,10),J("wasm",e,10)}Object.defineProperty(E.versions,"web",{value:uf,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":(Oe,R,c)=>{var w;c.r(R),c.d(R,{Tensor:()=>Q.Tensor,createInferenceSession:()=>fe,deviceToExecutionProviders:()=>J,isONNXProxy:()=>Z,isONNXTensor:()=>j});var z=c("./src/env.js"),G=c("?2ce3"),re=c("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Q=c("./node_modules/onnxruntime-common/dist/esm/index.js");const g=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 M,y;const C=Symbol.for("onnxruntime");if(C in globalThis)y=globalThis[C];else if(z.apis.IS_NODE_ENV){switch(y=G??(w||(w=c.t(G,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),M=["cpu"]}else y=re,z.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),z.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),M=["wasm"];const q=y.InferenceSession;function J(N=null){if(!N)return M;switch(N){case"auto":return v;case"gpu":return v.filter(I=>["webgpu","cuda","dml","webnn-gpu"].includes(I))}if(v.includes(N))return[g[N]??N];throw new Error(`Unsupported device: "${N}". Should be one of: ${v.join(", ")}.`)}let ie=null;async function fe(N,I,_){ie&&await ie;const k=q.create(N,I);ie??(ie=k);const E=await k;return E.config=_,E}function j(N){return N instanceof y.Tensor}const X=y==null?void 0:y.env;X!=null&&X.wasm&&(X.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${z.env.version}/dist/`,X.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(X.wasm.numThreads=1)),X!=null&&X.webgpu&&(X.webgpu.powerPreference="high-performance");function Z(){var N;return(N=X==null?void 0:X.wasm)==null?void 0:N.proxy}z.env.backends.onnx=X},"./src/base/feature_extraction_utils.js":(Oe,R,c)=>{c.r(R),c.d(R,{FeatureExtractor:()=>re,validate_audio_inputs:()=>Q});var w=c("./src/utils/constants.js"),z=c("./src/utils/generic.js"),G=c("./src/utils/hub.js");class re extends z.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,M){const y=await(0,G.getModelJSON)(v,w.FEATURE_EXTRACTOR_NAME,!0,M);return new this(y)}}function Q(g,v){var M;if(!(g instanceof Float32Array||g instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((M=g==null?void 0:g.constructor)==null?void 0:M.name)??typeof g} 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":(Oe,R,c)=>{c.r(R),c.d(R,{ImageProcessor:()=>N,post_process_instance_segmentation:()=>Z,post_process_object_detection:()=>C,post_process_panoptic_segmentation:()=>X,post_process_semantic_segmentation:()=>q});var w=c("./src/utils/generic.js"),z=c("./src/utils/tensor.js"),G=c("./src/utils/maths.js");c("./src/utils/image.js");var re=c("./src/utils/core.js"),Q=c("./src/utils/hub.js"),g=c("./src/utils/constants.js");function v(I,_,k=0,E=null){const ee=I/_;let Y=(0,G.bankers_round)(ee)*_;return E!==null&&Y>E&&(Y=Math.floor(ee)*_),Y_&&Re.push(Ye)}else{let Ye=(0,G.max)(ke.data)[1];if(Ye===ye-1||(Ke=(0,G.softmax)(ke.data),Ke[Ye]<_))continue;Re.push(Ye)}for(const Ye of Re){let at=ce[he].data;at=y(at),Le!==null&&(at=at.map((We,le)=>We*Le[(le+1)%2])),_e.boxes.push(at),_e.classes.push(Ye),_e.scores.push(Ke[Ye])}}Ce.push(_e)}return Ce}function q(I,_=null){const k=I.logits,E=k.dims[0];if(_!==null&&_.length!==E)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ee=[];for(let Y=0;YLe[Re]&&(Le[Re]=ke[Re],_e[Re]=he)}const U=new Array(me.dims[0]);for(let he=0;he<_e.length;++he){const ke=_e[he];U[ke]=ke}const ce=U.filter(he=>he!==void 0);ee.push({segmentation:Ee,labels:ce})}return ee}function J(I,_,k,E){const ee=[],Y=[],de=[];for(let me=0;mek&&(ee.push(Ce),Y.push(_e),de.push(Ee))}return[ee,Y,de]}function ie(I,_,k,E=.5,ee=.8){const Y=[];let de=0,me=0;const ye=_[k].data;for(let Ee=0;Ee=E&&++me;let Ce=de>0&&me>0;return Ce&&(Ce=de/me>ee),[Ce,Y]}function fe(I,_,k,E,ee,Y=null,de=null){const[me,ye]=de??I[0].dims,Ce=new z.Tensor("int32",new Int32Array(me*ye),[me,ye]),Ee=[];if(de!==null)for(let he=0;he_e[Ke]&&(Le[Ke]=he,_e[Ke]=Re[Ke])}let U=0;const ce=Ce.data;for(let he=0;he200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(I,_)/Math.min(I,_)}`);let Y=Math.round(I/k)*k,de=Math.round(_/k)*k;if(Y*de>ee){const me=Math.sqrt(I*_/ee);Y=Math.floor(I/me/k)*k,de=Math.floor(_/me/k)*k}else if(Y*deY?Ce=Math.floor(Y*ye/ee):Y>ee&&(ye=Math.floor(ee*Ce/Y)),await _.resize(Ce,ye,{resample:E}))}async crop_margin(_,k=200){const E=_.clone().grayscale(),ee=(0,G.min)(E.data)[0],de=(0,G.max)(E.data)[0]-ee;if(de===0)return _;const me=k/255;let ye=E.width,Ce=E.height,Ee=0,Le=0;const _e=E.data;for(let U=0;Uthis.preprocess(Y)));return{pixel_values:(0,z.stack)(E.map(Y=>Y.pixel_values),0),original_sizes:E.map(Y=>Y.original_size),reshaped_input_sizes:E.map(Y=>Y.reshaped_input_size)}}static async from_pretrained(_,k){const E=await(0,Q.getModelJSON)(_,g.IMAGE_PROCESSOR_NAME,!0,k);return new this(E)}}},"./src/base/processing_utils.js":(Oe,R,c)=>{c.r(R),c.d(R,{Processor:()=>re});var w=c("./src/utils/constants.js"),z=c("./src/utils/generic.js"),G=c("./src/utils/hub.js");class re extends z.Callable{constructor(g,v){super(),this.config=g,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(g,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(g,{tokenize:!1,...v})}batch_decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...g)}async _call(g,...v){for(const M of[this.image_processor,this.feature_extractor,this.tokenizer])if(M)return M(g,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(g,v){const[M,y]=await Promise.all([this.uses_processor_config?(0,G.getModelJSON)(g,w.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(C=>C in this).map(async C=>{const q=await this[C].from_pretrained(g,v);return[C.replace(/_class$/,""),q]})).then(Object.fromEntries)]);return new this(M,y)}}ve(re,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),ve(re,"uses_processor_config",!1)},"./src/configs.js":(Oe,R,c)=>{c.r(R),c.d(R,{AutoConfig:()=>v,PretrainedConfig:()=>g,getKeyValueShapes:()=>Q});var w=c("./src/utils/core.js"),z=c("./src/utils/hub.js");async function G(M,y){return await(0,z.getModelJSON)(M,"config.json",!0,y)}function re(M){const y={};let C={};switch(M.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":C=re(M.text_config);break;case"moondream1":C=re(M.phi_config);break;case"musicgen":C=re(M.decoder);break;case"multi_modality":C=re(M.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size";break;case"llama":case"olmo":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size",y.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.dim_kv="head_dim";break;case"openelm":y.num_heads="num_kv_heads",y.num_layers="num_transformer_layers",y.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":y.num_heads="num_heads",y.num_layers="num_layers",y.hidden_size="hidden_size";break;case"bloom":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="hidden_size";break;case"mpt":y.num_heads="n_heads",y.num_layers="n_layers",y.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":y.num_decoder_layers="num_decoder_layers",y.num_decoder_heads="num_heads",y.decoder_dim_kv="d_kv",y.num_encoder_layers="num_layers",y.num_encoder_heads="num_heads",y.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":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="d_model",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="d_model";break;case"speecht5":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="hidden_size",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="hidden_size";break;case"trocr":y.num_encoder_layers=y.num_decoder_layers="decoder_layers",y.num_encoder_heads=y.num_decoder_heads="decoder_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="d_model";break;case"musicgen_decoder":y.num_encoder_layers=y.num_decoder_layers="num_hidden_layers",y.num_encoder_heads=y.num_decoder_heads="num_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const J=re(M.decoder),ie="num_decoder_layers"in J,fe=(0,w.pick)(M,["model_type","is_encoder_decoder"]);return ie?(fe.num_decoder_layers=J.num_decoder_layers,fe.num_decoder_heads=J.num_decoder_heads,fe.decoder_hidden_size=J.decoder_hidden_size,fe.num_encoder_layers=J.num_encoder_layers,fe.num_encoder_heads=J.num_encoder_heads,fe.encoder_hidden_size=J.encoder_hidden_size):(fe.num_layers=J.num_layers,fe.num_heads=J.num_heads,fe.hidden_size=J.hidden_size),fe}const q={...C,...(0,w.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const J in y)q[J]=M[y[J]];return q}function Q(M,{prefix:y="past_key_values",batch_size:C=1}={}){const q={},J=M.normalized_config;if(J.is_encoder_decoder&&"num_encoder_heads"in J&&"num_decoder_heads"in J){const ie=J.encoder_dim_kv??J.encoder_hidden_size/J.num_encoder_heads,fe=J.decoder_dim_kv??J.decoder_hidden_size/J.num_decoder_heads,j=[C,J.num_encoder_heads,0,ie],X=[C,J.num_decoder_heads,0,fe];for(let Z=0;Z{var E,ee;c.r(R),c.d(R,{apis:()=>fe,env:()=>_});var w=c("?569f"),z=c("?3f59"),G=c("?154a");const re="3.1.1",Q=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((E=self.constructor)==null?void 0:E.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,C=typeof process<"u",q=C&&((ee=process==null?void 0:process.release)==null?void 0:ee.name)==="node",J=!k(w),ie=!k(z),fe=Object.freeze({IS_BROWSER_ENV:Q,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:C,IS_NODE_ENV:q,IS_FS_AVAILABLE:J,IS_PATH_AVAILABLE:ie}),j=J&&ie;let X="./";if(j){const Y=Object({url:self.location.href}).url;Y?X=z.dirname(z.dirname(G.fileURLToPath(Y))):typeof __dirname<"u"&&(X=z.dirname(__dirname))}const Z=j?z.join(X,"/.cache/"):null,N="/models/",I=j?z.join(X,N):N,_={version:re,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Q||g),localModelPath:I,useFS:J,useBrowserCache:v,useFSCache:J,cacheDir:Z,useCustomCache:!1,customCache:null};function k(Y){return Object.keys(Y).length===0}},"./src/generation/configuration_utils.js":(Oe,R,c)=>{c.r(R),c.d(R,{GenerationConfig:()=>z});var w=c("./src/utils/core.js");class z{constructor(re){ve(this,"max_length",20);ve(this,"max_new_tokens",null);ve(this,"min_length",0);ve(this,"min_new_tokens",null);ve(this,"early_stopping",!1);ve(this,"max_time",null);ve(this,"do_sample",!1);ve(this,"num_beams",1);ve(this,"num_beam_groups",1);ve(this,"penalty_alpha",null);ve(this,"use_cache",!0);ve(this,"temperature",1);ve(this,"top_k",50);ve(this,"top_p",1);ve(this,"typical_p",1);ve(this,"epsilon_cutoff",0);ve(this,"eta_cutoff",0);ve(this,"diversity_penalty",0);ve(this,"repetition_penalty",1);ve(this,"encoder_repetition_penalty",1);ve(this,"length_penalty",1);ve(this,"no_repeat_ngram_size",0);ve(this,"bad_words_ids",null);ve(this,"force_words_ids",null);ve(this,"renormalize_logits",!1);ve(this,"constraints",null);ve(this,"forced_bos_token_id",null);ve(this,"forced_eos_token_id",null);ve(this,"remove_invalid_values",!1);ve(this,"exponential_decay_length_penalty",null);ve(this,"suppress_tokens",null);ve(this,"streamer",null);ve(this,"begin_suppress_tokens",null);ve(this,"forced_decoder_ids",null);ve(this,"guidance_scale",null);ve(this,"num_return_sequences",1);ve(this,"output_attentions",!1);ve(this,"output_hidden_states",!1);ve(this,"output_scores",!1);ve(this,"return_dict_in_generate",!1);ve(this,"pad_token_id",null);ve(this,"bos_token_id",null);ve(this,"eos_token_id",null);ve(this,"encoder_no_repeat_ngram_size",0);ve(this,"decoder_start_token_id",null);ve(this,"generation_kwargs",{});Object.assign(this,(0,w.pick)(re,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Oe,R,c)=>{c.r(R),c.d(R,{ClassifierFreeGuidanceLogitsProcessor:()=>j,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>G,LogitsProcessorList:()=>Q,LogitsWarper:()=>re,MinLengthLogitsProcessor:()=>J,MinNewTokensLengthLogitsProcessor:()=>ie,NoBadWordsLogitsProcessor:()=>fe,NoRepeatNGramLogitsProcessor:()=>C,RepetitionPenaltyLogitsProcessor:()=>q,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>X,TopKLogitsWarper:()=>N,TopPLogitsWarper:()=>Z,WhisperTimeStampLogitsProcessor:()=>y});var w=c("./src/utils/generic.js");c("./src/utils/tensor.js");var z=c("./src/utils/maths.js");class G extends w.Callable{_call(_,k){throw Error("`_call` should be implemented in a subclass")}}class re extends w.Callable{_call(_,k){throw Error("`_call` should be implemented in a subclass")}}class Q extends w.Callable{constructor(){super(),this.processors=[]}push(_){this.processors.push(_)}extend(_){this.processors.push(..._)}_call(_,k){let E=k;for(const ee of this.processors)E=ee(_,E);return E}[Symbol.iterator](){return this.processors.values()}}class g extends G{constructor(_){super(),this.bos_token_id=_}_call(_,k){for(let E=0;E<_.length;++E)if(_[E].length===1){const ee=k[E].data;ee.fill(-1/0),ee[this.bos_token_id]=0}return k}}class v extends G{constructor(_,k){super(),this.max_length=_,this.eos_token_id=Array.isArray(k)?k:[k]}_call(_,k){for(let E=0;E<_.length;++E)if(_[E].length===this.max_length-1){const ee=k[E].data;ee.fill(-1/0);for(const Y of this.eos_token_id)ee[Y]=0}return k}}class M extends G{constructor(_,k){super(),this.begin_suppress_tokens=_,this.begin_index=k}_call(_,k){for(let E=0;E<_.length;++E)if(_[E].length===this.begin_index){const ee=k[E].data;for(const Y of this.begin_suppress_tokens)ee[Y]=-1/0}return k}}class y extends G{constructor(_,k){super(),this.eos_token_id=Array.isArray(_.eos_token_id)?_.eos_token_id[0]:_.eos_token_id,this.no_timestamps_token_id=_.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=k.length,k.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=_.max_initial_timestamp_index}_call(_,k){for(let E=0;E<_.length;++E){const ee=k[E].data;if(ee[this.no_timestamps_token_id]=-1/0,_[E].length===this.begin_index-1){ee.fill(-1/0),ee[this.timestamp_begin]=0;continue}const Y=_[E].slice(this.begin_index),de=Y.length>=1&&Y[Y.length-1]>=this.timestamp_begin,me=Y.length<2||Y[Y.length-2]>=this.timestamp_begin;if(de&&(me?ee.subarray(this.timestamp_begin).fill(-1/0):ee.subarray(0,this.eos_token_id).fill(-1/0)),_[E].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 ye=(0,z.log_softmax)(ee),Ce=Math.log(ye.subarray(this.timestamp_begin).map(Math.exp).reduce((Le,_e)=>Le+_e)),Ee=(0,z.max)(ye.subarray(0,this.timestamp_begin))[0];Ce>Ee&&ee.subarray(0,this.timestamp_begin).fill(-1/0)}return k}}class C extends G{constructor(_){super(),this.no_repeat_ngram_size=_}getNgrams(_){const k=_.length,E=[];for(let Y=0;Y1 to use the classifier free guidance processor, got guidance scale ${_}.`);this.guidance_scale=_}_call(_,k){if(k.dims[0]!==2*_.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 ${k.dims[0]} for the logits and ${_.length} for the input ids.`);const E=_.length,ee=k.slice([0,E],null),Y=k.slice([E,k.dims[0]],null);for(let de=0;de1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${_}`);if(!Number.isInteger(E)||E<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${E}`);this.top_p=_,this.filter_value=k,this.min_tokens_to_keep=E}}class N extends re{constructor(_,{filter_value:k=-1/0,min_tokens_to_keep:E=1}={}){if(super(),!Number.isInteger(_)||_<0)throw new Error(`\`top_k\` must be a positive integer, but is ${_}`);this.top_k=Math.max(_,E),this.filter_value=k}}},"./src/generation/logits_sampler.js":(Oe,R,c)=>{c.r(R),c.d(R,{LogitsSampler:()=>re});var w=c("./src/utils/generic.js"),z=c("./src/utils/tensor.js"),G=c("./src/utils/maths.js");c("./src/generation/configuration_utils.js");class re extends w.Callable{constructor(y){super(),this.generation_config=y}async _call(y){return this.sample(y)}async sample(y){throw Error("sample should be implemented in subclasses.")}getLogits(y,C){let q=y.dims.at(-1),J=y.data;if(C===-1)J=J.slice(-q);else{let ie=C*q;J=J.slice(ie,ie+q)}return J}randomSelect(y){let C=0;for(let J=0;J1)return new v(y);if(y.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${y.num_return_sequences}.`);return new Q(y)}}class Q extends re{async sample(y){const C=(0,G.max)(y.data)[1];return[[BigInt(C),0]]}}class g extends re{async sample(y){let C=y.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[q,J]=await(0,z.topk)(y,C),ie=(0,G.softmax)(q.data);return Array.from({length:this.generation_config.num_beams},()=>{const fe=this.randomSelect(ie);return[J.data[fe],Math.log(ie[fe])]})}}class v extends re{async sample(y){let C=y.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[q,J]=await(0,z.topk)(y,C),ie=(0,G.softmax)(q.data);return Array.from({length:this.generation_config.num_beams},(fe,j)=>[J.data[j],Math.log(ie[j])])}}},"./src/generation/stopping_criteria.js":(Oe,R,c)=>{c.r(R),c.d(R,{EosTokenCriteria:()=>Q,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>re,StoppingCriteria:()=>z,StoppingCriteriaList:()=>G});var w=c("./src/utils/generic.js");class z extends w.Callable{_call(M,y){throw Error("StoppingCriteria needs to be subclassed")}}class G extends w.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof G?M=M.criteria:M instanceof z&&(M=[M]),this.criteria.push(...M)}_call(M,y){const C=new Array(M.length).fill(!1);for(const q of this.criteria){const J=q(M,y);for(let ie=0;iey.length>=this.max_length)}}class Q extends z{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,y){return M.map(C=>{const q=C.at(-1);return this.eos_token_id.some(J=>q==J)})}}class g extends z{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,y){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Oe,R,c)=>{c.r(R),c.d(R,{BaseStreamer:()=>re,TextStreamer:()=>g,WhisperTextStreamer:()=>v});var w=c("./src/utils/core.js"),z=c("./src/tokenizers.js"),G=c("./src/env.js");class re{put(y){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Q=G.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class g extends re{constructor(y,{skip_prompt:C=!1,callback_function:q=null,token_callback_function:J=null,decode_kwargs:ie={},...fe}={}){super(),this.tokenizer=y,this.skip_prompt=C,this.callback_function=q??Q,this.token_callback_function=J,this.decode_kwargs={...ie,...fe},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var ie;if(y.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 C=y[0];(ie=this.token_callback_function)==null||ie.call(this,C),this.token_cache=(0,w.mergeArrays)(this.token_cache,C);const q=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let J;q.endsWith(` `)?(J=q.slice(this.print_len),this.token_cache=[],this.print_len=0):q.length>0&&(0,z.is_chinese_char)(q.charCodeAt(q.length-1))?(J=q.slice(this.print_len),this.print_len+=J.length):(J=q.slice(this.print_len,q.lastIndexOf(" ")+1),this.print_len+=J.length),this.on_finalized_text(J,!1)}end(){let y;this.token_cache.length>0?(y=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):y="",this.next_tokens_are_prompt=!0,this.on_finalized_text(y,!0)}on_finalized_text(y,C){var q,J;y.length>0&&((q=this.callback_function)==null||q.call(this,y)),C&&this.callback_function===Q&&G.apis.IS_PROCESS_AVAILABLE&&((J=this.callback_function)==null||J.call(this,` `))}}class v extends g{constructor(y,{skip_prompt:C=!1,callback_function:q=null,token_callback_function:J=null,on_chunk_start:ie=null,on_chunk_end:fe=null,on_finalize:j=null,time_precision:X=.02,skip_special_tokens:Z=!0,decode_kwargs:N={}}={}){super(y,{skip_prompt:C,callback_function:q,token_callback_function:J,decode_kwargs:{skip_special_tokens:Z,...N}}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=ie,this.on_chunk_end=fe,this.on_finalize=j,this.time_precision=X,this.waiting_for_timestamp=!1}put(y){var q,J;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const C=y[0];if(C.length===1){const ie=Number(C[0])-this.timestamp_begin;if(ie>=0){const fe=ie*this.time_precision;this.waiting_for_timestamp?(q=this.on_chunk_end)==null||q.call(this,fe):(J=this.on_chunk_start)==null||J.call(this,fe),this.waiting_for_timestamp=!this.waiting_for_timestamp,y=[[]]}}return super.put(y)}end(){var y;super.end(),(y=this.on_finalize)==null||y.call(this)}}},"./src/models.js":(Oe,R,c)=>{c.r(R),c.d(R,{ASTForAudioClassification:()=>Da,ASTModel:()=>Yo,ASTPreTrainedModel:()=>kt,AlbertForMaskedLM:()=>Nn,AlbertForQuestionAnswering:()=>jn,AlbertForSequenceClassification:()=>Rn,AlbertModel:()=>Cn,AlbertPreTrainedModel:()=>Ot,AutoModel:()=>ya,AutoModelForAudioClassification:()=>ec,AutoModelForAudioFrameClassification:()=>rc,AutoModelForCTC:()=>Zd,AutoModelForCausalLM:()=>Wd,AutoModelForDepthEstimation:()=>oc,AutoModelForDocumentQuestionAnswering:()=>sc,AutoModelForImageClassification:()=>Hd,AutoModelForImageFeatureExtraction:()=>lc,AutoModelForImageMatting:()=>nc,AutoModelForImageSegmentation:()=>op,AutoModelForImageToImage:()=>Ma,AutoModelForMaskGeneration:()=>Jd,AutoModelForMaskedLM:()=>np,AutoModelForNormalEstimation:()=>ic,AutoModelForObjectDetection:()=>Xd,AutoModelForPoseEstimation:()=>ac,AutoModelForQuestionAnswering:()=>Gd,AutoModelForSemanticSegmentation:()=>qd,AutoModelForSeq2SeqLM:()=>sp,AutoModelForSequenceClassification:()=>Rd,AutoModelForSpeechSeq2Seq:()=>Nd,AutoModelForTextToSpectrogram:()=>Ud,AutoModelForTextToWaveform:()=>Vd,AutoModelForTokenClassification:()=>jd,AutoModelForUniversalSegmentation:()=>Qd,AutoModelForVision2Seq:()=>Kd,AutoModelForXVector:()=>tc,AutoModelForZeroShotObjectDetection:()=>Yd,BartForConditionalGeneration:()=>Ue,BartForSequenceClassification:()=>lt,BartModel:()=>Pe,BartPretrainedModel:()=>Me,BaseModelOutput:()=>je,BeitForImageClassification:()=>ru,BeitModel:()=>tu,BeitPreTrainedModel:()=>Mo,BertForMaskedLM:()=>et,BertForQuestionAnswering:()=>ze,BertForSequenceClassification:()=>Qe,BertForTokenClassification:()=>qe,BertModel:()=>$e,BertPreTrainedModel:()=>we,BlenderbotForConditionalGeneration:()=>qt,BlenderbotModel:()=>Cr,BlenderbotPreTrainedModel:()=>Jt,BlenderbotSmallForConditionalGeneration:()=>Gr,BlenderbotSmallModel:()=>hs,BlenderbotSmallPreTrainedModel:()=>lr,BloomForCausalLM:()=>kl,BloomModel:()=>Sl,BloomPreTrainedModel:()=>mi,CLIPModel:()=>ja,CLIPPreTrainedModel:()=>cn,CLIPSegForImageSegmentation:()=>Ya,CLIPSegModel:()=>Xa,CLIPSegPreTrainedModel:()=>ri,CLIPTextModel:()=>bc,CLIPTextModelWithProjection:()=>Na,CLIPVisionModel:()=>vc,CLIPVisionModelWithProjection:()=>Ua,CamembertForMaskedLM:()=>qs,CamembertForQuestionAnswering:()=>vn,CamembertForSequenceClassification:()=>Qs,CamembertForTokenClassification:()=>Ds,CamembertModel:()=>as,CamembertPreTrainedModel:()=>Fr,CausalLMOutput:()=>hn,CausalLMOutputWithPast:()=>$p,ChineseCLIPModel:()=>Ka,ChineseCLIPPreTrainedModel:()=>Cs,ClapAudioModelWithProjection:()=>sd,ClapModel:()=>td,ClapPreTrainedModel:()=>Lo,ClapTextModelWithProjection:()=>rd,CodeGenForCausalLM:()=>ll,CodeGenModel:()=>al,CodeGenPreTrainedModel:()=>ys,CohereForCausalLM:()=>_l,CohereModel:()=>xc,CoherePreTrainedModel:()=>wo,ConvBertForMaskedLM:()=>Je,ConvBertForQuestionAnswering:()=>At,ConvBertForSequenceClassification:()=>ot,ConvBertForTokenClassification:()=>ut,ConvBertModel:()=>Ae,ConvBertPreTrainedModel:()=>ue,ConvNextForImageClassification:()=>bu,ConvNextModel:()=>Bi,ConvNextPreTrainedModel:()=>zi,ConvNextV2ForImageClassification:()=>Ac,ConvNextV2Model:()=>vu,ConvNextV2PreTrainedModel:()=>Ri,DPTForDepthEstimation:()=>Fi,DPTModel:()=>xo,DPTPreTrainedModel:()=>To,DebertaForMaskedLM:()=>Ls,DebertaForQuestionAnswering:()=>Ys,DebertaForSequenceClassification:()=>Xs,DebertaForTokenClassification:()=>un,DebertaModel:()=>Ts,DebertaPreTrainedModel:()=>Dt,DebertaV2ForMaskedLM:()=>Zs,DebertaV2ForQuestionAnswering:()=>it,DebertaV2ForSequenceClassification:()=>zs,DebertaV2ForTokenClassification:()=>ps,DebertaV2Model:()=>Js,DebertaV2PreTrainedModel:()=>xs,DecisionTransformerModel:()=>fd,DecisionTransformerPreTrainedModel:()=>md,DeiTForImageClassification:()=>cu,DeiTModel:()=>$c,DeiTPreTrainedModel:()=>ki,DepthAnythingForDepthEstimation:()=>_u,DepthAnythingPreTrainedModel:()=>fu,DepthProForDepthEstimation:()=>wu,DepthProPreTrainedModel:()=>Co,DetrForObjectDetection:()=>su,DetrForSegmentation:()=>Ci,DetrModel:()=>Cc,DetrObjectDetectionOutput:()=>Ms,DetrPreTrainedModel:()=>bo,DetrSegmentationOutput:()=>nu,Dinov2ForImageClassification:()=>Ic,Dinov2Model:()=>Tu,Dinov2PreTrainedModel:()=>ji,DistilBertForMaskedLM:()=>Sr,DistilBertForQuestionAnswering:()=>Bs,DistilBertForSequenceClassification:()=>Wr,DistilBertForTokenClassification:()=>en,DistilBertModel:()=>It,DistilBertPreTrainedModel:()=>Mt,DonutSwinModel:()=>Kn,DonutSwinPreTrainedModel:()=>Li,EfficientNetForImageClassification:()=>ad,EfficientNetModel:()=>Gc,EfficientNetPreTrainedModel:()=>Zi,ElectraForMaskedLM:()=>Ct,ElectraForQuestionAnswering:()=>Nr,ElectraForSequenceClassification:()=>ar,ElectraForTokenClassification:()=>Mr,ElectraModel:()=>Et,ElectraPreTrainedModel:()=>xt,EsmForMaskedLM:()=>As,EsmForSequenceClassification:()=>br,EsmForTokenClassification:()=>Tn,EsmModel:()=>Br,EsmPreTrainedModel:()=>ts,FalconForCausalLM:()=>Nc,FalconModel:()=>ed,FalconPreTrainedModel:()=>Xi,FastViTForImageClassification:()=>Hl,FastViTModel:()=>Kl,FastViTPreTrainedModel:()=>yi,Florence2ForConditionalGeneration:()=>Ba,Florence2PreTrainedModel:()=>fs,GLPNForDepthEstimation:()=>Mu,GLPNModel:()=>kc,GLPNPreTrainedModel:()=>Di,GPT2LMHeadModel:()=>Tc,GPT2Model:()=>Ja,GPT2PreTrainedModel:()=>si,GPTBigCodeForCausalLM:()=>il,GPTBigCodeModel:()=>ol,GPTBigCodePreTrainedModel:()=>ii,GPTJForCausalLM:()=>nl,GPTJModel:()=>sl,GPTJPreTrainedModel:()=>oi,GPTNeoForCausalLM:()=>el,GPTNeoModel:()=>$s,GPTNeoPreTrainedModel:()=>_o,GPTNeoXForCausalLM:()=>rl,GPTNeoXModel:()=>tl,GPTNeoXPreTrainedModel:()=>ni,Gemma2ForCausalLM:()=>Ml,Gemma2Model:()=>yl,Gemma2PreTrainedModel:()=>An,GemmaForCausalLM:()=>wl,GemmaModel:()=>gl,GemmaPreTrainedModel:()=>ci,GraniteForCausalLM:()=>fl,GraniteModel:()=>ml,GranitePreTrainedModel:()=>go,GroupViTModel:()=>Gl,GroupViTPreTrainedModel:()=>Wl,HieraForImageClassification:()=>hu,HieraModel:()=>pu,HieraPreTrainedModel:()=>Ai,HubertForCTC:()=>Gu,HubertForSequenceClassification:()=>Ku,HubertModel:()=>Wu,HubertPreTrainedModel:()=>zc,Idefics3ForConditionalGeneration:()=>Us,Idefics3PreTrainedModel:()=>Ra,ImageMattingOutput:()=>dc,JAISLMHeadModel:()=>fo,JAISModel:()=>Za,JAISPreTrainedModel:()=>ws,JinaCLIPModel:()=>Ha,JinaCLIPPreTrainedModel:()=>mo,JinaCLIPTextModel:()=>qa,JinaCLIPVisionModel:()=>Qa,LlamaForCausalLM:()=>dl,LlamaModel:()=>ul,LlamaPreTrainedModel:()=>ai,LlavaForConditionalGeneration:()=>ho,LlavaOnevisionForConditionalGeneration:()=>La,LlavaPreTrainedModel:()=>ei,LongT5ForConditionalGeneration:()=>xe,LongT5Model:()=>_r,LongT5PreTrainedModel:()=>kn,M2M100ForConditionalGeneration:()=>Wi,M2M100Model:()=>Su,M2M100PreTrainedModel:()=>Vi,MBartForCausalLM:()=>gr,MBartForConditionalGeneration:()=>Tt,MBartForSequenceClassification:()=>Wt,MBartModel:()=>pt,MBartPreTrainedModel:()=>mt,MPNetForMaskedLM:()=>co,MPNetForQuestionAnswering:()=>js,MPNetForSequenceClassification:()=>rn,MPNetForTokenClassification:()=>Es,MPNetModel:()=>Bn,MPNetPreTrainedModel:()=>Rs,MT5ForConditionalGeneration:()=>oe,MT5Model:()=>K,MT5PreTrainedModel:()=>T,MarianMTModel:()=>Ui,MarianModel:()=>Ni,MarianPreTrainedModel:()=>Hn,MaskFormerForInstanceSegmentation:()=>yu,MaskFormerModel:()=>So,MaskFormerPreTrainedModel:()=>$o,MaskedLMOutput:()=>Jr,MgpstrForSceneTextRecognition:()=>ia,MgpstrModelOutput:()=>gd,MgpstrPreTrainedModel:()=>wd,MistralForCausalLM:()=>Ju,MistralModel:()=>qi,MistralPreTrainedModel:()=>Hi,MobileBertForMaskedLM:()=>Dn,MobileBertForQuestionAnswering:()=>zn,MobileBertForSequenceClassification:()=>Ln,MobileBertModel:()=>uo,MobileBertPreTrainedModel:()=>tn,MobileLLMForCausalLM:()=>pl,MobileLLMModel:()=>cl,MobileLLMPreTrainedModel:()=>li,MobileNetV1ForImageClassification:()=>dd,MobileNetV1Model:()=>ud,MobileNetV1PreTrainedModel:()=>ss,MobileNetV2ForImageClassification:()=>Jn,MobileNetV2Model:()=>cd,MobileNetV2PreTrainedModel:()=>Bo,MobileNetV3ForImageClassification:()=>ra,MobileNetV3Model:()=>pd,MobileNetV3PreTrainedModel:()=>ta,MobileNetV4ForImageClassification:()=>na,MobileNetV4Model:()=>hd,MobileNetV4PreTrainedModel:()=>sa,MobileViTForImageClassification:()=>bi,MobileViTModel:()=>Xl,MobileViTPreTrainedModel:()=>Mi,MobileViTV2ForImageClassification:()=>xi,MobileViTV2Model:()=>Ti,MobileViTV2PreTrainedModel:()=>vi,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>za,MptForCausalLM:()=>Il,MptModel:()=>Al,MptPreTrainedModel:()=>fi,MultiModalityCausalLM:()=>oa,MultiModalityPreTrainedModel:()=>_d,MusicgenForCausalLM:()=>Hc,MusicgenForConditionalGeneration:()=>ld,MusicgenModel:()=>Kc,MusicgenPreTrainedModel:()=>ea,NomicBertModel:()=>dt,NomicBertPreTrainedModel:()=>nt,OPTForCausalLM:()=>Ol,OPTModel:()=>Fl,OPTPreTrainedModel:()=>_i,OlmoForCausalLM:()=>di,OlmoModel:()=>hl,OlmoPreTrainedModel:()=>ui,OpenELMForCausalLM:()=>vl,OpenELMModel:()=>bl,OpenELMPreTrainedModel:()=>yo,OwlViTForObjectDetection:()=>Jl,OwlViTModel:()=>Yl,OwlViTPreTrainedModel:()=>Ei,Owlv2ForObjectDetection:()=>eu,Owlv2Model:()=>Zl,Owlv2PreTrainedModel:()=>Pi,PatchTSMixerForPrediction:()=>Md,PatchTSMixerModel:()=>yd,PatchTSMixerPreTrainedModel:()=>ua,PatchTSTForPrediction:()=>la,PatchTSTModel:()=>qc,PatchTSTPreTrainedModel:()=>aa,Phi3ForCausalLM:()=>$l,Phi3Model:()=>Cl,Phi3PreTrainedModel:()=>ur,PhiForCausalLM:()=>Pl,PhiModel:()=>Pc,PhiPreTrainedModel:()=>hi,PreTrainedModel:()=>le,PretrainedMixin:()=>vr,PvtForImageClassification:()=>Rl,PvtModel:()=>Bl,PvtPreTrainedModel:()=>Gn,PyAnnoteForAudioFrameClassification:()=>Fu,PyAnnoteModel:()=>Oc,PyAnnotePreTrainedModel:()=>Io,QuestionAnsweringModelOutput:()=>ns,Qwen2ForCausalLM:()=>Ec,Qwen2Model:()=>Tl,Qwen2PreTrainedModel:()=>pi,Qwen2VLForConditionalGeneration:()=>El,Qwen2VLPreTrainedModel:()=>xl,RTDetrForObjectDetection:()=>iu,RTDetrModel:()=>ou,RTDetrObjectDetectionOutput:()=>au,RTDetrPreTrainedModel:()=>$i,ResNetForImageClassification:()=>Sc,ResNetModel:()=>mu,ResNetPreTrainedModel:()=>Ii,RoFormerForMaskedLM:()=>_t,RoFormerForQuestionAnswering:()=>V,RoFormerForSequenceClassification:()=>A,RoFormerForTokenClassification:()=>ne,RoFormerModel:()=>ht,RoFormerPreTrainedModel:()=>gt,RobertaForMaskedLM:()=>qr,RobertaForQuestionAnswering:()=>Ut,RobertaForSequenceClassification:()=>ms,RobertaForTokenClassification:()=>Ps,RobertaModel:()=>wr,RobertaPreTrainedModel:()=>De,SamImageSegmentationOutput:()=>$u,SamModel:()=>Ao,SamPreTrainedModel:()=>Cu,SapiensForDepthEstimation:()=>Oi,SapiensForNormalEstimation:()=>gu,SapiensForSemanticSegmentation:()=>Po,SapiensPreTrainedModel:()=>Eo,SegformerForImageClassification:()=>nd,SegformerForSemanticSegmentation:()=>Wc,SegformerModel:()=>Vc,SegformerPreTrainedModel:()=>zo,Seq2SeqLMOutput:()=>ip,SequenceClassifierOutput:()=>tr,SiglipModel:()=>Va,SiglipPreTrainedModel:()=>ti,SiglipTextModel:()=>Wa,SiglipVisionModel:()=>Ga,SpeechT5ForSpeechToText:()=>Ki,SpeechT5ForTextToSpeech:()=>Qu,SpeechT5HifiGan:()=>Xu,SpeechT5Model:()=>Bc,SpeechT5PreTrainedModel:()=>Do,SqueezeBertForMaskedLM:()=>xn,SqueezeBertForQuestionAnswering:()=>Pn,SqueezeBertForSequenceClassification:()=>En,SqueezeBertModel:()=>dn,SqueezeBertPreTrainedModel:()=>Ns,StableLmForCausalLM:()=>id,StableLmModel:()=>od,StableLmPreTrainedModel:()=>Ji,Starcoder2ForCausalLM:()=>jc,Starcoder2Model:()=>Zu,Starcoder2PreTrainedModel:()=>Qi,Swin2SRForImageSuperResolution:()=>rs,Swin2SRModel:()=>on,Swin2SRPreTrainedModel:()=>vo,SwinForImageClassification:()=>nn,SwinModel:()=>sn,SwinPreTrainedModel:()=>Vs,T5ForConditionalGeneration:()=>Sn,T5Model:()=>Un,T5PreTrainedModel:()=>$n,TableTransformerForObjectDetection:()=>uu,TableTransformerModel:()=>lu,TableTransformerObjectDetectionOutput:()=>du,TableTransformerPreTrainedModel:()=>Si,TokenClassifierOutput:()=>Yr,TrOCRForCausalLM:()=>Rc,TrOCRPreTrainedModel:()=>Yu,UniSpeechForCTC:()=>zu,UniSpeechForSequenceClassification:()=>Bu,UniSpeechModel:()=>Lu,UniSpeechPreTrainedModel:()=>qn,UniSpeechSatForAudioFrameClassification:()=>Nu,UniSpeechSatForCTC:()=>ju,UniSpeechSatForSequenceClassification:()=>Dc,UniSpeechSatModel:()=>Ru,UniSpeechSatPreTrainedModel:()=>Qn,ViTForImageClassification:()=>Ll,ViTMAEModel:()=>Nl,ViTMAEPreTrainedModel:()=>jl,ViTMSNForImageClassification:()=>Vl,ViTMSNModel:()=>Ul,ViTMSNPreTrainedModel:()=>wi,ViTModel:()=>Dl,ViTPreTrainedModel:()=>gi,VisionEncoderDecoderModel:()=>Zo,VitMatteForImageMatting:()=>Ql,VitMattePreTrainedModel:()=>ql,VitPoseForPoseEstimation:()=>zl,VitPosePreTrainedModel:()=>Wn,VitsModel:()=>Yi,VitsModelOutput:()=>cc,VitsPreTrainedModel:()=>Uc,Wav2Vec2BertForCTC:()=>Lc,Wav2Vec2BertForSequenceClassification:()=>Vu,Wav2Vec2BertModel:()=>Uu,Wav2Vec2BertPreTrainedModel:()=>Fo,Wav2Vec2ForAudioFrameClassification:()=>Iu,Wav2Vec2ForCTC:()=>Au,Wav2Vec2ForSequenceClassification:()=>Fc,Wav2Vec2Model:()=>ku,Wav2Vec2PreTrainedModel:()=>pn,WavLMForAudioFrameClassification:()=>qu,WavLMForCTC:()=>Yn,WavLMForSequenceClassification:()=>Gi,WavLMForXVector:()=>Hu,WavLMModel:()=>Oo,WavLMPreTrainedModel:()=>Xn,WeSpeakerResNetModel:()=>Du,WeSpeakerResNetPreTrainedModel:()=>Ou,WhisperForConditionalGeneration:()=>er,WhisperModel:()=>Vn,WhisperPreTrainedModel:()=>Jo,XLMForQuestionAnswering:()=>Zt,XLMForSequenceClassification:()=>yr,XLMForTokenClassification:()=>wt,XLMModel:()=>us,XLMPreTrainedModel:()=>Rr,XLMRobertaForMaskedLM:()=>Fs,XLMRobertaForQuestionAnswering:()=>Ze,XLMRobertaForSequenceClassification:()=>St,XLMRobertaForTokenClassification:()=>po,XLMRobertaModel:()=>Is,XLMRobertaPreTrainedModel:()=>Dr,XLMWithLMHeadModel:()=>or,XVectorOutput:()=>uc,YolosForObjectDetection:()=>Eu,YolosModel:()=>xu,YolosObjectDetectionOutput:()=>Pu,YolosPreTrainedModel:()=>ko});var w=c("./src/configs.js"),z=c("./src/backends/onnx.js"),G=c("./src/utils/dtypes.js"),re=c("./src/utils/generic.js"),Q=c("./src/utils/core.js"),g=c("./src/utils/hub.js"),v=c("./src/utils/constants.js"),M=c("./src/generation/logits_process.js"),y=c("./src/generation/configuration_utils.js"),C=c("./src/utils/tensor.js"),q=c("./src/utils/image.js"),J=c("./src/utils/maths.js"),ie=c("./src/generation/stopping_criteria.js"),fe=c("./src/generation/logits_sampler.js"),j=c("./src/env.js"),X=c("./src/models/whisper/generation_whisper.js"),Z=c("./src/models/whisper/common_whisper.js");const N={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8},I=new Map,_=new Map,k=new Map;async function E(f,S,D){var $r;const Te=(($r=D.config)==null?void 0:$r["transformers.js_config"])??{};let Ie=D.device??Te.device;Ie&&typeof Ie!="string"&&(Ie.hasOwnProperty(S)?Ie=Ie[S]:(console.warn(`device not specified for "${S}". Using the default device.`),Ie=null));const Se=Ie??(j.apis.IS_NODE_ENV?"cpu":"wasm"),Xe=(0,z.deviceToExecutionProviders)(Se);let tt=D.dtype??Te.dtype;if(typeof tt!="string"&&(tt&&tt.hasOwnProperty(S)?tt=tt[S]:(tt=G.DEFAULT_DEVICE_DTYPE_MAPPING[Se]??G.DATA_TYPES.fp32,console.warn(`dtype not specified for "${S}". Using the default dtype (${tt}) for this device (${Se}).`))),tt===G.DATA_TYPES.auto){let pr=Te.dtype;typeof pr!="string"&&(pr=pr[S]),pr&&pr!==G.DATA_TYPES.auto&&G.DATA_TYPES.hasOwnProperty(pr)?tt=pr:tt=G.DEFAULT_DEVICE_DTYPE_MAPPING[Se]??G.DATA_TYPES.fp32}const ft=tt;if(G.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ft)){if(ft===G.DATA_TYPES.fp16&&Se==="webgpu"&&!await(0,G.isWebGpuFp16Supported)())throw new Error(`The device (${Se}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${ft}. Should be one of: ${Object.keys(G.DATA_TYPES).join(", ")}`);const bt=Te.kv_cache_dtype?typeof Te.kv_cache_dtype=="string"?Te.kv_cache_dtype:Te.kv_cache_dtype[ft]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const Ht={dtype:ft,kv_cache_dtype:bt},jt=G.DEFAULT_DTYPE_SUFFIX_MAPPING[ft],Lt=`${D.subfolder??""}/${S}${jt}.onnx`,Gt={...D.session_options};Gt.executionProviders??(Gt.executionProviders=Xe);const sr=Te.free_dimension_overrides;sr?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=sr):Se.startsWith("webnn")&&!Gt.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 ir=(0,g.getModelFile)(f,Lt,!0,D),Xt=D.use_external_data_format??Te.use_external_data_format;let dr=[];if(Xt&&(Xt===!0||typeof Xt=="object"&&Xt.hasOwnProperty(S)&&Xt[S]===!0)){if(j.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const pr=`${S}${jt}.onnx_data`,kr=`${D.subfolder??""}/${pr}`;dr.push(new Promise(async(Lr,os)=>{const Kr=await(0,g.getModelFile)(f,kr,!0,D);Lr({path:pr,data:Kr})}))}else Gt.externalData!==void 0&&(dr=Gt.externalData.map(async pr=>{if(typeof pr.data=="string"){const kr=await(0,g.getModelFile)(f,pr.data,!0,D);return{...pr,data:kr}}return pr}));if(dr.length>0&&(Gt.externalData=await Promise.all(dr)),Se==="webgpu"){const pr=(0,w.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(pr).length>0&&!(0,z.isONNXProxy)()){const kr={};for(const Lr in pr)kr[Lr]="gpu-buffer";Gt.preferredOutputLocation=kr}}return{buffer:await ir,session_options:Gt,session_config:Ht}}async function ee(f,S,D){return Object.fromEntries(await Promise.all(Object.keys(S).map(async Te=>{const{buffer:Ie,session_options:Se,session_config:Xe}=await E(f,S[Te],D),tt=await(0,z.createInferenceSession)(Ie,Se,Xe);return[Te,tt]})))}async function Y(f,S,D){return Object.fromEntries(await Promise.all(Object.keys(S).map(async Te=>{const Ie=await(0,g.getModelJSON)(f,S[Te],!1,D);return[Te,Ie]})))}function de(f,S){const D=Object.create(null),Te=[];for(const Xe of f.inputNames){const tt=S[Xe];if(!(tt instanceof C.Tensor)){Te.push(Xe);continue}D[Xe]=(0,z.isONNXProxy)()?tt.clone():tt}if(Te.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Te.join(", ")}.`);const Ie=Object.keys(S).length,Se=f.inputNames.length;if(Ie>Se){let Xe=Object.keys(S).filter(tt=>!f.inputNames.includes(tt));console.warn(`WARNING: Too many inputs were provided (${Ie} > ${Se}). The following inputs will be ignored: "${Xe.join(", ")}".`)}return D}async function me(f,S){const D=de(f,S);try{const Te=Object.fromEntries(Object.entries(D).map(([Se,Xe])=>[Se,Xe.ort_tensor]));let Ie=await f.run(Te);return Ie=ye(Ie),Ie}catch(Te){const Ie=Object.fromEntries(Object.entries(D).map(([Se,{type:Xe,dims:tt,data:ft}])=>[Se,{type:Xe,dims:tt,data:ft}]));throw console.error(`An error occurred during model execution: "${Te}".`),console.error("Inputs given to model:",Ie),Te}}function ye(f){for(let S in f)(0,z.isONNXTensor)(f[S])?f[S]=new C.Tensor(f[S]):typeof f[S]=="object"&&ye(f[S]);return f}function Ce(f){if(f instanceof C.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(S=>S.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new C.Tensor("int64",BigInt64Array.from(f.flat().map(S=>BigInt(S))),[f.length,f[0].length])}else return new C.Tensor("int64",BigInt64Array.from(f.map(S=>BigInt(S))),[1,f.length])}function Ee(f){return new C.Tensor("bool",[f],[1])}async function Le(f,S){let{encoder_outputs:D,input_ids:Te,decoder_input_ids:Ie,...Se}=S;if(!D){const tt=(0,Q.pick)(S,f.sessions.model.inputNames);D=(await _e(f,tt)).last_hidden_state}return Se.input_ids=Ie,Se.encoder_hidden_states=D,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Se.encoder_attention_mask=S.attention_mask),await U(f,Se,!0)}async function _e(f,S){const D=f.sessions.model,Te=(0,Q.pick)(S,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!Te.inputs_embeds){if(!S.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Te.inputs_embeds=await f.encode_text({input_ids:S.input_ids})}return D.inputNames.includes("token_type_ids")&&!Te.token_type_ids&&(Te.token_type_ids=new C.Tensor("int64",new BigInt64Array(Te.input_ids.data.length),Te.input_ids.dims)),await me(D,Te)}async function U(f,S,D=!1){const Te=f.sessions[D?"decoder_model_merged":"model"],{past_key_values:Ie,...Se}=S;Te.inputNames.includes("use_cache_branch")&&(Se.use_cache_branch=Ee(!!Ie)),Te.inputNames.includes("position_ids")&&Se.attention_mask&&!Se.position_ids&&(Se.position_ids=Re(Se,Ie)),f.addPastKeyValues(Se,Ie);const Xe=(0,Q.pick)(Se,Te.inputNames);return await me(Te,Xe)}function ce({image_token_id:f,inputs_embeds:S,image_features:D,input_ids:Te,attention_mask:Ie}){const Se=Te.tolist().map(bt=>bt.reduce((Ht,jt,Lt)=>(jt==f&&Ht.push(Lt),Ht),[])),Xe=Se.reduce((bt,Ht)=>bt+Ht.length,0),tt=D.dims[0];if(Xe!==tt)throw new Error(`Image features and image tokens do not match: tokens: ${Xe}, features ${tt}`);let ft=0;for(let bt=0;btSe.dims[1])){if(Iett==f.config.image_token_index)){const tt=f.config.num_image_tokens;if(!tt)throw new Error("`num_image_tokens` is missing in the model configuration.");const ft=Se.dims[1]-(Ie-tt);D.input_ids=Se.slice(null,[-ft,null]),D.attention_mask=(0,C.ones)([1,Ie+ft])}}}return D}function Ye(f,S,D,Te){return D.past_key_values&&(S=S.map(Ie=>[Ie.at(-1)])),{...D,decoder_input_ids:Ce(S)}}function at(f,...S){return f.config.is_encoder_decoder?Ye(f,...S):Ke(f,...S)}function We(f,S,D,Te){const Ie=!!D.past_key_values;return Te.guidance_scale!==null&&Te.guidance_scale>1&&(Ie?D.input_ids=(0,C.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,C.cat)([D.input_ids,(0,C.full_like)(D.input_ids,BigInt(Te.pad_token_id))],0),D.attention_mask=(0,C.cat)([D.attention_mask,(0,C.full_like)(D.attention_mask,0n)],0))),(Ie||!D.pixel_values)&&(D.pixel_values=(0,C.full)([0,0,3,384,384],1)),Ie&&(D.images_seq_mask=new C.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new C.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class le extends re.Callable{constructor(D,Te,Ie){super();ve(this,"main_input_name","input_ids");ve(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=Te,this.configs=Ie;const Se=k.get(this.constructor),Xe=I.get(Se);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Xe){case N.DecoderOnly:this.can_generate=!0,this._forward=U,this._prepare_inputs_for_generation=Ke;break;case N.Seq2Seq:case N.Vision2Seq:case N.Musicgen:this.can_generate=!0,this._forward=Le,this._prepare_inputs_for_generation=Ye;break;case N.EncoderDecoder:this._forward=Le;break;case N.ImageTextToText:this.can_generate=!0,this._forward=he,this._prepare_inputs_for_generation=at;break;case N.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=We;break;default:this._forward=_e;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Te;const D=[];for(const Ie of Object.values(this.sessions))(Te=Ie==null?void 0:Ie.handler)!=null&&Te.dispose&&D.push(Ie.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:Te=null,config:Ie=null,cache_dir:Se=null,local_files_only:Xe=!1,revision:tt="main",model_file_name:ft=null,subfolder:bt="onnx",device:Ht=null,dtype:jt=null,use_external_data_format:Lt=null,session_options:Gt={}}={}){let sr={progress_callback:Te,config:Ie,cache_dir:Se,local_files_only:Xe,revision:tt,model_file_name:ft,subfolder:bt,device:Ht,dtype:jt,use_external_data_format:Lt,session_options:Gt};const ir=k.get(this),Xt=I.get(ir);Ie=sr.config=await w.AutoConfig.from_pretrained(D,sr);let dr;if(Xt===N.DecoderOnly)dr=await Promise.all([ee(D,{model:sr.model_file_name??"model"},sr),Y(D,{generation_config:"generation_config.json"},sr)]);else if(Xt===N.Seq2Seq||Xt===N.Vision2Seq)dr=await Promise.all([ee(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},sr),Y(D,{generation_config:"generation_config.json"},sr)]);else if(Xt===N.MaskGeneration)dr=await Promise.all([ee(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},sr)]);else if(Xt===N.EncoderDecoder)dr=await Promise.all([ee(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},sr)]);else if(Xt===N.ImageTextToText){const Or={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ie.is_encoder_decoder&&(Or.model="encoder_model"),dr=await Promise.all([ee(D,Or,sr),Y(D,{generation_config:"generation_config.json"},sr)])}else if(Xt===N.Musicgen)dr=await Promise.all([ee(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},sr),Y(D,{generation_config:"generation_config.json"},sr)]);else if(Xt===N.MultiModality)dr=await Promise.all([ee(D,{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"},sr),Y(D,{generation_config:"generation_config.json"},sr)]);else{if(Xt!==N.EncoderOnly){const Or=ir??(Ie==null?void 0:Ie.model_type);Or!=="custom"&&console.warn(`Model type for '${Or}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}dr=await Promise.all([ee(D,{model:sr.model_file_name??"model"},sr)])}return new this(Ie,...dr)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const Te=new M.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&Te.push(new M.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&Te.push(new M.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&Te.push(new M.TopPLogitsWarper(D.top_p)),Te}_get_logits_processor(D,Te,Ie=null){const Se=new M.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&Se.push(new M.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&Se.push(new M.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&Se.push(new M.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&Se.push(new M.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&Se.push(new M.MinNewTokensLengthLogitsProcessor(Te,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&Se.push(new M.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&Se.push(new M.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Xe=Te>1||D.forced_bos_token_id===null?Te:Te+1;Se.push(new M.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Xe))}return D.guidance_scale!==null&&D.guidance_scale>1&&Se.push(new M.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),Ie!==null&&Se.extend(Ie),Se}_prepare_generation_config(D,Te,Ie=y.GenerationConfig){const Se={...this.config};for(const tt of["decoder","generator","text_config"])tt in Se&&Object.assign(Se,Se[tt]);const Xe=new Ie(Se);return Object.assign(Xe,this.generation_config??{}),D&&Object.assign(Xe,D),Te&&Object.assign(Xe,(0,Q.pick)(Te,Object.getOwnPropertyNames(Xe))),Xe}_get_stopping_criteria(D,Te=null){const Ie=new ie.StoppingCriteriaList;return D.max_length!==null&&Ie.push(new ie.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&Ie.push(new ie.EosTokenCriteria(D.eos_token_id)),Te&&Ie.extend(Te),Ie}_validate_model_class(){if(!this.can_generate){const D=[Pd,ca,da,bd],Te=k.get(this.constructor),Ie=new Set,Se=this.config.model_type;for(const tt of D){const ft=tt.get(Se);ft&&Ie.add(ft[0])}let Xe=`The current model class (${Te}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ie.size>0&&(Xe+=` Please use the following class instead: ${[...Ie].join(", ")}`),Error(Xe)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:Te,model_inputs:Ie,is_encoder_decoder:Se}){return Ie.past_key_values=this.getPastKeyValues(Te,Ie.past_key_values),Ie.input_ids=new C.Tensor("int64",D.flat(),[D.length,1]),Se||(Ie.attention_mask=(0,C.cat)([Ie.attention_mask,(0,C.ones)([Ie.attention_mask.dims[0],1])],1)),Ie.position_ids=null,Ie}_prepare_model_inputs({inputs:D,bos_token_id:Te,model_kwargs:Ie}){const Se=(0,Q.pick)(Ie,this.forward_params),Xe=this.main_input_name;if(Xe in Se){if(D)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[Xe]=D;return{inputs_tensor:Se[Xe],model_inputs:Se,model_input_name:Xe}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:Te,model_input_name:Ie,generation_config:Se}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Te.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:tt,pixel_values:ft,attention_mask:bt,...Ht}=Te,jt=await this._prepare_inputs_embeds(Te);Te={...Ht,...(0,Q.pick)(jt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Xe}=await _e(this,Te);if(Se.guidance_scale!==null&&Se.guidance_scale>1)Xe=(0,C.cat)([Xe,(0,C.full_like)(Xe,0)],0),"attention_mask"in Te&&(Te.attention_mask=(0,C.cat)([Te.attention_mask,(0,C.zeros_like)(Te.attention_mask)],0));else if(Te.decoder_input_ids){const tt=Ce(Te.decoder_input_ids).dims[0];if(tt!==Xe.dims[0]){if(Xe.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Xe.dims[0]}) than the decoder inputs (${tt}).`);Xe=(0,C.cat)(Array.from({length:tt},()=>Xe),0)}}return Te.encoder_outputs=Xe,Te}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:Te,model_kwargs:Ie,decoder_start_token_id:Se,bos_token_id:Xe,generation_config:tt}){let{decoder_input_ids:ft,...bt}=Ie;if(!(ft instanceof C.Tensor)){if(ft)Array.isArray(ft[0])||(ft=Array.from({length:D},()=>ft));else if(Se??(Se=Xe),this.config.model_type==="musicgen")ft=Array.from({length:D*this.config.decoder.num_codebooks},()=>[Se]);else if(Array.isArray(Se)){if(Se.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${Se.length}`);ft=Se}else ft=Array.from({length:D},()=>[Se]);ft=Ce(ft)}return Ie.decoder_attention_mask=(0,C.ones_like)(ft),{input_ids:ft,model_inputs:bt}}async generate({inputs:D=null,generation_config:Te=null,logits_processor:Ie=null,stopping_criteria:Se=null,streamer:Xe=null,...tt}){this._validate_model_class(),Te=this._prepare_generation_config(Te,tt);let{inputs_tensor:ft,model_inputs:bt,model_input_name:Ht}=this._prepare_model_inputs({inputs:D,model_kwargs:tt});const jt=this.config.is_encoder_decoder;jt&&("encoder_outputs"in bt||(bt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ft,model_inputs:bt,model_input_name:Ht,generation_config:Te})));let Lt;jt?{input_ids:Lt,model_inputs:bt}=this._prepare_decoder_input_ids_for_generation({batch_size:bt[Ht].dims.at(0),model_input_name:Ht,model_kwargs:bt,decoder_start_token_id:Te.decoder_start_token_id,bos_token_id:Te.bos_token_id,generation_config:Te}):Lt=bt[Ht];let Gt=Lt.dims.at(-1);Te.max_new_tokens!==null&&(Te.max_length=Gt+Te.max_new_tokens);const sr=this._get_logits_processor(Te,Gt,Ie),ir=this._get_stopping_criteria(Te,Se),Xt=bt[Ht].dims.at(0),dr=fe.LogitsSampler.getSampler(Te),Or=new Array(Xt).fill(0),$r=Lt.tolist();Xe&&Xe.put($r);let pr,kr={};for(;;){if(bt=this.prepare_inputs_for_generation($r,bt,Te),pr=await this.forward(bt),Te.output_attentions&&Te.return_dict_in_generate){const _s=this.getAttentions(pr);for(const Ws in _s)Ws in kr||(kr[Ws]=[]),kr[Ws].push(_s[Ws])}const Kr=pr.logits.slice(null,-1,null),Ss=sr($r,Kr),In=[];for(let _s=0;_s_s))break;bt=this._update_model_kwargs_for_generation({generated_input_ids:In,outputs:pr,model_inputs:bt,is_encoder_decoder:jt})}Xe&&Xe.end();const Lr=this.getPastKeyValues(pr,bt.past_key_values,!0),os=new C.Tensor("int64",$r.flat(),[$r.length,$r[0].length]);if(Te.return_dict_in_generate)return{sequences:os,past_key_values:Lr,...kr};for(const Kr of Object.values(pr))Kr.location==="gpu-buffer"&&Kr.dispose();return os}getPastKeyValues(D,Te,Ie=!1){const Se=Object.create(null);for(const Xe in D)if(Xe.startsWith("present")){const tt=Xe.replace("present","past_key_values"),ft=Xe.includes("encoder");if(ft&&Te?Se[tt]=Te[tt]:Se[tt]=D[Xe],Te&&(!ft||Ie)){const bt=Te[tt];bt.location==="gpu-buffer"&&bt.dispose()}}return Se}getAttentions(D){const Te={};for(const Ie of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Se in D)Se.startsWith(Ie)&&(Ie in Te||(Te[Ie]=[]),Te[Ie].push(D[Se]));return Te}addPastKeyValues(D,Te){var Ie,Se,Xe;if(Te)Object.assign(D,Te);else{const tt=this.sessions.decoder_model_merged??this.sessions.model,ft=((Ie=tt==null?void 0:tt.config)==null?void 0:Ie.kv_cache_dtype)??"float32",bt=ft==="float16"?new Uint16Array:[],Ht=((Xe=(Se=D[this.main_input_name]??D.attention_mask)==null?void 0:Se.dims)==null?void 0:Xe[0])??1,jt=(0,w.getKeyValueShapes)(this.config,{batch_size:Ht});for(const Lt in jt)D[Lt]=new C.Tensor(ft,bt,jt[Lt])}}async encode_image({pixel_values:D}){const Te=(await me(this.sessions.vision_encoder,{pixel_values:D})).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 (${Te.dims[1]}).`),this.config.num_image_tokens=Te.dims[1]),Te}async encode_text({input_ids:D}){return(await me(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}}class He{}class je extends He{constructor({last_hidden_state:S,hidden_states:D=null,attentions:Te=null}){super(),this.last_hidden_state=S,this.hidden_states=D,this.attentions=Te}}class we extends le{}class $e extends we{}class et extends we{async _call(S){return new Jr(await super._call(S))}}class Qe extends we{async _call(S){return new tr(await super._call(S))}}class qe extends we{async _call(S){return new Yr(await super._call(S))}}class ze extends we{async _call(S){return new ns(await super._call(S))}}class nt extends le{}class dt extends nt{}class gt extends le{}class ht extends gt{}class _t extends gt{async _call(S){return new Jr(await super._call(S))}}class A extends gt{async _call(S){return new tr(await super._call(S))}}class ne extends gt{async _call(S){return new Yr(await super._call(S))}}class V extends gt{async _call(S){return new ns(await super._call(S))}}class ue extends le{}class Ae extends ue{}class Je extends ue{async _call(S){return new Jr(await super._call(S))}}class ot extends ue{async _call(S){return new tr(await super._call(S))}}class ut extends ue{async _call(S){return new Yr(await super._call(S))}}class At extends ue{async _call(S){return new ns(await super._call(S))}}class xt extends le{}class Et extends xt{}class Ct extends xt{async _call(S){return new Jr(await super._call(S))}}class ar extends xt{async _call(S){return new tr(await super._call(S))}}class Mr extends xt{async _call(S){return new Yr(await super._call(S))}}class Nr extends xt{async _call(S){return new ns(await super._call(S))}}class Fr extends le{}class as extends Fr{}class qs extends Fr{async _call(S){return new Jr(await super._call(S))}}class Qs extends Fr{async _call(S){return new tr(await super._call(S))}}class Ds extends Fr{async _call(S){return new Yr(await super._call(S))}}class vn extends Fr{async _call(S){return new ns(await super._call(S))}}class Dt extends le{}class Ts extends Dt{}class Ls extends Dt{async _call(S){return new Jr(await super._call(S))}}class Xs extends Dt{async _call(S){return new tr(await super._call(S))}}class un extends Dt{async _call(S){return new Yr(await super._call(S))}}class Ys extends Dt{async _call(S){return new ns(await super._call(S))}}class xs extends le{}class Js extends xs{}class Zs extends xs{async _call(S){return new Jr(await super._call(S))}}class zs extends xs{async _call(S){return new tr(await super._call(S))}}class ps extends xs{async _call(S){return new Yr(await super._call(S))}}class it extends xs{async _call(S){return new ns(await super._call(S))}}class Mt extends le{}class It extends Mt{}class Wr extends Mt{async _call(S){return new tr(await super._call(S))}}class en extends Mt{async _call(S){return new Yr(await super._call(S))}}class Bs extends Mt{async _call(S){return new ns(await super._call(S))}}class Sr extends Mt{async _call(S){return new Jr(await super._call(S))}}class ts extends le{}class Br extends ts{}class As extends ts{async _call(S){return new Jr(await super._call(S))}}class br extends ts{async _call(S){return new tr(await super._call(S))}}class Tn extends ts{async _call(S){return new Yr(await super._call(S))}}class tn extends le{}class uo extends tn{}class Dn extends tn{async _call(S){return new Jr(await super._call(S))}}class Ln extends tn{async _call(S){return new tr(await super._call(S))}}class zn extends tn{async _call(S){return new ns(await super._call(S))}}class Rs extends le{}class Bn extends Rs{}class co extends Rs{async _call(S){return new Jr(await super._call(S))}}class rn extends Rs{async _call(S){return new tr(await super._call(S))}}class Es extends Rs{async _call(S){return new Yr(await super._call(S))}}class js extends Rs{async _call(S){return new ns(await super._call(S))}}class Ns extends le{}class dn extends Ns{}class xn extends Ns{async _call(S){return new Jr(await super._call(S))}}class En extends Ns{async _call(S){return new tr(await super._call(S))}}class Pn extends Ns{async _call(S){return new ns(await super._call(S))}}class Ot extends le{}class Cn extends Ot{}class Rn extends Ot{async _call(S){return new tr(await super._call(S))}}class jn extends Ot{async _call(S){return new ns(await super._call(S))}}class Nn extends Ot{async _call(S){return new Jr(await super._call(S))}}class $n extends le{constructor(){super(...arguments);ve(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Un extends $n{}class Sn extends $n{}class kn extends le{}class _r extends kn{}class xe extends kn{}class T extends le{}class K extends T{}class oe extends T{}class Me extends le{}class Pe extends Me{}class Ue extends Me{}class lt extends Me{async _call(S){return new tr(await super._call(S))}}class mt extends le{}class pt extends mt{}class Tt extends mt{}class Wt extends mt{async _call(S){return new tr(await super._call(S))}}class gr extends mt{}class Jt extends le{}class Cr extends Jt{}class qt extends Jt{}class lr extends le{}class hs extends lr{}class Gr extends lr{}class De extends le{}class wr extends De{}class qr extends De{async _call(S){return new Jr(await super._call(S))}}class ms extends De{async _call(S){return new tr(await super._call(S))}}class Ps extends De{async _call(S){return new Yr(await super._call(S))}}class Ut extends De{async _call(S){return new ns(await super._call(S))}}class Rr extends le{}class us extends Rr{}class or extends Rr{async _call(S){return new Jr(await super._call(S))}}class yr extends Rr{async _call(S){return new tr(await super._call(S))}}class wt extends Rr{async _call(S){return new Yr(await super._call(S))}}class Zt extends Rr{async _call(S){return new ns(await super._call(S))}}class Dr extends le{}class Is extends Dr{}class Fs extends Dr{async _call(S){return new Jr(await super._call(S))}}class St extends Dr{async _call(S){return new tr(await super._call(S))}}class po extends Dr{async _call(S){return new Yr(await super._call(S))}}class Ze extends Dr{async _call(S){return new ns(await super._call(S))}}class kt extends le{}class Yo extends kt{}class Da extends kt{}class Jo extends le{constructor(){super(...arguments);ve(this,"requires_attention_mask",!1);ve(this,"main_input_name","input_features");ve(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Vn extends Jo{}class er extends Jo{_prepare_generation_config(S,D){return super._prepare_generation_config(S,D,X.WhisperGenerationConfig)}_retrieve_init_tokens(S){const D=[S.decoder_start_token_id];let Te=S.language;const Ie=S.task;if(S.is_multilingual){Te||(console.warn("No language specified - defaulting to English (en)."),Te="en");const Xe=`<|${(0,Z.whisper_language_to_code)(Te)}|>`;D.push(S.lang_to_id[Xe]),D.push(S.task_to_id[Ie??"transcribe"])}else if(Te||Ie)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!S.return_timestamps&&S.no_timestamps_token_id&&D.at(-1)!==S.no_timestamps_token_id?D.push(S.no_timestamps_token_id):S.return_timestamps&&D.at(-1)===S.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(Se=>Se!=null)}async generate({inputs:S=null,generation_config:D=null,logits_processor:Te=null,stopping_criteria:Ie=null,...Se}){D=this._prepare_generation_config(D,Se);const Xe=Se.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(Te??(Te=new M.LogitsProcessorList),Te.push(new M.WhisperTimeStampLogitsProcessor(D,Xe))),D.begin_suppress_tokens&&(Te??(Te=new M.LogitsProcessorList),Te.push(new M.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Xe.length))),D.return_token_timestamps){if(!D.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.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const tt=await super.generate({inputs:S,generation_config:D,logits_processor:Te,decoder_input_ids:Xe,...Se});return D.return_token_timestamps&&(tt.token_timestamps=this._extract_token_timestamps(tt,D.alignment_heads,D.num_frames)),tt}_extract_token_timestamps(S,D,Te=null,Ie=.02){if(!S.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`.");Te==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 Xe=S.cross_attentions,tt=Array.from({length:this.config.decoder_layers},(ir,Xt)=>(0,C.cat)(Xe.map(dr=>dr[Xt]),2)),ft=(0,C.stack)(D.map(([ir,Xt])=>{if(ir>=tt.length)throw new Error(`Layer index ${ir} is out of bounds for cross attentions (length ${tt.length}).`);return Te?tt[ir].slice(null,Xt,null,[0,Te]):tt[ir].slice(null,Xt)})).transpose(1,0,2,3),[bt,Ht]=(0,C.std_mean)(ft,-2,0,!0),jt=ft.clone();for(let ir=0;irdr[os+1]-dr[os]),pr=(0,Q.mergeArrays)([1],$r).map(Lr=>!!Lr),kr=[];for(let Lr=0;LrLt.findIndex(Gt=>Gt==Se)),ft=tt.every(Lt=>Lt===-1),bt=tt.every(Lt=>Lt!==-1);if(!ft&&!bt)throw new Error("Every input should contain either 0 or 1 image token.");if(ft)return{inputs_embeds:S,attention_mask:Ie};const Ht=[],jt=[];for(let Lt=0;LtArray.from({length:S.dims[0]},$r=>Array.from({length:S.dims[1]},pr=>1))),sr=D?D.tolist():[],ir=Te?Te.tolist():[];let Xt=0,dr=0;for(let Or=0;OrLt[Or][Ur]==1),kr=$r.reduce((Ar,Ur,mn)=>(Ur==ft&&Ar.push(mn),Ar),[]).map(Ar=>$r[Ar+1]),Lr=kr.filter(Ar=>Ar==Xe).length,os=kr.filter(Ar=>Ar==tt).length;let Kr=[],Ss=0,In=Lr,pc=os;for(let Ar=0;ArZr>Ss&&an==Xe),mn=$r.findIndex((an,Zr)=>Zr>Ss&&an==tt),fn=In>0&&Ur!==-1?Ur:$r.length+1,_n=pc>0&&mn!==-1?mn:$r.length+1;let eo,Ta,xa,hc;fn<_n?([Ta,xa,hc]=sr[Xt],++Xt,--In,eo=fn):([Ta,xa,hc]=ir[dr],++dr,--pc,eo=_n);const[mc,Ea,Pa]=[Number(Ta),Math.floor(Number(xa)/bt),Math.floor(Number(hc)/bt)],Ca=eo-Ss,No=Kr.length>0?(0,J.max)(Kr.at(-1))[0]+1:0;Kr.push(Array.from({length:3*Ca},(an,Zr)=>No+Zr%Ca));const $a=Ca+No,Uo=mc*Ea*Pa,Sp=Array.from({length:Uo},(an,Zr)=>$a+Math.floor(Zr/(Ea*Pa))),ap=Array.from({length:Uo},(an,Zr)=>$a+Math.floor(Zr/Pa)%Ea),fc=Array.from({length:Uo},(an,Zr)=>$a+Zr%Pa);Kr.push([Sp,ap,fc].flat()),Ss=eo+Uo}if(Ss<$r.length){const Ar=Kr.length>0?(0,J.max)(Kr.at(-1))[0]+1:0,Ur=$r.length-Ss;Kr.push(Array.from({length:3*Ur},(mn,fn)=>Ar+fn%Ur))}const _s=Kr.reduce((Ar,Ur)=>Ar+Ur.length,0),Ws=new Array(_s);let ba=0;for(let Ar=0;Ar<3;++Ar)for(let Ur=0;Urjt[Xt%jt.length]),sr=Array.from({length:Lt[0]},(ir,Xt)=>(0,J.max)(jt.subarray(Lt[1]*Xt,Lt[1]*(Xt+1)))[0]+1+Lt[1]);return[new C.Tensor("int64",Gt,[3,...Lt]),new C.Tensor("int64",sr,[sr.length,1])]}else{const[jt,Lt]=S.dims,Gt=BigInt64Array.from({length:3*jt*Lt},(sr,ir)=>BigInt(Math.floor(ir%Lt/jt)));return[new C.Tensor("int64",Gt,[3,...S.dims]),(0,C.zeros)([jt,1])]}}async encode_image({pixel_values:S,image_grid_thw:D}){return(await me(this.sessions.vision_encoder,{pixel_values:S,grid_thw:D})).image_features}_merge_input_ids_with_image_features(S){return ce({image_token_id:this.config.image_token_id,...S})}prepare_inputs_for_generation(S,D,Te){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const Ie=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),Se=D.rope_deltas.map(Xe=>Ie+Xe);D.position_ids=(0,C.stack)([Se,Se,Se],0)}return D}}class hi extends le{}class Pc extends hi{}class Pl extends hi{}class ur extends le{}class Cl extends ur{}class $l extends ur{}class mi extends le{}class Sl extends mi{}class kl extends mi{}class fi extends le{}class Al extends fi{}class Il extends fi{}class _i extends le{}class Fl extends _i{}class Ol extends _i{}class gi extends le{}class Dl extends gi{}class Ll extends gi{async _call(S){return new tr(await super._call(S))}}class Wn extends le{}class zl extends Wn{}class Gn extends le{}class Bl extends Gn{}class Rl extends Gn{async _call(S){return new tr(await super._call(S))}}class jl extends le{}class Nl extends jl{}class wi extends le{}class Ul extends wi{}class Vl extends wi{async _call(S){return new tr(await super._call(S))}}class Wl extends le{}class Gl extends Wl{}class yi extends le{}class Kl extends yi{}class Hl extends yi{async _call(S){return new tr(await super._call(S))}}class ql extends le{}class Ql extends ql{async _call(S){return new dc(await super._call(S))}}class Mi extends le{}class Xl extends Mi{}class bi extends Mi{async _call(S){return new tr(await super._call(S))}}class vi extends le{}class Ti extends vi{}class xi extends vi{async _call(S){return new tr(await super._call(S))}}class Ei extends le{}class Yl extends Ei{}class Jl extends Ei{}class Pi extends le{}class Zl extends Pi{}class eu extends Pi{}class Mo extends le{}class tu extends Mo{}class ru extends Mo{async _call(S){return new tr(await super._call(S))}}class bo extends le{}class Cc extends bo{}class su extends bo{async _call(S){return new Ms(await super._call(S))}}class Ci extends bo{async _call(S){return new nu(await super._call(S))}}class Ms extends He{constructor({logits:S,pred_boxes:D}){super(),this.logits=S,this.pred_boxes=D}}class nu extends He{constructor({logits:S,pred_boxes:D,pred_masks:Te}){super(),this.logits=S,this.pred_boxes=D,this.pred_masks=Te}}class $i extends le{}class ou extends $i{}class iu extends $i{async _call(S){return new au(await super._call(S))}}class au extends He{constructor({logits:S,pred_boxes:D}){super(),this.logits=S,this.pred_boxes=D}}class Si extends le{}class lu extends Si{}class uu extends Si{async _call(S){return new du(await super._call(S))}}class du extends Ms{}class ki extends le{}class $c extends ki{}class cu extends ki{async _call(S){return new tr(await super._call(S))}}class Ai extends le{}class pu extends Ai{}class hu extends Ai{async _call(S){return new tr(await super._call(S))}}class Ii extends le{}class mu extends Ii{}class Sc extends Ii{async _call(S){return new tr(await super._call(S))}}class Vs extends le{}class sn extends Vs{}class nn extends Vs{async _call(S){return new tr(await super._call(S))}}class vo extends le{}class on extends vo{}class rs extends vo{}class To extends le{}class xo extends To{}class Fi extends To{}class fu extends le{}class _u extends fu{}class Eo extends le{}class Po extends Eo{}class Oi extends Eo{}class gu extends Eo{}class Co extends le{}class wu extends Co{}class $o extends le{}class So extends $o{}class yu extends $o{}class Di extends le{}class kc extends Di{}class Mu extends Di{}class Li extends le{}class Kn extends Li{}class zi extends le{}class Bi extends zi{}class bu extends zi{async _call(S){return new tr(await super._call(S))}}class Ri extends le{}class vu extends Ri{}class Ac extends Ri{async _call(S){return new tr(await super._call(S))}}class ji extends le{}class Tu extends ji{}class Ic extends ji{async _call(S){return new tr(await super._call(S))}}class ko extends le{}class xu extends ko{}class Eu extends ko{async _call(S){return new Pu(await super._call(S))}}class Pu extends He{constructor({logits:S,pred_boxes:D}){super(),this.logits=S,this.pred_boxes=D}}class Cu extends le{}class Ao extends Cu{async get_image_embeddings({pixel_values:S}){return await _e(this,{pixel_values:S})}async forward(S){if((!S.image_embeddings||!S.image_positional_embeddings)&&(S={...S,...await this.get_image_embeddings(S)}),!S.input_labels&&S.input_points){const Te=S.input_points.dims.slice(0,-1),Ie=Te.reduce((Se,Xe)=>Se*Xe,1);S.input_labels=new C.Tensor("int64",new BigInt64Array(Ie).fill(1n),Te)}const D={image_embeddings:S.image_embeddings,image_positional_embeddings:S.image_positional_embeddings};return S.input_points&&(D.input_points=S.input_points),S.input_labels&&(D.input_labels=S.input_labels),S.input_boxes&&(D.input_boxes=S.input_boxes),await me(this.sessions.prompt_encoder_mask_decoder,D)}async _call(S){return new $u(await super._call(S))}}class $u extends He{constructor({iou_scores:S,pred_masks:D}){super(),this.iou_scores=S,this.pred_masks=D}}class Hn extends le{}class Ni extends Hn{}class Ui extends Hn{}class Vi extends le{}class Su extends Vi{}class Wi extends Vi{}class pn extends le{}class ku extends pn{}class Au extends pn{async _call(S){return new hn(await super._call(S))}}class Fc extends pn{async _call(S){return new tr(await super._call(S))}}class Iu extends pn{async _call(S){return new Yr(await super._call(S))}}class Io extends le{}class Oc extends Io{}class Fu extends Io{async _call(S){return new Yr(await super._call(S))}}class Ou extends le{}class Du extends Ou{}class qn extends le{}class Lu extends qn{}class zu extends qn{async _call(S){return new hn(await super._call(S))}}class Bu extends qn{async _call(S){return new tr(await super._call(S))}}class Qn extends le{}class Ru extends Qn{}class ju extends Qn{async _call(S){return new hn(await super._call(S))}}class Dc extends Qn{async _call(S){return new tr(await super._call(S))}}class Nu extends Qn{async _call(S){return new Yr(await super._call(S))}}class Fo extends le{}class Uu extends Fo{}class Lc extends Fo{async _call(S){return new hn(await super._call(S))}}class Vu extends Fo{async _call(S){return new tr(await super._call(S))}}class zc extends le{}class Wu extends pn{}class Gu extends pn{async _call(S){return new hn(await super._call(S))}}class Ku extends pn{async _call(S){return new tr(await super._call(S))}}class Xn extends le{}class Oo extends Xn{}class Yn extends Xn{async _call(S){return new hn(await super._call(S))}}class Gi extends Xn{async _call(S){return new tr(await super._call(S))}}class Hu extends Xn{async _call(S){return new uc(await super._call(S))}}class qu extends Xn{async _call(S){return new Yr(await super._call(S))}}class Do extends le{}class Bc extends Do{}class Ki extends Do{}class Qu extends Do{async generate_speech(S,D,{threshold:Te=.5,minlenratio:Ie=0,maxlenratio:Se=20,vocoder:Xe=null}={}){const tt={input_ids:S},{encoder_outputs:ft,encoder_attention_mask:bt}=await _e(this,tt),Ht=ft.dims[1]/this.config.reduction_factor,jt=Math.floor(Ht*Se),Lt=Math.floor(Ht*Ie),Gt=this.config.num_mel_bins;let sr=[],ir=null,Xt=null,dr=0;for(;;){++dr;const pr=Ee(!!Xt);let kr;Xt?kr=Xt.output_sequence_out:kr=new C.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Lr={use_cache_branch:pr,output_sequence:kr,encoder_attention_mask:bt,speaker_embeddings:D,encoder_hidden_states:ft};this.addPastKeyValues(Lr,ir),Xt=await me(this.sessions.decoder_model_merged,Lr),ir=this.getPastKeyValues(Xt,ir);const{prob:os,spectrum:Kr}=Xt;if(sr.push(Kr),dr>=Lt&&(Array.from(os.data).filter(Ss=>Ss>=Te).length>0||dr>=jt))break}const Or=(0,C.cat)(sr),{waveform:$r}=await me(Xe.sessions.model,{spectrogram:Or});return{spectrogram:Or,waveform:$r}}}class Xu extends le{constructor(){super(...arguments);ve(this,"main_input_name","spectrogram")}}class Yu extends le{}class Rc extends Yu{}class Hi extends le{}class qi extends Hi{}class Ju extends Hi{}class Qi extends le{}class Zu extends Qi{}class jc extends Qi{}class Xi extends le{}class ed extends Xi{}class Nc extends Xi{}class Lo extends le{}class td extends Lo{}class rd extends Lo{static async from_pretrained(S,D={}){return D.model_file_name??(D.model_file_name="text_model"),super.from_pretrained(S,D)}}class sd extends Lo{static async from_pretrained(S,D={}){return D.model_file_name??(D.model_file_name="audio_model"),super.from_pretrained(S,D)}}class Uc extends le{}class Yi extends Uc{async _call(S){return new cc(await super._call(S))}}class zo extends le{}class Vc extends zo{}class nd extends zo{}class Wc extends zo{}class Ji extends le{}class od extends Ji{}class id extends Ji{}class Zi extends le{}class Gc extends Zi{}class ad extends Zi{async _call(S){return new tr(await super._call(S))}}class ea extends le{}class Kc extends ea{}class Hc extends ea{}class ld extends le{constructor(){super(...arguments);ve(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(D){const[Te,Ie]=D.dims,Se=this.config.decoder.num_codebooks,Xe=Ie-Se;let tt=0;for(let Ht=0;Ht0&&Gt<=Xe&&(D.data[tt++]=D.data[Ht])}const ft=Math.floor(Te/Se),bt=tt/(ft*Se);return new C.Tensor(D.type,D.data.slice(0,tt),[ft,Se,bt])}prepare_inputs_for_generation(D,Te,Ie){let Se=structuredClone(D);for(let tt=0;tt=ft&&(Se[tt][ft]=BigInt(this.config.decoder.pad_token_id));return Ie.guidance_scale!==null&&Ie.guidance_scale>1&&(Se=Se.concat(Se)),super.prepare_inputs_for_generation(Se,Te,Ie)}async generate(D){const Te=await super.generate(D),Ie=this._apply_and_filter_by_delay_pattern_mask(Te).unsqueeze_(0),{audio_values:Se}=await me(this.sessions.encodec_decode,{audio_codes:Ie});return Se}}class ss extends le{}class ud extends ss{}class dd extends ss{async _call(S){return new tr(await super._call(S))}}class Bo extends le{}class cd extends Bo{}class Jn extends Bo{async _call(S){return new tr(await super._call(S))}}class ta extends le{}class pd extends ta{}class ra extends ta{async _call(S){return new tr(await super._call(S))}}class sa extends le{}class hd extends sa{}class na extends sa{async _call(S){return new tr(await super._call(S))}}class md extends le{}class fd extends md{}class _d extends le{}class oa extends _d{constructor(...D){super(...D);ve(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(D){const Te=this._generation_mode??"text";let Ie;if(Te==="text"||!D.past_key_values){const bt=this.sessions.prepare_inputs_embeds,Ht=(0,Q.pick)(D,bt.inputNames);Ie=await me(bt,Ht)}else{const bt=this.sessions.gen_img_embeds,Ht=(0,Q.pick)({image_ids:D.input_ids},bt.inputNames);Ie=await me(bt,Ht)}const Se={...D,...Ie},Xe=await U(this,Se),tt=this.sessions[Te==="text"?"lm_head":"gen_head"];if(!tt)throw new Error(`Unable to find "${tt}" generation head`);const ft=await me(tt,(0,Q.pick)(Xe,tt.inputNames));return{...Ie,...Xe,...ft}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const Te=(D.inputs??D[this.main_input_name]).dims[1],Se=(await super.generate(D)).slice(null,[Te,null]),Xe=this.sessions.image_decode,{decoded_image:tt}=await me(Xe,{generated_tokens:Se}),ft=tt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),bt=[];for(const Ht of ft){const jt=q.RawImage.fromTensor(Ht);bt.push(jt)}return bt}}class gd extends He{constructor({char_logits:S,bpe_logits:D,wp_logits:Te}){super(),this.char_logits=S,this.bpe_logits=D,this.wp_logits=Te}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class wd extends le{}class ia extends wd{async _call(S){return new gd(await super._call(S))}}class aa extends le{}class qc extends aa{}class la extends aa{}class ua extends le{}class yd extends ua{}class Md extends ua{}class vr{static async from_pretrained(S,{progress_callback:D=null,config:Te=null,cache_dir:Ie=null,local_files_only:Se=!1,revision:Xe="main",model_file_name:tt=null,subfolder:ft="onnx",device:bt=null,dtype:Ht=null,use_external_data_format:jt=null,session_options:Lt={}}={}){const Gt={progress_callback:D,config:Te,cache_dir:Ie,local_files_only:Se,revision:Xe,model_file_name:tt,subfolder:ft,device:bt,dtype:Ht,use_external_data_format:jt,session_options:Lt};if(Gt.config=await w.AutoConfig.from_pretrained(S,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const sr of this.MODEL_CLASS_MAPPINGS){const ir=sr.get(Gt.config.model_type);if(ir)return await ir[1].from_pretrained(S,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await le.from_pretrained(S,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}ve(vr,"MODEL_CLASS_MAPPINGS",null),ve(vr,"BASE_IF_FAIL",!1);const Qc=new Map([["bert",["BertModel",$e]],["nomic_bert",["NomicBertModel",dt]],["roformer",["RoFormerModel",ht]],["electra",["ElectraModel",Et]],["esm",["EsmModel",Br]],["convbert",["ConvBertModel",Ae]],["camembert",["CamembertModel",as]],["deberta",["DebertaModel",Ts]],["deberta-v2",["DebertaV2Model",Js]],["mpnet",["MPNetModel",Bn]],["albert",["AlbertModel",Cn]],["distilbert",["DistilBertModel",It]],["roberta",["RobertaModel",wr]],["xlm",["XLMModel",us]],["xlm-roberta",["XLMRobertaModel",Is]],["clap",["ClapModel",td]],["clip",["CLIPModel",ja]],["clipseg",["CLIPSegModel",Xa]],["chinese_clip",["ChineseCLIPModel",Ka]],["siglip",["SiglipModel",Va]],["jina_clip",["JinaCLIPModel",Ha]],["mobilebert",["MobileBertModel",uo]],["squeezebert",["SqueezeBertModel",dn]],["wav2vec2",["Wav2Vec2Model",ku]],["wav2vec2-bert",["Wav2Vec2BertModel",Uu]],["unispeech",["UniSpeechModel",Lu]],["unispeech-sat",["UniSpeechSatModel",Ru]],["hubert",["HubertModel",Wu]],["wavlm",["WavLMModel",Oo]],["audio-spectrogram-transformer",["ASTModel",Yo]],["vits",["VitsModel",Yi]],["pyannote",["PyAnnoteModel",Oc]],["wespeaker-resnet",["WeSpeakerResNetModel",Du]],["detr",["DetrModel",Cc]],["rt_detr",["RTDetrModel",ou]],["table-transformer",["TableTransformerModel",lu]],["vit",["ViTModel",Dl]],["pvt",["PvtModel",Bl]],["vit_msn",["ViTMSNModel",Ul]],["vit_mae",["ViTMAEModel",Nl]],["groupvit",["GroupViTModel",Gl]],["fastvit",["FastViTModel",Kl]],["mobilevit",["MobileViTModel",Xl]],["mobilevitv2",["MobileViTV2Model",Ti]],["owlvit",["OwlViTModel",Yl]],["owlv2",["Owlv2Model",Zl]],["beit",["BeitModel",tu]],["deit",["DeiTModel",$c]],["hiera",["HieraModel",pu]],["convnext",["ConvNextModel",Bi]],["convnextv2",["ConvNextV2Model",vu]],["dinov2",["Dinov2Model",Tu]],["resnet",["ResNetModel",mu]],["swin",["SwinModel",sn]],["swin2sr",["Swin2SRModel",on]],["donut-swin",["DonutSwinModel",Kn]],["yolos",["YolosModel",xu]],["dpt",["DPTModel",xo]],["glpn",["GLPNModel",kc]],["hifigan",["SpeechT5HifiGan",Xu]],["efficientnet",["EfficientNetModel",Gc]],["decision_transformer",["DecisionTransformerModel",fd]],["patchtst",["PatchTSTForPrediction",qc]],["patchtsmixer",["PatchTSMixerForPrediction",yd]],["mobilenet_v1",["MobileNetV1Model",ud]],["mobilenet_v2",["MobileNetV2Model",cd]],["mobilenet_v3",["MobileNetV3Model",pd]],["mobilenet_v4",["MobileNetV4Model",hd]],["maskformer",["MaskFormerModel",So]],["mgp-str",["MgpstrForSceneTextRecognition",ia]]]),Xc=new Map([["t5",["T5Model",Un]],["longt5",["LongT5Model",_r]],["mt5",["MT5Model",K]],["bart",["BartModel",Pe]],["mbart",["MBartModel",pt]],["marian",["MarianModel",Ni]],["whisper",["WhisperModel",Vn]],["m2m_100",["M2M100Model",Su]],["blenderbot",["BlenderbotModel",Cr]],["blenderbot-small",["BlenderbotSmallModel",hs]]]),Yc=new Map([["bloom",["BloomModel",Sl]],["jais",["JAISModel",Za]],["gpt2",["GPT2Model",Ja]],["gptj",["GPTJModel",sl]],["gpt_bigcode",["GPTBigCodeModel",ol]],["gpt_neo",["GPTNeoModel",$s]],["gpt_neox",["GPTNeoXModel",tl]],["codegen",["CodeGenModel",al]],["llama",["LlamaModel",ul]],["olmo",["OlmoModel",hl]],["mobilellm",["MobileLLMModel",cl]],["granite",["GraniteModel",ml]],["cohere",["CohereModel",xc]],["gemma",["GemmaModel",gl]],["gemma2",["Gemma2Model",yl]],["openelm",["OpenELMModel",bl]],["qwen2",["Qwen2Model",Tl]],["phi",["PhiModel",Pc]],["phi3",["Phi3Model",Cl]],["mpt",["MptModel",Al]],["opt",["OPTModel",Fl]],["mistral",["MistralModel",qi]],["starcoder2",["Starcoder2Model",Zu]],["falcon",["FalconModel",ed]],["stablelm",["StableLmModel",od]]]),bd=new Map([["speecht5",["SpeechT5ForSpeechToText",Ki]],["whisper",["WhisperForConditionalGeneration",er]]]),vd=new Map([["speecht5",["SpeechT5ForTextToSpeech",Qu]]]),Td=new Map([["vits",["VitsModel",Yi]],["musicgen",["MusicgenForConditionalGeneration",ld]]]),xd=new Map([["bert",["BertForSequenceClassification",Qe]],["roformer",["RoFormerForSequenceClassification",A]],["electra",["ElectraForSequenceClassification",ar]],["esm",["EsmForSequenceClassification",br]],["convbert",["ConvBertForSequenceClassification",ot]],["camembert",["CamembertForSequenceClassification",Qs]],["deberta",["DebertaForSequenceClassification",Xs]],["deberta-v2",["DebertaV2ForSequenceClassification",zs]],["mpnet",["MPNetForSequenceClassification",rn]],["albert",["AlbertForSequenceClassification",Rn]],["distilbert",["DistilBertForSequenceClassification",Wr]],["roberta",["RobertaForSequenceClassification",ms]],["xlm",["XLMForSequenceClassification",yr]],["xlm-roberta",["XLMRobertaForSequenceClassification",St]],["bart",["BartForSequenceClassification",lt]],["mbart",["MBartForSequenceClassification",Wt]],["mobilebert",["MobileBertForSequenceClassification",Ln]],["squeezebert",["SqueezeBertForSequenceClassification",En]]]),Ed=new Map([["bert",["BertForTokenClassification",qe]],["roformer",["RoFormerForTokenClassification",ne]],["electra",["ElectraForTokenClassification",Mr]],["esm",["EsmForTokenClassification",Tn]],["convbert",["ConvBertForTokenClassification",ut]],["camembert",["CamembertForTokenClassification",Ds]],["deberta",["DebertaForTokenClassification",un]],["deberta-v2",["DebertaV2ForTokenClassification",ps]],["mpnet",["MPNetForTokenClassification",Es]],["distilbert",["DistilBertForTokenClassification",en]],["roberta",["RobertaForTokenClassification",Ps]],["xlm",["XLMForTokenClassification",wt]],["xlm-roberta",["XLMRobertaForTokenClassification",po]]]),da=new Map([["t5",["T5ForConditionalGeneration",Sn]],["longt5",["LongT5ForConditionalGeneration",xe]],["mt5",["MT5ForConditionalGeneration",oe]],["bart",["BartForConditionalGeneration",Ue]],["mbart",["MBartForConditionalGeneration",Tt]],["marian",["MarianMTModel",Ui]],["m2m_100",["M2M100ForConditionalGeneration",Wi]],["blenderbot",["BlenderbotForConditionalGeneration",qt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Gr]]]),Pd=new Map([["bloom",["BloomForCausalLM",kl]],["gpt2",["GPT2LMHeadModel",Tc]],["jais",["JAISLMHeadModel",fo]],["gptj",["GPTJForCausalLM",nl]],["gpt_bigcode",["GPTBigCodeForCausalLM",il]],["gpt_neo",["GPTNeoForCausalLM",el]],["gpt_neox",["GPTNeoXForCausalLM",rl]],["codegen",["CodeGenForCausalLM",ll]],["llama",["LlamaForCausalLM",dl]],["olmo",["OlmoForCausalLM",di]],["mobilellm",["MobileLLMForCausalLM",pl]],["granite",["GraniteForCausalLM",fl]],["cohere",["CohereForCausalLM",_l]],["gemma",["GemmaForCausalLM",wl]],["gemma2",["Gemma2ForCausalLM",Ml]],["openelm",["OpenELMForCausalLM",vl]],["qwen2",["Qwen2ForCausalLM",Ec]],["phi",["PhiForCausalLM",Pl]],["phi3",["Phi3ForCausalLM",$l]],["mpt",["MptForCausalLM",Il]],["opt",["OPTForCausalLM",Ol]],["mbart",["MBartForCausalLM",gr]],["mistral",["MistralForCausalLM",Ju]],["starcoder2",["Starcoder2ForCausalLM",jc]],["falcon",["FalconForCausalLM",Nc]],["trocr",["TrOCRForCausalLM",Rc]],["stablelm",["StableLmForCausalLM",id]]]),Jc=new Map([["multi_modality",["MultiModalityCausalLM",oa]]]),Cd=new Map([["bert",["BertForMaskedLM",et]],["roformer",["RoFormerForMaskedLM",_t]],["electra",["ElectraForMaskedLM",Ct]],["esm",["EsmForMaskedLM",As]],["convbert",["ConvBertForMaskedLM",Je]],["camembert",["CamembertForMaskedLM",qs]],["deberta",["DebertaForMaskedLM",Ls]],["deberta-v2",["DebertaV2ForMaskedLM",Zs]],["mpnet",["MPNetForMaskedLM",co]],["albert",["AlbertForMaskedLM",Nn]],["distilbert",["DistilBertForMaskedLM",Sr]],["roberta",["RobertaForMaskedLM",qr]],["xlm",["XLMWithLMHeadModel",or]],["xlm-roberta",["XLMRobertaForMaskedLM",Fs]],["mobilebert",["MobileBertForMaskedLM",Dn]],["squeezebert",["SqueezeBertForMaskedLM",xn]]]),$d=new Map([["bert",["BertForQuestionAnswering",ze]],["roformer",["RoFormerForQuestionAnswering",V]],["electra",["ElectraForQuestionAnswering",Nr]],["convbert",["ConvBertForQuestionAnswering",At]],["camembert",["CamembertForQuestionAnswering",vn]],["deberta",["DebertaForQuestionAnswering",Ys]],["deberta-v2",["DebertaV2ForQuestionAnswering",it]],["mpnet",["MPNetForQuestionAnswering",js]],["albert",["AlbertForQuestionAnswering",jn]],["distilbert",["DistilBertForQuestionAnswering",Bs]],["roberta",["RobertaForQuestionAnswering",Ut]],["xlm",["XLMForQuestionAnswering",Zt]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ze]],["mobilebert",["MobileBertForQuestionAnswering",zn]],["squeezebert",["SqueezeBertForQuestionAnswering",Pn]]]),ca=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Zo]],["idefics3",["Idefics3ForConditionalGeneration",Us]]]),Zc=new Map([["llava",["LlavaForConditionalGeneration",ho]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",La]],["moondream1",["Moondream1ForConditionalGeneration",za]],["florence2",["Florence2ForConditionalGeneration",Ba]],["qwen2-vl",["Qwen2VLForConditionalGeneration",El]],["idefics3",["Idefics3ForConditionalGeneration",Us]]]),ep=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Zo]]]),Sd=new Map([["vit",["ViTForImageClassification",Ll]],["pvt",["PvtForImageClassification",Rl]],["vit_msn",["ViTMSNForImageClassification",Vl]],["fastvit",["FastViTForImageClassification",Hl]],["mobilevit",["MobileViTForImageClassification",bi]],["mobilevitv2",["MobileViTV2ForImageClassification",xi]],["beit",["BeitForImageClassification",ru]],["deit",["DeiTForImageClassification",cu]],["hiera",["HieraForImageClassification",hu]],["convnext",["ConvNextForImageClassification",bu]],["convnextv2",["ConvNextV2ForImageClassification",Ac]],["dinov2",["Dinov2ForImageClassification",Ic]],["resnet",["ResNetForImageClassification",Sc]],["swin",["SwinForImageClassification",nn]],["segformer",["SegformerForImageClassification",nd]],["efficientnet",["EfficientNetForImageClassification",ad]],["mobilenet_v1",["MobileNetV1ForImageClassification",dd]],["mobilenet_v2",["MobileNetV2ForImageClassification",Jn]],["mobilenet_v3",["MobileNetV3ForImageClassification",ra]],["mobilenet_v4",["MobileNetV4ForImageClassification",na]]]),kd=new Map([["detr",["DetrForObjectDetection",su]],["rt_detr",["RTDetrForObjectDetection",iu]],["table-transformer",["TableTransformerForObjectDetection",uu]],["yolos",["YolosForObjectDetection",Eu]]]),Ad=new Map([["owlvit",["OwlViTForObjectDetection",Jl]],["owlv2",["Owlv2ForObjectDetection",eu]]]),tp=new Map([["detr",["DetrForSegmentation",Ci]],["clipseg",["CLIPSegForImageSegmentation",Ya]]]),Zn=new Map([["segformer",["SegformerForSemanticSegmentation",Wc]],["sapiens",["SapiensForSemanticSegmentation",Po]]]),pa=new Map([["detr",["DetrForSegmentation",Ci]],["maskformer",["MaskFormerForInstanceSegmentation",yu]]]),ha=new Map([["sam",["SamModel",Ao]]]),ma=new Map([["wav2vec2",["Wav2Vec2ForCTC",Au]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Lc]],["unispeech",["UniSpeechForCTC",zu]],["unispeech-sat",["UniSpeechSatForCTC",ju]],["wavlm",["WavLMForCTC",Yn]],["hubert",["HubertForCTC",Gu]]]),fa=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Fc]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Vu]],["unispeech",["UniSpeechForSequenceClassification",Bu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Dc]],["wavlm",["WavLMForSequenceClassification",Gi]],["hubert",["HubertForSequenceClassification",Ku]],["audio-spectrogram-transformer",["ASTForAudioClassification",Da]]]),Id=new Map([["wavlm",["WavLMForXVector",Hu]]]),Fd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Nu]],["wavlm",["WavLMForAudioFrameClassification",qu]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Iu]],["pyannote",["PyAnnoteForAudioFrameClassification",Fu]]]),_a=new Map([["vitmatte",["VitMatteForImageMatting",Ql]]]),Od=new Map([["patchtst",["PatchTSTForPrediction",la]],["patchtsmixer",["PatchTSMixerForPrediction",Md]]]),Dd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",rs]]]),Ld=new Map([["dpt",["DPTForDepthEstimation",Fi]],["depth_anything",["DepthAnythingForDepthEstimation",_u]],["glpn",["GLPNForDepthEstimation",Mu]],["sapiens",["SapiensForDepthEstimation",Oi]],["depth_pro",["DepthProForDepthEstimation",wu]]]),ga=new Map([["sapiens",["SapiensForNormalEstimation",gu]]]),zd=new Map([["vitpose",["VitPoseForPoseEstimation",zl]]]),Bd=new Map([["clip",["CLIPVisionModelWithProjection",Ua]],["siglip",["SiglipVisionModel",Ga]],["jina_clip",["JinaCLIPVisionModel",Qa]]]),wa=[[Qc,N.EncoderOnly],[Xc,N.EncoderDecoder],[Yc,N.DecoderOnly],[xd,N.EncoderOnly],[Ed,N.EncoderOnly],[da,N.Seq2Seq],[bd,N.Seq2Seq],[Pd,N.DecoderOnly],[Jc,N.MultiModality],[Cd,N.EncoderOnly],[$d,N.EncoderOnly],[ca,N.Vision2Seq],[Zc,N.ImageTextToText],[Sd,N.EncoderOnly],[tp,N.EncoderOnly],[pa,N.EncoderOnly],[Zn,N.EncoderOnly],[_a,N.EncoderOnly],[Od,N.EncoderOnly],[Dd,N.EncoderOnly],[Ld,N.EncoderOnly],[ga,N.EncoderOnly],[zd,N.EncoderOnly],[kd,N.EncoderOnly],[Ad,N.EncoderOnly],[ha,N.MaskGeneration],[ma,N.EncoderOnly],[fa,N.EncoderOnly],[vd,N.Seq2Seq],[Td,N.EncoderOnly],[Id,N.EncoderOnly],[Fd,N.EncoderOnly],[Bd,N.EncoderOnly]];for(const[f,S]of wa)for(const[D,Te]of f.values())I.set(D,S),k.set(Te,D),_.set(D,Te);const rp=[["MusicgenForConditionalGeneration",ld,N.Musicgen],["CLIPTextModelWithProjection",Na,N.EncoderOnly],["SiglipTextModel",Wa,N.EncoderOnly],["JinaCLIPTextModel",qa,N.EncoderOnly],["ClapTextModelWithProjection",rd,N.EncoderOnly],["ClapAudioModelWithProjection",sd,N.EncoderOnly]];for(const[f,S,D]of rp)I.set(f,D),k.set(S,f),_.set(f,S);class ya extends vr{}ve(ya,"MODEL_CLASS_MAPPINGS",wa.map(S=>S[0])),ve(ya,"BASE_IF_FAIL",!0);class Rd extends vr{}ve(Rd,"MODEL_CLASS_MAPPINGS",[xd]);class jd extends vr{}ve(jd,"MODEL_CLASS_MAPPINGS",[Ed]);class sp extends vr{}ve(sp,"MODEL_CLASS_MAPPINGS",[da]);class Nd extends vr{}ve(Nd,"MODEL_CLASS_MAPPINGS",[bd]);class Ud extends vr{}ve(Ud,"MODEL_CLASS_MAPPINGS",[vd]);class Vd extends vr{}ve(Vd,"MODEL_CLASS_MAPPINGS",[Td]);class Wd extends vr{}ve(Wd,"MODEL_CLASS_MAPPINGS",[Pd]);class np extends vr{}ve(np,"MODEL_CLASS_MAPPINGS",[Cd]);class Gd extends vr{}ve(Gd,"MODEL_CLASS_MAPPINGS",[$d]);class Kd extends vr{}ve(Kd,"MODEL_CLASS_MAPPINGS",[ca]);class Hd extends vr{}ve(Hd,"MODEL_CLASS_MAPPINGS",[Sd]);class op extends vr{}ve(op,"MODEL_CLASS_MAPPINGS",[tp]);class qd extends vr{}ve(qd,"MODEL_CLASS_MAPPINGS",[Zn]);class Qd extends vr{}ve(Qd,"MODEL_CLASS_MAPPINGS",[pa]);class Xd extends vr{}ve(Xd,"MODEL_CLASS_MAPPINGS",[kd]);class Yd extends vr{}ve(Yd,"MODEL_CLASS_MAPPINGS",[Ad]);class Jd extends vr{}ve(Jd,"MODEL_CLASS_MAPPINGS",[ha]);class Zd extends vr{}ve(Zd,"MODEL_CLASS_MAPPINGS",[ma]);class ec extends vr{}ve(ec,"MODEL_CLASS_MAPPINGS",[fa]);class tc extends vr{}ve(tc,"MODEL_CLASS_MAPPINGS",[Id]);class rc extends vr{}ve(rc,"MODEL_CLASS_MAPPINGS",[Fd]);class sc extends vr{}ve(sc,"MODEL_CLASS_MAPPINGS",[ep]);class nc extends vr{}ve(nc,"MODEL_CLASS_MAPPINGS",[_a]);class Ma extends vr{}ve(Ma,"MODEL_CLASS_MAPPINGS",[Dd]);class oc extends vr{}ve(oc,"MODEL_CLASS_MAPPINGS",[Ld]);class ic extends vr{}ve(ic,"MODEL_CLASS_MAPPINGS",[ga]);class ac extends vr{}ve(ac,"MODEL_CLASS_MAPPINGS",[zd]);class lc extends vr{}ve(lc,"MODEL_CLASS_MAPPINGS",[Bd]);class ip extends He{constructor({logits:S,past_key_values:D,encoder_outputs:Te,decoder_attentions:Ie=null,cross_attentions:Se=null}){super(),this.logits=S,this.past_key_values=D,this.encoder_outputs=Te,this.decoder_attentions=Ie,this.cross_attentions=Se}}class tr extends He{constructor({logits:S}){super(),this.logits=S}}class uc extends He{constructor({logits:S,embeddings:D}){super(),this.logits=S,this.embeddings=D}}class Yr extends He{constructor({logits:S}){super(),this.logits=S}}class Jr extends He{constructor({logits:S}){super(),this.logits=S}}class ns extends He{constructor({start_logits:S,end_logits:D}){super(),this.start_logits=S,this.end_logits=D}}class hn extends He{constructor({logits:S}){super(),this.logits=S}}class $p extends He{constructor({logits:S,past_key_values:D}){super(),this.logits=S,this.past_key_values=D}}class dc extends He{constructor({alphas:S}){super(),this.alphas=S}}class cc extends He{constructor({waveform:S,spectrogram:D}){super(),this.waveform=S,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(Oe,R,c)=>{c.r(R),c.d(R,{ASTFeatureExtractor:()=>G});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var z=c("./src/utils/audio.js");class G extends w.FeatureExtractor{constructor(Q){super(Q);const g=this.config.sampling_rate,v=(0,z.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let M=0;M{c.r(R),c.d(R,{AutoFeatureExtractor:()=>re});var w=c("./src/utils/constants.js"),z=c("./src/utils/hub.js");c("./src/base/feature_extraction_utils.js");var G=c("./src/models/feature_extractors.js");class re{static async from_pretrained(g,v={}){const M=await(0,z.getModelJSON)(g,w.FEATURE_EXTRACTOR_NAME,!0,v),y=M.feature_extractor_type,C=G[y];if(!C)throw new Error(`Unknown feature_extractor_type: '${y}'. Please report this at ${w.GITHUB_ISSUE_URL}.`);return new C(M)}}},"./src/models/auto/image_processing_auto.js":(Oe,R,c)=>{c.r(R),c.d(R,{AutoImageProcessor:()=>Q});var w=c("./src/utils/constants.js"),z=c("./src/utils/hub.js"),G=c("./src/base/image_processors_utils.js"),re=c("./src/models/image_processors.js");class Q{static async from_pretrained(v,M={}){const y=await(0,z.getModelJSON)(v,w.IMAGE_PROCESSOR_NAME,!0,M),C=y.image_processor_type??y.feature_extractor_type;let q=re[C];return q||(C!==void 0&&console.warn(`Image processor type '${C}' not found, assuming base ImageProcessor. Please report this at ${w.GITHUB_ISSUE_URL}.`),q=G.ImageProcessor),new q(y)}}},"./src/models/auto/processing_auto.js":(Oe,R,c)=>{c.r(R),c.d(R,{AutoProcessor:()=>v});var w=c("./src/utils/constants.js"),z=c("./src/utils/hub.js"),G=c("./src/base/processing_utils.js"),re=c("./src/models/processors.js"),Q=c("./src/models/image_processors.js"),g=c("./src/models/feature_extractors.js");class v{static async from_pretrained(y,C={}){const q=await(0,z.getModelJSON)(y,w.IMAGE_PROCESSOR_NAME,!0,C),{image_processor_type:J,feature_extractor_type:ie,processor_class:fe}=q;if(fe&&re[fe])return re[fe].from_pretrained(y,C);if(!J&&!ie)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const j={};if(J){const Z=Q[J];if(!Z)throw new Error(`Unknown image_processor_type: '${J}'.`);j.image_processor=new Z(q)}if(ie){const Z=Q[ie];if(Z)j.image_processor=new Z(q);else{const N=g[ie];if(!N)throw new Error(`Unknown feature_extractor_type: '${ie}'.`);j.feature_extractor=new N(q)}}const X={};return new G.Processor(X,j)}}},"./src/models/beit/image_processing_beit.js":(Oe,R,c)=>{c.r(R),c.d(R,{BeitFeatureExtractor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(Oe,R,c)=>{c.r(R),c.d(R,{BitImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(Oe,R,c)=>{c.r(R),c.d(R,{ChineseCLIPFeatureExtractor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(Oe,R,c)=>{c.r(R),c.d(R,{ClapFeatureExtractor:()=>G});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var z=c("./src/utils/audio.js");class G extends w.FeatureExtractor{constructor(Q){super(Q),this.mel_filters=(0,z.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,z.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,z.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(Q,g,v,M){let y;const C=Q.length-g;if(C>0)if(v==="rand_trunc"){const q=Math.floor(Math.random()*(C+1));Q=Q.subarray(q,q+g),y=await this._extract_fbank_features(Q,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(C<0){let q=new Float64Array(g);if(q.set(Q),M==="repeat")for(let J=Q.length;J{c.r(R),c.d(R,{CLIPFeatureExtractor:()=>G,CLIPImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/convnext/image_processing_convnext.js":(Oe,R,c)=>{c.r(R),c.d(R,{ConvNextFeatureExtractor:()=>G,ConvNextImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{constructor(Q){super(Q),this.crop_pct=this.config.crop_pct??.875}async resize(Q){var v;const g=(v=this.size)==null?void 0:v.shortest_edge;if(g===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(g<384){const M=Math.floor(g/this.crop_pct),[y,C]=this.get_resize_output_image_size(Q,{shortest_edge:M});Q=await Q.resize(y,C,{resample:this.resample}),Q=await Q.center_crop(g,g)}else Q=await Q.resize(g,g,{resample:this.resample});return Q}}class G extends z{}},"./src/models/deit/image_processing_deit.js":(Oe,R,c)=>{c.r(R),c.d(R,{DeiTFeatureExtractor:()=>G,DeiTImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/detr/image_processing_detr.js":(Oe,R,c)=>{c.r(R),c.d(R,{DetrFeatureExtractor:()=>re,DetrImageProcessor:()=>G});var w=c("./src/base/image_processors_utils.js"),z=c("./src/utils/tensor.js");class G extends w.ImageProcessor{async _call(g){const v=await super._call(g),M=[v.pixel_values.dims[0],64,64],y=(0,z.full)(M,1n);return{...v,pixel_mask:y}}post_process_object_detection(...g){return(0,w.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,w.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,w.post_process_instance_segmentation)(...g)}}class re extends G{}},"./src/models/donut/image_processing_donut.js":(Oe,R,c)=>{c.r(R),c.d(R,{DonutFeatureExtractor:()=>G,DonutImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{pad_image(Q,g,v,M={}){const[y,C,q]=g;let J=this.image_mean;Array.isArray(this.image_mean)||(J=new Array(q).fill(J));let ie=this.image_std;Array.isArray(ie)||(ie=new Array(q).fill(J));const fe=J.map((j,X)=>-j/ie[X]);return super.pad_image(Q,g,v,{center:!0,constant_values:fe,...M})}}class G extends z{}},"./src/models/dpt/image_processing_dpt.js":(Oe,R,c)=>{c.r(R),c.d(R,{DPTFeatureExtractor:()=>G,DPTImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/efficientnet/image_processing_efficientnet.js":(Oe,R,c)=>{c.r(R),c.d(R,{EfficientNetImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{constructor(re){super(re),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(Q=>Q*Q))}}},"./src/models/feature_extractors.js":(Oe,R,c)=>{c.r(R),c.d(R,{ASTFeatureExtractor:()=>w.ASTFeatureExtractor,ClapFeatureExtractor:()=>z.ClapFeatureExtractor,ImageFeatureExtractor:()=>y.ImageProcessor,PyAnnoteFeatureExtractor:()=>G.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>re.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>Q.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>g.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>v.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var w=c("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),z=c("./src/models/clap/feature_extraction_clap.js"),G=c("./src/models/pyannote/feature_extraction_pyannote.js"),re=c("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),Q=c("./src/models/speecht5/feature_extraction_speecht5.js"),g=c("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),v=c("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=c("./src/models/whisper/feature_extraction_whisper.js"),y=c("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(Oe,R,c)=>{c.r(R),c.d(R,{Florence2Processor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js");class re extends w.Processor{constructor(g,v){super(g,v);const{tasks_answer_post_processing_type:M,task_prompts_without_inputs:y,task_prompts_with_input:C}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(M??{})),this.task_prompts_without_inputs=new Map(Object.entries(y??{})),this.task_prompts_with_input=new Map(Object.entries(C??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(g){typeof g=="string"&&(g=[g]);const v=[];for(const M of g)if(this.task_prompts_without_inputs.has(M))v.push(this.task_prompts_without_inputs.get(M));else{for(const[y,C]of this.task_prompts_with_input)if(M.includes(y)){v.push(C.replaceAll("{input}",M).replaceAll(y,""));break}v.length!==g.length&&v.push(M)}return v}post_process_generation(g,v,M){const y=this.tasks_answer_post_processing_type.get(v)??"pure_text";g=g.replaceAll("","").replaceAll("","");let C;switch(y){case"pure_text":C=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const q=y==="ocr"?"quad_boxes":"bboxes",J=g.matchAll(this.regexes[q]),ie=[],fe=[];for(const[j,X,...Z]of J)ie.push(X?X.trim():ie.at(-1)??""),fe.push(Z.map((N,I)=>(Number(N)+.5)/this.size_per_bin*M[I%2]));C={labels:ie,[q]:fe};break;default:throw new Error(`Task "${v}" (of type "${y}") not yet implemented.`)}return{[v]:C}}async _call(g,v=null,M={}){if(!g&&!v)throw new Error("Either text or images must be provided");const y=await this.image_processor(g,M),C=v?this.tokenizer(v,M):{};return{...y,...C}}}ve(re,"tokenizer_class",G.AutoTokenizer),ve(re,"image_processor_class",z.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(Oe,R,c)=>{c.r(R),c.d(R,{GLPNFeatureExtractor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/idefics3/image_processing_idefics3.js":(Oe,R,c)=>{c.r(R),c.d(R,{Idefics3ImageProcessor:()=>G});var w=c("./src/base/image_processors_utils.js"),z=c("./src/utils/tensor.js");class G extends w.ImageProcessor{constructor(Q){super(Q),this.do_image_splitting=Q.do_image_splitting??!0,this.max_image_size=Q.max_image_size}get_resize_for_vision_encoder(Q,g){let[v,M]=Q.dims.slice(-2);const y=M/v;return M>=v?(M=Math.ceil(M/g)*g,v=Math.floor(M/y),v=Math.ceil(v/g)*g):(v=Math.ceil(v/g)*g,M=Math.floor(v*y),M=Math.ceil(M/g)*g),{height:v,width:M}}async _call(Q,{do_image_splitting:g=null,return_row_col_info:v=!1}={}){let M;if(!Array.isArray(Q))M=[[Q]];else{if(Q.length===0||!Q[0])throw new Error("No images provided.");Array.isArray(Q[0])?M=Q:M=[Q]}let y=[],C=[],q=[];const J=[],ie=[];for(const k of M){let E=await Promise.all(k.map(de=>this.preprocess(de)));J.push(...E.map(de=>de.original_size)),ie.push(...E.map(de=>de.reshaped_input_size)),E.forEach(de=>de.pixel_values.unsqueeze_(0));const{longest_edge:ee}=this.max_image_size;let Y;if(g??this.do_image_splitting){let de=new Array(E.length),me=new Array(E.length);Y=await Promise.all(E.map(async(ye,Ce)=>{const Ee=this.get_resize_for_vision_encoder(ye.pixel_values,ee),Le=await(0,z.interpolate_4d)(ye.pixel_values,{size:[Ee.height,Ee.width]}),{frames:_e,num_splits_h:U,num_splits_w:ce}=await this.split_image(Le,this.max_image_size);return de[Ce]=U,me[Ce]=ce,(0,z.cat)(_e,0)})),C.push(de),q.push(me)}else{const de=[ee,ee];Y=await Promise.all(E.map(me=>(0,z.interpolate_4d)(me.pixel_values,{size:de}))),C.push(new Array(E.length).fill(0)),q.push(new Array(E.length).fill(0))}y.push((0,z.cat)(Y,0))}const fe=y.length,[j,X,Z,N]=y[0].dims;let I,_;if(fe===1)I=y[0].unsqueeze_(0),_=(0,z.full)([fe,j,Z,N],!0);else{const k=Math.max(...y.map(Y=>Y.dims.at(0)));_=(0,z.full)([fe,k,Z,N],!0);const E=_.data,ee=k*Z*N;for(let Y=0;Yv||q>M){J=Math.ceil(C/v),ie=Math.ceil(q/M);const fe=Math.ceil(C/J),j=Math.ceil(q/ie);for(let N=0;N{c.r(R),c.d(R,{Idefics3Processor:()=>M});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js");c("./src/utils/image.js");var re=c("./src/utils/core.js");function Q(y,C,q,J,ie,fe){let j="";for(let X=0;X`+ie.repeat(y);j+=` `}return j+=` ${J}${fe}`+ie.repeat(y)+`${J}`,j}function g(y,C,q,J){return`${C}${J}`+q.repeat(y)+`${C}`}function v(y,C,q,J,ie,fe){return y===0&&C===0?g(q,J,ie,fe):Q(q,y,C,J,ie,fe)}class M extends w.Processor{constructor(){super(...arguments);ve(this,"fake_image_token","");ve(this,"image_token","");ve(this,"global_img_token","")}async _call(q,J=null,ie={}){ie.return_row_col_info??(ie.return_row_col_info=!0);let fe;J&&(fe=await this.image_processor(J,ie)),Array.isArray(q)||(q=[q]);const j=fe.rows??[new Array(q.length).fill(0)],X=fe.cols??[new Array(q.length).fill(0)],Z=this.config.image_seq_len,N=[],I=[];for(let k=0;kv(Ce,Y[Ee],Z,this.fake_image_token,this.image_token,this.global_img_token)),me=E.split(this.image_token);if(me.length===0)throw new Error("The image token should be present in the text.");let ye=me[0];for(let Ce=0;Ce{c.r(R),c.d(R,{BeitFeatureExtractor:()=>w.BeitFeatureExtractor,BitImageProcessor:()=>z.BitImageProcessor,CLIPFeatureExtractor:()=>re.CLIPFeatureExtractor,CLIPImageProcessor:()=>re.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>G.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>Q.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>Q.ConvNextImageProcessor,DPTFeatureExtractor:()=>y.DPTFeatureExtractor,DPTImageProcessor:()=>y.DPTImageProcessor,DeiTFeatureExtractor:()=>g.DeiTFeatureExtractor,DeiTImageProcessor:()=>g.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>M.DonutFeatureExtractor,DonutImageProcessor:()=>M.DonutImageProcessor,EfficientNetImageProcessor:()=>C.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>q.GLPNFeatureExtractor,Idefics3ImageProcessor:()=>J.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>fe.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>j.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>X.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Z.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>Z.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>N.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>N.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>I.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>I.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>E.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>E.MobileViTImageProcessor,NougatImageProcessor:()=>ee.NougatImageProcessor,OwlViTFeatureExtractor:()=>de.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>de.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Y.Owlv2ImageProcessor,PvtImageProcessor:()=>me.PvtImageProcessor,Qwen2VLImageProcessor:()=>ye.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Ce.RTDetrImageProcessor,SamImageProcessor:()=>Ee.SamImageProcessor,SegformerFeatureExtractor:()=>Le.SegformerFeatureExtractor,SegformerImageProcessor:()=>Le.SegformerImageProcessor,SiglipImageProcessor:()=>_e.SiglipImageProcessor,Swin2SRImageProcessor:()=>U.Swin2SRImageProcessor,VLMImageProcessor:()=>ie.VLMImageProcessor,ViTFeatureExtractor:()=>ce.ViTFeatureExtractor,ViTImageProcessor:()=>ce.ViTImageProcessor,VitMatteImageProcessor:()=>he.VitMatteImageProcessor,VitPoseImageProcessor:()=>ke.VitPoseImageProcessor,YolosFeatureExtractor:()=>Re.YolosFeatureExtractor,YolosImageProcessor:()=>Re.YolosImageProcessor});var w=c("./src/models/beit/image_processing_beit.js"),z=c("./src/models/bit/image_processing_bit.js"),G=c("./src/models/chinese_clip/image_processing_chinese_clip.js"),re=c("./src/models/clip/image_processing_clip.js"),Q=c("./src/models/convnext/image_processing_convnext.js"),g=c("./src/models/deit/image_processing_deit.js"),v=c("./src/models/detr/image_processing_detr.js"),M=c("./src/models/donut/image_processing_donut.js"),y=c("./src/models/dpt/image_processing_dpt.js"),C=c("./src/models/efficientnet/image_processing_efficientnet.js"),q=c("./src/models/glpn/image_processing_glpn.js"),J=c("./src/models/idefics3/image_processing_idefics3.js"),ie=c("./src/models/janus/image_processing_janus.js"),fe=c("./src/models/jina_clip/image_processing_jina_clip.js"),j=c("./src/models/llava_onevision/image_processing_llava_onevision.js"),X=c("./src/models/mask2former/image_processing_mask2former.js"),Z=c("./src/models/maskformer/image_processing_maskformer.js"),N=c("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),I=c("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),_=c("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=c("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),E=c("./src/models/mobilevit/image_processing_mobilevit.js"),ee=c("./src/models/nougat/image_processing_nougat.js"),Y=c("./src/models/owlv2/image_processing_owlv2.js"),de=c("./src/models/owlvit/image_processing_owlvit.js"),me=c("./src/models/pvt/image_processing_pvt.js"),ye=c("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Ce=c("./src/models/rt_detr/image_processing_rt_detr.js"),Ee=c("./src/models/sam/image_processing_sam.js"),Le=c("./src/models/segformer/image_processing_segformer.js"),_e=c("./src/models/siglip/image_processing_siglip.js"),U=c("./src/models/swin2sr/image_processing_swin2sr.js"),ce=c("./src/models/vit/image_processing_vit.js"),he=c("./src/models/vitmatte/image_processing_vitmatte.js"),ke=c("./src/models/vitpose/image_processing_vitpose.js"),Re=c("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(Oe,R,c)=>{c.r(R),c.d(R,{VLMImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{constructor(re){super({do_pad:!0,pad_size:{width:re.image_size,height:re.image_size},...re}),this.constant_values=this.config.background_color.map(Q=>Q*this.rescale_factor)}pad_image(re,Q,g,v){return super.pad_image(re,Q,g,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(Oe,R,c)=>{c.r(R),c.d(R,{VLChatProcessor:()=>v});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js"),re=c("./src/utils/core.js"),Q=c("./src/utils/tensor.js"),g=c("./src/utils/image.js");class v extends w.Processor{constructor(y,C){super(y,C),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(y,{images:C=null,chat_template:q="default"}={}){C?Array.isArray(C)||(C=[C]):C=await Promise.all(y.filter(Y=>Y.images).flatMap(Y=>Y.images).map(Y=>g.RawImage.read(Y)));const J=this.tokenizer,ie=J.apply_chat_template(y,{tokenize:!1,add_generation_prompt:!0,chat_template:q}),fe=Y=>J.encode(Y,{add_special_tokens:!1}),j=ie.split(this.image_tag),X=j.length-1;if(C.length!==X)throw new Error(`Number of images provided (${C.length}) does not match number of "${this.image_tag}" image tags (${X})`);const[Z,N,I]=J.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let _=fe(j[0]),k=new Array(_.length).fill(!1);for(let Y=1;Y0){const Y=await this.image_processor(C);return Y.pixel_values.unsqueeze_(0),{...ee,...Y}}return ee}}ve(v,"image_processor_class",z.AutoImageProcessor),ve(v,"tokenizer_class",G.AutoTokenizer),ve(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(Oe,R,c)=>{c.r(R),c.d(R,{JinaCLIPImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{constructor(re){const{resize_mode:Q,fill_color:g,interpolation:v,size:M,...y}=re,C=Q==="squash"?{width:M,height:M}:Q==="shortest"?{shortest_edge:M}:{longest_edge:M},q=v==="bicubic"?3:2;super({...y,size:C,resample:q,do_center_crop:!0,crop_size:M,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(Oe,R,c)=>{c.r(R),c.d(R,{JinaCLIPProcessor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js");class re extends w.Processor{async _call(g=null,v=null,M={}){if(!g&&!v)throw new Error("Either text or images must be provided");const y=g?this.tokenizer(g,M):{},C=v?await this.image_processor(v,M):{};return{...y,...C}}}ve(re,"tokenizer_class",G.AutoTokenizer),ve(re,"image_processor_class",z.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(Oe,R,c)=>{c.r(R),c.d(R,{LlavaOnevisionImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(Oe,R,c)=>{c.r(R),c.d(R,{Mask2FormerImageProcessor:()=>z});var w=c("./src/models/maskformer/image_processing_maskformer.js");class z extends w.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(Oe,R,c)=>{c.r(R),c.d(R,{MaskFormerFeatureExtractor:()=>G,MaskFormerImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_panoptic_segmentation(...Q){return(0,w.post_process_panoptic_segmentation)(...Q)}post_process_instance_segmentation(...Q){return(0,w.post_process_instance_segmentation)(...Q)}}class G extends z{}},"./src/models/mgp_str/processing_mgp_str.js":(Oe,R,c)=>{c.r(R),c.d(R,{MgpstrProcessor:()=>g});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js"),re=c("./src/utils/maths.js");const Q={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends w.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(M,y){if(!Q.hasOwnProperty(y))throw new Error(`Format ${y} is not supported.`);const[C,q]=Q[y],J=this[C].bind(this),[ie,fe]=M.dims,j=[],X=[],Z=M.tolist();for(let I=0;I0?E.reduce((Y,de)=>Y*de,1):0;X.push(k),j.push(ee)}return[J(X),j]}char_decode(M){return this.char_tokenizer.batch_decode(M).map(y=>y.replaceAll(" ",""))}bpe_decode(M){return this.bpe_tokenizer.batch_decode(M)}wp_decode(M){return this.wp_tokenizer.batch_decode(M).map(y=>y.replaceAll(" ",""))}batch_decode([M,y,C]){const[q,J]=this._decode_helper(M,"char"),[ie,fe]=this._decode_helper(y,"bpe"),[j,X]=this._decode_helper(C,"wp"),Z=[],N=[];for(let I=0;I{c.r(R),c.d(R,{MobileNetV1FeatureExtractor:()=>G,MobileNetV1ImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(Oe,R,c)=>{c.r(R),c.d(R,{MobileNetV2FeatureExtractor:()=>G,MobileNetV2ImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(Oe,R,c)=>{c.r(R),c.d(R,{MobileNetV3FeatureExtractor:()=>G,MobileNetV3ImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(Oe,R,c)=>{c.r(R),c.d(R,{MobileNetV4FeatureExtractor:()=>G,MobileNetV4ImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/mobilevit/image_processing_mobilevit.js":(Oe,R,c)=>{c.r(R),c.d(R,{MobileViTFeatureExtractor:()=>G,MobileViTImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/nougat/image_processing_nougat.js":(Oe,R,c)=>{c.r(R),c.d(R,{NougatImageProcessor:()=>z});var w=c("./src/models/donut/image_processing_donut.js");class z extends w.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(Oe,R,c)=>{c.r(R),c.d(R,{Owlv2ImageProcessor:()=>z});var w=c("./src/models/owlvit/image_processing_owlvit.js");class z extends w.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(Oe,R,c)=>{c.r(R),c.d(R,{OwlViTFeatureExtractor:()=>G,OwlViTImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_object_detection(...Q){return(0,w.post_process_object_detection)(...Q)}}class G extends z{}},"./src/models/owlvit/processing_owlvit.js":(Oe,R,c)=>{c.r(R),c.d(R,{OwlViTProcessor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js");class re extends w.Processor{}ve(re,"tokenizer_class",G.AutoTokenizer),ve(re,"image_processor_class",z.AutoImageProcessor)},"./src/models/processors.js":(Oe,R,c)=>{c.r(R),c.d(R,{Florence2Processor:()=>w.Florence2Processor,Idefics3Processor:()=>G.Idefics3Processor,JinaCLIPProcessor:()=>Q.JinaCLIPProcessor,MgpstrProcessor:()=>z.MgpstrProcessor,OwlViTProcessor:()=>g.OwlViTProcessor,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,Qwen2VLProcessor:()=>M.Qwen2VLProcessor,SamProcessor:()=>y.SamProcessor,SpeechT5Processor:()=>C.SpeechT5Processor,VLChatProcessor:()=>re.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>q.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>J.WhisperProcessor});var w=c("./src/models/florence2/processing_florence2.js"),z=c("./src/models/mgp_str/processing_mgp_str.js"),G=c("./src/models/idefics3/processing_idefics3.js"),re=c("./src/models/janus/processing_janus.js"),Q=c("./src/models/jina_clip/processing_jina_clip.js"),g=c("./src/models/owlvit/processing_owlvit.js"),v=c("./src/models/pyannote/processing_pyannote.js"),M=c("./src/models/qwen2_vl/processing_qwen2_vl.js"),y=c("./src/models/sam/processing_sam.js"),C=c("./src/models/speecht5/processing_speecht5.js"),q=c("./src/models/wav2vec2/processing_wav2vec2.js"),J=c("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(Oe,R,c)=>{c.r(R),c.d(R,{PvtImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(Oe,R,c)=>{c.r(R),c.d(R,{PyAnnoteFeatureExtractor:()=>G});var w=c("./src/base/feature_extraction_utils.js"),z=c("./src/utils/tensor.js");class G extends w.FeatureExtractor{async _call(Q){(0,w.validate_audio_inputs)(Q,"PyAnnoteFeatureExtractor"),Q instanceof Float64Array&&(Q=new Float32Array(Q));const g=[1,1,Q.length];return{input_values:new z.Tensor("float32",Q,g)}}}},"./src/models/pyannote/processing_pyannote.js":(Oe,R,c)=>{c.r(R),c.d(R,{PyAnnoteProcessor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/feature_extraction_auto.js"),G=c("./src/utils/maths.js");class re extends w.Processor{async _call(g){return await this.feature_extractor(g)}samples_to_frames(g){return(g-this.config.offset)/this.config.step}post_process_speaker_diarization(g,v){const M=v/this.samples_to_frames(v)/this.config.sampling_rate,y=[];for(const C of g.tolist()){const q=[];let J=-1;for(let ie=0;ie({id:ie,start:fe*M,end:j*M,confidence:X/(j-fe)})))}return y}}ve(re,"feature_extractor_class",z.AutoFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(Oe,R,c)=>{c.r(R),c.d(R,{Qwen2VLImageProcessor:()=>G});var w=c("./src/base/image_processors_utils.js"),z=c("./src/utils/tensor.js");class G extends w.ImageProcessor{async _call(Q,...g){const{pixel_values:v,original_sizes:M,reshaped_input_sizes:y}=await super._call(Q,...g);let C=v;const{temporal_patch_size:q,merge_size:J,patch_size:ie}=this.config;C.dims[0]===1&&(C=(0,z.cat)(Array.from({length:q},()=>C),0));const fe=C.dims[0]/q,j=C.dims[1],X=Math.floor(C.dims[2]/ie),Z=Math.floor(C.dims[3]/ie),N=C.view(fe,q,j,Math.floor(X/J),J,ie,Math.floor(Z/J),J,ie).permute(0,3,6,4,7,2,1,5,8).view(fe*X*Z,j*q*ie*ie),I=new z.Tensor("int64",[fe,X,Z],[1,3]);return{pixel_values:N,image_grid_thw:I,original_sizes:M,reshaped_input_sizes:y}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(Oe,R,c)=>{c.r(R),c.d(R,{Qwen2VLProcessor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js"),G=c("./src/tokenizers.js");c("./src/utils/image.js");class re extends w.Processor{async _call(g,v=null,...M){Array.isArray(g)||(g=[g]);let y,C;if(v&&(y=await this.image_processor(v),C=y.image_grid_thw),C){let J=this.image_processor.config.merge_size**2,ie=0;const fe=C.tolist();g=g.map(j=>{for(;j.includes("<|image_pad|>");){const X=Number(fe[ie++].reduce((Z,N)=>Z*N,1n));j=j.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(X/J)))}return j.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...y}}}ve(re,"image_processor_class",z.AutoImageProcessor),ve(re,"tokenizer_class",G.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(Oe,R,c)=>{c.r(R),c.d(R,{RTDetrImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_object_detection(...re){return(0,w.post_process_object_detection)(...re)}}},"./src/models/sam/image_processing_sam.js":(Oe,R,c)=>{c.r(R),c.d(R,{SamImageProcessor:()=>re});var w=c("./src/base/image_processors_utils.js"),z=c("./src/utils/core.js"),G=c("./src/utils/tensor.js");class re extends w.ImageProcessor{reshape_input_points(g,v,M,y=!1){g=structuredClone(g);let C=(0,z.calculateDimensions)(g);if(C.length===3)y||(C=[1,...C]),g=[g];else if(C.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 q=0;qy!==v.dims[C]))throw Error(`The first ${M.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new G.Tensor("int64",g.flat(1/0).map(BigInt),M)}async _call(g,{input_points:v=null,input_labels:M=null,input_boxes:y=null}={}){const C=await super._call(g);if(v&&(C.input_points=this.reshape_input_points(v,C.original_sizes,C.reshaped_input_sizes)),M){if(!C.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");C.input_labels=this.add_input_labels(M,C.input_points)}return y&&(C.input_boxes=this.reshape_input_points(y,C.original_sizes,C.reshaped_input_sizes,!0)),C}async post_process_masks(g,v,M,{mask_threshold:y=0,binarize:C=!0,pad_size:q=null}={}){const J=[];q=q??this.pad_size;const ie=[q.height,q.width];for(let fe=0;fey&&(I[_]=1);Z=new G.Tensor("bool",I,Z.dims)}J.push(Z)}return J}generate_crop_boxes(g,v,{crop_n_layers:M=0,overlap_ratio:y=.3413333333333333,points_per_crop:C=32,crop_n_points_downscale_factor:q=1}={}){}}},"./src/models/sam/processing_sam.js":(Oe,R,c)=>{c.r(R),c.d(R,{SamProcessor:()=>G});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/image_processing_auto.js");class G extends w.Processor{async _call(...Q){return await this.image_processor(...Q)}post_process_masks(...Q){return this.image_processor.post_process_masks(...Q)}reshape_input_points(...Q){return this.image_processor.reshape_input_points(...Q)}}ve(G,"image_processor_class",z.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(Oe,R,c)=>{c.r(R),c.d(R,{SeamlessM4TFeatureExtractor:()=>re});var w=c("./src/base/feature_extraction_utils.js"),z=c("./src/utils/tensor.js"),G=c("./src/utils/audio.js");class re extends w.FeatureExtractor{constructor(g){super(g);const v=this.config.sampling_rate,M=(0,G.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let y=0;yM*32768),(0,G.spectrogram)(g,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(g,{padding:v=!0,pad_to_multiple_of:M=2,do_normalize_per_mel_bins:y=!0,return_attention_mask:C=!0}={}){(0,w.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let q=await this._extract_fbank_features(g,this.config.max_length);if(y){const[I,_]=q.dims,k=q.data;for(let E=0;E<_;++E){let ee=0;for(let ye=0;ye0){const ee=new Float32Array(_*(I+E));ee.set(k),ee.fill(this.config.padding_value,k.length);const Y=I+E;q=new z.Tensor(q.type,ee,[Y,_]),C&&(J=new z.Tensor("int64",new BigInt64Array(Y),[1,Y]),J.data.fill(1n,0,I))}}const[ie,fe]=q.dims,j=this.config.stride;if(ie%j!==0)throw new Error(`The number of frames (${ie}) must be a multiple of the stride (${j}).`);const Z=q.view(1,Math.floor(ie/j),fe*j),N={input_features:Z};if(C){const I=Z.dims[1],_=new BigInt64Array(I);if(J){const k=J.data;for(let E=1,ee=0;E{c.r(R),c.d(R,{SegformerFeatureExtractor:()=>G,SegformerImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_semantic_segmentation(...Q){return(0,w.post_process_semantic_segmentation)(...Q)}}class G extends z{}},"./src/models/siglip/image_processing_siglip.js":(Oe,R,c)=>{c.r(R),c.d(R,{SiglipImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(Oe,R,c)=>{c.r(R),c.d(R,{SpeechT5FeatureExtractor:()=>z});var w=c("./src/base/feature_extraction_utils.js");class z extends w.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(Oe,R,c)=>{c.r(R),c.d(R,{SpeechT5Processor:()=>re});var w=c("./src/base/processing_utils.js"),z=c("./src/tokenizers.js"),G=c("./src/models/auto/feature_extraction_auto.js");class re extends w.Processor{async _call(g){return await this.feature_extractor(g)}}ve(re,"tokenizer_class",z.AutoTokenizer),ve(re,"feature_extractor_class",G.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(Oe,R,c)=>{c.r(R),c.d(R,{Swin2SRImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{pad_image(re,Q,g,v={}){const[M,y,C]=Q;return super.pad_image(re,Q,{width:y+(g-y%g)%g,height:M+(g-M%g)%g},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(Oe,R,c)=>{c.r(R),c.d(R,{ViTFeatureExtractor:()=>G,ViTImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{}class G extends z{}},"./src/models/vitmatte/image_processing_vitmatte.js":(Oe,R,c)=>{c.r(R),c.d(R,{VitMatteImageProcessor:()=>G});var w=c("./src/base/image_processors_utils.js"),z=c("./src/utils/tensor.js");class G extends w.ImageProcessor{async _call(Q,g){Array.isArray(Q)||(Q=[Q]),Array.isArray(g)||(g=[g]);const v=await Promise.all(Q.map(C=>this.preprocess(C))),M=await Promise.all(g.map(C=>this.preprocess(C,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,z.stack)(v.map((C,q)=>(0,z.cat)([C.pixel_values,M[q].pixel_values],0)),0),original_sizes:v.map(C=>C.original_size),reshaped_input_sizes:v.map(C=>C.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(Oe,R,c)=>{c.r(R),c.d(R,{VitPoseImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_pose_estimation(re,Q,{threshold:g=null}={}){const v=re.tolist(),[M,y,C,q]=re.dims,J=[];for(let ie=0;ie{c.r(R),c.d(R,{Wav2Vec2FeatureExtractor:()=>G});var w=c("./src/base/feature_extraction_utils.js"),z=c("./src/utils/tensor.js");class G extends w.FeatureExtractor{_zero_mean_unit_var_norm(Q){const v=Q.reduce((y,C)=>y+C,0)/Q.length,M=Q.reduce((y,C)=>y+(C-v)**2,0)/Q.length;return Q.map(y=>(y-v)/Math.sqrt(M+1e-7))}async _call(Q){(0,w.validate_audio_inputs)(Q,"Wav2Vec2FeatureExtractor"),Q instanceof Float64Array&&(Q=new Float32Array(Q));let g=Q;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const v=[1,g.length];return{input_values:new z.Tensor("float32",g,v),attention_mask:new z.Tensor("int64",new BigInt64Array(g.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(Oe,R,c)=>{c.r(R),c.d(R,{Wav2Vec2ProcessorWithLM:()=>G});var w=c("./src/base/processing_utils.js"),z=c("./src/models/auto/feature_extraction_auto.js");class G extends w.Processor{async _call(Q){return await this.feature_extractor(Q)}}ve(G,"feature_extractor_class",z.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(Oe,R,c)=>{c.r(R),c.d(R,{WeSpeakerFeatureExtractor:()=>G});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var z=c("./src/utils/audio.js");class G extends w.FeatureExtractor{constructor(Q){super(Q);const g=this.config.sampling_rate,v=(0,z.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let M=0;Mg*32768),(0,z.spectrogram)(Q,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(Q){(0,w.validate_audio_inputs)(Q,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(Q)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=g.mean(1).data,M=g.data,[y,C,q]=g.dims;for(let J=0;J{c.r(R),c.d(R,{WHISPER_LANGUAGE_MAPPING:()=>z,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>G,whisper_language_to_code:()=>re});const w=[["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"]],z=new Map(w),G=new Map([...w.map(([Q,g])=>[g,Q]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function re(Q){Q=Q.toLowerCase();let g=G.get(Q);if(g===void 0)if(z.has(Q))g=Q;else{const M=Q.length===2?z.keys():z.values();throw new Error(`Language "${Q}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(Oe,R,c)=>{c.r(R),c.d(R,{WhisperFeatureExtractor:()=>re});var w=c("./src/base/feature_extraction_utils.js");c("./src/utils/tensor.js");var z=c("./src/utils/audio.js"),G=c("./src/utils/maths.js");class re extends w.FeatureExtractor{constructor(g){var v;super(g),(v=this.config).mel_filters??(v.mel_filters=(0,z.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,z.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const v=await(0,z.spectrogram)(g,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}),M=v.data,y=(0,G.max)(M)[0];for(let C=0;Cthis.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=g.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(g)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(Oe,R,c)=>{c.r(R),c.d(R,{WhisperGenerationConfig:()=>z});var w=c("./src/generation/configuration_utils.js");class z extends w.GenerationConfig{constructor(){super(...arguments);ve(this,"return_timestamps",null);ve(this,"return_token_timestamps",null);ve(this,"num_frames",null);ve(this,"alignment_heads",null);ve(this,"task",null);ve(this,"language",null);ve(this,"no_timestamps_token_id",null);ve(this,"prompt_ids",null);ve(this,"is_multilingual",null);ve(this,"lang_to_id",null);ve(this,"task_to_id",null);ve(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(Oe,R,c)=>{c.r(R),c.d(R,{WhisperProcessor:()=>re});var w=c("./src/models/auto/feature_extraction_auto.js"),z=c("./src/tokenizers.js"),G=c("./src/base/processing_utils.js");class re extends G.Processor{async _call(g){return await this.feature_extractor(g)}}ve(re,"tokenizer_class",z.AutoTokenizer),ve(re,"feature_extractor_class",w.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(Oe,R,c)=>{c.r(R),c.d(R,{YolosFeatureExtractor:()=>G,YolosImageProcessor:()=>z});var w=c("./src/base/image_processors_utils.js");class z extends w.ImageProcessor{post_process_object_detection(...Q){return(0,w.post_process_object_detection)(...Q)}}class G extends z{}},"./src/ops/registry.js":(Oe,R,c)=>{c.r(R),c.d(R,{TensorOpRegistry:()=>re});var w=c("./src/backends/onnx.js"),z=c("./src/utils/tensor.js");const G=async(Q,g,v)=>{const M=await(0,w.createInferenceSession)(new Uint8Array(Q),g);return async y=>{const C=Object.fromEntries(Object.entries(y).map(([J,ie])=>[J,ie.ort_tensor])),q=await M.run(C);return Array.isArray(v)?v.map(J=>new z.Tensor(q[J])):new z.Tensor(q[v])}};class re{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=G([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=G([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=G([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=G([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=G([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=G([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}}ve(re,"session_options",{})},"./src/pipelines.js":(Oe,R,c)=>{c.r(R),c.d(R,{AudioClassificationPipeline:()=>me,AutomaticSpeechRecognitionPipeline:()=>Ce,DepthEstimationPipeline:()=>Ye,DocumentQuestionAnsweringPipeline:()=>ke,FeatureExtractionPipeline:()=>Y,FillMaskPipeline:()=>Z,ImageClassificationPipeline:()=>Le,ImageFeatureExtractionPipeline:()=>de,ImageSegmentationPipeline:()=>_e,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Ee,ObjectDetectionPipeline:()=>ce,Pipeline:()=>ie,QuestionAnsweringPipeline:()=>X,SummarizationPipeline:()=>I,Text2TextGenerationPipeline:()=>N,TextClassificationPipeline:()=>fe,TextGenerationPipeline:()=>E,TextToAudioPipeline:()=>Re,TokenClassificationPipeline:()=>j,TranslationPipeline:()=>_,ZeroShotAudioClassificationPipeline:()=>ye,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>U,ZeroShotObjectDetectionPipeline:()=>he,pipeline:()=>le});var w=c("./src/tokenizers.js"),z=c("./src/models.js"),G=c("./src/models/auto/processing_auto.js");c("./src/base/processing_utils.js");var re=c("./src/utils/generic.js"),Q=c("./src/utils/core.js"),g=c("./src/utils/maths.js"),v=c("./src/utils/audio.js"),M=c("./src/utils/tensor.js"),y=c("./src/utils/image.js");async function C(je){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(we=>y.RawImage.read(we)))}async function q(je,we){return Array.isArray(je)||(je=[je]),await Promise.all(je.map($e=>typeof $e=="string"||$e instanceof URL?(0,v.read_audio)($e,we):$e instanceof Float64Array?new Float32Array($e):$e))}function J(je,we){we&&(je=je.map(ze=>ze|0));const[$e,et,Qe,qe]=je;return{xmin:$e,ymin:et,xmax:Qe,ymax:qe}}class ie extends re.Callable{constructor({task:we,model:$e,tokenizer:et=null,processor:Qe=null}){super(),this.task=we,this.model=$e,this.tokenizer=et,this.processor=Qe}async dispose(){await this.model.dispose()}}class fe extends ie{constructor(we){super(we)}async _call(we,{top_k:$e=1}={}){const et=this.tokenizer(we,{padding:!0,truncation:!0}),Qe=await this.model(et),qe=this.model.config.problem_type==="multi_label_classification"?dt=>dt.sigmoid():dt=>new M.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),ze=this.model.config.id2label,nt=[];for(const dt of Qe.logits){const gt=qe(dt),ht=await(0,M.topk)(gt,$e),_t=ht[0].tolist(),ne=ht[1].tolist().map((V,ue)=>({label:ze?ze[V]:`LABEL_${V}`,score:_t[ue]}));$e===1?nt.push(...ne):nt.push(ne)}return Array.isArray(we)||$e===1?nt:nt[0]}}class j extends ie{constructor(we){super(we)}async _call(we,{ignore_labels:$e=["O"]}={}){const et=Array.isArray(we),Qe=this.tokenizer(et?we:[we],{padding:!0,truncation:!0}),ze=(await this.model(Qe)).logits,nt=this.model.config.id2label,dt=[];for(let gt=0;gtut==this.tokenizer.sep_token_id);dt[_t].map((ut,At)=>ut==1&&(At===0||At>ne&>.findIndex(xt=>xt==A[At])===-1));const V=qe[_t].tolist(),ue=ze[_t].tolist();for(let ut=1;utAt==A[ut])!==-1)&&(V[ut]=-1/0,ue[ut]=-1/0);const Ae=(0,g.softmax)(V).map((ut,At)=>[ut,At]),Je=(0,g.softmax)(ue).map((ut,At)=>[ut,At]);Ae[0][0]=0,Je[0][0]=0;const ot=(0,Q.product)(Ae,Je).filter(ut=>ut[0][1]<=ut[1][1]).map(ut=>[ut[0][1],ut[1][1],ut[0][0]*ut[1][0]]).sort((ut,At)=>At[2]-ut[2]);for(let ut=0;utV==this.tokenizer.mask_token_id);if(gt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ht=Qe[nt][gt],_t=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(ht.data),ht.dims),$e),A=_t[0].tolist(),ne=_t[1].tolist();qe.push(ne.map((V,ue)=>{const Ae=dt.slice();return Ae[gt]=V,{score:A[ue],token:Number(V),token_str:this.tokenizer.model.vocab[V],sequence:this.tokenizer.decode(Ae,{skip_special_tokens:!0})}}))}return Array.isArray(we)?qe:qe[0]}}class N extends ie{constructor($e){super($e);ve(this,"_key","generated_text")}async _call($e,et={}){Array.isArray($e)||($e=[$e]),this.model.config.prefix&&($e=$e.map(gt=>this.model.config.prefix+gt));const Qe=this.model.config.task_specific_params;Qe&&Qe[this.task]&&Qe[this.task].prefix&&($e=$e.map(gt=>Qe[this.task].prefix+gt));const qe=this.tokenizer,ze={padding:!0,truncation:!0};let nt;this instanceof _&&"_build_translation_inputs"in qe?nt=qe._build_translation_inputs($e,ze,et):nt=qe($e,ze);const dt=await this.model.generate({...nt,...et});return qe.batch_decode(dt,{skip_special_tokens:!0}).map(gt=>({[this._key]:gt}))}}class I extends N{constructor($e){super($e);ve(this,"_key","summary_text")}}class _ extends N{constructor($e){super($e);ve(this,"_key","translation_text")}}function k(je){return Array.isArray(je)&&je.every(we=>"role"in we&&"content"in we)}class E extends ie{constructor(we){super(we)}async _call(we,$e={}){let et=!1,Qe=!1,qe;if(typeof we=="string")qe=we=[we];else if(Array.isArray(we)&&we.every(ne=>typeof ne=="string"))et=!0,qe=we;else{if(k(we))we=[we];else if(Array.isArray(we)&&we.every(k))et=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Qe=!0,qe=we.map(ne=>this.tokenizer.apply_chat_template(ne,{tokenize:!1,add_generation_prompt:!0}))}const ze=$e.add_special_tokens??!1,nt=Qe?!1:$e.return_full_text??!0;this.tokenizer.padding_side="left";const dt=this.tokenizer(qe,{add_special_tokens:ze,padding:!0,truncation:!0}),gt=await this.model.generate({...dt,...$e}),ht=this.tokenizer.batch_decode(gt,{skip_special_tokens:!0});let _t;!nt&&dt.input_ids.dims.at(-1)>0&&(_t=this.tokenizer.batch_decode(dt.input_ids,{skip_special_tokens:!0}).map(ne=>ne.length));const A=Array.from({length:we.length},ne=>[]);for(let ne=0;ne[$e.toLowerCase(),et])),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(we,$e,{hypothesis_template:et="This example is {}.",multi_label:Qe=!1}={}){const qe=Array.isArray(we);qe||(we=[we]),Array.isArray($e)||($e=[$e]);const ze=$e.map(gt=>et.replace("{}",gt)),nt=Qe||$e.length===1,dt=[];for(const gt of we){const ht=[];for(const ne of ze){const V=this.tokenizer(gt,{text_pair:ne,padding:!0,truncation:!0}),ue=await this.model(V);nt?ht.push([ue.logits.data[this.contradiction_id],ue.logits.data[this.entailment_id]]):ht.push(ue.logits.data[this.entailment_id])}const A=(nt?ht.map(ne=>(0,g.softmax)(ne)[1]):(0,g.softmax)(ht)).map((ne,V)=>[ne,V]).sort((ne,V)=>V[0]-ne[0]);dt.push({sequence:gt,labels:A.map(ne=>$e[ne[1]]),scores:A.map(ne=>ne[0])})}return qe?dt:dt[0]}}class Y extends ie{constructor(we){super(we)}async _call(we,{pooling:$e="none",normalize:et=!1,quantize:Qe=!1,precision:qe="binary"}={}){const ze=this.tokenizer(we,{padding:!0,truncation:!0}),nt=await this.model(ze);let dt=nt.last_hidden_state??nt.logits??nt.token_embeddings;if($e!=="none")if($e==="mean")dt=(0,M.mean_pooling)(dt,ze.attention_mask);else if($e==="cls")dt=dt.slice(null,0);else throw Error(`Pooling method '${$e}' not supported.`);return et&&(dt=dt.normalize(2,-1)),Qe&&(dt=(0,M.quantize_embeddings)(dt,qe)),dt}}class de extends ie{constructor(we){super(we)}async _call(we,{pool:$e=null}={}){const et=await C(we),{pixel_values:Qe}=await this.processor(et),qe=await this.model({pixel_values:Qe});let ze;if($e){if(!("pooler_output"in qe))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");ze=qe.pooler_output}else ze=qe.last_hidden_state??qe.logits??qe.image_embeds;return ze}}class me extends ie{constructor(we){super(we)}async _call(we,{top_k:$e=5}={}){const et=this.processor.feature_extractor.config.sampling_rate,Qe=await q(we,et),qe=this.model.config.id2label,ze=[];for(const nt of Qe){const dt=await this.processor(nt),ht=(await this.model(dt)).logits[0],_t=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(ht.data),ht.dims),$e),A=_t[0].tolist(),V=_t[1].tolist().map((ue,Ae)=>({label:qe?qe[ue]:`LABEL_${ue}`,score:A[Ae]}));ze.push(V)}return Array.isArray(we)?ze:ze[0]}}class ye extends ie{constructor(we){super(we)}async _call(we,$e,{hypothesis_template:et="This is a sound of {}."}={}){const Qe=!Array.isArray(we);Qe&&(we=[we]);const qe=$e.map(ht=>et.replace("{}",ht)),ze=this.tokenizer(qe,{padding:!0,truncation:!0}),nt=this.processor.feature_extractor.config.sampling_rate,dt=await q(we,nt),gt=[];for(const ht of dt){const _t=await this.processor(ht),A=await this.model({...ze,..._t}),ne=(0,g.softmax)(A.logits_per_audio.data);gt.push([...ne].map((V,ue)=>({score:V,label:$e[ue]})))}return Qe?gt[0]:gt}}class Ce extends ie{constructor(we){super(we)}async _call(we,$e={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(we,$e);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(we,$e);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(we,$e){$e.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),$e.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const et=!Array.isArray(we);et&&(we=[we]);const Qe=this.processor.feature_extractor.config.sampling_rate,qe=await q(we,Qe),ze=[];for(const nt of qe){const dt=await this.processor(nt),ht=(await this.model(dt)).logits[0],_t=[];for(const ne of ht)_t.push((0,g.max)(ne.data)[1]);const A=this.tokenizer.decode(_t);ze.push({text:A})}return et?ze[0]:ze}async _call_whisper(we,$e){const et=$e.return_timestamps??!1,Qe=$e.chunk_length_s??0,qe=$e.force_full_sequences??!1;let ze=$e.stride_length_s??null;const nt={...$e};et==="word"&&(nt.return_token_timestamps=!0,nt.return_timestamps=!1);const dt=!Array.isArray(we);dt&&(we=[we]);const gt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ht=this.processor.feature_extractor.config.hop_length,_t=this.processor.feature_extractor.config.sampling_rate,A=await q(we,_t),ne=[];for(const V of A){let ue=[];if(Qe>0){if(ze===null)ze=Qe/6;else if(Qe<=ze)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ot=_t*Qe,ut=_t*ze,At=ot-2*ut;let xt=0;for(;;){const Et=xt+ot,Ct=V.subarray(xt,Et),ar=await this.processor(Ct),Mr=xt===0,Nr=Et>=V.length;if(ue.push({stride:[Ct.length,Mr?0:ut,Nr?0:ut],input_features:ar.input_features,is_last:Nr}),Nr)break;xt+=At}}else ue=[{stride:[V.length,0,0],input_features:(await this.processor(V)).input_features,is_last:!0}];for(const ot of ue){nt.num_frames=Math.floor(ot.stride[0]/ht);const ut=await this.model.generate({inputs:ot.input_features,...nt});et==="word"?(ot.tokens=ut.sequences.tolist()[0],ot.token_timestamps=ut.token_timestamps.tolist()[0].map(At=>(0,g.round)(At,2))):ot.tokens=ut[0].tolist(),ot.stride=ot.stride.map(At=>At/_t)}const[Ae,Je]=this.tokenizer._decode_asr(ue,{time_precision:gt,return_timestamps:et,force_full_sequences:qe});ne.push({text:Ae,...Je})}return dt?ne[0]:ne}}class Ee extends ie{constructor(we){super(we)}async _call(we,$e={}){const et=Array.isArray(we),Qe=await C(we),{pixel_values:qe}=await this.processor(Qe),ze=[];for(const nt of qe){nt.dims=[1,...nt.dims];const dt=await this.model.generate({inputs:nt,...$e}),gt=this.tokenizer.batch_decode(dt,{skip_special_tokens:!0}).map(ht=>({generated_text:ht.trim()}));ze.push(gt)}return et?ze:ze[0]}}class Le extends ie{constructor(we){super(we)}async _call(we,{top_k:$e=5}={}){const et=await C(we),{pixel_values:Qe}=await this.processor(et),qe=await this.model({pixel_values:Qe}),ze=this.model.config.id2label,nt=[];for(const dt of qe.logits){const gt=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),$e),ht=gt[0].tolist(),A=gt[1].tolist().map((ne,V)=>({label:ze?ze[ne]:`LABEL_${ne}`,score:ht[V]}));nt.push(A)}return Array.isArray(we)?nt:nt[0]}}class _e extends ie{constructor(we){super(we),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(we,{threshold:$e=.5,mask_threshold:et=.5,overlap_mask_area_threshold:Qe=.8,label_ids_to_fuse:qe=null,target_sizes:ze=null,subtask:nt=null}={}){if(Array.isArray(we)&&we.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const gt=await C(we),ht=gt.map(Je=>[Je.height,Je.width]),{pixel_values:_t,pixel_mask:A}=await this.processor(gt),ne=await this.model({pixel_values:_t,pixel_mask:A});let V=null;if(nt!==null)V=this.subtasks_mapping[nt];else for(let[Je,ot]of Object.entries(this.subtasks_mapping))if(ot in this.processor.image_processor){V=this.processor.image_processor[ot].bind(this.processor.image_processor),nt=Je;break}const ue=this.model.config.id2label,Ae=[];if(nt==="panoptic"||nt==="instance"){const Je=V(ne,$e,et,Qe,qe,ze??ht)[0],ot=Je.segmentation;for(const ut of Je.segments_info){const At=new Uint8ClampedArray(ot.data.length);for(let Et=0;Etet.replace("{}",A)),nt=this.tokenizer(ze,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:dt}=await this.processor(qe),gt=await this.model({...nt,pixel_values:dt}),ht=this.model.config.model_type==="siglip"?A=>A.sigmoid().data:A=>(0,g.softmax)(A.data),_t=[];for(const A of gt.logits_per_image){const V=[...ht(A)].map((ue,Ae)=>({score:ue,label:$e[Ae]}));V.sort((ue,Ae)=>Ae.score-ue.score),_t.push(V)}return Qe?_t:_t[0]}}class ce extends ie{constructor(we){super(we)}async _call(we,{threshold:$e=.9,percentage:et=!1}={}){const Qe=Array.isArray(we);if(Qe&&we.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const qe=await C(we),ze=et?null:qe.map(ne=>[ne.height,ne.width]),{pixel_values:nt,pixel_mask:dt}=await this.processor(qe),gt=await this.model({pixel_values:nt,pixel_mask:dt}),ht=this.processor.image_processor.post_process_object_detection(gt,$e,ze),_t=this.model.config.id2label,A=ht.map(ne=>ne.boxes.map((V,ue)=>({score:ne.scores[ue],label:_t[ne.classes[ue]],box:J(V,!et)})));return Qe?A:A[0]}}class he extends ie{constructor(we){super(we)}async _call(we,$e,{threshold:et=.1,top_k:Qe=null,percentage:qe=!1}={}){const ze=Array.isArray(we),nt=await C(we),dt=this.tokenizer($e,{padding:!0,truncation:!0}),gt=await this.processor(nt),ht=[];for(let _t=0;_t({score:Ae.scores[ut],label:$e[Ae.classes[ut]],box:J(ot,!qe)})).sort((ot,ut)=>ut.score-ot.score);Qe!==null&&(Je=Je.slice(0,Qe)),ht.push(Je)}return ze?ht:ht[0]}}class ke extends ie{constructor(we){super(we)}async _call(we,$e,et={}){const Qe=(await C(we))[0],{pixel_values:qe}=await this.processor(Qe),ze=`${$e}`,nt=this.tokenizer(ze,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,dt=await this.model.generate({inputs:qe,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:nt,...et}),ht=this.tokenizer.batch_decode(dt)[0].match(/(.*?)<\/s_answer>/);let _t=null;return ht&&ht.length>=2&&(_t=ht[1].trim()),[{answer:_t}]}}class Re extends ie{constructor($e){super($e);ve(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=$e.vocoder??null}async _call($e,{speaker_embeddings:et=null}={}){return this.processor?this._call_text_to_spectrogram($e,{speaker_embeddings:et}):this._call_text_to_waveform($e)}async _call_text_to_waveform($e){const et=this.tokenizer($e,{padding:!0,truncation:!0}),{waveform:Qe}=await this.model(et),qe=this.model.config.sampling_rate;return{audio:Qe.data,sampling_rate:qe}}async _call_text_to_spectrogram($e,{speaker_embeddings:et}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await z.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof et=="string"||et instanceof URL)&&(et=new Float32Array(await(await fetch(et)).arrayBuffer())),et instanceof Float32Array)et=new M.Tensor("float32",et,[1,et.length]);else if(!(et instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Qe}=this.tokenizer($e,{padding:!0,truncation:!0}),{waveform:qe}=await this.model.generate_speech(Qe,et,{vocoder:this.vocoder}),ze=this.processor.feature_extractor.config.sampling_rate;return{audio:qe.data,sampling_rate:ze}}}class Ke extends ie{constructor(we){super(we)}async _call(we){const $e=await C(we),et=await this.processor($e),Qe=await this.model(et),qe=[];for(const ze of Qe.reconstruction){const nt=ze.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");qe.push(y.RawImage.fromTensor(nt))}return qe.length>1?qe:qe[0]}}class Ye extends ie{constructor(we){super(we)}async _call(we){const $e=await C(we),et=await this.processor($e),{predicted_depth:Qe}=await this.model(et),qe=[];for(let ze=0;ze<$e.length;++ze){const nt=(0,M.interpolate)(Qe[ze],$e[ze].size.reverse(),"bilinear",!1),dt=nt.mul_(255/(0,g.max)(nt.data)[0]).to("uint8");qe.push({predicted_depth:Qe[ze],depth:y.RawImage.fromTensor(dt)})}return qe.length>1?qe:qe[0]}}const at=Object.freeze({"text-classification":{tokenizer:w.AutoTokenizer,pipeline:fe,model:z.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:w.AutoTokenizer,pipeline:j,model:z.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:w.AutoTokenizer,pipeline:X,model:z.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:w.AutoTokenizer,pipeline:Z,model:z.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:w.AutoTokenizer,pipeline:I,model:z.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:w.AutoTokenizer,pipeline:_,model:z.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:w.AutoTokenizer,pipeline:N,model:z.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:w.AutoTokenizer,pipeline:E,model:z.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:w.AutoTokenizer,pipeline:ee,model:z.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:me,model:z.AutoModelForAudioClassification,processor:G.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:w.AutoTokenizer,pipeline:ye,model:z.AutoModel,processor:G.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:w.AutoTokenizer,pipeline:Ce,model:[z.AutoModelForSpeechSeq2Seq,z.AutoModelForCTC],processor:G.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:w.AutoTokenizer,pipeline:Re,model:[z.AutoModelForTextToWaveform,z.AutoModelForTextToSpectrogram],processor:[G.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:w.AutoTokenizer,pipeline:Ee,model:z.AutoModelForVision2Seq,processor:G.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Le,model:z.AutoModelForImageClassification,processor:G.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:_e,model:[z.AutoModelForImageSegmentation,z.AutoModelForSemanticSegmentation,z.AutoModelForUniversalSegmentation],processor:G.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:w.AutoTokenizer,pipeline:U,model:z.AutoModel,processor:G.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ce,model:z.AutoModelForObjectDetection,processor:G.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:w.AutoTokenizer,pipeline:he,model:z.AutoModelForZeroShotObjectDetection,processor:G.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:w.AutoTokenizer,pipeline:ke,model:z.AutoModelForDocumentQuestionAnswering,processor:G.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Ke,model:z.AutoModelForImageToImage,processor:G.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ye,model:z.AutoModelForDepthEstimation,processor:G.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:w.AutoTokenizer,pipeline:Y,model:z.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:G.AutoProcessor,pipeline:de,model:[z.AutoModelForImageFeatureExtraction,z.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),We=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function le(je,we=null,{progress_callback:$e=null,config:et=null,cache_dir:Qe=null,local_files_only:qe=!1,revision:ze="main",device:nt=null,dtype:dt=null,model_file_name:gt=null,session_options:ht={}}={}){je=We[je]??je;const _t=at[je.split("_",1)[0]];if(!_t)throw Error(`Unsupported pipeline: ${je}. Must be one of [${Object.keys(at)}]`);we||(we=_t.default.model,console.log(`No model specified. Using default model: "${we}".`));const A={progress_callback:$e,config:et,cache_dir:Qe,local_files_only:qe,revision:ze,device:nt,dtype:dt,model_file_name:gt,session_options:ht},ne=new Map([["tokenizer",_t.tokenizer],["model",_t.model],["processor",_t.processor]]),V=await He(ne,we,A);V.task=je,(0,Q.dispatchCallback)($e,{status:"ready",task:je,model:we});const ue=_t.pipeline;return new ue(V)}async function He(je,we,$e){const et=Object.create(null),Qe=[];for(const[qe,ze]of je.entries()){if(!ze)continue;let nt;Array.isArray(ze)?nt=new Promise(async(dt,gt)=>{var _t,A;let ht;for(const ne of ze){if(ne===null){dt(null);return}try{dt(await ne.from_pretrained(we,$e));return}catch(V){if((_t=V.message)!=null&&_t.includes("Unsupported model type"))ht=V;else if((A=V.message)!=null&&A.includes("Could not locate file"))ht=V;else{gt(V);return}}}gt(ht)}):nt=ze.from_pretrained(we,$e),et[qe]=nt,Qe.push(nt)}await Promise.all(Qe);for(const[qe,ze]of Object.entries(et))et[qe]=await ze;return et}},"./src/tokenizers.js":(Oe,R,c)=>{c.r(R),c.d(R,{AlbertTokenizer:()=>Ls,AutoTokenizer:()=>_r,BartTokenizer:()=>Bs,BertTokenizer:()=>Ts,BlenderbotSmallTokenizer:()=>jn,BlenderbotTokenizer:()=>Rn,BloomTokenizer:()=>As,CLIPTokenizer:()=>En,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>xn,CodeLlamaTokenizer:()=>tn,CohereTokenizer:()=>Sn,ConvBertTokenizer:()=>Zs,DebertaTokenizer:()=>Ys,DebertaV2Tokenizer:()=>xs,DistilBertTokenizer:()=>ps,ElectraTokenizer:()=>It,EsmTokenizer:()=>Rs,FalconTokenizer:()=>Ln,GPT2Tokenizer:()=>en,GPTNeoXTokenizer:()=>zn,GemmaTokenizer:()=>co,Grok1Tokenizer:()=>rn,HerbertTokenizer:()=>Js,LlamaTokenizer:()=>Tn,M2M100Tokenizer:()=>Ns,MBart50Tokenizer:()=>ts,MBartTokenizer:()=>Sr,MPNetTokenizer:()=>Dn,MarianTokenizer:()=>Ot,MgpstrTokenizer:()=>kn,MobileBertTokenizer:()=>Xs,NllbTokenizer:()=>js,NougatTokenizer:()=>$n,PreTrainedTokenizer:()=>Dt,Qwen2Tokenizer:()=>Bn,RoFormerTokenizer:()=>zs,RobertaTokenizer:()=>Br,SiglipTokenizer:()=>Pn,SpeechT5Tokenizer:()=>Nn,SqueezeBertTokenizer:()=>un,T5Tokenizer:()=>Wr,TokenizerModel:()=>de,VitsTokenizer:()=>Un,Wav2Vec2CTCTokenizer:()=>Cn,WhisperTokenizer:()=>dn,XLMRobertaTokenizer:()=>uo,XLMTokenizer:()=>Mt,is_chinese_char:()=>Z});var w=c("./src/utils/generic.js"),z=c("./src/utils/core.js"),G=c("./src/utils/hub.js"),re=c("./src/utils/maths.js"),Q=c("./src/utils/tensor.js"),g=c("./src/utils/data-structures.js"),v=c("./node_modules/@huggingface/jinja/dist/index.js"),M=c("./src/models/whisper/common_whisper.js");c("./src/utils/constants.js");async function y(xe,T){const K=await Promise.all([(0,G.getModelJSON)(xe,"tokenizer.json",!0,T),(0,G.getModelJSON)(xe,"tokenizer_config.json",!0,T)]);return T.legacy!==null&&(K[1].legacy=T.legacy),K}function C(xe,T){const K=[];let oe=0;for(const Me of xe.matchAll(T)){const Pe=Me[0];oe0&&K.push(Pe),oe=Me.index+Pe.length}return oe=19968&&xe<=40959||xe>=13312&&xe<=19903||xe>=131072&&xe<=173791||xe>=173824&&xe<=177983||xe>=177984&&xe<=178207||xe>=178208&&xe<=183983||xe>=63744&&xe<=64255||xe>=194560&&xe<=195103}function N(xe,T,K){const oe=[];let Me=0;for(;Methis.tokens_to_ids.get(K)??this.unk_token_id)}convert_ids_to_tokens(T){return T.map(K=>this.vocab[K]??this.unk_token)}}class me extends de{constructor(T){super(T),this.tokens_to_ids=J(T.vocab),this.unk_token_id=this.tokens_to_ids.get(T.unk_token),this.unk_token=T.unk_token,this.max_input_chars_per_word=T.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[K,oe]of this.tokens_to_ids)this.vocab[oe]=K}encode(T){const K=[];for(const oe of T){const Me=[...oe];if(Me.length>this.max_input_chars_per_word){K.push(this.unk_token);continue}let Pe=!1,Ue=0;const lt=[];for(;Ue0&&(Tt=this.config.continuing_subword_prefix+Tt),this.tokens_to_ids.has(Tt)){pt=Tt;break}--mt}if(pt===null){Pe=!0;break}lt.push(pt),Ue=mt}Pe?K.push(this.unk_token):K.push(...lt)}return K}}class ye extends de{constructor(T,K){super(T);const oe=T.vocab.length;this.vocab=new Array(oe),this.scores=new Array(oe);for(let Me=0;Me[Me,Pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=K.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,re.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new g.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(T){const K=T.chars,oe=1;let Me=0;for(;Me{const xe=[...Array.from({length:94},(Me,Pe)=>Pe+33),...Array.from({length:12},(Me,Pe)=>Pe+161),...Array.from({length:82},(Me,Pe)=>Pe+174)],T=xe.slice();let K=0;for(let Me=0;Me<256;++Me)xe.includes(Me)||(xe.push(Me),T.push(256+K),K+=1);const oe=T.map(Me=>String.fromCharCode(Me));return Object.fromEntries(xe.map((Me,Pe)=>[Me,oe[Pe]]))})(),Ee=(0,z.reverseDictionary)(Ce);class Le extends de{constructor(T){super(T),this.tokens_to_ids=J(T.vocab),this.unk_token_id=this.tokens_to_ids.get(T.unk_token),this.unk_token=T.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[oe,Me]of this.tokens_to_ids)this.vocab[Me]=oe;const K=Array.isArray(T.merges[0]);this.merges=K?T.merges:T.merges.map(oe=>oe.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((oe,Me)=>[JSON.stringify(oe),Me])),this.end_of_word_suffix=T.end_of_word_suffix,this.continuing_subword_suffix=T.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(T){if(T.length===0)return[];const K=this.cache.get(T);if(K!==void 0)return K;const oe=Array.from(T);this.end_of_word_suffix&&(oe[oe.length-1]+=this.end_of_word_suffix);let Me=[];if(oe.length>1){const Pe=new g.PriorityQueue((mt,pt)=>mt.score`<0x${lt.toString(16).toUpperCase().padStart(2,"0")}>`);Ue.every(lt=>this.tokens_to_ids.has(lt))?K.push(...Ue):K.push(this.unk_token)}else K.push(this.unk_token)}return K}}class _e extends de{constructor(T,K){super(T),this.tokens_to_ids=J(K.target_lang?T.vocab[K.target_lang]:T.vocab),this.bos_token=K.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=K.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=K.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=K.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[oe,Me]of this.tokens_to_ids)this.vocab[Me]=oe}encode(T){return T}}class U extends w.Callable{constructor(T){super(),this.config=T}static fromConfig(T){if(T===null)return null;switch(T.type){case"BertNormalizer":return new He(T);case"Precompiled":return new Mr(T);case"Sequence":return new le(T);case"Replace":return new ce(T);case"NFC":return new he(T);case"NFKC":return new ke(T);case"NFKD":return new Re(T);case"Strip":return new Ke(T);case"StripAccents":return new Ye(T);case"Lowercase":return new at(T);case"Prepend":return new We(T);default:throw new Error(`Unknown Normalizer type: ${T.type}`)}}normalize(T){throw Error("normalize should be implemented in subclass.")}_call(T){return this.normalize(T)}}class ce extends U{normalize(T){const K=q(this.config.pattern);return K===null?T:T.replaceAll(K,this.config.content)}}class he extends U{normalize(T){return T=T.normalize("NFC"),T}}class ke extends U{normalize(T){return T=T.normalize("NFKC"),T}}class Re extends U{normalize(T){return T=T.normalize("NFKD"),T}}class Ke extends U{normalize(T){return this.config.strip_left&&this.config.strip_right?T=T.trim():(this.config.strip_left&&(T=T.trimStart()),this.config.strip_right&&(T=T.trimEnd())),T}}class Ye extends U{normalize(T){return T=j(T),T}}class at extends U{normalize(T){return T=T.toLowerCase(),T}}class We extends U{normalize(T){return T=this.config.prepend+T,T}}class le extends U{constructor(T){super(T),this.normalizers=T.normalizers.map(K=>U.fromConfig(K))}normalize(T){return this.normalizers.reduce((K,oe)=>oe.normalize(K),T)}}class He extends U{_tokenize_chinese_chars(T){const K=[];for(let oe=0;oethis.pre_tokenize_text(oe,K)):this.pre_tokenize_text(T,K)).flat()}_call(T,K){return this.pre_tokenize(T,K)}}class we extends je{constructor(T){super(),this.pattern=new RegExp(`[^\\s${_}]+|[${_}]`,"gu")}pre_tokenize_text(T,K){return T.trim().match(this.pattern)||[]}}class $e extends je{constructor(T){super(),this.config=T,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=Ce,this.text_encoder=new TextEncoder}pre_tokenize_text(T,K){return this.add_prefix_space&&!T.startsWith(" ")&&(T=" "+T),(this.use_regex?T.match(this.pattern)||[]:[T]).map(Me=>Array.from(this.text_encoder.encode(Me),Pe=>this.byte_encoder[Pe]).join(""))}}class et extends je{constructor(T){super(),this.config=T,this.pattern=q(this.config.pattern,this.config.invert)}pre_tokenize_text(T,K){var oe;return this.pattern===null?[]:this.config.invert?T.match(this.pattern)||[]:((oe=this.config.behavior)==null?void 0:oe.toLowerCase())==="removed"?T.split(this.pattern).filter(Me=>Me):C(T,this.pattern)}}class Qe extends je{constructor(T){super(),this.config=T,this.pattern=new RegExp(`[^${_}]+|[${_}]+`,"gu")}pre_tokenize_text(T,K){return T.match(this.pattern)||[]}}class qe extends je{constructor(T){super(),this.config=T;const K=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(K,"gu")}pre_tokenize_text(T,K){return T.match(this.pattern)||[]}}class ze extends w.Callable{constructor(T){super(),this.config=T}static fromConfig(T){if(T===null)return null;switch(T.type){case"TemplateProcessing":return new gt(T);case"ByteLevel":return new ht(T);case"RobertaProcessing":return new dt(T);case"BertProcessing":return new nt(T);case"Sequence":return new _t(T);default:throw new Error(`Unknown PostProcessor type: ${T.type}`)}}post_process(T,...K){throw Error("post_process should be implemented in subclass.")}_call(T,...K){return this.post_process(T,...K)}}class nt extends ze{constructor(T){super(T),this.cls=T.cls[0],this.sep=T.sep[0]}post_process(T,K=null,{add_special_tokens:oe=!0}={}){oe&&(T=(0,z.mergeArrays)([this.cls],T,[this.sep]));let Me=new Array(T.length).fill(0);if(K!==null){const Pe=oe&&this instanceof dt?[this.sep]:[],Ue=oe?[this.sep]:[];T=(0,z.mergeArrays)(T,Pe,K,Ue),Me=(0,z.mergeArrays)(Me,new Array(K.length+Pe.length+Ue.length).fill(1))}return{tokens:T,token_type_ids:Me}}}class dt extends nt{}class gt extends ze{constructor(T){super(T),this.single=T.single,this.pair=T.pair}post_process(T,K=null,{add_special_tokens:oe=!0}={}){const Me=K===null?this.single:this.pair;let Pe=[],Ue=[];for(const lt of Me)"SpecialToken"in lt?oe&&(Pe.push(lt.SpecialToken.id),Ue.push(lt.SpecialToken.type_id)):"Sequence"in lt&&(lt.Sequence.id==="A"?(Pe=(0,z.mergeArrays)(Pe,T),Ue=(0,z.mergeArrays)(Ue,new Array(T.length).fill(lt.Sequence.type_id))):lt.Sequence.id==="B"&&(Pe=(0,z.mergeArrays)(Pe,K),Ue=(0,z.mergeArrays)(Ue,new Array(K.length).fill(lt.Sequence.type_id))));return{tokens:Pe,token_type_ids:Ue}}}class ht extends ze{post_process(T,K=null){return K&&(T=(0,z.mergeArrays)(T,K)),{tokens:T}}}class _t extends ze{constructor(T){super(T),this.processors=T.processors.map(K=>ze.fromConfig(K))}post_process(T,K=null,oe={}){let Me;for(const Pe of this.processors)if(Pe instanceof ht)T=Pe.post_process(T).tokens,K&&(K=Pe.post_process(K).tokens);else{const Ue=Pe.post_process(T,K,oe);T=Ue.tokens,Me=Ue.token_type_ids}return{tokens:T,token_type_ids:Me}}}class A extends w.Callable{constructor(T){super(),this.config=T,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=T.trim_offsets}static fromConfig(T){if(T===null)return null;switch(T.type){case"WordPiece":return new Je(T);case"Metaspace":return new ar(T);case"ByteLevel":return new ot(T);case"Replace":return new ne(T);case"ByteFallback":return new V(T);case"Fuse":return new ue(T);case"Strip":return new Ae(T);case"Sequence":return new At(T);case"CTC":return new ut(T);case"BPEDecoder":return new xt(T);default:throw new Error(`Unknown Decoder type: ${T.type}`)}}_call(T){return this.decode(T)}decode(T){return this.decode_chain(T).join("")}decode_chain(T){throw Error("`decode_chain` should be implemented in subclass.")}}class ne extends A{decode_chain(T){const K=q(this.config.pattern);return K===null?T:T.map(oe=>oe.replaceAll(K,this.config.content))}}class V extends A{constructor(T){super(T),this.text_decoder=new TextDecoder}decode_chain(T){const K=[];let oe=[];for(const Me of T){let Pe=null;if(Me.length===6&&Me.startsWith("<0x")&&Me.endsWith(">")){const Ue=parseInt(Me.slice(3,5),16);isNaN(Ue)||(Pe=Ue)}if(Pe!==null)oe.push(Pe);else{if(oe.length>0){const Ue=this.text_decoder.decode(Uint8Array.from(oe));K.push(Ue),oe=[]}K.push(Me)}}if(oe.length>0){const Me=this.text_decoder.decode(Uint8Array.from(oe));K.push(Me),oe=[]}return K}}class ue extends A{decode_chain(T){return[T.join("")]}}class Ae extends A{constructor(T){super(T),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(T){return T.map(K=>{let oe=0;for(let Pe=0;Pe(oe!==0&&(K.startsWith(this.config.prefix)?K=K.replace(this.config.prefix,""):K=" "+K),this.cleanup&&(K=fe(K)),K))}}class ot extends A{constructor(T){super(T),this.byte_decoder=Ee,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(T){const K=T.join(""),oe=new Uint8Array([...K].map(Pe=>this.byte_decoder[Pe]));return this.text_decoder.decode(oe)}decode_chain(T){const K=[];let oe=[];for(const Me of T)this.added_tokens.find(Pe=>Pe.content===Me)!==void 0?(oe.length>0&&(K.push(this.convert_tokens_to_string(oe)),oe=[]),K.push(Me)):oe.push(Me);return oe.length>0&&K.push(this.convert_tokens_to_string(oe)),K}}class ut extends A{constructor(T){super(T),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(T){if(T.length===0)return"";const K=[T[0]];for(let Pe=1;PePe!==this.pad_token).join("");return this.cleanup&&(Me=fe(Me).replaceAll(this.word_delimiter_token," ").trim()),Me}decode_chain(T){return[this.convert_tokens_to_string(T)]}}class At extends A{constructor(T){super(T),this.decoders=T.decoders.map(K=>A.fromConfig(K))}decode_chain(T){return this.decoders.reduce((K,oe)=>oe.decode_chain(K),T)}}class xt extends A{constructor(T){super(T),this.suffix=this.config.suffix}decode_chain(T){return T.map((K,oe)=>K.replaceAll(this.suffix,oe===T.length-1?"":" "))}}class Et extends A{decode_chain(T){let K="";for(let oe=1;oeoe.normalize("NFKC")).join("~"):T=T.normalize("NFKC"),T}}class Nr extends je{constructor(T){super(),this.tokenizers=T.pretokenizers.map(K=>je.fromConfig(K))}pre_tokenize_text(T,K){return this.tokenizers.reduce((oe,Me)=>Me.pre_tokenize(oe,K),[T])}}class Fr extends je{constructor(T){super()}pre_tokenize_text(T,K){return T.match(/\w+|[^\w\s]+/g)||[]}}class as extends je{constructor(T){super()}pre_tokenize_text(T,K){return I(T)}}class qs extends je{constructor(T){super(),this.config=T,this.pattern=q(this.config.pattern),this.content=this.config.content}pre_tokenize_text(T,K){return this.pattern===null?[T]:[T.replaceAll(this.pattern,this.config.content)]}}const Qs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ds(xe,T,K,oe){for(const Me of Object.keys(xe)){const Pe=T-xe[Me].length,Ue=K(Me),lt=new Array(Pe).fill(Ue);xe[Me]=oe==="right"?(0,z.mergeArrays)(xe[Me],lt):(0,z.mergeArrays)(lt,xe[Me])}}function vn(xe,T){for(const K of Object.keys(xe))xe[K].length=T}class Dt extends w.Callable{constructor(K,oe){super();ve(this,"return_token_type_ids",!1);ve(this,"padding_side","right");this._tokenizer_config=oe,this.normalizer=U.fromConfig(K.normalizer),this.pre_tokenizer=je.fromConfig(K.pre_tokenizer),this.model=de.fromConfig(K.model,oe),this.post_processor=ze.fromConfig(K.post_processor),this.decoder=A.fromConfig(K.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Me of K.added_tokens){const Pe=new Y(Me);this.added_tokens.push(Pe),this.model.tokens_to_ids.set(Pe.content,Pe.id),this.model.vocab[Pe.id]=Pe.content,Pe.special&&(this.special_tokens.push(Pe.content),this.all_special_ids.push(Pe.id))}if(this.additional_special_tokens=oe.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,Pe)=>Pe.content.length-Me.content.length).map(Me=>`${Me.lstrip?"\\s*":""}(${(0,z.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.model_max_length=oe.model_max_length,this.remove_space=oe.remove_space,this.clean_up_tokenization_spaces=oe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=oe.do_lowercase_and_remove_accent??!1,oe.padding_side&&(this.padding_side=oe.padding_side),this.legacy=!1,this.chat_template=oe.chat_template??null,Array.isArray(this.chat_template)){const Me=Object.create(null);for(const{name:Pe,template:Ue}of this.chat_template){if(typeof Pe!="string"||typeof Ue!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Me[Pe]=Ue}this.chat_template=Me}this._compiled_template_cache=new Map}getToken(...K){for(const oe of K){const Me=this._tokenizer_config[oe];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(K,{progress_callback:oe=null,config:Me=null,cache_dir:Pe=null,local_files_only:Ue=!1,revision:lt="main",legacy:mt=null}={}){const pt=await y(K,{progress_callback:oe,config:Me,cache_dir:Pe,local_files_only:Ue,revision:lt,legacy:mt});return new this(...pt)}_call(K,{text_pair:oe=null,add_special_tokens:Me=!0,padding:Pe=!1,truncation:Ue=null,max_length:lt=null,return_tensor:mt=!0,return_token_type_ids:pt=null}={}){const Tt=Array.isArray(K);let Wt;if(Tt){if(K.length===0)throw Error("text array must be non-empty");if(oe!==null){if(Array.isArray(oe)){if(K.length!==oe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Wt=K.map((Jt,Cr)=>this._encode_plus(Jt,{text_pair:oe[Cr],add_special_tokens:Me,return_token_type_ids:pt}))}else Wt=K.map(Jt=>this._encode_plus(Jt,{add_special_tokens:Me,return_token_type_ids:pt}))}else{if(K==null)throw Error("text may not be null or undefined");if(Array.isArray(oe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Wt=[this._encode_plus(K,{text_pair:oe,add_special_tokens:Me,return_token_type_ids:pt})]}if(lt===null?Pe==="max_length"?lt=this.model_max_length:lt=(0,re.max)(Wt.map(Jt=>Jt.input_ids.length))[0]:Ue||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."),lt=Math.min(lt,this.model_max_length??1/0),Pe||Ue)for(let Jt=0;Jtlt?Ue&&vn(Wt[Jt],lt):Pe&&Ds(Wt[Jt],lt,Cr=>Cr==="input_ids"?this.pad_token_id:0,this.padding_side));const gr={};if(mt){if(!(Pe&&Ue)&&Wt.some(Cr=>{var qt;for(const lr of Object.keys(Cr))if(Cr[lr].length!==((qt=Wt[0][lr])==null?void 0:qt.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 Jt=[Wt.length,Wt[0].input_ids.length];for(const Cr of Object.keys(Wt[0]))gr[Cr]=new Q.Tensor("int64",BigInt64Array.from(Wt.flatMap(qt=>qt[Cr]).map(BigInt)),Jt)}else{for(const Jt of Object.keys(Wt[0]))gr[Jt]=Wt.map(Cr=>Cr[Jt]);if(!Tt)for(const Jt of Object.keys(gr))gr[Jt]=gr[Jt][0]}return gr}_encode_text(K){return K===null?null:(this.added_tokens_regex?K.split(this.added_tokens_regex).filter(Pe=>Pe):[K]).map((Pe,Ue)=>{if(this.added_tokens.find(mt=>mt.content===Pe)!==void 0)return Pe;{if(this.remove_space===!0&&(Pe=Pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Pe=X(Pe)),this.normalizer!==null&&(Pe=this.normalizer(Pe)),Pe.length===0)return[];const mt=this.pre_tokenizer!==null?this.pre_tokenizer(Pe,{section_index:Ue}):[Pe];return this.model(mt)}}).flat()}_encode_plus(K,{text_pair:oe=null,add_special_tokens:Me=!0,return_token_type_ids:Pe=null}={}){const{tokens:Ue,token_type_ids:lt}=this._tokenize_helper(K,{pair:oe,add_special_tokens:Me}),mt=this.model.convert_tokens_to_ids(Ue),pt={input_ids:mt,attention_mask:new Array(mt.length).fill(1)};return(Pe??this.return_token_type_ids)&<&&(pt.token_type_ids=lt),pt}_tokenize_helper(K,{pair:oe=null,add_special_tokens:Me=!1}={}){const Pe=this._encode_text(K),Ue=this._encode_text(oe);return this.post_processor?this.post_processor(Pe,Ue,{add_special_tokens:Me}):{tokens:(0,z.mergeArrays)(Pe??[],Ue??[])}}tokenize(K,{pair:oe=null,add_special_tokens:Me=!1}={}){return this._tokenize_helper(K,{pair:oe,add_special_tokens:Me}).tokens}encode(K,{text_pair:oe=null,add_special_tokens:Me=!0,return_token_type_ids:Pe=null}={}){return this._encode_plus(K,{text_pair:oe,add_special_tokens:Me,return_token_type_ids:Pe}).input_ids}batch_decode(K,oe={}){return K instanceof Q.Tensor&&(K=K.tolist()),K.map(Me=>this.decode(Me,oe))}decode(K,oe={}){if(K instanceof Q.Tensor&&(K=ie(K)),!Array.isArray(K)||K.length===0||!(0,z.isIntegralNumber)(K[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(K,oe)}decode_single(K,{skip_special_tokens:oe=!1,clean_up_tokenization_spaces:Me=null}){let Pe=this.model.convert_ids_to_tokens(K);oe&&(Pe=Pe.filter(lt=>!this.special_tokens.includes(lt)));let Ue=this.decoder?this.decoder(Pe):Pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ue=Ue.replaceAll(this.decoder.end_of_word_suffix," "),oe&&(Ue=Ue.trim())),(Me??this.clean_up_tokenization_spaces)&&(Ue=fe(Ue)),Ue}get_chat_template({chat_template:K=null,tools:oe=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Me=this.chat_template;if(K!==null&&Object.hasOwn(Me,K))K=Me[K];else if(K===null)if(oe!==null&&"tool_use"in Me)K=Me.tool_use;else if("default"in Me)K=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(K===null)if(this.chat_template)K=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 K}apply_chat_template(K,{tools:oe=null,documents:Me=null,chat_template:Pe=null,add_generation_prompt:Ue=!1,tokenize:lt=!0,padding:mt=!1,truncation:pt=!1,max_length:Tt=null,return_tensor:Wt=!0,return_dict:gr=!1,tokenizer_kwargs:Jt={},...Cr}={}){if(Pe=this.get_chat_template({chat_template:Pe,tools:oe}),typeof Pe!="string")throw Error(`chat_template must be a string, but got ${typeof Pe}`);let qt=this._compiled_template_cache.get(Pe);qt===void 0&&(qt=new v.Template(Pe),this._compiled_template_cache.set(Pe,qt));const lr=Object.create(null);for(const Gr of Qs){const De=this.getToken(Gr);De&&(lr[Gr]=De)}const hs=qt.render({messages:K,add_generation_prompt:Ue,tools:oe,documents:Me,...lr,...Cr});if(lt){const Gr=this._call(hs,{add_special_tokens:!1,padding:mt,truncation:pt,max_length:Tt,return_tensor:Wt,...Jt});return gr?Gr:Gr.input_ids}return hs}}class Ts extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Ls extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Xs extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class un extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Ys extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class xs extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Js extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Zs extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class zs extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class ps extends Dt{}class it extends Dt{}class Mt extends Dt{constructor(K,oe){super(K,oe);ve(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 It extends Dt{constructor(){super(...arguments);ve(this,"return_token_type_ids",!0)}}class Wr extends Dt{}class en extends Dt{}class Bs extends Dt{}class Sr extends Dt{constructor(T,K){super(T,K),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)),this.lang_to_token=oe=>oe}_build_translation_inputs(T,K,oe){return Es(this,T,K,oe)}}class ts extends Sr{}class Br extends Dt{}class As extends Dt{}const br="▁";class Tn extends Dt{constructor(K,oe){super(K,oe);ve(this,"padding_side","left");this.legacy=oe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Ct({replacement:br,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(K){if(K===null)return null;if(this.legacy||K.length===0)return super._encode_text(K);let oe=super._encode_text(br+K.replaceAll(br," "));return oe.length>1&&oe[0]===br&&this.special_tokens.includes(oe[1])&&(oe=oe.slice(1)),oe}}class tn extends Dt{}class uo extends Dt{}class Dn extends Dt{}class Ln extends Dt{}class zn extends Dt{}class Rs extends Dt{}class Bn extends Dt{}class co extends Dt{}class rn extends Dt{}function Es(xe,T,K,oe){if(!("language_codes"in xe)||!Array.isArray(xe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in xe)||!(xe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in xe)||typeof xe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Me=oe.src_lang,Pe=oe.tgt_lang;if(!xe.language_codes.includes(Pe))throw new Error(`Target language code "${Pe}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);if(Me!==void 0){if(!xe.language_codes.includes(Me))throw new Error(`Source language code "${Me}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);for(const Ue of xe.post_processor.config.single)if("SpecialToken"in Ue&&xe.languageRegex.test(Ue.SpecialToken.id)){Ue.SpecialToken.id=xe.lang_to_token(Me);break}}return oe.forced_bos_token_id=xe.model.convert_tokens_to_ids([xe.lang_to_token(Pe)])[0],xe._call(T,K)}class js extends Dt{constructor(T,K){super(T,K),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)),this.lang_to_token=oe=>oe}_build_translation_inputs(T,K,oe){return Es(this,T,K,oe)}}class Ns extends Dt{constructor(T,K){super(T,K),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(oe=>this.languageRegex.test(oe)).map(oe=>oe.slice(2,-2)),this.lang_to_token=oe=>`__${oe}__`}_build_translation_inputs(T,K,oe){return Es(this,T,K,oe)}}class dn extends Dt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(T,{return_timestamps:K=!1,return_language:oe=!1,time_precision:Me=null,force_full_sequences:Pe=!0}={}){if(Me===null)throw Error("Must specify time_precision");let Ue=null;const lt=K==="word";function mt(){return{language:Ue,timestamp:[null,null],text:""}}const pt=[];let Tt=mt(),Wt=0;const gr=this.timestamp_begin;let Jt=[],Cr=[],qt=!1,lr=null;const hs=new Set(this.all_special_ids);for(const wr of T){const qr=wr.tokens,ms=lt?wr.token_timestamps:null;let Ps=null,Ut=gr;if("stride"in wr){const[or,yr,wt]=wr.stride;if(Wt-=yr,lr=or-wt,yr&&(Ut=yr/Me+gr),wt)for(let Zt=qr.length-1;Zt>=0;--Zt){const Dr=Number(qr[Zt]);if(Dr>=gr){if(Ps!==null&&(Dr-gr)*Me=gr){const wt=(yr-gr)*Me+Wt,Zt=(0,re.round)(wt,2);if(Ps!==null&&yr>=Ps)qt=!0;else if(qt||Jt.length>0&&yr0?(Jt.push(Rr),lt&&Cr.push(us)):Jt.every(or=>or.length===0)&&(Tt=mt(),Jt=[],Rr=[],Cr=[],us=[])}if(Jt.length>0){if(Pe&&K)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[wr,qr]=this.findLongestCommonSequence(Jt,Cr),ms=this.decode(wr);Tt.text=ms,lt&&(Tt.words=this.collateWordTimestamps(wr,qr,Ue)),pt.push(Tt)}let Gr=Object.create(null);const De=pt.map(wr=>wr.text).join("");if(K||oe){for(let wr=0;wr0;let lt=Ue?[]:null,mt=Ue?K[0]:null;for(let pt=1;ptZt===us[Dr]&&mt[qr+Dr]<=K[pt][Ut+Dr]).length:or=Ps.filter((Zt,Dr)=>Zt===us[Dr]).length;const yr=wr/1e4,wt=or/wr+yr;or>1&&wt>Wt&&(Wt=wt,gr=[qr,ms,Ut,Rr])}const[Cr,qt,lr,hs]=gr,Gr=Math.floor((qt+Cr)/2),De=Math.floor((hs+lr)/2);Pe.push(...oe.slice(0,Gr)),oe=Tt.slice(De),Me=oe.length,Ue&&(lt.push(...mt.slice(0,Gr)),mt=K[pt].slice(De))}return Pe.push(...oe),Ue?(lt.push(...mt),[Pe,lt]):[Pe,[]]}collateWordTimestamps(T,K,oe){const[Me,Pe,Ue]=this.combineTokensIntoWords(T,oe),lt=[];for(let mt=0;mt=Me){const lt=((Ue-Me)*oe).toFixed(2);Pe.push(`<|${lt}|>`),Pe.push([])}else Pe[Pe.length-1].push(Ue);return Pe=Pe.map(Ue=>typeof Ue=="string"?Ue:super.decode(Ue,K)),Pe.join("")}splitTokensOnUnicode(T){const K=this.decode(T,{decode_with_timestamps:!0}),oe="�",Me=[],Pe=[],Ue=[];let lt=[],mt=[],pt=0;for(let Tt=0;Tt=this.model.tokens_to_ids.get("<|endoftext|>"),Cr=Tt.startsWith(" "),qt=Tt.trim(),lr=mt.test(qt);if(Jt||Cr||lr||Pe.length===0)Pe.push(Tt),Ue.push(Wt),lt.push(gr);else{const hs=Pe.length-1;Pe[hs]+=Tt,Ue[hs].push(...Wt),lt[hs].push(...gr)}}return[Pe,Ue,lt]}mergePunctuations(T,K,oe,Me,Pe){const Ue=structuredClone(T),lt=structuredClone(K),mt=structuredClone(oe);let pt=Ue.length-2,Tt=Ue.length-1;for(;pt>=0;)Ue[pt].startsWith(" ")&&Me.includes(Ue[pt].trim())?(Ue[Tt]=Ue[pt]+Ue[Tt],lt[Tt]=(0,z.mergeArrays)(lt[pt],lt[Tt]),mt[Tt]=(0,z.mergeArrays)(mt[pt],mt[Tt]),Ue[pt]="",lt[pt]=[],mt[pt]=[]):Tt=pt,--pt;for(pt=0,Tt=1;TtWt),lt.filter(Wt=>Wt.length>0),mt.filter(Wt=>Wt.length>0)]}}class xn extends Dt{}class En extends Dt{}class Pn extends Dt{}class Ot extends Dt{constructor(T,K){super(T,K),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(oe=>this.languageRegex.test(oe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(T){if(T===null)return null;const[K,...oe]=T.trim().split(this.languageRegex);if(oe.length===0)return super._encode_text(K);if(oe.length===2){const[Me,Pe]=oe;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,z.mergeArrays)([Me],super._encode_text(Pe))}}}class Cn extends Dt{}class Rn extends Dt{}class jn extends Dt{}class Nn extends Dt{}class $n extends Dt{}class Un extends Dt{constructor(T,K){super(T,K),this.decoder=new Et({})}}class Sn extends Dt{}class kn extends Dt{}class _r{static async from_pretrained(T,{progress_callback:K=null,config:oe=null,cache_dir:Me=null,local_files_only:Pe=!1,revision:Ue="main",legacy:lt=null}={}){var gr;const[mt,pt]=await y(T,{progress_callback:K,config:oe,cache_dir:Me,local_files_only:Pe,revision:Ue,legacy:lt}),Tt=((gr=pt.tokenizer_class)==null?void 0:gr.replace(/Fast$/,""))??"PreTrainedTokenizer";let Wt=this.TOKENIZER_CLASS_MAPPING[Tt];return Wt||(console.warn(`Unknown tokenizer class "${Tt}", attempting to construct from base class.`),Wt=Dt),new Wt(mt,pt)}}ve(_r,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Wr,DistilBertTokenizer:ps,CamembertTokenizer:it,DebertaTokenizer:Ys,DebertaV2Tokenizer:xs,BertTokenizer:Ts,HerbertTokenizer:Js,ConvBertTokenizer:Zs,RoFormerTokenizer:zs,XLMTokenizer:Mt,ElectraTokenizer:It,MobileBertTokenizer:Xs,SqueezeBertTokenizer:un,AlbertTokenizer:Ls,GPT2Tokenizer:en,BartTokenizer:Bs,MBartTokenizer:Sr,MBart50Tokenizer:ts,RobertaTokenizer:Br,WhisperTokenizer:dn,CodeGenTokenizer:xn,CLIPTokenizer:En,SiglipTokenizer:Pn,MarianTokenizer:Ot,BloomTokenizer:As,NllbTokenizer:js,M2M100Tokenizer:Ns,LlamaTokenizer:Tn,CodeLlamaTokenizer:tn,XLMRobertaTokenizer:uo,MPNetTokenizer:Dn,FalconTokenizer:Ln,GPTNeoXTokenizer:zn,EsmTokenizer:Rs,Wav2Vec2CTCTokenizer:Cn,BlenderbotTokenizer:Rn,BlenderbotSmallTokenizer:jn,SpeechT5Tokenizer:Nn,NougatTokenizer:$n,VitsTokenizer:Un,Qwen2Tokenizer:Bn,GemmaTokenizer:co,Grok1Tokenizer:rn,CohereTokenizer:Sn,MgpstrTokenizer:kn,PreTrainedTokenizer:Dt})},"./src/utils/audio.js":(Oe,R,c)=>{c.r(R),c.d(R,{hamming:()=>M,hanning:()=>v,mel_filter_bank:()=>j,read_audio:()=>Q,spectrogram:()=>_,window_function:()=>k});var w=c("./src/utils/hub.js"),z=c("./src/utils/maths.js"),G=c("./src/utils/core.js"),re=c("./src/utils/tensor.js");async function Q(E,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 Y=await(await(0,w.getFile)(E)).arrayBuffer(),de=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${de.sampleRate}Hz.`);const me=await de.decodeAudioData(Y);let ye;if(me.numberOfChannels===2){const Ce=Math.sqrt(2),Ee=me.getChannelData(0),Le=me.getChannelData(1);ye=new Float32Array(Ee.length);for(let _e=0;_e2595*Math.log10(1+E/700),kaldi:E=>1127*Math.log(1+E/700),slaney:(E,ee=1e3,Y=15,de=27/Math.log(6.4))=>E>=ee?Y+Math.log(E/ee)*de:3*E/200};function C(E,ee="htk"){const Y=y[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?Y(E):E.map(de=>Y(de))}const q={htk:E=>700*(10**(E/2595)-1),kaldi:E=>700*(Math.exp(E/1127)-1),slaney:(E,ee=1e3,Y=15,de=Math.log(6.4)/27)=>E>=Y?ee*Math.exp(de*(E-Y)):200*E/3};function J(E,ee="htk"){const Y=q[ee];if(!Y)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof E=="number"?Y(E):E.map(de=>Y(de))}function ie(E,ee){const Y=Float64Array.from({length:ee.length-1},(Ce,Ee)=>ee[Ee+1]-ee[Ee]),de=Array.from({length:E.length},()=>new Array(ee.length));for(let Ce=0;Cenew Array(E.length));for(let Ce=0;CeE+de*ye)}function j(E,ee,Y,de,me,ye=null,Ce="htk",Ee=!1){if(ye!==null&&ye!=="slaney")throw new Error('norm must be one of null or "slaney"');const Le=C(Y,Ce),_e=C(de,Ce),U=fe(Le,_e,ee+2);let ce=J(U,Ce),he;if(Ee){const Re=me/(E*2);he=C(Float64Array.from({length:E},(Ke,Ye)=>Ye*Re),Ce),ce=U}else he=fe(0,Math.floor(me/2),E);const ke=ie(he,ce);if(ye!==null&&ye==="slaney")for(let Re=0;Reme)throw Error(`frame_length (${Y}) may not be larger than fft_length (${me})`);if(je!==Y)throw new Error(`Length of the window (${je}) must equal frame_length (${Y})`);if(de<=0)throw new Error("hop_length must be greater than zero");if(ye===null&&U!==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(Ce){if(Ee!=="reflect")throw new Error(`pad_mode="${Ee}" not implemented yet.`);const A=Math.floor((me-1)/2)+1;E=X(E,A,A)}let we=Math.floor(1+Math.floor((E.length-Y)/de));at!==null&&wewe?le&&(Qe=We):Qe=et=We);const qe=new z.FFT(me),ze=new Float64Array(me),nt=new Float64Array(qe.outputBufferSize),dt=new Float32Array($e*Qe);for(let A=0;A=1;--ue)ze[ue]-=_e*ze[ue-1];ze[0]*=1-_e}for(let ue=0;ueMath.pow(Ee,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(Y&&(Ce=Ce.subarray(0,E)),de===null)return Ce;if(E>de)throw new Error(`Length of the window (${E}) may not be larger than frame_length (${de})`);return Ce}},"./src/utils/constants.js":(Oe,R,c)=>{c.r(R),c.d(R,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>z,FEATURE_EXTRACTOR_NAME:()=>G,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>w,IMAGE_PROCESSOR_NAME:()=>re,PROCESSOR_NAME:()=>Q});const w="https://github.com/huggingface/transformers.js/issues/new/choose",z="config.json",G="preprocessor_config.json",re=G,Q="processor_config.json",g="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(Oe,R,c)=>{c.r(R),c.d(R,{calculateDimensions:()=>v,calculateReflectOffset:()=>q,count:()=>fe,dispatchCallback:()=>w,escapeRegExp:()=>G,isIntegralNumber:()=>Q,isNullishDimension:()=>g,isTypedArray:()=>re,len:()=>ie,mergeArrays:()=>y,pick:()=>J,pop:()=>M,product:()=>C,reverseDictionary:()=>z});function w(j,X){j&&j(X)}function z(j){return Object.fromEntries(Object.entries(j).map(([X,Z])=>[Z,X]))}function G(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(j){var X,Z,N;return((N=(Z=(X=j==null?void 0:j.prototype)==null?void 0:X.__proto__)==null?void 0:Z.constructor)==null?void 0:N.name)==="TypedArray"}function Q(j){return Number.isInteger(j)||typeof j=="bigint"}function g(j){return j==null||j===-1}function v(j){const X=[];let Z=j;for(;Array.isArray(Z);)X.push(Z.length),Z=Z[0];return X}function M(j,X,Z=void 0){const N=j[X];if(N!==void 0)return delete j[X],N;if(Z===void 0)throw Error(`Key ${X} does not exist in object.`);return Z}function y(...j){return Array.prototype.concat.apply([],j)}function C(...j){return j.reduce((X,Z)=>X.flatMap(N=>Z.map(I=>[N,I])))}function q(j,X){return Math.abs((j+X)%(2*X)-X)}function J(j,X){return Object.assign({},...X.map(Z=>{if(j[Z]!==void 0)return{[Z]:j[Z]}}))}function ie(j){let X=0;for(const Z of j)++X;return X}function fe(j,X){let Z=0;for(const N of j)N===X&&++Z;return Z}},"./src/utils/data-structures.js":(Oe,R,c)=>{c.r(R),c.d(R,{CharTrie:()=>z,PriorityQueue:()=>w,TokenLattice:()=>re});class w{constructor(v=(y,C)=>y>C,M=1/0){this._heap=[],this._comparator=v,this._maxSize=M}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 M of v)if(this.size0&&this._swap(0,M),this._heap.pop(),this._siftDown(),v}replace(v){const M=this.peek();return this._heap[0]=v,this._siftDown(),M}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,M){return this._comparator(this._heap[v],this._heap[M])}_swap(v,M){const y=this._heap[v];this._heap[v]=this._heap[M],this._heap[M]=y}_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 C=new Q(this.bosTokenId,0,0,0,0),q=new Q(this.eosTokenId,1,this.len,0,0);this.nodes.push(C.clone()),this.nodes.push(q.clone()),this.beginNodes[this.len].push(q),this.endNodes[0].push(C)}insert(v,M,y,C){const q=this.nodes.length,J=new Q(C,q,v,M,y);this.beginNodes[v].push(J),this.endNodes[v+M].push(J),this.nodes.push(J)}viterbi(){const v=this.len;let M=0;for(;M<=v;){if(this.beginNodes[M].length==0)return[];for(let ie of this.beginNodes[M]){ie.prev=null;let fe=0,j=null;for(let X of this.endNodes[M]){const Z=X.backtraceScore+ie.score;(j===null||Z>fe)&&(j=X.clone(),fe=Z)}if(j!==null)ie.prev=j,ie.backtraceScore=fe;else return[]}++M}const y=[],q=this.beginNodes[v][0].prev;if(q===null)return[];let J=q.clone();for(;J.prev!==null;)y.push(J.clone()),J=J.clone().prev.clone();return y.reverse(),y}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class Q{constructor(v,M,y,C,q){this.tokenId=v,this.nodeId=M,this.pos=y,this.length=C,this.score=q,this.prev=null,this.backtraceScore=0}clone(){const v=new Q(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(Oe,R,c)=>{c.r(R),c.d(R,{DEVICE_TYPES:()=>w});const w=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":(Oe,R,c)=>{c.r(R),c.d(R,{DATA_TYPES:()=>re,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Q,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>G});var w=c("./src/env.js"),z=c("./src/utils/devices.js");const G=function(){let v;return async function(){if(v===void 0)if(!w.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),re=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Q=Object.freeze({[z.DEVICE_TYPES.wasm]:re.q8}),g=Object.freeze({[re.fp32]:"",[re.fp16]:"_fp16",[re.int8]:"_int8",[re.uint8]:"_uint8",[re.q8]:"_quantized",[re.q4]:"_q4",[re.q4f16]:"_q4f16",[re.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Oe,R,c)=>{c.r(R),c.d(R,{Callable:()=>w});const w=class{constructor(){let z=function(...G){return z._call(...G)};return Object.setPrototypeOf(z,new.target.prototype)}_call(...z){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Oe,R,c)=>{c.r(R),c.d(R,{getFile:()=>M,getModelFile:()=>ie,getModelJSON:()=>fe});var w=c("?7a2c"),z=c("?a42a"),G=c("./src/env.js"),re=c("./src/utils/core.js");const Q={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 g{constructor(N){if(this.filePath=N,this.headers=new Headers,this.exists=w.existsSync(N),this.exists){this.status=200,this.statusText="OK";let I=w.statSync(N);this.headers.set("content-length",I.size.toString()),this.updateContentType();let _=this;this.body=new ReadableStream({start(k){_.arrayBuffer().then(E=>{k.enqueue(new Uint8Array(E)),k.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const N=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Q[N]??"application/octet-stream")}clone(){let N=new g(this.filePath);return N.exists=this.exists,N.status=this.status,N.statusText=this.statusText,N.headers=new Headers(this.headers),N}async arrayBuffer(){return(await w.promises.readFile(this.filePath)).buffer}async blob(){const N=await w.promises.readFile(this.filePath);return new Blob([N],{type:this.headers.get("content-type")})}async text(){return await w.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(Z,N=null,I=null){let _;try{_=new URL(Z)}catch{return!1}return!(N&&!N.includes(_.protocol)||I&&!I.includes(_.hostname))}async function M(Z){var N;if(G.env.useFS&&!v(Z,["http:","https:","blob:"]))return new g(Z);if(typeof process<"u"&&((N=process==null?void 0:process.release)==null?void 0:N.name)==="node"){const I=!!(gs!=null&&gs.TESTING_REMOTELY),_=G.env.version,k=new Headers;if(k.set("User-Agent",`transformers.js/${_}; is_ci/${I};`),v(Z,["http:","https:"],["huggingface.co","hf.co"])){const ee=(gs==null?void 0:gs.HF_TOKEN)??(gs==null?void 0:gs.HF_ACCESS_TOKEN);ee&&k.set("Authorization",`Bearer ${ee}`)}return fetch(Z,{headers:k})}else return fetch(Z)}const y={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 C(Z,N,I){if(!I)return null;const _=y[Z]??`Error (${Z}) occurred while trying to load file`;throw Error(`${_}: "${N}".`)}class q{constructor(N){this.path=N}async match(N){let I=z.join(this.path,N),_=new g(I);if(_.exists)return _}async put(N,I){const _=Buffer.from(await I.arrayBuffer());let k=z.join(this.path,N);try{await w.promises.mkdir(z.dirname(k),{recursive:!0}),await w.promises.writeFile(k,_)}catch(E){console.warn("An error occurred while writing the file to cache:",E)}}}async function J(Z,...N){for(let I of N)try{let _=await Z.match(I);if(_)return _}catch{continue}}async function ie(Z,N,I=!0,_={}){if(!G.env.allowLocalModels){if(_.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(!G.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,re.dispatchCallback)(_.progress_callback,{status:"initiate",name:Z,file:N});let k;if(!k&&G.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{k=await caches.open("transformers-cache")}catch(he){console.warn("An error occurred while opening the browser cache:",he)}}if(!k&&G.env.useFSCache&&(k=new q(_.cache_dir??G.env.cacheDir)),!k&&G.env.useCustomCache){if(!G.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!G.env.customCache.match||!G.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");k=G.env.customCache}const E=_.revision??"main";let ee=X(Z,N),Y=X(G.env.localModelPath,ee),de=X(G.env.remoteHost,G.env.remotePathTemplate.replaceAll("{model}",Z).replaceAll("{revision}",encodeURIComponent(E)),N),me=E==="main"?ee:X(Z,E,N),ye,Ce=k instanceof q?me:de,Ee=!1,Le;k&&(Le=await J(k,Y,Ce));const _e=Le!==void 0;if(Le===void 0){if(G.env.allowLocalModels)if(v(ee,["http:","https:"])){if(_.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!G.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{Le=await M(Y),ye=Y}catch(ke){console.warn(`Unable to load from local path "${Y}": "${ke}"`)}if(Le===void 0||Le.status===404){if(_.local_files_only||!G.env.allowRemoteModels){if(I)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Y}".`);return null}if(Le=await M(de),Le.status!==200)return C(Le.status,de,I);ye=Ce}Ee=k&&typeof Response<"u"&&Le instanceof Response&&Le.status===200}(0,re.dispatchCallback)(_.progress_callback,{status:"download",name:Z,file:N});const U={status:"progress",name:Z,file:N};let ce;return _.progress_callback?_e&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ce=new Uint8Array(await Le.arrayBuffer()),(0,re.dispatchCallback)(_.progress_callback,{...U,progress:100,loaded:ce.length,total:ce.length})):ce=await j(Le,he=>{(0,re.dispatchCallback)(_.progress_callback,{...U,...he})}):ce=new Uint8Array(await Le.arrayBuffer()),Ee&&ye&&await k.match(ye)===void 0&&await k.put(ye,new Response(ce,{headers:Le.headers})).catch(he=>{console.warn(`Unable to add response to browser cache: ${he}.`)}),(0,re.dispatchCallback)(_.progress_callback,{status:"done",name:Z,file:N}),ce}async function fe(Z,N,I=!0,_={}){let k=await ie(Z,N,I,_);if(k===null)return{};let ee=new TextDecoder("utf-8").decode(k);return JSON.parse(ee)}async function j(Z,N){const I=Z.headers.get("Content-Length");I===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let _=parseInt(I??"0"),k=new Uint8Array(_),E=0;const ee=Z.body.getReader();async function Y(){const{done:de,value:me}=await ee.read();if(de)return;let ye=E+me.length;if(ye>_){_=ye;let Ee=new Uint8Array(_);Ee.set(k),k=Ee}k.set(me,E),E=ye;const Ce=E/_*100;return N({progress:Ce,loaded:E,total:_}),Y()}return await Y(),k}function X(...Z){return Z=Z.map((N,I)=>(I&&(N=N.replace(new RegExp("^/"),"")),I!==Z.length-1&&(N=N.replace(new RegExp("/$"),"")),N)),Z.join("/")}},"./src/utils/image.js":(Oe,R,c)=>{c.r(R),c.d(R,{RawImage:()=>J,load_image:()=>ie});var w=c("./src/utils/core.js"),z=c("./src/utils/hub.js"),G=c("./src/env.js"),re=c("./src/utils/tensor.js"),Q=c("?2b25");let g,v,M;const y=G.apis.IS_BROWSER_ENV||G.apis.IS_WEBWORKER_ENV;if(y)g=(fe,j)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(fe,j)},M=self.createImageBitmap,v=self.ImageData;else if(Q)M=async fe=>{const X=(await fe.metadata()).channels,{data:Z,info:N}=await fe.rotate().raw().toBuffer({resolveWithObject:!0}),I=new J(new Uint8ClampedArray(Z),N.width,N.height,N.channels);return X!==void 0&&X!==N.channels&&I.convert(X),I};else throw new Error("Unable to load image processing library.");const C={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},q=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class J{constructor(j,X,Z,N){this.data=j,this.width=X,this.height=Z,this.channels=N}get size(){return[this.width,this.height]}static async read(j){if(j instanceof J)return j;if(typeof j=="string"||j instanceof URL)return await this.fromURL(j);throw new Error(`Unsupported input type: ${typeof j}`)}static fromCanvas(j){if(!y)throw new Error("fromCanvas() is only supported in browser environments.");const Z=j.getContext("2d").getImageData(0,0,j.width,j.height).data;return new J(Z,j.width,j.height,4)}static async fromURL(j){const X=await(0,z.getFile)(j);if(X.status!==200)throw new Error(`Unable to read image from "${j}" (${X.status} ${X.statusText})`);const Z=await X.blob();return this.fromBlob(Z)}static async fromBlob(j){if(y){const X=await M(j),Z=g(X.width,X.height).getContext("2d");return Z.drawImage(X,0,0),new this(Z.getImageData(0,0,X.width,X.height).data,X.width,X.height,4)}else{const X=Q(await j.arrayBuffer());return await M(X)}}static fromTensor(j,X="CHW"){if(j.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${j.dims.length} dimensions.`);if(X==="CHW")j=j.transpose(1,2,0);else if(X!=="HWC")throw new Error(`Unsupported channel format: ${X}`);if(!(j.data instanceof Uint8ClampedArray||j.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${j.type}`);switch(j.dims[2]){case 1:case 2:case 3:case 4:return new J(j.data,j.dims[1],j.dims[0],j.dims[2]);default:throw new Error(`Unsupported number of channels: ${j.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const j=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let X=0,Z=0;X=0?E=Z:Y=-Z,N>=0?ee=N:de=-N,k.drawImage(_,E,ee,j,X,Y,de,j,X),new J(k.getImageData(0,0,j,X).data,j,X,4).convert(I)}else{let I=this.toSharp();if(Z>=0&&N>=0)I=I.extract({left:Math.floor(Z),top:Math.floor(N),width:j,height:X});else if(Z<=0&&N<=0){const _=Math.floor(-N),k=Math.floor(-Z);I=I.extend({top:_,left:k,right:j-this.width-k,bottom:X-this.height-_})}else{let _=[0,0],k=0;N<0?(_[0]=Math.floor(-N),_[1]=X-this.height-_[0]):k=Math.floor(N);let E=[0,0],ee=0;Z<0?(E[0]=Math.floor(-Z),E[1]=j-this.width-E[0]):ee=Math.floor(Z),I=I.extend({top:_[0],bottom:_[1],left:E[0],right:E[1]}).extract({left:ee,top:k,width:j,height:X})}return await M(I)}}async toBlob(j="image/png",X=1){if(!y)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:j,quality:X})}toTensor(j="CHW"){let X=new re.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(j!=="HWC")if(j==="CHW")X=X.permute(2,0,1);else throw new Error(`Unsupported channel format: ${j}`);return X}toCanvas(){if(!y)throw new Error("toCanvas() is only supported in browser environments.");const j=this.clone().rgba(),X=g(j.width,j.height),Z=new v(j.data,j.width,j.height);return X.getContext("2d").putImageData(Z,0,0),X}split(){const{data:j,width:X,height:Z,channels:N}=this,I=j.constructor,_=j.length/N,k=Array.from({length:N},()=>new I(_));for(let E=0;E<_;++E){const ee=N*E;for(let Y=0;Ynew J(E,X,Z,1))}_update(j,X,Z,N=null){return this.data=j,this.width=X,this.height=Z,N!==null&&(this.channels=N),this}clone(){return new J(this.data.slice(),this.width,this.height,this.channels)}convert(j){if(this.channels===j)return this;switch(j){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(j){if(y){if(G.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const X=j.split(".").pop().toLowerCase(),Z=q.get(X)??"image/png",N=await this.toBlob(Z),I=URL.createObjectURL(N),_=document.createElement("a");_.href=I,_.download=j,_.click(),_.remove()}else{if(G.env.useFS)return await this.toSharp().toFile(j);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(y)throw new Error("toSharp() is only supported in server-side environments.");return Q(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const ie=J.read.bind(J)},"./src/utils/maths.js":(Oe,R,c)=>{c.r(R),c.d(R,{FFT:()=>ie,bankers_round:()=>X,cos_sim:()=>g,dot:()=>Q,dynamic_time_warping:()=>Z,interpolate_data:()=>w,log_softmax:()=>re,magnitude:()=>v,max:()=>y,medianFilter:()=>fe,min:()=>M,permute_data:()=>z,round:()=>j,softmax:()=>G});function w(N,[I,_,k],[E,ee],Y="bilinear",de=!1){const me=ee/k,ye=E/_,Ce=new N.constructor(E*ee*I),Ee=_*k,Le=E*ee;for(let _e=0;_e=0;--de)E[de]=me,k[de]=I[_[de]],me*=k[de];const ee=_.map((de,me)=>E[_.indexOf(me)]),Y=new N.constructor(N.length);for(let de=0;de=0;--ye)me+=Ce%I[ye]*ee[ye],Ce=Math.floor(Ce/I[ye]);Y[me]=N[de]}return[Y,k]}function G(N){const I=y(N)[0],_=N.map(ee=>Math.exp(ee-I)),k=_.reduce((ee,Y)=>ee+Y,0);return _.map(ee=>ee/k)}function re(N){const I=y(N)[0];let _=0;for(let ee=0;eeee-I-k)}function Q(N,I){let _=0;for(let k=0;kI+_*_,0))}function M(N){if(N.length===0)throw Error("Array must not be empty");let I=N[0],_=0;for(let k=1;kI&&(I=N[k],_=k);return[Number(I),_]}function C(N){return N>0&&(N&N-1)===0}class q{constructor(I){if(this.size=I|0,this.size<=1||!C(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=I<<1,this.table=new Float64Array(this.size*2);for(let k=0;kk;k<<=1)++_;this._width=_%2===0?_-1:_,this._bitrev=new Int32Array(1<>>E&3)<>>1);for(let E=0;E>>1]=I[E];return k}toComplexArray(I,_){const k=_||this.createComplexArray();for(let E=0;E>>1],k[E+1]=0;return k}transform(I,_){if(I===_)throw new Error("Input and output buffers must be different");this._transform4(I,_,1)}realTransform(I,_){if(I===_)throw new Error("Input and output buffers must be different");this._realTransform4(I,_,1)}inverseTransform(I,_){if(I===_)throw new Error("Input and output buffers must be different");this._transform4(I,_,-1);for(let k=0;k>=2;Y>=2;Y>>=2){de=E/Y<<1;const Le=de>>>2;for(me=0;me>>1,Y>>>1)}else for(me=0,ye=0;me>>1,Y>>>1,k)}const Ee=this.table;for(Y>>=2;Y>=2;Y>>=2){de=E/Y<<1;const _e=de>>>1,U=_e>>>1,ce=U>>>1;for(me=0;me>>1;for(let _e=2;_e>1;++Ce){const Ee=(Ce+1-I)**2/2,Le=Math.sqrt(me**2+ye**2)**Ee,_e=Ee*Math.atan2(ye,me),U=2*Ce;ee[U]=Le*Math.cos(_e),ee[U+1]=Le*Math.sin(_e),Y[U]=ee[U],Y[U+1]=-ee[U+1]}this._slicedChirpBuffer=ee.subarray(_,k),this._f=new q(E>>1),this._f.transform(this._chirpBuffer,Y)}_transform(I,_,k){const E=this._buffer1,ee=this._buffer2,Y=this._outBuffer1,de=this._outBuffer2,me=this._chirpBuffer,ye=this._slicedChirpBuffer,Ce=this._a;if(k)for(let Ee=0;Ee>1,U=_[_e];E[Ee]=U*ye[Ee],E[Le]=U*ye[Le]}else for(let Ee=0;Ee=N.length&&(me=2*(N.length-1)-me),k[Y++]=N[me]}k.sort(),_[ee]=k[E]}return _}function j(N,I){const _=Math.pow(10,I);return Math.round(N*_)/_}function X(N){const I=Math.round(N);return Math.abs(N)%1===.5?I%2===0?I:I-1:I}function Z(N){const I=N.length,_=N[0].length,k=[I+1,_+1],E=Array.from({length:k[0]},()=>Array(k[1]).fill(1/0));E[0][0]=0;const ee=Array.from({length:k[0]},()=>Array(k[1]).fill(-1));for(let Ce=1;Ce0||de>0;)switch(me.push(Y-1),ye.push(de-1),ee[Y][de]){case 0:--Y,--de;break;case 1:--Y;break;case 2:--de;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Y}, ${de}]. Please file a bug report.`)}return me.reverse(),ye.reverse(),[me,ye]}},"./src/utils/tensor.js":(Oe,R,c)=>{c.r(R),c.d(R,{Tensor:()=>Q,cat:()=>N,full:()=>Y,full_like:()=>de,interpolate:()=>M,interpolate_4d:()=>y,layer_norm:()=>fe,matmul:()=>C,mean:()=>k,mean_pooling:()=>ie,ones:()=>me,ones_like:()=>ye,permute:()=>v,quantize_embeddings:()=>Le,rfft:()=>q,stack:()=>I,std_mean:()=>_,topk:()=>J,zeros:()=>Ce,zeros_like:()=>Ee});var w=c("./src/utils/maths.js"),z=c("./src/backends/onnx.js"),G=c("./src/ops/registry.js");const re=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 Q{constructor(...U){ve(this,"ort_tensor");return(0,z.isONNXTensor)(U[0])?this.ort_tensor=U[0]:this.ort_tensor=new z.Tensor(U[0],U[1],U[2]),new Proxy(this,{get:(ce,he)=>{if(typeof he=="string"){let ke=Number(he);if(Number.isInteger(ke))return ce._getitem(ke)}return ce[he]},set:(ce,he,ke)=>ce[he]=ke})}get dims(){return this.ort_tensor.dims}set dims(U){this.ort_tensor.dims=U}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[U,...ce]=this.dims;if(ce.length>0){const he=ce.reduce((ke,Re)=>ke*Re);for(let ke=0;ke0){const ke=he.reduce((Re,Ke)=>Re*Ke);return this._subarray(U,ke,he)}else return new Q(this.type,[this.data[U]],he)}indexOf(U){const ce=this.data;for(let he=0;heje)throw new Error(`Invalid slice: ${le}`);const we=[Math.max(He,0),Math.min(je,this.dims[We])];he.push(we),ce.push(we[1]-we[0])}else throw new Error(`Invalid slice: ${le}`)}const ke=he.map(([We,le])=>le-We),Re=ke.reduce((We,le)=>We*le),Ke=this.data,Ye=new Ke.constructor(Re),at=this.stride();for(let We=0;We=0;--He){const we=ke[He];le+=(je%we+he[He][0])*at[He],je=Math.floor(je/we)}Ye[We]=Ke[le]}return new Q(this.type,Ye,ce)}permute(...U){return v(this,U)}transpose(...U){return this.permute(...U)}sum(U=null,ce=!1){return this.norm(1,U,ce)}norm(U="fro",ce=null,he=!1){if(U==="fro")U=2;else if(typeof U=="string")throw Error(`Unsupported norm: ${U}`);const ke=this.data;if(ce===null){let Ye=ke.reduce((at,We)=>at+We**U,0)**(1/U);return new Q(this.type,[Ye],[])}ce=Z(ce,this.dims.length);const Re=this.dims.slice();Re[ce]=1;const Ke=new ke.constructor(ke.length/this.dims[ce]);for(let Ye=0;Ye=0;--We){const je=this.dims[We];if(We!==ce){const we=le%je;at+=we*He,He*=Re[We]}le=Math.floor(le/je)}Ke[at]+=ke[Ye]**U}if(U!==1)for(let Ye=0;Ye=0;--at){const He=this.dims[at];if(at!==ce){const je=We%He;Ye+=je*le,le*=this.dims[at]}We=Math.floor(We/He)}ke[Ke]/=Re[Ye]}return this}normalize(U=2,ce=1){return this.clone().normalize_(U,ce)}stride(){return E(this.dims)}squeeze(U=null){return new Q(this.type,this.data,j(this.dims,U))}squeeze_(U=null){return this.dims=j(this.dims,U),this}unsqueeze(U=null){return new Q(this.type,this.data,X(this.dims,U))}unsqueeze_(U=null){return this.dims=X(this.dims,U),this}flatten_(U=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let he=this.dims.slice(0,U),ke=this.dims.slice(U,ce+1),Re=this.dims.slice(ce+1);return this.dims=[...he,ke.reduce((Ke,Ye)=>Ke*Ye,1),...Re],this}flatten(U=0,ce=-1){return this.clone().flatten_(U,ce)}view(...U){let ce=-1;for(let ke=0;keYe!==ce?Re*Ke:Re,1);U[ce]=he.length/ke}return new Q(this.type,he,U)}neg_(){const U=this.data;for(let ce=0;ceRe*Ke);if(ce!==he)throw Error(`cannot reshape array of size ${ce} into shape (${U})`);let ke=_e;for(let Re=U.length-1;Re>=0;Re--)ke=ke.reduce((Ke,Ye)=>{let at=Ke[Ke.length-1];return at.lengthce!==1):typeof U=="number"?_e[U]===1&&_e.splice(U,1):Array.isArray(U)&&(_e=_e.filter((ce,he)=>ce!==1||!U.includes(he))),_e}function X(_e,U){return U=Z(U,_e.length+1),_e=_e.slice(),_e.splice(U,0,1),_e}function Z(_e,U,ce=null,he=!0){if(he&&(_e<-U||_e>=U))throw new Error(`IndexError: index ${_e} is out of bounds for dimension${ce===null?"":" "+ce} with size ${U}`);return _e<0&&(_e=(_e%U+U)%U),_e}function N(_e,U=0){U=Z(U,_e[0].dims.length);const ce=_e[0].dims.slice();ce[U]=_e.reduce((Ke,Ye)=>Ke+Ye.dims[U],0);const he=ce.reduce((Ke,Ye)=>Ke*Ye,1),ke=new _e[0].data.constructor(he),Re=_e[0].type;if(U===0){let Ke=0;for(const Ye of _e){const at=Ye.data;ke.set(at,Ke),Ke+=at.length}}else{let Ke=0;for(let Ye=0;Ye<_e.length;++Ye){const{data:at,dims:We}=_e[Ye];for(let le=0;le=0;--je){const et=We[je];let Qe=we%et;je===U&&(Qe+=Ke),He+=Qe*$e,$e*=ce[je],we=Math.floor(we/et)}ke[He]=at[le]}Ke+=We[U]}}return new Q(Re,ke,ce)}function I(_e,U=0){return N(_e.map(ce=>ce.unsqueeze(U)),U)}function _(_e,U=null,ce=1,he=!1){const ke=_e.data,Re=_e.dims;if(U===null){const je=ke.reduce((Qe,qe)=>Qe+qe,0)/ke.length,we=Math.sqrt(ke.reduce((Qe,qe)=>Qe+(qe-je)**2,0)/(ke.length-ce)),$e=new Q(_e.type,[je],[]);return[new Q(_e.type,[we],[]),$e]}U=Z(U,Re.length);const Ke=k(_e,U,he),Ye=Ke.data,at=Re.slice();at[U]=1;const We=new ke.constructor(ke.length/Re[U]);for(let He=0;He=0;--we){const Qe=Re[we];if(we!==U){const qe=$e%Qe;je+=qe*et,et*=at[we]}$e=Math.floor($e/Qe)}We[je]+=(ke[He]-Ye[je])**2}for(let He=0;Heat+We,0);return new Q(_e.type,[Ye/he.length],[])}const ke=_e.dims;U=Z(U,ke.length);const Re=ke.slice();Re[U]=1;const Ke=new he.constructor(he.length/ke[U]);for(let Ye=0;Ye=0;--We){const je=ke[We];if(We!==U){const we=le%je;at+=we*He,He*=Re[We]}le=Math.floor(le/je)}Ke[at]+=he[Ye]}if(ke[U]!==1)for(let Ye=0;Ye=0;--ce)U[ce]=he,he*=_e[ce];return U}function ee(_e,U,ce,he){const ke=_e.reduce((Re,Ke)=>Re*Ke,1);return new Q(ce,new he(ke).fill(U),_e)}function Y(_e,U){let ce,he;if(typeof U=="number")ce="float32",he=Float32Array;else if(typeof U=="bigint")ce="int64",he=BigInt64Array;else if(typeof U=="boolean")ce="bool",he=Uint8Array;else throw new Error(`Unsupported data type: ${typeof U}`);return ee(_e,U,ce,he)}function de(_e,U){return Y(_e.dims,U)}function me(_e){return ee(_e,1n,"int64",BigInt64Array)}function ye(_e){return me(_e.dims)}function Ce(_e){return ee(_e,0n,"int64",BigInt64Array)}function Ee(_e){return Ce(_e.dims)}function Le(_e,U){if(_e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(_e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(U))throw new Error("The precision must be either 'binary' or 'ubinary'");const ce=U==="binary",he=ce?"int8":"uint8",ke=ce?Int8Array:Uint8Array,Re=_e.data,Ke=new ke(Re.length/8);for(let Ye=0;Ye0?1:0,We=Math.floor(Ye/8),le=Ye%8;Ke[We]|=at<<7-le,ce&&le===0&&(Ke[We]-=128)}return new Q(he,Ke,[_e.dims[0],_e.dims[1]/8])}}},lo={};function fr(Oe){var R=lo[Oe];if(R!==void 0)return R.exports;var c=lo[Oe]={exports:{}};return ln[Oe](c,c.exports,fr),c.exports}fr.m=ln,(()=>{var Oe=Object.getPrototypeOf?c=>Object.getPrototypeOf(c):c=>c.__proto__,R;fr.t=function(c,w){if(w&1&&(c=this(c)),w&8||typeof c=="object"&&c&&(w&4&&c.__esModule||w&16&&typeof c.then=="function"))return c;var z=Object.create(null);fr.r(z);var G={};R=R||[null,Oe({}),Oe([]),Oe(Oe)];for(var re=w&2&&c;typeof re=="object"&&!~R.indexOf(re);re=Oe(re))Object.getOwnPropertyNames(re).forEach(Q=>G[Q]=()=>c[Q]);return G.default=()=>c,fr.d(z,G),z}})(),fr.d=(Oe,R)=>{for(var c in R)fr.o(R,c)&&!fr.o(Oe,c)&&Object.defineProperty(Oe,c,{enumerable:!0,get:R[c]})},fr.o=(Oe,R)=>Object.prototype.hasOwnProperty.call(Oe,R),fr.r=Oe=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Oe,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Oe,"__esModule",{value:!0})},(()=>{var Oe;if(typeof self.location.href=="string"&&(Oe=self.location.href),!Oe)throw new Error("Automatic publicPath is not supported in this browser");Oe=Oe.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),fr.p=Oe})(),fr.b=new URL("./",self.location.href);var u={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/fr.r(u),fr.d(u,{ASTFeatureExtractor:()=>bn.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>Qt.AlbertTokenizer,AudioClassificationPipeline:()=>zr.AudioClassificationPipeline,AutoConfig:()=>Pp.AutoConfig,AutoFeatureExtractor:()=>qm.AutoFeatureExtractor,AutoImageProcessor:()=>Xm.AutoImageProcessor,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>b.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>b.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Jm.AutoProcessor,AutoTokenizer:()=>Qt.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>zr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>Qt.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>Cp.BaseStreamer,BeitFeatureExtractor:()=>Kt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>Qt.BertTokenizer,BitImageProcessor:()=>Kt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>Qt.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>Qt.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>Qt.BloomTokenizer,CLIPFeatureExtractor:()=>Kt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Kt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModel:()=>b.CLIPTextModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>Qt.CLIPTokenizer,CLIPVisionModel:()=>b.CLIPVisionModel,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>Qt.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Kt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>bn.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>cs.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>Qt.CodeGenTokenizer,CodeLlamaTokenizer:()=>Qt.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>Qt.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>Qt.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Kt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Kt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Kt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Kt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>Qt.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>Qt.DebertaV2Tokenizer,DecisionTransformerModel:()=>b.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>b.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Kt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTImageProcessor:()=>Kt.DeiTImageProcessor,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>zr.DepthEstimationPipeline,DepthProForDepthEstimation:()=>b.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>b.DepthProPreTrainedModel,DetrFeatureExtractor:()=>Kt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrImageProcessor:()=>Kt.DetrImageProcessor,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>Qt.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>zr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Kt.DonutFeatureExtractor,DonutImageProcessor:()=>Kt.DonutImageProcessor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Kt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>Qt.ElectraTokenizer,EosTokenCriteria:()=>Oa.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>Qt.EsmTokenizer,FFT:()=>vs.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>Qt.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>zr.FeatureExtractionPipeline,FeatureExtractor:()=>Hm.FeatureExtractor,FillMaskPipeline:()=>zr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Os.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>cs.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>cs.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>Kt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>Qt.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>Qt.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>Qt.GemmaTokenizer,GraniteForCausalLM:()=>b.GraniteForCausalLM,GraniteModel:()=>b.GraniteModel,GranitePreTrainedModel:()=>b.GranitePreTrainedModel,Grok1Tokenizer:()=>Qt.Grok1Tokenizer,GroupViTModel:()=>b.GroupViTModel,GroupViTPreTrainedModel:()=>b.GroupViTPreTrainedModel,HerbertTokenizer:()=>Qt.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,Idefics3ForConditionalGeneration:()=>b.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>Kt.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>b.Idefics3PreTrainedModel,Idefics3Processor:()=>Os.Idefics3Processor,ImageClassificationPipeline:()=>zr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>zr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>bn.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageProcessor:()=>Qm.ImageProcessor,ImageSegmentationPipeline:()=>zr.ImageSegmentationPipeline,ImageToImagePipeline:()=>zr.ImageToImagePipeline,ImageToTextPipeline:()=>zr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Oa.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>Kt.JinaCLIPImageProcessor,JinaCLIPModel:()=>b.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>b.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>Os.JinaCLIPProcessor,JinaCLIPTextModel:()=>b.JinaCLIPTextModel,JinaCLIPVisionModel:()=>b.JinaCLIPVisionModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>Qt.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>b.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>Kt.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LogitsProcessor:()=>cs.LogitsProcessor,LogitsProcessorList:()=>cs.LogitsProcessorList,LogitsWarper:()=>cs.LogitsWarper,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>Qt.M2M100Tokenizer,MBart50Tokenizer:()=>Qt.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>Qt.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>Qt.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>Qt.MarianTokenizer,Mask2FormerImageProcessor:()=>Kt.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>Kt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>b.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>Kt.MaskFormerImageProcessor,MaskFormerModel:()=>b.MaskFormerModel,MaskFormerPreTrainedModel:()=>b.MaskFormerPreTrainedModel,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>Oa.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>b.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>b.MgpstrModelOutput,MgpstrPreTrainedModel:()=>b.MgpstrPreTrainedModel,MgpstrProcessor:()=>Os.MgpstrProcessor,MgpstrTokenizer:()=>Qt.MgpstrTokenizer,MinLengthLogitsProcessor:()=>cs.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>cs.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>Qt.MobileBertTokenizer,MobileLLMForCausalLM:()=>b.MobileLLMForCausalLM,MobileLLMModel:()=>b.MobileLLMModel,MobileLLMPreTrainedModel:()=>b.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>Kt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>Kt.MobileNetV1ImageProcessor,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Kt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>Kt.MobileNetV2ImageProcessor,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Kt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>Kt.MobileNetV3ImageProcessor,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Kt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>Kt.MobileNetV4ImageProcessor,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Kt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Kt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MultiModalityCausalLM:()=>b.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>b.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>Qt.NllbTokenizer,NoBadWordsLogitsProcessor:()=>cs.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>cs.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Kt.NougatImageProcessor,NougatTokenizer:()=>Qt.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>zr.ObjectDetectionPipeline,OlmoForCausalLM:()=>b.OlmoForCausalLM,OlmoModel:()=>b.OlmoModel,OlmoPreTrainedModel:()=>b.OlmoPreTrainedModel,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Kt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTImageProcessor:()=>Kt.OwlViTImageProcessor,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Os.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Kt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,PatchTSMixerForPrediction:()=>b.PatchTSMixerForPrediction,PatchTSMixerModel:()=>b.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>b.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>b.PatchTSTForPrediction,PatchTSTModel:()=>b.PatchTSTModel,PatchTSTPreTrainedModel:()=>b.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>zr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>Qt.PreTrainedTokenizer,PretrainedConfig:()=>Pp.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Ym.Processor,PvtForImageClassification:()=>b.PvtForImageClassification,PvtImageProcessor:()=>Kt.PvtImageProcessor,PvtModel:()=>b.PvtModel,PvtPreTrainedModel:()=>b.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>bn.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Os.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>zr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>Qt.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>b.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>Kt.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>b.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>Os.Qwen2VLProcessor,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Kt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>uh.RawImage,RepetitionPenaltyLogitsProcessor:()=>cs.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>Qt.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>Qt.RobertaTokenizer,SamImageProcessor:()=>Kt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Os.SamProcessor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>bn.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Kt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>Kt.SegformerImageProcessor,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Kt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>Qt.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>bn.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Os.SpeechT5Processor,SpeechT5Tokenizer:()=>Qt.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>Qt.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>Oa.StoppingCriteria,StoppingCriteriaList:()=>Oa.StoppingCriteriaList,SummarizationPipeline:()=>zr.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>cs.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Kt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>Qt.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>cs.TemperatureLogitsWarper,Tensor:()=>Xr.Tensor,Text2TextGenerationPipeline:()=>zr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>zr.TextClassificationPipeline,TextGenerationPipeline:()=>zr.TextGenerationPipeline,TextStreamer:()=>Cp.TextStreamer,TextToAudioPipeline:()=>zr.TextToAudioPipeline,TokenClassificationPipeline:()=>zr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>Qt.TokenizerModel,TopKLogitsWarper:()=>cs.TopKLogitsWarper,TopPLogitsWarper:()=>cs.TopPLogitsWarper,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>zr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>Os.VLChatProcessor,VLMImageProcessor:()=>Kt.VLMImageProcessor,ViTFeatureExtractor:()=>Kt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Kt.ViTImageProcessor,ViTMAEModel:()=>b.ViTMAEModel,ViTMAEPreTrainedModel:()=>b.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>b.ViTMSNForImageClassification,ViTMSNModel:()=>b.ViTMSNModel,ViTMSNPreTrainedModel:()=>b.ViTMSNPreTrainedModel,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Kt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>b.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>Kt.VitPoseImageProcessor,VitPosePreTrainedModel:()=>b.VitPosePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>Qt.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>Qt.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>bn.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Os.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>bn.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>bn.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Os.WhisperProcessor,WhisperTextStreamer:()=>Cp.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>cs.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>Qt.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>Qt.XLMRobertaTokenizer,XLMTokenizer:()=>Qt.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Kt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosImageProcessor:()=>Kt.YolosImageProcessor,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>zr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>zr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>zr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>zr.ZeroShotObjectDetectionPipeline,bankers_round:()=>vs.bankers_round,cat:()=>Xr.cat,cos_sim:()=>vs.cos_sim,dot:()=>vs.dot,dynamic_time_warping:()=>vs.dynamic_time_warping,env:()=>Km.env,full:()=>Xr.full,full_like:()=>Xr.full_like,getKeyValueShapes:()=>Pp.getKeyValueShapes,hamming:()=>Qo.hamming,hanning:()=>Qo.hanning,interpolate:()=>Xr.interpolate,interpolate_4d:()=>Xr.interpolate_4d,interpolate_data:()=>vs.interpolate_data,is_chinese_char:()=>Qt.is_chinese_char,layer_norm:()=>Xr.layer_norm,load_image:()=>uh.load_image,log_softmax:()=>vs.log_softmax,magnitude:()=>vs.magnitude,matmul:()=>Xr.matmul,max:()=>vs.max,mean:()=>Xr.mean,mean_pooling:()=>Xr.mean_pooling,medianFilter:()=>vs.medianFilter,mel_filter_bank:()=>Qo.mel_filter_bank,min:()=>vs.min,ones:()=>Xr.ones,ones_like:()=>Xr.ones_like,permute:()=>Xr.permute,permute_data:()=>vs.permute_data,pipeline:()=>zr.pipeline,quantize_embeddings:()=>Xr.quantize_embeddings,read_audio:()=>Qo.read_audio,rfft:()=>Xr.rfft,round:()=>vs.round,softmax:()=>vs.softmax,spectrogram:()=>Qo.spectrogram,stack:()=>Xr.stack,std_mean:()=>Xr.std_mean,topk:()=>Xr.topk,window_function:()=>Qo.window_function,zeros:()=>Xr.zeros,zeros_like:()=>Xr.zeros_like});var Km=fr("./src/env.js"),zr=fr("./src/pipelines.js"),b=fr("./src/models.js"),Qt=fr("./src/tokenizers.js"),Pp=fr("./src/configs.js"),Qo=fr("./src/utils/audio.js"),uh=fr("./src/utils/image.js"),Xr=fr("./src/utils/tensor.js"),vs=fr("./src/utils/maths.js"),Hm=fr("./src/base/feature_extraction_utils.js"),bn=fr("./src/models/feature_extractors.js"),qm=fr("./src/models/auto/feature_extraction_auto.js"),Qm=fr("./src/base/image_processors_utils.js"),Kt=fr("./src/models/image_processors.js"),Xm=fr("./src/models/auto/image_processing_auto.js"),Ym=fr("./src/base/processing_utils.js"),Os=fr("./src/models/processors.js"),Jm=fr("./src/models/auto/processing_auto.js"),Cp=fr("./src/generation/streamers.js"),Oa=fr("./src/generation/stopping_criteria.js"),cs=fr("./src/generation/logits_process.js");u.ASTFeatureExtractor,u.ASTForAudioClassification,u.ASTModel,u.ASTPreTrainedModel,u.AlbertForMaskedLM,u.AlbertForQuestionAnswering,u.AlbertForSequenceClassification,u.AlbertModel,u.AlbertPreTrainedModel,u.AlbertTokenizer,u.AudioClassificationPipeline,u.AutoConfig,u.AutoFeatureExtractor,u.AutoImageProcessor,u.AutoModel,u.AutoModelForAudioClassification,u.AutoModelForAudioFrameClassification,u.AutoModelForCTC;var Zm=u.AutoModelForCausalLM;u.AutoModelForDepthEstimation,u.AutoModelForDocumentQuestionAnswering,u.AutoModelForImageClassification,u.AutoModelForImageFeatureExtraction,u.AutoModelForImageMatting,u.AutoModelForImageSegmentation,u.AutoModelForImageToImage,u.AutoModelForMaskGeneration,u.AutoModelForMaskedLM,u.AutoModelForNormalEstimation,u.AutoModelForObjectDetection,u.AutoModelForPoseEstimation,u.AutoModelForQuestionAnswering,u.AutoModelForSemanticSegmentation,u.AutoModelForSeq2SeqLM,u.AutoModelForSequenceClassification,u.AutoModelForSpeechSeq2Seq,u.AutoModelForTextToSpectrogram,u.AutoModelForTextToWaveform,u.AutoModelForTokenClassification,u.AutoModelForUniversalSegmentation,u.AutoModelForVision2Seq,u.AutoModelForXVector,u.AutoModelForZeroShotObjectDetection,u.AutoProcessor;var ef=u.AutoTokenizer;u.AutomaticSpeechRecognitionPipeline,u.BartForConditionalGeneration,u.BartForSequenceClassification,u.BartModel,u.BartPretrainedModel,u.BartTokenizer,u.BaseModelOutput,u.BaseStreamer,u.BeitFeatureExtractor,u.BeitForImageClassification,u.BeitModel,u.BeitPreTrainedModel,u.BertForMaskedLM,u.BertForQuestionAnswering,u.BertForSequenceClassification,u.BertForTokenClassification,u.BertModel,u.BertPreTrainedModel,u.BertTokenizer,u.BitImageProcessor,u.BlenderbotForConditionalGeneration,u.BlenderbotModel,u.BlenderbotPreTrainedModel,u.BlenderbotSmallForConditionalGeneration,u.BlenderbotSmallModel,u.BlenderbotSmallPreTrainedModel,u.BlenderbotSmallTokenizer,u.BlenderbotTokenizer,u.BloomForCausalLM,u.BloomModel,u.BloomPreTrainedModel,u.BloomTokenizer,u.CLIPFeatureExtractor,u.CLIPImageProcessor,u.CLIPModel,u.CLIPPreTrainedModel,u.CLIPSegForImageSegmentation,u.CLIPSegModel,u.CLIPSegPreTrainedModel,u.CLIPTextModel,u.CLIPTextModelWithProjection,u.CLIPTokenizer,u.CLIPVisionModel,u.CLIPVisionModelWithProjection,u.CamembertForMaskedLM,u.CamembertForQuestionAnswering,u.CamembertForSequenceClassification,u.CamembertForTokenClassification,u.CamembertModel,u.CamembertPreTrainedModel,u.CamembertTokenizer,u.CausalLMOutput,u.CausalLMOutputWithPast,u.ChineseCLIPFeatureExtractor,u.ChineseCLIPModel,u.ChineseCLIPPreTrainedModel,u.ClapAudioModelWithProjection,u.ClapFeatureExtractor,u.ClapModel,u.ClapPreTrainedModel,u.ClapTextModelWithProjection,u.ClassifierFreeGuidanceLogitsProcessor,u.CodeGenForCausalLM,u.CodeGenModel,u.CodeGenPreTrainedModel,u.CodeGenTokenizer,u.CodeLlamaTokenizer,u.CohereForCausalLM,u.CohereModel,u.CoherePreTrainedModel,u.CohereTokenizer,u.ConvBertForMaskedLM,u.ConvBertForQuestionAnswering,u.ConvBertForSequenceClassification,u.ConvBertForTokenClassification,u.ConvBertModel,u.ConvBertPreTrainedModel,u.ConvBertTokenizer,u.ConvNextFeatureExtractor,u.ConvNextForImageClassification,u.ConvNextImageProcessor,u.ConvNextModel,u.ConvNextPreTrainedModel,u.ConvNextV2ForImageClassification,u.ConvNextV2Model,u.ConvNextV2PreTrainedModel,u.DPTFeatureExtractor,u.DPTForDepthEstimation,u.DPTImageProcessor,u.DPTModel,u.DPTPreTrainedModel,u.DebertaForMaskedLM,u.DebertaForQuestionAnswering,u.DebertaForSequenceClassification,u.DebertaForTokenClassification,u.DebertaModel,u.DebertaPreTrainedModel,u.DebertaTokenizer,u.DebertaV2ForMaskedLM,u.DebertaV2ForQuestionAnswering,u.DebertaV2ForSequenceClassification,u.DebertaV2ForTokenClassification,u.DebertaV2Model,u.DebertaV2PreTrainedModel,u.DebertaV2Tokenizer,u.DecisionTransformerModel,u.DecisionTransformerPreTrainedModel,u.DeiTFeatureExtractor,u.DeiTForImageClassification,u.DeiTImageProcessor,u.DeiTModel,u.DeiTPreTrainedModel,u.DepthAnythingForDepthEstimation,u.DepthAnythingPreTrainedModel,u.DepthEstimationPipeline,u.DepthProForDepthEstimation,u.DepthProPreTrainedModel,u.DetrFeatureExtractor,u.DetrForObjectDetection,u.DetrForSegmentation,u.DetrImageProcessor,u.DetrModel,u.DetrObjectDetectionOutput,u.DetrPreTrainedModel,u.DetrSegmentationOutput,u.Dinov2ForImageClassification,u.Dinov2Model,u.Dinov2PreTrainedModel,u.DistilBertForMaskedLM,u.DistilBertForQuestionAnswering,u.DistilBertForSequenceClassification,u.DistilBertForTokenClassification,u.DistilBertModel,u.DistilBertPreTrainedModel,u.DistilBertTokenizer,u.DocumentQuestionAnsweringPipeline,u.DonutFeatureExtractor,u.DonutImageProcessor,u.DonutSwinModel,u.DonutSwinPreTrainedModel,u.EfficientNetForImageClassification,u.EfficientNetImageProcessor,u.EfficientNetModel,u.EfficientNetPreTrainedModel,u.ElectraForMaskedLM,u.ElectraForQuestionAnswering,u.ElectraForSequenceClassification,u.ElectraForTokenClassification,u.ElectraModel,u.ElectraPreTrainedModel,u.ElectraTokenizer,u.EosTokenCriteria,u.EsmForMaskedLM,u.EsmForSequenceClassification,u.EsmForTokenClassification,u.EsmModel,u.EsmPreTrainedModel,u.EsmTokenizer,u.FFT,u.FalconForCausalLM,u.FalconModel,u.FalconPreTrainedModel,u.FalconTokenizer,u.FastViTForImageClassification,u.FastViTModel,u.FastViTPreTrainedModel,u.FeatureExtractionPipeline,u.FeatureExtractor,u.FillMaskPipeline,u.Florence2ForConditionalGeneration,u.Florence2PreTrainedModel,u.Florence2Processor,u.ForcedBOSTokenLogitsProcessor,u.ForcedEOSTokenLogitsProcessor,u.GLPNFeatureExtractor,u.GLPNForDepthEstimation,u.GLPNModel,u.GLPNPreTrainedModel,u.GPT2LMHeadModel,u.GPT2Model,u.GPT2PreTrainedModel,u.GPT2Tokenizer,u.GPTBigCodeForCausalLM,u.GPTBigCodeModel,u.GPTBigCodePreTrainedModel,u.GPTJForCausalLM,u.GPTJModel,u.GPTJPreTrainedModel,u.GPTNeoForCausalLM,u.GPTNeoModel,u.GPTNeoPreTrainedModel,u.GPTNeoXForCausalLM,u.GPTNeoXModel,u.GPTNeoXPreTrainedModel,u.GPTNeoXTokenizer,u.Gemma2ForCausalLM,u.Gemma2Model,u.Gemma2PreTrainedModel,u.GemmaForCausalLM,u.GemmaModel,u.GemmaPreTrainedModel,u.GemmaTokenizer,u.GraniteForCausalLM,u.GraniteModel,u.GranitePreTrainedModel,u.Grok1Tokenizer,u.GroupViTModel,u.GroupViTPreTrainedModel,u.HerbertTokenizer,u.HieraForImageClassification,u.HieraModel,u.HieraPreTrainedModel,u.HubertForCTC,u.HubertForSequenceClassification,u.HubertModel,u.HubertPreTrainedModel,u.Idefics3ForConditionalGeneration,u.Idefics3ImageProcessor,u.Idefics3PreTrainedModel,u.Idefics3Processor,u.ImageClassificationPipeline,u.ImageFeatureExtractionPipeline,u.ImageFeatureExtractor,u.ImageMattingOutput,u.ImageProcessor,u.ImageSegmentationPipeline,u.ImageToImagePipeline,u.ImageToTextPipeline;var tf=u.InterruptableStoppingCriteria;u.JAISLMHeadModel,u.JAISModel,u.JAISPreTrainedModel,u.JinaCLIPImageProcessor,u.JinaCLIPModel,u.JinaCLIPPreTrainedModel,u.JinaCLIPProcessor,u.JinaCLIPTextModel,u.JinaCLIPVisionModel,u.LlamaForCausalLM,u.LlamaModel,u.LlamaPreTrainedModel,u.LlamaTokenizer,u.LlavaForConditionalGeneration,u.LlavaOnevisionForConditionalGeneration,u.LlavaOnevisionImageProcessor,u.LlavaPreTrainedModel,u.LogitsProcessor,u.LogitsProcessorList,u.LogitsWarper,u.LongT5ForConditionalGeneration,u.LongT5Model,u.LongT5PreTrainedModel,u.M2M100ForConditionalGeneration,u.M2M100Model,u.M2M100PreTrainedModel,u.M2M100Tokenizer,u.MBart50Tokenizer,u.MBartForCausalLM,u.MBartForConditionalGeneration,u.MBartForSequenceClassification,u.MBartModel,u.MBartPreTrainedModel,u.MBartTokenizer,u.MPNetForMaskedLM,u.MPNetForQuestionAnswering,u.MPNetForSequenceClassification,u.MPNetForTokenClassification,u.MPNetModel,u.MPNetPreTrainedModel,u.MPNetTokenizer,u.MT5ForConditionalGeneration,u.MT5Model,u.MT5PreTrainedModel,u.MarianMTModel,u.MarianModel,u.MarianPreTrainedModel,u.MarianTokenizer,u.Mask2FormerImageProcessor,u.MaskFormerFeatureExtractor,u.MaskFormerForInstanceSegmentation,u.MaskFormerImageProcessor,u.MaskFormerModel,u.MaskFormerPreTrainedModel,u.MaskedLMOutput,u.MaxLengthCriteria,u.MgpstrForSceneTextRecognition,u.MgpstrModelOutput,u.MgpstrPreTrainedModel,u.MgpstrProcessor,u.MgpstrTokenizer,u.MinLengthLogitsProcessor,u.MinNewTokensLengthLogitsProcessor,u.MistralForCausalLM,u.MistralModel,u.MistralPreTrainedModel,u.MobileBertForMaskedLM,u.MobileBertForQuestionAnswering,u.MobileBertForSequenceClassification,u.MobileBertModel,u.MobileBertPreTrainedModel,u.MobileBertTokenizer,u.MobileLLMForCausalLM,u.MobileLLMModel,u.MobileLLMPreTrainedModel,u.MobileNetV1FeatureExtractor,u.MobileNetV1ForImageClassification,u.MobileNetV1ImageProcessor,u.MobileNetV1Model,u.MobileNetV1PreTrainedModel,u.MobileNetV2FeatureExtractor,u.MobileNetV2ForImageClassification,u.MobileNetV2ImageProcessor,u.MobileNetV2Model,u.MobileNetV2PreTrainedModel,u.MobileNetV3FeatureExtractor,u.MobileNetV3ForImageClassification,u.MobileNetV3ImageProcessor,u.MobileNetV3Model,u.MobileNetV3PreTrainedModel,u.MobileNetV4FeatureExtractor,u.MobileNetV4ForImageClassification,u.MobileNetV4ImageProcessor,u.MobileNetV4Model,u.MobileNetV4PreTrainedModel,u.MobileViTFeatureExtractor,u.MobileViTForImageClassification,u.MobileViTImageProcessor,u.MobileViTModel,u.MobileViTPreTrainedModel,u.MobileViTV2ForImageClassification,u.MobileViTV2Model,u.MobileViTV2PreTrainedModel,u.ModelOutput,u.Moondream1ForConditionalGeneration,u.MptForCausalLM,u.MptModel,u.MptPreTrainedModel,u.MultiModalityCausalLM,u.MultiModalityPreTrainedModel,u.MusicgenForCausalLM,u.MusicgenForConditionalGeneration,u.MusicgenModel,u.MusicgenPreTrainedModel,u.NllbTokenizer,u.NoBadWordsLogitsProcessor,u.NoRepeatNGramLogitsProcessor,u.NomicBertModel,u.NomicBertPreTrainedModel,u.NougatImageProcessor,u.NougatTokenizer,u.OPTForCausalLM,u.OPTModel,u.OPTPreTrainedModel,u.ObjectDetectionPipeline,u.OlmoForCausalLM,u.OlmoModel,u.OlmoPreTrainedModel,u.OpenELMForCausalLM,u.OpenELMModel,u.OpenELMPreTrainedModel,u.OwlViTFeatureExtractor,u.OwlViTForObjectDetection,u.OwlViTImageProcessor,u.OwlViTModel,u.OwlViTPreTrainedModel,u.OwlViTProcessor,u.Owlv2ForObjectDetection,u.Owlv2ImageProcessor,u.Owlv2Model,u.Owlv2PreTrainedModel,u.PatchTSMixerForPrediction,u.PatchTSMixerModel,u.PatchTSMixerPreTrainedModel,u.PatchTSTForPrediction,u.PatchTSTModel,u.PatchTSTPreTrainedModel,u.Phi3ForCausalLM,u.Phi3Model,u.Phi3PreTrainedModel,u.PhiForCausalLM,u.PhiModel,u.PhiPreTrainedModel,u.Pipeline,u.PreTrainedModel,u.PreTrainedTokenizer,u.PretrainedConfig,u.PretrainedMixin,u.Processor,u.PvtForImageClassification,u.PvtImageProcessor,u.PvtModel,u.PvtPreTrainedModel,u.PyAnnoteFeatureExtractor,u.PyAnnoteForAudioFrameClassification,u.PyAnnoteModel,u.PyAnnotePreTrainedModel,u.PyAnnoteProcessor,u.QuestionAnsweringModelOutput,u.QuestionAnsweringPipeline,u.Qwen2ForCausalLM,u.Qwen2Model,u.Qwen2PreTrainedModel,u.Qwen2Tokenizer,u.Qwen2VLForConditionalGeneration,u.Qwen2VLImageProcessor,u.Qwen2VLPreTrainedModel,u.Qwen2VLProcessor,u.RTDetrForObjectDetection,u.RTDetrImageProcessor,u.RTDetrModel,u.RTDetrObjectDetectionOutput,u.RTDetrPreTrainedModel,u.RawImage,u.RepetitionPenaltyLogitsProcessor,u.ResNetForImageClassification,u.ResNetModel,u.ResNetPreTrainedModel,u.RoFormerForMaskedLM,u.RoFormerForQuestionAnswering,u.RoFormerForSequenceClassification,u.RoFormerForTokenClassification,u.RoFormerModel,u.RoFormerPreTrainedModel,u.RoFormerTokenizer,u.RobertaForMaskedLM,u.RobertaForQuestionAnswering,u.RobertaForSequenceClassification,u.RobertaForTokenClassification,u.RobertaModel,u.RobertaPreTrainedModel,u.RobertaTokenizer,u.SamImageProcessor,u.SamImageSegmentationOutput,u.SamModel,u.SamPreTrainedModel,u.SamProcessor,u.SapiensForDepthEstimation,u.SapiensForNormalEstimation,u.SapiensForSemanticSegmentation,u.SapiensPreTrainedModel,u.SeamlessM4TFeatureExtractor,u.SegformerFeatureExtractor,u.SegformerForImageClassification,u.SegformerForSemanticSegmentation,u.SegformerImageProcessor,u.SegformerModel,u.SegformerPreTrainedModel,u.Seq2SeqLMOutput,u.SequenceClassifierOutput,u.SiglipImageProcessor,u.SiglipModel,u.SiglipPreTrainedModel,u.SiglipTextModel,u.SiglipTokenizer,u.SiglipVisionModel,u.SpeechT5FeatureExtractor,u.SpeechT5ForSpeechToText,u.SpeechT5ForTextToSpeech,u.SpeechT5HifiGan,u.SpeechT5Model,u.SpeechT5PreTrainedModel,u.SpeechT5Processor,u.SpeechT5Tokenizer,u.SqueezeBertForMaskedLM,u.SqueezeBertForQuestionAnswering,u.SqueezeBertForSequenceClassification,u.SqueezeBertModel,u.SqueezeBertPreTrainedModel,u.SqueezeBertTokenizer,u.StableLmForCausalLM,u.StableLmModel,u.StableLmPreTrainedModel,u.Starcoder2ForCausalLM,u.Starcoder2Model,u.Starcoder2PreTrainedModel,u.StoppingCriteria,u.StoppingCriteriaList,u.SummarizationPipeline,u.SuppressTokensAtBeginLogitsProcessor,u.Swin2SRForImageSuperResolution,u.Swin2SRImageProcessor,u.Swin2SRModel,u.Swin2SRPreTrainedModel,u.SwinForImageClassification,u.SwinModel,u.SwinPreTrainedModel,u.T5ForConditionalGeneration,u.T5Model,u.T5PreTrainedModel,u.T5Tokenizer,u.TableTransformerForObjectDetection,u.TableTransformerModel,u.TableTransformerObjectDetectionOutput,u.TableTransformerPreTrainedModel,u.TemperatureLogitsWarper,u.Tensor,u.Text2TextGenerationPipeline,u.TextClassificationPipeline,u.TextGenerationPipeline;var rf=u.TextStreamer;u.TextToAudioPipeline,u.TokenClassificationPipeline,u.TokenClassifierOutput,u.TokenizerModel,u.TopKLogitsWarper,u.TopPLogitsWarper,u.TrOCRForCausalLM,u.TrOCRPreTrainedModel,u.TranslationPipeline,u.UniSpeechForCTC,u.UniSpeechForSequenceClassification,u.UniSpeechModel,u.UniSpeechPreTrainedModel,u.UniSpeechSatForAudioFrameClassification,u.UniSpeechSatForCTC,u.UniSpeechSatForSequenceClassification,u.UniSpeechSatModel,u.UniSpeechSatPreTrainedModel,u.VLChatProcessor,u.VLMImageProcessor,u.ViTFeatureExtractor,u.ViTForImageClassification,u.ViTImageProcessor,u.ViTMAEModel,u.ViTMAEPreTrainedModel,u.ViTMSNForImageClassification,u.ViTMSNModel,u.ViTMSNPreTrainedModel,u.ViTModel,u.ViTPreTrainedModel,u.VisionEncoderDecoderModel,u.VitMatteForImageMatting,u.VitMatteImageProcessor,u.VitMattePreTrainedModel,u.VitPoseForPoseEstimation,u.VitPoseImageProcessor,u.VitPosePreTrainedModel,u.VitsModel,u.VitsModelOutput,u.VitsPreTrainedModel,u.VitsTokenizer,u.Wav2Vec2BertForCTC,u.Wav2Vec2BertForSequenceClassification,u.Wav2Vec2BertModel,u.Wav2Vec2BertPreTrainedModel,u.Wav2Vec2CTCTokenizer,u.Wav2Vec2FeatureExtractor,u.Wav2Vec2ForAudioFrameClassification,u.Wav2Vec2ForCTC,u.Wav2Vec2ForSequenceClassification,u.Wav2Vec2Model,u.Wav2Vec2PreTrainedModel,u.Wav2Vec2ProcessorWithLM,u.WavLMForAudioFrameClassification,u.WavLMForCTC,u.WavLMForSequenceClassification,u.WavLMForXVector,u.WavLMModel,u.WavLMPreTrainedModel,u.WeSpeakerFeatureExtractor,u.WeSpeakerResNetModel,u.WeSpeakerResNetPreTrainedModel,u.WhisperFeatureExtractor,u.WhisperForConditionalGeneration,u.WhisperModel,u.WhisperPreTrainedModel,u.WhisperProcessor,u.WhisperTextStreamer,u.WhisperTimeStampLogitsProcessor,u.WhisperTokenizer,u.XLMForQuestionAnswering,u.XLMForSequenceClassification,u.XLMForTokenClassification,u.XLMModel,u.XLMPreTrainedModel,u.XLMRobertaForMaskedLM,u.XLMRobertaForQuestionAnswering,u.XLMRobertaForSequenceClassification,u.XLMRobertaForTokenClassification,u.XLMRobertaModel,u.XLMRobertaPreTrainedModel,u.XLMRobertaTokenizer,u.XLMTokenizer,u.XLMWithLMHeadModel,u.XVectorOutput,u.YolosFeatureExtractor,u.YolosForObjectDetection,u.YolosImageProcessor,u.YolosModel,u.YolosObjectDetectionOutput,u.YolosPreTrainedModel,u.ZeroShotAudioClassificationPipeline,u.ZeroShotClassificationPipeline,u.ZeroShotImageClassificationPipeline,u.ZeroShotObjectDetectionPipeline,u.bankers_round,u.cat,u.cos_sim,u.dot,u.dynamic_time_warping,u.env,u.full,u.full_like,u.getKeyValueShapes,u.hamming,u.hanning,u.interpolate,u.interpolate_4d,u.interpolate_data,u.is_chinese_char,u.layer_norm,u.load_image,u.log_softmax,u.magnitude,u.matmul,u.max,u.mean,u.mean_pooling,u.medianFilter,u.mel_filter_bank,u.min,u.ones,u.ones_like,u.permute,u.permute_data,u.pipeline,u.quantize_embeddings,u.read_audio,u.rfft,u.round,u.softmax,u.spectrogram,u.stack,u.std_mean,u.topk,u.window_function,u.zeros,u.zeros_like;const Mc=new tf;async function sf(){try{return(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{return!1}}class Xo{static async getInstance(R=null){return this.model_id??(this.model_id=await sf()?"Xenova/Phi-3-mini-4k-instruct_fp16":"Xenova/Phi-3-mini-4k-instruct"),this.tokenizer??(this.tokenizer=ef.from_pretrained(this.model_id,{legacy:!0,progress_callback:R})),this.model??(this.model=Zm.from_pretrained(this.model_id,{dtype:"q4",device:"webgpu",use_external_data_format:!0,progress_callback:R})),Promise.all([this.tokenizer,this.model])}}ve(Xo,"model_id",null),ve(Xo,"model",null),ve(Xo,"tokenizer",null),ve(Xo,"streamer",null);async function nf(Oe){const[R,c]=await Xo.getInstance(),w=R.apply_chat_template(Oe,{add_generation_prompt:!0,return_dict:!0});let z,G=0,re;const Q=()=>{z??(z=performance.now()),G++>0&&(re=G/(performance.now()-z)*1e3)},g=C=>{self.postMessage({status:"update",output:C,tps:re,numTokens:G})},v=new rf(R,{skip_prompt:!0,skip_special_tokens:!0,callback_function:g,token_callback_function:Q});self.postMessage({status:"start"});const M=await c.generate({...w,max_new_tokens:512,streamer:v,stopping_criteria:Mc}),y=R.batch_decode(M,{skip_special_tokens:!1});self.postMessage({status:"complete",output:y})}async function of(){self.postMessage({status:"loading",data:"Loading model..."});const[Oe,R]=await Xo.getInstance(w=>{self.postMessage(w)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const c=Oe("a");await R.generate({...c,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async Oe=>{const{type:R,data:c}=Oe.data;switch(R){case"load":of();break;case"generate":Mc.reset(),nf(c);break;case"interrupt":Mc.interrupt();break;case"reset":Mc.reset();break}})})();